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
Python
UTF-8
467
3.21875
3
[]
no_license
from easygui import * import sys # A nice welcome message ret_val = msgbox("Hello, World!") if ret_val is None: # User closed msgbox sys.exit(0) msg = "What is your favorite flavor?\nOr Press <cancel> to exit." title = "Ice Cream Survey" choices = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"] while True: choice = choicebox(msg, title, choices) if choice is None: sys.exit(0) msgbox("You chose: {}".format(choice), "Survey Result")
Python
UTF-8
743
3.609375
4
[]
no_license
# This exercise reads from one file and writes to another. # Amith, 01/11 from sys import argv # This allows us to check if a file exists. from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file, to_file) # we could do these two on one line. How? in_file = open(from_file) inData = in_file.read() # inData = open(from_file).read() # Note the use of len here. Length of the file. print "The file %s is %d bytes long" % (from_file, len(inData)) print "Does the output file exist? %r" % exists(to_file) # print "Ready? Hit RETURN to continue, CTRL-C to abort" # raw_input("?") open(to_file, 'w').write(inData) # See, in one line! print "All done!" in_file.close() # how to close out_file?
C
UTF-8
1,064
3.203125
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
/******************************************************************************* * NAME * avv - angle between two vectors * * SYNOPSIS * #include <math.h> * #include <mcce.h> * * double avv(VECTOR v1, VECTOR v2); * * DESCRIPTION * The avv() function returns the angle in radians between two vectors. * * RETURN VALUE * The returned floating point number is between 0 and pi. * * SEE ALSO * vdotv * * DEPENDENCY * vector_normalize * * EXAMPLE * #include <math.h> * #include <mcce.h> * ... * VECTOR v1, v2; * float phi; * ... * phi=avv(v1, v2); * * AUTHOR * Junjun Mao, 05/28/2003 *******************************************************************************/ #include <math.h> #include "mcce.h" double avv(VECTOR v1, VECTOR v2) { double t; v1 = vector_normalize(v1); v2 = vector_normalize(v2); t = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; if (t>1.0) t = 1.0; else if (t < -1.0) t = -1.0; return acos(t); }
JavaScript
UTF-8
416
3.453125
3
[]
no_license
var fs = require('fs'); /* //readFileSync 동기 console.log('A'); var result = fs.readFileSync('syntax/sample.txt','utf8'); console.log(result); console.log('C'); //readFileSync는 return값을 줌. */ //readFileAsync 비동기 console.log('A'); fs.readFile('syntax/sample.txt','utf8',function(err,result){ console.log(result); }); //readFile은 return 값을 주는게 아님 console.log('C');
Java
UTF-8
560
1.710938
2
[]
no_license
package cn.sancell.xingqiu.goods.fragment.listener; import cn.sancell.xingqiu.homeclassify.bean.ProductInfoDataBean; import cn.sancell.xingqiu.homeuser.bean.AddressListDataBean; public interface OnGoodsInfoListener { void onScrollChange(float alpha); //滑动渐变 void showShareBtn(boolean canShare); //是否可分享 void getGoodsInfo(ProductInfoDataBean data); void showCartTip(String str); //购物车提示 void updateAddress(AddressListDataBean.AddressItemBean item); //更新地址 void callHospital(String phone); }
Ruby
UTF-8
1,898
3.640625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def get_first_name_of_season_winner(data, season) new_array = [] data.each do |seasons, all_people| if seasons == season all_people.each do |person| person.each do |statistic, value| if value == "Winner" new_array << person["name"].split(" ") end end end end end return new_array[0][0] end def get_contestant_name(data, occupation) # code here new_array = [] data.each do |seasons, all_people| all_people.each do |person| person.each do |statistic, value| if value == occupation new_array << person["name"] end end end end return new_array[0] end def count_contestants_by_hometown(data, hometown) # code here new_array = [] counter = 0 data.each do |seasons, all_people| all_people.each do |person| person.each do |statistic, value| if value == hometown new_array << person["name"] counter += 1 end end end end return counter end def get_occupation(data, hometown) # code here new_array = [] data.each do |seasons, all_people| all_people.each do |person| person.each do |statistic, value| if value == hometown new_array << person["occupation"] end end end end return new_array[0] end def get_average_age_for_season(data, season) array = [] number = nil counter = 0 data.each do |seasons, all_people| if seasons == season all_people.each do |person| person.each do |statistic, value| if statistic == "age" array << person["age"].to_f counter +=1 number = array.inject(0){|sum,x| sum + x } /array.size.to_f end end end end end return number.round end
PHP
UTF-8
1,284
2.59375
3
[]
no_license
<?php // required headers header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Methods: POST"); header("Access-Control-Max-Age: 3600"); header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); // include database and object file include_once '../config/database.php'; include_once '../objects/news.php'; include_once '../../verify.php'; require_once '../../vendor/autoload.php'; if(!verify()) header('location:/login'); // get database connection $database = new Database(); $db = $database->getConnection(); // prepare product object $news = new News($db); // set product id to be deleted $news->id = __post('id'); $news->deleteImage(); //delete the news if ($news->delete()) { // delete comments & likes by news_id $news->deleteComments(); $news->deleteLikes(); // set response code - 200 ok http_response_code(200); // tell the news echo json_encode(array("message" => "News was deleted.")); } // if unable to delete the news else { // set response code - 503 service unavailable http_response_code(503); // tell the user echo json_encode(array("message" => "Unable to delete news.")); }
Python
UTF-8
175
3.390625
3
[]
no_license
# text1 = "hello" # text2 = "world" # print(text1, text2) # print("the end", "or is it", "keep watching to learn about python", 456, 354) print((lambda x, z: x + z) (10, 20))
Java
UTF-8
7,552
2.40625
2
[]
no_license
package cn.edustar.jitar.pojos; import java.io.Serializable; import java.util.Date; /** * 教研活动的对象 * @author 孟宪会 * */ public class Action implements Serializable, Cloneable { /** * */ private static final long serialVersionUID = 6530165023991769371L; /** 标识 */ @SuppressWarnings("unused") private int id; /** 活动标识 */ private int actionId; /** 活动标题 */ private String title; /** 活动对象所有者类型 */ private String ownerType; /** 活动所属于的对象 */ private Integer ownerId; /** 活动创建日期 */ private Date createDate = new Date(); /** 活动创建人 */ private int createUserId; /** 活动类型:0,不限制(任意参加);1,只能组内人员参加;2,只能邀请 */ private int actionType; /** 活动描述 */ private String description; /** 参与人数限制:0,不限制 */ private int userLimit; /** 活动开始时间 */ private Date startDateTime = new Date(); /** 活动结束时间 */ private Date finishDateTime = new Date(); /** 活动报名截止时间 */ private Date attendLimitDateTime = new Date(); /** 活动地点 */ private String place; /** 活动参加人数 */ private int attendCount; /** 活动确认参加人数 */ private int attendSuccessCount; /** * 活动确认不参加人数 */ private int attendQuitCount; /** 活动没有回应人数 */ private int AttendFailCount; /** 活动状态 * -1:待删除(回收站) * 0:正常 * 1:待审批 * 2:已经关闭 * 3:锁定 */ private int status; /** 活动方式 */ private int visibility; /** 是否锁定 */ private int isLock; /** 是否锁定:0表示胃锁定,1表示锁定 */ public int getIsLock() { return isLock; } /** 是否锁定:0表示胃锁定,1表示锁定 */ public void setIsLock(int isLock) { this.isLock = isLock; } /** 活动是否公开:0公开,1非公开,只有参与人员可见 */ public int getVisibility() { return visibility; } /** 活动是否公开:0公开,1非公开,只有参与人员可见 */ public void setVisibility(int visibility) { this.visibility = visibility; } /** 活动创建时间 */ public Date getCreateDate() { return createDate; } /** 活动创建时间 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** 活动标识 */ public int getId() { return this.actionId; } /** 活动标识 */ public void setId(int id) { this.actionId = id; } /** 活动标识 */ public int getActionId() { return actionId; } /** 活动标识 */ public void setActionId(int actionId) { this.actionId = actionId; } /** 活动标题 */ public String getTitle() { return title; } /** 活动标题 */ public void setTitle(String title) { this.title = title; } /** 活动所属对象的标识 */ public Integer getOwnerId() { return ownerId; } /** 活动所属对象的标识 */ public void setOwnerId(Integer ownerId) { this.ownerId = ownerId; } /** 活动创建者标识 */ public int getCreateUserId() { return createUserId; } /** 活动创建者标识 */ public void setCreateUserId(int createUserId) { this.createUserId = createUserId; } /** 活动类型:0,不限制(任意参加);1,只能组内人员参加;2,只能邀请 */ public int getActionType() { return actionType; } /** 活动类型:0,不限制(任意参加);1,只能组内人员参加;2,只能邀请 */ public void setActionType(int actionType) { this.actionType = actionType; } /** 活动描述 */ public String getDescription() { return description; } /** 活动描述 */ public void setDescription(String description) { this.description = description; } /** 活动参与用户数量限制 */ public int getUserLimit() { return userLimit; } /** 活动参与用户数量限制 */ public void setUserLimit(int userLimit) { this.userLimit = userLimit; } /** 活动开始时间 */ public Date getStartDateTime() { return startDateTime; } /** 活动开始时间 */ public void setStartDateTime(Date startDateTime) { this.startDateTime = startDateTime; } /** 活动结束时间 */ public Date getFinishDateTime() { return finishDateTime; } /** 活动结束时间 */ public void setFinishDateTime(Date finishDateTime) { this.finishDateTime = finishDateTime; } /** 活动报名截止时间 */ public Date getAttendLimitDateTime() { return attendLimitDateTime; } /** 活动报名截止时间 */ public void setAttendLimitDateTime(Date attendLimitDateTime) { this.attendLimitDateTime = attendLimitDateTime; } /** 活动地点 */ public String getPlace() { return place; } /** 活动地点 */ public void setPlace(String place) { this.place = place; } /** 活动已经参与人数 */ public int getAttendCount() { return attendCount; } /** 活动已经参与人数 */ public void setAttendCount(int attendCount) { this.attendCount = attendCount; } /** 活动确认参与人数 */ public int getAttendSuccessCount() { return attendSuccessCount; } /** 活动确认参与人数 */ public void setAttendSuccessCount(int attendSuccessCount) { this.attendSuccessCount = attendSuccessCount; } /** 活动确认不参与人数 */ public int getAttendQuitCount() { return attendQuitCount; } /** 活动确认不参与人数 */ public void setAttendQuitCount(int attendQuitCount) { this.attendQuitCount = attendQuitCount; } /** 活动状态 * -1:待删除(回收站) * 0:正常 * 1:待审批 * 2:已经关闭 * 3:锁定 */ public int getStatus() { return status; } /** 活动状态 * -1:待删除(回收站) * 0:正常 * 1:待审批 * 2:已经关闭 * 3:锁定 */ public void setStatus(int status) { this.status = status; } /** 活动确认不参与人数 */ public int getAttendFailCount() { return AttendFailCount; } /** 活动确认不参与人数 */ public void setAttendFailCount(int attendFailCount) { AttendFailCount = attendFailCount; } /** 活动所属的对象类型:目前有user,group,course */ public String getOwnerType() { return ownerType; } /** 活动所属的对象类型:目前有user,group,course */ public void setOwnerType(String ownerType) { this.ownerType = ownerType; } @Override public String toString() { return "Action [id=" + id + ", actionId=" + actionId + ", title=" + title + ", ownerType=" + ownerType + ", ownerId=" + ownerId + ", createDate=" + createDate + ", createUserId=" + createUserId + ", actionType=" + actionType + ", userLimit=" + userLimit + ", startDateTime=" + startDateTime + ", finishDateTime=" + finishDateTime + ", attendLimitDateTime=" + attendLimitDateTime + ", attendCount=" + attendCount + ", attendSuccessCount=" + attendSuccessCount + ", attendQuitCount=" + attendQuitCount + ", AttendFailCount=" + AttendFailCount + ", status=" + status + ", visibility=" + visibility + ", isLock=" + isLock + "]"; } }
C++
UTF-8
840
3.609375
4
[]
no_license
给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例 1: 输入: 1 输出: true 解释: 2^0 = 1 示例 2: 输入: 16 输出: true 解释: 2^4 = 16 示例 3: 输入: 218 输出: false ------------------------------------- 思路:如果是2的幂,则二进制数必然是 1后面n个0(n∈[0,+无穷)) 这样的形式 所以采用位移算法,有0时不管,遇到1时就判断这个数再位移一位后是不是0 --------------------------------- class Solution { public: bool isPowerOfTwo(int n) { if(n <= 0)return false; int tmp; while(n != 0) { if(n & 1 != 0){ tmp = n>>1; if(tmp == 0)return true; else return false; } n = n>>1; } return true; } };
Markdown
UTF-8
2,904
3.703125
4
[ "MIT" ]
permissive
--- title: "1. Linked List - Singly Linked List" tag: DataStructure --- singly linked list - 한 방향으로 노드가 노드를 가리키는 구조 - 노드는 data 와 link 를 가진다 - 보통 que(fifo) 를 구현 할 때 이런 방법을 많이 쓴다 - 첫번째 데이터 추가/삭제 시에 O(1), 데이터 검색은 O(n) - 단점: 검색할 때 무조건 앞쪽부터 노드를 쭉 거쳐야 하므로 index 를 사용하는 array 보다 비효율적 - 장점: 데이터 수정 시 이동이 필요없다 (link 만 바꿔주면 ok, 배열의 경우 데이터 삽입, 삭제 시 모든 데이터가 한칸씩 이동해야함) ``` class SList: # linked list 안쪽에 Node 를 정의해주었다. # 경우에 따라 다르겠지만 이런 방식도 잘 익혀두자. class Node: def __init__(self, item, link): self.item = item self.next = link def __init__(self): self.head = None self.size = 0 def size(self): return self.size def is_empty(self): return self.size == 0 # list 의 가장 앞에 노드 생성 def insert_front(self, item): if self.is_empty(): # 첫 노드가 생성, next 는 None 이 된다. self.head = self.Node(item, None) else: # head Node 를 새로 생성 및 설정, # previous head 는 새로운 head 의 next 로 설정 self.head = self.Node(item, self.head) self.size += 1 def insert_after(self, item, p): # p 는 Node object # p.next 에 생성될 Node 를 연결시켜준 뒤 # 생성될 Node 는 p.next 를 link(next) p.next = SList.Node(item, p.next) self.size += 1 def delete_front(self): if self.is_empty(): raise EmptyError('Underflow') else: self.head = self.head.next self.size -= 1 def delete_after(self, p): if self.is_empty(): raise EmptyError('Underflow') t = p.next # a -> b -> c 중에서 b.next = c p.next = t.next # b.next = c.next -> Node c 가 사라지고 다음 노드를 연결시킨다 self.size -= 1 def search(self, target): p = self.head # 첫번째 노드부터 검색 시작 for k in range(self.size): # list size 만큼 loop if target == p.item: # target 과 node item 일치 검사 # return k # 몇 번째 노드인지 숫자로 리턴 return p # 노드 객체 자체를 리턴 p = p.next # 다음 노드로 변경 return None def print_list(self): p = self.head while p: if p.next != None: print(p.item, '->', end=' ') else: print(p.item) p = p.next class EmptyError(Exception): pass ``` ```
Java
UTF-8
251
2.1875
2
[]
no_license
package HW_10.task_2; public class Journal extends Library { int yetAnotherPrametr; public Journal(String title, String author, int yetAnotherPrametr){ super(title, author); this.yetAnotherPrametr = yetAnotherPrametr; } }
Python
UTF-8
2,190
2.765625
3
[]
no_license
# FOR CCA EDITING ONLY from IPython.core.magic import (Magics, magics_class, cell_magic) from re import sub @magics_class class CCAMagics(Magics): @cell_magic def write2file(self, line, cell): """ Purpose: This magic-hack executes the current cell or writes it to a file, the twist with the original %%writefile is that it can indeed execute the cell normally based on an externally-defined switch. This is useful for continuous editing & debugging. Set notebook switch to OFF for general development and debugging, set it to ON to update all saved cells in order to sync with notebook. Syntax: %%wf2 nameOfFile.py switchVariable Remarks: this command is less safe than the original %%writefile and just overwrites pre-existing files if there were any without warnings, this is fine (and desirable) in the context for which it was designed. Also the retrieval of the switch is unsafe, again, if this is used within the context of which it was created, it should be fine. Author: thibaut@cambridgecoding, Aug16 """ # retrieve name of file & switch variable line = line.split(" ") fname = line[0] client = eval(line[1]) if client in ['CONTENT','DEV+CONTENT']: with open(fname,'w') as f: cell = sub(r'#</?cca>.*(\r?\n|\z)','',cell) f.write(cell) if client=='DEV+CONTENT': get_ipython().run_cell(cell) elif client in ['STUDENT','DEV+STUDENT']: opentag = "#<cca>" closetag = "#</cca>" idx_open = cell.find(opentag) idx_open = idx_open if idx_open else 0 tmpcell = "" if idx_open: tmpcell+=cell[0:idx_open-1] idx_close = cell.find(closetag) tmpcell += cell[idx_close+len(closetag):] # output that with open(fname,'w') as f: f.write(tmpcell) if client=='DEV+STUDENT': get_ipython().run_cell(cell) else: get_ipython().run_cell(cell) get_ipython().register_magics(CCAMagics)
Java
UTF-8
352
2.046875
2
[]
no_license
package org.marcoavila.ddd.transaction; import org.marcoavila.ddd.Entity; import org.marcoavila.ddd.facade.BaseReturn; /** * Abstraction that represents an Domain transaction. * * @author Marco Avila */ public interface DomainTransaction<AGGREGATE extends Entity<?>> { public BaseReturn<AGGREGATE> execute(AGGREGATE rootEntity); }
PHP
UTF-8
1,024
2.625
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateGameServerPlayerStats extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('game_server_player_stats', function (Blueprint $table) { $table->increments('id'); $table->integer('gid')->unsigned(); $table->integer('pid')->unsigned(); $table->string('statsKey'); $table->string('statsValue'); $table->timestamps(); $table->foreign('gid')->references('gid')->on('game_server_stats'); $table->foreign('pid')->references('id')->on('game_heroes'); $table->unique(['gid', 'pid', 'statsKey']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('game_server_player_stats'); } }
Java
UTF-8
1,006
3.0625
3
[]
no_license
package com.im.sky.lock.juc.aqs.test; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.LockSupport; /** * @author jiangchangwei * @date 2019-11-30 下午 4:08 **/ public class LockSupportTest { private static ConcurrentLinkedQueue<Thread> queue = new ConcurrentLinkedQueue(); public static void main(String[] args) { for(int i = 0; i < 10; i++) { Thread t = new Thread(() -> { say(); }); t.start(); } Thread t2 = new Thread(() -> { while (true) { Thread t = queue.poll(); if(t != null) { LockSupport.unpark(t); } } }); t2.start(); } private static void say() { System.out.println("再见"); queue.add(Thread.currentThread()); LockSupport.park(); System.out.println("再也不见"); } }
Java
UTF-8
738
2.125
2
[]
no_license
package fr.valkya.valkyris.client.gui.faction; import java.util.ArrayList; import java.util.List; import net.minecraft.client.gui.GuiScreen; public class GuiFacInfos extends GuiScreen { public static List<String> infos; public GuiFacInfos() { infos = new ArrayList<String>(); } @Override public void initGui() { // PacketRequestFactionInfos pkt = new PacketRequestFactionInfos(); // Valorion.getValorion().getProxy().getNetwork().sendToServer(pkt); } @Override public void drawScreen(int p_73863_1_, int p_73863_2_, float p_73863_3_) { int height = 0; for(String str : infos) { drawString(fontRendererObj, str, 0, height, -1); height+=11; } super.drawScreen(p_73863_1_, p_73863_2_, p_73863_3_); } }
JavaScript
UTF-8
3,943
2.5625
3
[]
no_license
require('dotenv').config(); const express = require('express'); const cors = require('cors'); const request = require('superagent'); const app = express(); app.use(cors()); let latitude; let longitude; app.get('/location', async(req, res, next) => { try { const location = req.query.search; const URL = `https://us1.locationiq.com/v1/search.php?key=${process.env.GEOCODE_API_KEY}&q=${location}&format=json`; const locationData = await request.get(URL); const firstResult = locationData.body[0]; latitude = firstResult.lat; longitude = firstResult.lon; res.json({ formatted_query: firstResult.display_name, latitude: latitude, longitude: longitude, }); } catch (err) { next(err); } }); const getWeatherData = async(latitude, longitude) => { const darkSkyData = await request.get(`https://api.darksky.net/forecast/${process.env.DARKSKY_API_KEY}/${latitude},${longitude}`); return darkSkyData.body.daily.data.map(forecast => { return { forecast: forecast.summary, time: new Date(forecast.time * 1000) }; }); }; app.get('/weather', async(req, res, next) => { try { const portlandWeather = await getWeatherData(latitude, longitude); res.json(portlandWeather); } catch (err) { next(err); } }); app.get('/events', async(req, res, next) => { try { const eventful = await request .get(`http://api.eventful.com/json/events/search?app_key=${process.env.EVENTFUL_API_KEY}&where=${latitude},${longitude}&within=25`); const eventfulObject = JSON.parse(eventful.text); const eventfulMap = eventfulObject.events.event.map(event => { return { link: event.url, name: event.title, event_date: event.start_time, summary: event.description === null ? 'N/A' : event.description, }; }); res.json(eventfulMap); } catch (err) { next(err); } }); app.get('/reviews', async(req, res, next) => { try { const yelpStuff = await request .get(`https://api.yelp.com/v3/businesses/search?term=restaurants&latitude=${latitude}&longitude=${longitude}`) .set('Authorization', `Bearer ${process.env.YELP_API_KEY}`); const yelpObject = JSON.parse(yelpStuff.text); const yelpBusinesses = yelpObject.businesses.map(business => { return { name: business.name, image_url: business.image_url, price: business.price, rating: business.rating, url: business.url }; }); res.json(yelpBusinesses); } catch (err) { next(err); } }); app.get('/trails', async(req, res, next) => { try { const trails = await request .get(`https://www.hikingproject.com/data/get-trails?lat=${latitude}&lon=${longitude}&maxDistance=10&key=${process.env.TRAILS_API_KEY}`); const trailsObject = JSON.parse(trails.text); const trailsMap = trailsObject.trails.map(trail => { return { name: trail.name, location: trail.location, length: trail.length, stars: trail.stars, star_votes: trail.starVotes, summary: trail.summary, trail_url: trail.url, conditions: trail.conditionStatus, condition_date: trail.conditionDate.split(' ')[0], condition_time: trail.conditionDate.split(' ')[1] }; }); res.json(trailsMap); } catch (err) { next(err); } }); app.get('*', (req, res) => { res.json({ onNo: '404' }); }); module.exports = { app: app };
Python
UTF-8
416
3.421875
3
[]
no_license
''' def palindrom(n): k = 0 temp = n while n > 0: k += (n % 10) k *= 10 n = n/10 return (k/10) == temp ''' def palindrom(n): return list(reversed(str(n))) == list(str(n)) def prime(n): for i in range(2,n): if(n % i == 0): return False return True i = 0 temp = 2 while i != 100: if(palindrom(temp)): if(prime(temp)):print temp;i+=1 temp +=1
Java
UTF-8
4,882
1.929688
2
[ "MIT" ]
permissive
package me.prettyprint.hom.openjpa; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.apache.openjpa.kernel.OpenJPAStateManager; import org.apache.openjpa.meta.ClassMetaData; import org.apache.openjpa.meta.FieldMetaData; import org.apache.openjpa.meta.JavaTypes; import org.apache.openjpa.util.OpenJPAId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.ColumnMapRowMapper; import me.prettyprint.cassandra.model.HColumnImpl; import me.prettyprint.cassandra.model.MutatorImpl; import me.prettyprint.cassandra.serializers.BytesArraySerializer; import me.prettyprint.cassandra.serializers.LongSerializer; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.cassandra.utils.StringUtils; import me.prettyprint.hector.api.Cluster; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SliceQuery; import me.prettyprint.hom.EntityManagerConfigurator; import me.prettyprint.hom.openjpa.EntityFacade.ColumnMeta; /** * Holds the {@link Cluster} and {@link Keyspace} references needed * for accessing Cassandra * * @author zznate */ public class CassandraStore { private static final Logger log = LoggerFactory.getLogger(CassandraStore.class); private final Cluster cluster; private final CassandraStoreConfiguration conf; private Keyspace keyspace; private MappingUtils mappingUtils; public CassandraStore(CassandraStoreConfiguration conf) { this.conf = conf; this.cluster = HFactory.getCluster(conf.getValue(EntityManagerConfigurator.CLUSTER_NAME_PROP) .getOriginalValue()); // TODO needs passthrough of other configuration mappingUtils = new MappingUtils(); } public CassandraStore open() { this.keyspace = HFactory.createKeyspace(conf.getValue(EntityManagerConfigurator.KEYSPACE_PROP) .getOriginalValue(), cluster); return this; } public boolean getObject(OpenJPAStateManager stateManager) { ClassMetaData metaData = stateManager.getMetaData(); EntityFacade entityFacade = new EntityFacade(metaData); Object idObj = stateManager.getId(); SliceQuery<byte[], String, byte[]> sliceQuery = mappingUtils.buildSliceQuery(idObj, entityFacade, keyspace); //stateManager.storeObject(0, idObj); QueryResult<ColumnSlice<String, byte[]>> result = sliceQuery.execute(); for (Map.Entry<String, ColumnMeta<?>> entry : entityFacade.getColumnMeta().entrySet()) { HColumn<String, byte[]> column = result.get().getColumnByName(entry.getKey()); if ( column != null ) stateManager.storeObject(entry.getValue().fieldId, entry.getValue().serializer.fromBytes(column.getValue())); } return true; } public Mutator storeObject(Mutator mutator, OpenJPAStateManager stateManager, Object idObj) { if ( mutator == null ) mutator = new MutatorImpl(keyspace, BytesArraySerializer.get()); if ( log.isDebugEnabled() ) { log.debug("Adding mutation (insertion) for class {}", stateManager.getManagedInstance().getClass().getName()); } ClassMetaData metaData = stateManager.getMetaData(); EntityFacade entityFacade = new EntityFacade(metaData); Object field; for (Map.Entry<String,ColumnMeta<?>> entry : entityFacade.getColumnMeta().entrySet()) { field = stateManager.fetch(entry.getValue().fieldId); if ( field != null ) { mutator.addInsertion(mappingUtils.getKeyBytes(idObj), entityFacade.getColumnFamilyName(), new HColumnImpl(entry.getKey(), field, keyspace.createClock(), StringSerializer.get(), entry.getValue().serializer)); } } return mutator; } public Mutator removeObject(Mutator mutator, OpenJPAStateManager stateManager, Object idObj) { if ( mutator == null ) mutator = new MutatorImpl(keyspace, BytesArraySerializer.get()); if ( log.isDebugEnabled() ) { log.debug("Adding mutation (deletion) for class {}", stateManager.getManagedInstance().getClass().getName()); } ClassMetaData metaData = stateManager.getMetaData(); EntityFacade entityFacade = new EntityFacade(metaData); mutator.addDeletion(mappingUtils.getKeyBytes(idObj), entityFacade.getColumnFamilyName(),null,StringSerializer.get()); return mutator; } public Cluster getCluster() { return cluster; } public Keyspace getKeyspace() { return keyspace; } }
Markdown
UTF-8
343
3.140625
3
[]
no_license
# Literally Just Stairs A minecraft datapack which changes the stair recipe to be more realistic. <h1>Reasoning For Changes</h1> <br> <p>My reasoning for this stems from the fact that a minecraft stair is exactly 3/4 of a block. This means that if you put in 6 planks, as the recipe requires, 6 * 3/4 = 8, so you should receive 8 stairs.</p>
Swift
UTF-8
3,155
3.046875
3
[]
no_license
// // Machine.swift // ImageMachinev2 // // Created by Ilyasa Azmi on 12/03/20. // Copyright © 2020 Ilyasa Azmi. All rights reserved. // import Foundation import UIKit import os.log class Machine: NSObject, NSCoding { //MARK: Properties var name: String var photo: UIImage? // var rating: Int var type: String var qrcode: Int var lastMaintenanceDate: Date //MARK: Archiving Paths static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! static let ArchiveURL = DocumentsDirectory.appendingPathComponent("machines") //MARK: Types struct PropertyKey { static let name = "name" static let photo = "photo" static let type = "type" static let qrcode = "qrcode" static let lastDate = "date" } //MARK: Initialization init?(name: String, photo: UIImage?, type: String, qrcode: Int, date: Date) { // The name must not be empty guard !name.isEmpty else { return nil } // Initialize stored properties. self.name = name self.photo = photo // self.rating = rating self.type = type self.qrcode = qrcode self.lastMaintenanceDate = date } //MARK: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: PropertyKey.name) aCoder.encode(photo, forKey: PropertyKey.photo) aCoder.encode(type, forKey: PropertyKey.type) aCoder.encode(qrcode, forKey: PropertyKey.qrcode) aCoder.encode(lastMaintenanceDate, forKey: PropertyKey.lastDate) } required convenience init?(coder aDecoder: NSCoder) { // The name is required. If we cannot decode a name string, the initializer should fail. // guard (aDecoder.decodeObject(forKey: PropertyKey.name) as? String) != nil else { // os_log("Unable to decode the name for a Machine object.", log: OSLog.default, type: .debug) // return nil // } // Because photo is an optional property of Machine, just use conditional cast. let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage let name = aDecoder.decodeObject(forKey: PropertyKey.name) as! String let type = aDecoder.decodeObject(forKey: PropertyKey.type) as! String // guard (aDecoder.decodeObject(forKey: PropertyKey.type) as? String) != nil else { // os_log("Unable to decode the name for a Machine object.", log: OSLog.default, type: .debug) // return nil // } let qrcode = aDecoder.decodeInteger(forKey: PropertyKey.qrcode) // guard (aDecoder.decodeObject(forKey: PropertyKey.lastDate) as? Date) != nil else { // os_log("Unable to decode the name for a Machine object.", log: OSLog.default, type: .debug) // return nil // } // Must call designated initializer. self.init(name: name, photo: photo, type: type, qrcode: qrcode, date: Date() ) } }
Go
UTF-8
6,168
2.78125
3
[ "MIT" ]
permissive
package usecase import ( "context" "fmt" "github.com/camphor-/relaym-server/domain/entity" "github.com/camphor-/relaym-server/domain/event" "github.com/camphor-/relaym-server/domain/repository" "github.com/camphor-/relaym-server/domain/spotify" ) // SessionUseCase はセッションに関するユースケースです。 type SessionUseCase struct { sessionRepo repository.Session userRepo repository.User playerCli spotify.Player trackCli spotify.TrackClient userCli spotify.User pusher event.Pusher timerUC *SessionTimerUseCase } // NewSessionUseCase はSessionUseCaseのポインタを生成します。 func NewSessionUseCase(sessionRepo repository.Session, userRepo repository.User, playerCli spotify.Player, trackCli spotify.TrackClient, userCli spotify.User, pusher event.Pusher, timerUC *SessionTimerUseCase) *SessionUseCase { return &SessionUseCase{ sessionRepo: sessionRepo, userRepo: userRepo, playerCli: playerCli, trackCli: trackCli, userCli: userCli, pusher: pusher, timerUC: timerUC, } } // EnqueueTrack はセッションのqueueにTrackを追加します。 func (s *SessionUseCase) EnqueueTrack(ctx context.Context, sessionID string, trackURI string) error { session, err := s.sessionRepo.FindByID(ctx, sessionID) if err != nil { return fmt.Errorf("FindByID sessionID=%s: %w", sessionID, err) } err = s.sessionRepo.StoreQueueTrack(ctx, &entity.QueueTrackToStore{ URI: trackURI, SessionID: sessionID, }) if err != nil { return fmt.Errorf("StoreQueueTrack URI=%s, sessionID=%s: %w", trackURI, sessionID, err) } if session.ShouldCallEnqueueAPINow() { err = s.playerCli.Enqueue(ctx, trackURI, session.DeviceID) if err != nil { return fmt.Errorf("Enqueue URI=%s, sessionID=%s: %w", trackURI, sessionID, err) } } s.pusher.Push(&event.PushMessage{ SessionID: sessionID, Msg: entity.EventAddTrack, }) return nil } // CreateSession は与えられたセッション名のセッションを作成します。 func (s *SessionUseCase) CreateSession(ctx context.Context, sessionName string, creatorID string, allowToControlByOthers bool) (*entity.SessionWithUser, error) { creator, err := s.userRepo.FindByID(creatorID) if err != nil { return nil, fmt.Errorf("FindByID userID=%s: %w", creatorID, err) } newSession, err := entity.NewSession(sessionName, creatorID, allowToControlByOthers) if err != nil { return nil, fmt.Errorf("NewSession sessionName=%s: %w", sessionName, err) } err = s.sessionRepo.StoreSession(ctx, newSession) if err != nil { return nil, fmt.Errorf("StoreSession sessionName=%s: %w", sessionName, err) } return entity.NewSessionWithUser(newSession, creator), nil } // CanConnectToPusher はイベントをクライアントにプッシュするためのコネクションを貼れるかどうかチェックします。 func (s *SessionUseCase) CanConnectToPusher(ctx context.Context, sessionID string) error { sess, err := s.sessionRepo.FindByID(ctx, sessionID) if err != nil { return fmt.Errorf("find session id=%s: %w", sessionID, err) } // セッションが再生中なのに同期チェックがされていなかったら始める // サーバ再起動でタイマーがなくなると、イベントが正しくクライアントに送られなくなるのでこのタイミングで復旧させる。 if exists := s.timerUC.existsTimer(sessionID); !exists && sess.IsPlaying() { fmt.Printf("session timer not found: create timer: sessionID=%s\n", sessionID) go s.timerUC.startTrackEndTrigger(ctx, sessionID) } return nil } // SetDevice は指定されたidのセッションの作成者と再生する端末を紐付けて再生するデバイスを指定します。 func (s *SessionUseCase) SetDevice(ctx context.Context, sessionID string, deviceID string) error { sess, err := s.sessionRepo.FindByID(ctx, sessionID) if err != nil { return fmt.Errorf("find session id=%s: %w", sessionID, err) } sess.DeviceID = deviceID if err := s.sessionRepo.Update(ctx, sess); err != nil { return fmt.Errorf("update device id: device_id=%s session_id=%s: %w", deviceID, sess.ID, err) } return nil } // GetSession は指定されたidからsessionの情報を返します func (s *SessionUseCase) GetSession(ctx context.Context, sessionID string) (*entity.SessionWithUser, []*entity.Track, *entity.CurrentPlayingInfo, error) { session, err := s.sessionRepo.FindByIDForUpdate(ctx, sessionID) if err != nil { return nil, nil, nil, fmt.Errorf("FindByID sessionID=%s: %w", sessionID, err) } creator, err := s.userRepo.FindByID(session.CreatorID) if err != nil { return nil, nil, nil, fmt.Errorf("FindByID userID=%s: %w", session.CreatorID, err) } trackURIs := make([]string, len(session.QueueTracks)) for i, queueTrack := range session.QueueTracks { trackURIs[i] = queueTrack.URI } tracks, err := s.trackCli.GetTracksFromURI(ctx, trackURIs) if err != nil { return nil, nil, nil, fmt.Errorf("get tracks: track_uris=%s: %w", trackURIs, err) } cpi, err := s.playerCli.CurrentlyPlaying(ctx) if err != nil { return nil, nil, nil, fmt.Errorf("CurrentlyPlaying: %w", err) } if !s.timerUC.existsTimer(sessionID) { return entity.NewSessionWithUser(session, creator), tracks, cpi, nil } isExpired, err := s.timerUC.isTimerExpired(sessionID) if isExpired { return entity.NewSessionWithUser(session, creator), tracks, cpi, nil } if err != nil { return nil, nil, nil, fmt.Errorf("isTimerExpired: %w", err) } if err := session.IsPlayingCorrectTrack(cpi); err != nil { s.timerUC.deleteTimer(session.ID) s.timerUC.handleInterrupt(session) if updateErr := s.sessionRepo.Update(ctx, session); updateErr != nil { return nil, nil, nil, fmt.Errorf("update session id=%s: %v: %w", session.ID, err, updateErr) } } return entity.NewSessionWithUser(session, creator), tracks, cpi, nil } // GetActiveDevices はログインしているユーザがSpotifyを起動している端末を取得します。 func (s *SessionUseCase) GetActiveDevices(ctx context.Context) ([]*entity.Device, error) { return s.userCli.GetActiveDevices(ctx) }
Python
UTF-8
151
2.65625
3
[]
no_license
import json from sklep import warzywa_i_owoce print(warzywa_i_owoce) dane_json = json.dumps(warzywa_i_owoce) print(dane_json) print(type(dane_json))
C++
UTF-8
14,901
2.71875
3
[ "MIT" ]
permissive
#include <CMathGeom3D.h> #include <CPlane3D.h> #include <CNPlane3D.h> #include <CMathGen.h> #include <CPoint3D.h> #include <CVector3D.h> #include <CLine3D.h> #include <CTriangle3D.h> #include <CMatrix3D.h> #include <CMatrix3DH.h> //! polygon orientation - clockwise or anti-clockwise CPolygonOrientation CMathGeom3D:: PolygonOrientation(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, double eye_x, double eye_y, double eye_z) { double off_x = eye_x - x1; double off_y = eye_y - y1; double off_z = eye_z - z1; double xd1d2, yd1d2, zd1d2; CrossProduct(x2 - x1, y2 - y1, z2 - z1, x3 - x2, y3 - y2, z3 - z2, &xd1d2, &yd1d2, &zd1d2); double dotprod = DotProduct(xd1d2, yd1d2, zd1d2, off_x, off_y, off_z); return (CPolygonOrientation) CMathGen::sign(dotprod); } //! polygon orientation - clockwise or anti-clockwise CPolygonOrientation CMathGeom3D:: PolygonOrientation(const CPoint3D &point1, const CPoint3D &point2, const CPoint3D &point3, const CPoint3D &eye) { CVector3D off(point1, eye); CVector3D d1d2 = CVector3D(point1, point2).crossProduct(CVector3D(point2, point3)); double dotprod = d1d2.dotProduct(off); return (CPolygonOrientation) CMathGen::sign(dotprod); } //------ //! intersection of line and plane bool CMathGeom3D:: LinePlaneIntersect(double line_x1, double line_y1, double line_z1, double line_x2, double line_y2, double line_z2, double plane_x, double plane_y, double plane_z, double plane_c, double *intersect_x, double *intersect_y, double *intersect_z, double *iparam) { double line_dx = line_x2 - line_x1; double line_dy = line_y2 - line_y1; double line_dz = line_z2 - line_z1; double d1 = DotProduct(line_dx, line_dy, line_dz, plane_x, plane_y, plane_z); if (fabs(d1) < CMathGen::EPSILON_E6) return false; double d2 = DotProduct(line_x1, line_y1, line_z1, plane_x, plane_y, plane_z); *iparam = (plane_c - d2)/d1; *intersect_x = line_x1 + (*iparam)*line_dx; *intersect_y = line_y1 + (*iparam)*line_dy; *intersect_z = line_z1 + (*iparam)*line_dz; return true; } //! intersection of line and plane bool CMathGeom3D:: LinePlaneIntersect(const CPoint3D &point1, const CPoint3D &point2, const CNPlane3D &normal, CPoint3D &ipoint, double &iparam) { CVector3D dvector(point1, point2); return LinePlaneIntersect(point1, dvector, normal, ipoint, iparam); } //! intersection of line and plane bool CMathGeom3D:: LinePlaneIntersect(const CPoint3D &point, const CVector3D &direction, const CNPlane3D &normal, CPoint3D &ipoint, double &iparam) { double d1 = direction.dotProduct(normal.getDirection()); if (fabs(d1) < CMathGen::EPSILON_E6) return false; CVector3D vector1(point); double d2 = vector1.dotProduct(normal.getDirection()); iparam = (normal.getScalar() - d2)/d1; ipoint = point + direction*iparam; return true; } //! intersection of line and plane bool CMathGeom3D:: LinePlaneIntersect(const CVector3D &vector1, const CVector3D &vector2, const CVector3D &normal, double normalc, CVector3D &ipoint, double &iparam) { CVector3D direction = vector2 - vector1; double d1 = direction.dotProduct(normal); if (fabs(d1) < CMathGen::EPSILON_E6) return false; double d2 = vector1.dotProduct(normal); iparam = (normalc - d2)/d1; ipoint = vector1 + direction*iparam; return true; } //! intersection of line and plane bool CMathGeom3D:: LinePlaneIntersect(const CLine3D &line, const CPlane3D &plane, CPoint3D &ipoint, double &iparam) { const CVector3D &normal = plane.getNormal(); double d1 = normal.dotProduct(line.vector()); if (fabs(d1) < CMathGen::EPSILON_E6) return false; double d2 = normal.dotProduct(CVector3D(line.start(), plane.getPoint())); iparam = d2/d1; ipoint = line.point(iparam); return true; } //-------- //! perpendicular connecting line between two lines bool CMathGeom3D:: LineBetweenLines(const CLine3D &line1, const CLine3D &line2, CLine3D &linei) { const CVector3D &v1 = line1.vector(); const CVector3D &v2 = line2.vector(); const CVector3D vd(line2.start(), line1.start()); double v22 = v2.dotProduct(v2); if (fabs(v22) < CMathGen::EPSILON_E6) return false; double v11 = v1.dotProduct(v1); double v21 = v2.dotProduct(v1); double d = v11*v22 - v21*v21; if (fabs(d) < CMathGen::EPSILON_E6) return false; double vd1 = vd.dotProduct(v1); double vd2 = vd.dotProduct(v2); double mu1 = (vd2*v21 - vd1*v22)/d; double mu2 = (vd2 + mu1*v21)/v22; linei = CLine3D(line1.point(mu1), line2.point(mu2)); return true; } //-------- //! line intersection between two planes bool CMathGeom3D:: PlaneIntersect(const CPlane3D &plane1, const CPlane3D &plane2, CLine3D &iline) { const CVector3D &normal1 = plane1.getNormal(); const CVector3D &normal2 = plane2.getNormal(); double n11 = normal1.dotProduct(normal1); double n12 = normal1.dotProduct(normal2); double n22 = normal2.dotProduct(normal2); double det = n11*n22 - n12*n12; if (fabs(det) < CMathGen::EPSILON_E6) return false; double idet = 1.0/det; double c1 = (plane1.getConstant()*n22 - plane2.getConstant())*n12*idet; double c2 = (plane2.getConstant()*n11 - plane1.getConstant())*n12*idet; CVector3D p = normal1.crossProduct(normal2); CPoint3D p1 = (c1*normal1 + c2*normal2).point(); CPoint3D p2 = p1 + p; iline = CLine3D(p1, p2); return true; } bool CMathGeom3D:: PlaneIntersect(const CPlane3D &plane1, const CPlane3D &plane2, const CPlane3D &plane3, CPoint3D &ipoint) { const CVector3D &normal1 = plane1.getNormal(); const CVector3D &normal2 = plane2.getNormal(); const CVector3D &normal3 = plane3.getNormal(); double d = normal1.dotProduct(normal2.crossProduct(normal3)); if (fabs(d) < CMathGen::EPSILON_E6) return false; double id = 1.0/d; ipoint = (plane1.getConstant()*normal2.crossProduct(normal3) + plane2.getConstant()*normal3.crossProduct(normal1) + plane3.getConstant()*normal1.crossProduct(normal2)).point(); ipoint *= id; return true; } void CMathGeom3D:: FaceNormal(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, double *nx, double *ny, double *nz, double *nc) { double xdiff1 = x2 - x1, ydiff1 = y2 - y1, zdiff1 = z2 - z1; double xdiff2 = x3 - x2, ydiff2 = y3 - y2, zdiff2 = z3 - z2; CrossProduct(xdiff1, ydiff1, zdiff1, xdiff2, ydiff2, zdiff2, nx, ny, nz); *nc = DotProduct(*nx, *ny, *nz, x1, y1, z1); } void CMathGeom3D:: FaceNormal(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, CNPlane3D &normal) { CVector3D diff1(x2 - x1, y2 - y1, z2 - z1); CVector3D diff2(x3 - x2, y3 - y2, z3 - z2); normal.setDirection(CVector3D::crossProduct(diff1, diff2)); normal.setScalar(CVector3D::dotProduct(normal.getDirection(), x1, y1, z1)); } void CMathGeom3D:: FaceNormal(const CPoint3D &point1, const CPoint3D &point2, const CPoint3D &point3, CNPlane3D &normal) { CVector3D diff1(point1, point2); CVector3D diff2(point2, point3); normal.setDirection(CVector3D::crossProduct(diff1, diff2)); normal.setScalar(CVector3D::dotProduct(normal.getDirection(), point1.x, point1.y, point1.z)); } bool CMathGeom3D:: Collinear(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3) { double xdiff1 = x2 - x1, ydiff1 = y2 - y1, zdiff1 = z2 - z1; double xdiff2 = x3 - x2, ydiff2 = y3 - y2, zdiff2 = z3 - z2; double nx, ny, nz; CrossProduct(xdiff1, ydiff1, zdiff1, xdiff2, ydiff2, zdiff2, &nx, &ny, &nz); return (fabs(nx) < CMathGen::EPSILON_E6 || fabs(ny) < CMathGen::EPSILON_E6 || fabs(nz) < CMathGen::EPSILON_E6); } double CMathGeom3D:: DotProduct(const CPoint3D &point1, const CPoint3D &point2) { return (point1.x*point2.x + point1.y*point2.y + point1.z*point2.z); } double CMathGeom3D:: DotProduct(double x1, double y1, double z1, const CPoint3D &point2) { return (x1*point2.x + y1*point2.y + z1*point2.z); } double CMathGeom3D:: DotProduct(const CPoint3D &point1, double x2, double y2, double z2) { return (point1.x*x2 + point1.y*y2 + point1.z*z2); } double CMathGeom3D:: DotProduct(double x1, double y1, double z1, double x2, double y2, double z2) { return (x1*x2 + y1*y2 + z1*z2); } void CMathGeom3D:: CrossProduct(double x1, double y1, double z1, double x2, double y2, double z2, double *x3, double *y3, double *z3) { *x3 = y1*z2 - z1*y2; *y3 = z1*x2 - x1*z2; *z3 = x1*y2 - y1*x2; } CPoint3D CMathGeom3D:: CrossProduct(const CPoint3D &point1, const CPoint3D &point2) { CPoint3D point; point.x = point1.y*point2.z - point1.z*point2.y; point.y = point1.z*point2.x - point1.x*point2.z; point.z = point1.x*point2.y - point1.y*point2.x; return point; } bool CMathGeom3D:: PointPlaneDistance(const CPoint3D &point, const CPlane3D &plane, double *dist) { const CVector3D &normal = plane.getNormal(); const CPoint3D &ppoint = plane.getPoint(); *dist = CVector3D(ppoint, point).dotProduct(normal)/normal.length(); return true; } bool CMathGeom3D:: PointLineDistance(const CPoint3D &point, const CLine3D &line, double *dist) { CVector3D pl(point, line.start()); CVector3D l = line.vector(); double u1 = pl.dotProduct(l); double u2 = l .lengthSqr(); if (u2 <= 0.0) return false; double u = u1/u2; if (u < 0.0 || u > 1.0) return false; CPoint3D intersection(line.start() + u*l); *dist = PointPointDistance(point, intersection); return true; } double CMathGeom3D:: PointPointDistance(const CPoint3D &point1, const CPoint3D &point2) { return sqrt((point1.x - point2.x)*(point1.x - point2.x) + (point1.y - point2.y)*(point1.y - point2.y) + (point1.z - point2.z)*(point1.z - point2.z)); } bool CMathGeom3D:: TrianglesCentroid(CTriangle3D *triangles, int num_triangles, CPoint3D &cpoint) { CPoint3D c; double a, d = 0; cpoint.zero(); for (int i = 0; i < num_triangles; ++i) { c = triangles[i].centroid(); a = triangles[i].area2(); cpoint += a*c; d += a; } if (fabs(d) < CMathGen::EPSILON_E6) return false; double id = 1.0/d; cpoint *= id; return true; } bool CMathGeom3D:: PointInside(double x, double y, double z, double *px, double *py, double *pz, int np) { double anglesum = PointAngleSum(x, y, z, px, py, pz, np); if (fabs(anglesum - 2.0*M_PI) < CMathGen::EPSILON_E6) return true; return false; } double CMathGeom3D:: PointAngleSum(double x, double y, double z, double *px, double *py, double *pz, int np) { double m1, m2; double x1, y1, z1, x2, y2, z2; double anglesum = 0, costheta; int i = np - 1; for (int j = 0; j < np; i = j++) { x1 = px[i] - x; y1 = py[i] - y; z1 = pz[i] - z; x2 = px[j] - x; y2 = py[j] - y; z2 = pz[j] - z; m1 = x1*x1 + y1*y1 + z1*z1; m2 = x2*x2 + y2*y2 + z2*z2; if (m1*m2 < CMathGen::EPSILON_E6) return 2.0*M_PI; costheta = (x1*x2 + y1*y2 + z1*z2)/(m1*m2); anglesum += acos(costheta); } return anglesum; } bool CMathGeom3D:: SphereLineIntersect(double xc, double yc, double zc, double r, double x1, double y1, double z1, double x2, double y2, double z2, double *xi1, double *yi1, double *zi1, double *xi2, double *yi2, double *zi2, int *num_i) { double dx = x2 - x1; double dy = y2 - y1; double dz = z2 - z1; double x1c = x1 - xc; double y1c = y1 - yc; double z1c = z1 - zc; double a = dx*dx + dy*dy + dz*dz; if (fabs(a) < CMathGen::EPSILON_E6) { *num_i = 0; return false; } double i2a = 0.5/a; double b = 2.0*(dx*x1c + dy*y1c + dz*z1c); double mb_i2a = -b*i2a; if (mb_i2a < 0.0 || mb_i2a > 1.0) // Not on line return false; double c = xc*xc + yc*yc + zc*zc + x1*x1 + y1*y1 + z1*z1 - 2.0*(xc*x1 + yc*y1 + zc*z1) - r*r; double b2_4ac = b*b - 4.0*a*c; if (b2_4ac < 0.0) { *num_i = 0; return false; } if (fabs(b2_4ac) < CMathGen::EPSILON_E6) { *num_i = 1; double mu = mb_i2a; *xi1 = x1 + mu*dx; *yi1 = y1 + mu*dy; *zi1 = z1 + mu*dz; return true; } double r_b2_4ac_i2a = sqrt(b2_4ac)*i2a; *num_i = 2; double mu1 = mb_i2a + r_b2_4ac_i2a; *xi1 = x1 + mu1*dx; *yi1 = y1 + mu1*dy; *xi1 = z1 + mu1*dz; double mu2 = mb_i2a - r_b2_4ac_i2a; *xi2 = x1 + mu2*dx; *yi2 = y1 + mu2*dy; *zi2 = z1 + mu2*dz; return true; } bool CMathGeom3D:: FourPointSphere(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, double x4, double y4, double z4, double *xc, double *yc, double *zc, double *r) { double d1 = x1*x1 + y1*y1 + z1*z1; double d2 = x2*x2 + y2*y2 + z2*z2; double d3 = x3*x3 + y3*y3 + z3*z3; double d4 = x4*x4 + y4*y4 + z4*z4; CMatrix3DH m11(x1, y1, z1, 1.0, x2, y2, z2, 1.0, x3, y3, z3, 1.0, x4, y4, z4, 1.0); double dm11 = m11.determinant(); if (fabs(dm11) < CMathGen::EPSILON_E6) return false; double idm11 = 1.0/dm11; CMatrix3DH m12(d1, y1, z1, 1.0, d2, y2, z2, 1.0, d3, y3, z3, 1.0, d4, y4, z4, 1.0); double dm12 = m12.determinant(); CMatrix3DH m13(x1, d1, z1, 1.0, x2, d2, z2, 1.0, x3, d3, z3, 1.0, x4, d4, z4, 1.0); double dm13 = m13.determinant(); CMatrix3DH m14(x1, y1, d1, 1.0, x2, y2, d2, 1.0, x3, y3, d3, 1.0, x4, y4, d4, 1.0); double dm14 = m14.determinant(); CMatrix3DH m15(d1, x1, y1, z1, d2, x2, y2, z2, d3, x3, y3, z3, d4, x4, y4, z4); double dm15 = m15.determinant(); *xc = 0.5*dm12*idm11; *yc = 0.5*dm13*idm11; *zc = 0.5*dm14*idm11; *r = sqrt((*xc)*(*xc) + (*yc)*(*yc) + (*zc)*(*zc) - dm15*idm11); return true; } //-------- double CMathGeom3D:: TetrahedronVolume(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3, double x4, double y4, double z4) { double ax = x1 - x4, ay = y1 - y4, az = z1 - z4; double bx = x2 - x4, by = y2 - y4, bz = z2 - z4; double cx = x3 - x4, cy = y3 - y4, cz = z3 - z4; return ax*(by*cz - bz*cy) + ay*(bz*cx - bx*cz) + az*(bx*cy - by*cx); } //-------- void CMathGeom3D:: orthogonalize(const std::vector<CVector3D> &ivectors, std::vector<CVector3D> &ovectors) { ovectors = ivectors; uint num = ivectors.size(); for (uint j = 1; j < num; ++j) { for (uint i = 0; i < j - 1; ++i) { CVector3D p = ovectors[i]*((ovectors[i].dotProduct(ovectors[j]))/ (ovectors[i].dotProduct(ovectors[i]))); ovectors[j] = ovectors[j] - p; } } }
Markdown
UTF-8
1,814
3.203125
3
[]
no_license
1. Our functional code is already pretty compact, so we probably won't be looking at it. What we illustrate here is refactoring our test code, since it isn't very maintainable as-is. 2. One easy update we can make is to use pytest fixtures. These are used to simplify the setup/teardown of tests. @pytest.fixture def default_inv(): return Inventory() @pytest.fixture def ten_pants_inv(): inv = Inventory() inv.set_stock('Pants', 50.00, 10) return inv def set_stock_helper(inv, name, price, quantity): prev_total = inv.total_stock() inv.set_stock(name, price, quantity) assert inv.items[name]['price'] == price assert inv.items[name]['quantity'] == quantity assert inv.total_stock() == prev_total + quantity def remove_stock_helper(inv, name, quantity): prev_total = inv.total_stock() prev_quantity = inv.items[name]['quantity'] prev_price = inv.items[name]['price'] inv.remove_stock(name, quantity) assert inv.items[name]['price'] == prev_price assert inv.items[name]['quantity'] == prev_quantity - quantity assert inv.total_stock() == prev_total - quantity def test_default_inventory(default_inv): assert default_inv.limit == 100 assert default_inv.total_stock() == 0 def test_ten_pants_inv(ten_pants_inv): assert ten_pants_inv.limit == 100 assert ten_pants_inv.items['Pants']['price'] == 50.00 assert ten_pants_inv.items['Pants']['quantity'] == 10 assert ten_pants_inv.total_stock() == 10 3. We've added a test, but reduced our code volume by about 25%!
C#
UTF-8
2,796
2.71875
3
[ "MIT" ]
permissive
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* TreeNode.cs -- generic tree node * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using CodeJam; using JetBrains.Annotations; using MoonSharp.Interpreter; #endregion namespace AM.Collections { /// <summary> /// Generic tree node. /// </summary> [PublicAPI] [MoonSharpUserData] public class TreeNode<T> { #region Properties /// <summary> /// Children nodes. /// </summary> [NotNull] public NonNullCollection<TreeNode<T>> Children { get; private set; } /// <summary> /// User defined value. /// </summary> public T Value { get; set; } #endregion #region Construction /// <summary> /// Constructor. /// </summary> public TreeNode() { Children = new NonNullCollection<TreeNode<T>>(); } /// <summary> /// Constructor. /// </summary> public TreeNode ( T value ) : this() { Value = value; } #endregion #region Private members #endregion #region Public methods /// <summary> /// Add child with a specified value. /// </summary> public TreeNode<T> AddChild ( T value ) { TreeNode<T> child = new TreeNode<T>(value); Children.Add(child); return child; } /// <summary> /// Get descendants of the node. /// </summary> [NotNull] [ItemNotNull] public NonNullCollection<TreeNode<T>> GetDescendants() { NonNullCollection<TreeNode<T>> result = new NonNullCollection<TreeNode<T>>(); foreach (TreeNode<T> child in Children) { result.Add(child); result.AddRange(child.GetDescendants()); } return result; } /// <summary> /// Walk through the tree starting the current node. /// </summary> public void Walk ( [NotNull] Action<TreeNode<T>> action ) { Code.NotNull(action, "action"); action(this); foreach (TreeNode<T> child in Children) { child.Walk(action); } } #endregion } }
C++
UTF-8
2,290
3.703125
4
[]
no_license
// Author: Trevor Parsons // Date: 6/20/18 // Description: Main function of HW1 that creates an arry of // 20 random variables from 1-100, sorts the array by ascending value, and // then promps the user for a number between 1-100 and tells the user if // that value is in the array of random numbers. #include <iostream> #include <ctime> #include <string> #include "functions.h" using namespace std; int main () { srand (time (NULL)); // Program Variables const int SIZE = 20; int randNums[SIZE]; bool duplicateTest; bool swap; int temp; int userNumber; bool cont = true; string userPref; // Assignment of random values to array do { duplicateTest = true; for (int i = 0; i < SIZE; i++) { randNums[i] = rand () % 100; }; for (int i = 0; i < SIZE - 1; i++) { for (int j = i + 1; j < SIZE; j++) { if (randNums[i] == randNums[j]) { duplicateTest = false; } } } } while (duplicateTest == false); // Bubble sort for values in array do { swap = false; for (int i = 0; i < SIZE - 1; i++) { if (randNums[i] > randNums[i + 1]) { temp = randNums[i]; randNums[i] = randNums[i + 1]; randNums[i + 1] = temp; swap = true; } } } while (swap); // Print random values in array for (int i = 0; i < SIZE; i++) { cout << randNums[i] << " "; } cout << endl << endl; // Check array for user value while (cont == true) { cout << "Please enter a whole number between 1 and 100" << endl; cin >> userNumber; if (randNums[binSearch (randNums, 20, userNumber)] == userNumber) { cout << "yes, the index of your number is: " << binSearch (randNums, 20, userNumber) << endl; } else { cout << "no" << endl; } cout << "Would you like to try another value? Please enter yes or no: " << endl; cin >> userPref; if (userPref == "no") cont = false; } return 0; }
C
UTF-8
645
4.15625
4
[]
no_license
/* 13. (MAT 89) Dizemos que um inteiro positivo n é perfeito se for igual à soma de seus divisores positivos diferentes de n. Exemplo: 6 é perfeito, pois 1+2+3 = 6. Dado um inteiro positivo n, verificar se n é perfeito. */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main(){ int n, i, soma = 0, resto; //Declara as variáveis. //Inserir primeiro número printf("Digite n:"); scanf("%d", &n); for(i = 1; i < n; i++) { if(n % i == 0) { soma = soma + i; } } if(soma == n) { printf("O número %d é perfeito.", n); return 0; } printf("O número %d não é perfeito.", n); return 0; }
Python
UTF-8
1,410
3.28125
3
[]
no_license
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree1(self, preorder, inorder): if len(preorder) == 0: return None root = TreeNode(preorder[0]) rootidx = -1 for index, val in enumerate(inorder): if val == root.val: rootidx = index inleft = inorder[:rootidx] preleft = preorder[1:rootidx + 1] inright = inorder[rootidx + 1:] preright = preorder[rootidx + 1:] root.left = self.buildTree(preleft, inleft) root.right = self.buildTree(preright, inright) return root def buildTree2(self, preorder, inorder): # Optimized version of the above code map_inorder = dict() for index, val in enumerate(inorder): map_inorder[val] = index return self.helper(preorder, 0, len(preorder) - 1, inorder, 0, len(inorder) - 1, map_inorder) def helper(self, preorder, prestart, preend, inorder, instart, inend, map_inorder): if prestart > preend or instart > inend: return None rootVal = preorder[prestart] rootidx = map_inorder[rootVal] root = TreeNode(rootVal) num_left = rootidx - instart root.left = self.helper(preorder, prestart + 1, prestart + num_left, inorder, instart, rootidx - 1, map_inorder) root.right = self.helper(preorder, prestart + num_left + 1, preend, inorder, rootidx + 1, inend, map_inorder) return root
SQL
UTF-8
795
3.890625
4
[]
no_license
use furama_database; -- 7. Hiển thị thông tin IDDichVu, TenDichVu, DienTich, SoNguoiToiDa, ChiPhiThue, TenLoaiDichVu -- của tất cả các loại dịch vụ đã từng được Khách hàng đặt phòng trong năm 2018 -- nhưng chưa từng được Khách hàng đặt phòng trong năm 2019. select dv.id_dich_vu,dv.ten_dich_vu,dv.dien_tich,dv.so_nguoi_toi_da,dv.chi_phi_thue,ldv.ten_loai_dich_vu from dich_vu dv join loai_dich_vu ldv on dv.id_loai_dich_vu = ldv.id_loai_dich_vu join hop_dong hd on hd.id_dich_vu = dv.id_dich_vu where (year(hd.ngay_lam_hop_dong)=2018) and (hd.id_dich_vu not in (select hd.id_dich_vu from hop_dong where (year(hd.ngay_lam_hop_dong)=2019) ) ) group by dv.id_dich_vu ;
Java
UTF-8
921
3
3
[]
no_license
package com.itheima.test11; import java.util.Arrays; import java.util.Random; public class DoubleColorBallUtil { // 产生双色球的代码 public static String create() { String[] red = {"01","02","03","04","05","06","07","08","09","10", "11","12","13","14","15","16","17","18","19","20","21","22","23", "24","25","26","27","28","29","30","31","32","33"}; //创建蓝球 String[] blue = "01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16".split(","); boolean[] used = new boolean[red.length]; Random r = new Random(); String[] all = new String[7]; for(int i = 0;i<6;i++) { int idx; do { idx = r.nextInt(red.length);//0-32 } while (used[idx]);//如果使用了继续找下一个 used[idx] = true;//标记使用了 all[i] = red[idx];//取出一个未使用的红球 } all[all.length-1] = blue[r.nextInt(blue.length)]; Arrays.sort(all); return Arrays.toString(all); } }
C
UTF-8
1,495
4.03125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> typedef struct queue { int capacity; int rear, front; int *arr; } queue; int main() { queue *q = NULL; q = createQueue(4); int item; while(1) { system("cls"); printMetaDeta(q); switch(menu()) { case 1: printf("Enter item -> "); scanf("%d",&item); enqueue(q, item); break; case 2: dequeue(q); break; case 3: printf("Peek %d ",peek(q)); break; case 4: viewList(q); break; case 5: exit(0); break; default: printf("Invalid choice!!!"); } getch(); } return 0; } void viewList(queue *q) { int i; if(q->front >= 0) for(i = q->front; i <= q->rear; i++) printf("%d ", q->arr[i]); else printf("List is empty"); } void printMetaDeta(queue *q) { printf("Queue is empty? %s\n",isEmpty(q)? "Yes" : "No"); printf("Queue is full? %s\n", isFull(q)? "Yes" : "No"); printf("Queue has %d items\n",countItems(q)); } int menu() { int n; printf("\n1.Enqueue"); printf("\n2.Dequeue"); printf("\n3.Peek"); printf("\n4.View List"); printf("\n5.Exit"); printf("\nEnter your choice ->"); scanf("%d",&n); return n; }
C++
UTF-8
804
2.6875
3
[]
no_license
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <map> #include <vector> #include <algorithm> #include <math.h> #define pb push_back using namespace std; int h; int w = 1; void printfChar(char c, int n) { for (int i = 0; i < n; i++) printf("%C", c); } void solve() { printfChar(' ', h - 1); printfChar('*', 1); printfChar(' ', h - 1); printf("\n"); for (int i = 2; i <= h - 1; i++) { printfChar(' ', h - i); printfChar('*', 1); printfChar(' ', w); printfChar('*', 1); printfChar(' ', h - i); printf("\n"); w += 2; } printfChar('*', w + 2); } int main() { freopen("labiec15", "r", stdin); scanf("%d", &h); solve(); return 0; }
C
UTF-8
585
3.578125
4
[]
no_license
#include<stdio.h> #include<stdlib.h> char * inputstring(); int main() { char *a; char ch; int num = 0, i; printf("Input the sentence : "); a = inputstring(); printf("result : "); printf("%s\n", a); return 0; } char * inputstring() { char *a, *temp; char c; int i, count = 0; while(1) { scanf("%c", &c); if(c == '\n') break; count++; temp = (char *)malloc(sizeof(char) * count); for(i = 0; i < count - 1; i++) { temp[i] = a[i]; } temp[count - 1] = c; a = (char *)malloc(sizeof(char) * count); a = temp; } a[count] = '\0'; return a; }
Markdown
UTF-8
5,958
2.640625
3
[]
no_license
# <img src="/res/xsdk-logo.png" width="128"> Draft document generated by the IDEAS xSDK project. We are actively soliciting suggestions from the community at https://xsdk.info/policies. # xSDK Community Installation Policies Version 0.5.0, June 27, 2019 [https://xsdk.info/policies](https://xsdk.info/policies) ## Background [What is software configuration?][1] and [How to configure software][2]. ## Motivation Combinations of multiple software packages developed by different groups have become essential for large-scale computational science, where the capabilities needed for modeling, simulation, and analysis are broader than any single team has resources to address. The often-tedious trial-and-error process of obtaining, configuring, and installing any single tool may arguably be manageable. From the perspective of an end-user application scientist, however, handling each tool’s installation idiosyncrasies can easily become overwhelming when dealing with several packages in combination. Worse, such problems are compounded by the need for consistency among packages to be used within the same application in terms of compiler, compiler version, exotic compiler optimization options, and common third-party packages such as BLAS and HDF5. ## Goal A key aspect of work in the [IDEAS software productivity project][3] is developing an Extreme-scale Scientific Software Development Kit ([xSDK](http://xsdk.info)). As an initial step in this work, our goal is to define and implement a standard subset<sup>1</sup> of configure and CMake<sup>2</sup> options for xSDK and other HPC packages in order to make the configuration and installation process as efficient as possible on standard Linux distributions and Mac OS, as well as on target machines at DOE computing facilities (ALCF, NERSC, OLCF). Note that we are not requiring that all packages use the same installation software, merely that they follow the same standard procedure with the same option names for installation. This approach provides maximum flexibility for each package to select the most suitable toolchain to use for its package. ## Impact Development of a standard xSDK package installation interface is a foundational step toward the seamless combined use of multiple xSDK libraries. The impact of this work is that all xSDK packages will have standard configuration and build instructions, as well as a tester to ensure that all functionality works properly. In addition, because new packages in the xSDK will follow the same standard, it is possible to make the installations "scriptable," that is, to write tools to install many packages automatically. This work is part of the [xSDK Community Package Policies][4]. ## xSDK Standard Configure and CMake Options<sup>3</sup> 1. [Implement the xSDK defaults option.](/installation_policies/1.md) 2. [Identify location to install package.](/installation_policies/2.md) 3. [Select compilers and compiler flags.](/installation_policies/3.md) 4. [Create libraries with debugging information and possible additional error checking.](/installation_policies/4.md) 5. [Select option used for indicating whether to build shared libraries.](/installation_policies/5.md) 6. [Build interface for a particular additional language.](/installation_policies/6.md) 7. [Determine precision for packages that build only for one precision. Packages that handle all precisions automatically are free to ignore this option.](/installation_policies/7.md) 8. [Determine index size for packages that build only for one index size. Packages that handle all precisions automatically are free to ignore this option.](/installation_policies/8.md) 9. [Set location of BLAS and LAPACK libraries.](/installation_policies/9.md) 10. [Determine other package libraries and include directories.](/installation_policies/10.md) 11. [In the XSDK mode, XSDK projects should not rely on users providing any library path information in environmental variables.](/installation_policies/11.md) 12. [Provide commands for compiling, installing, and "smoke" testing.](/installation_policies/12.md) 13. [Package should provide a machine-readable output to show provenance.](/installation_policies/13.md) For further discussion and examples of the xSDK standard Configure and CMake options see [discussions_and_examples.md](/installation_policies/discussion_and_examples.md). + Changes in version 0.5.0, June 27, 2019: + Changed installation policies 13 and 10 and examples in 10 ## Authors This document was prepared by Roscoe Bartlett, Jason Sarich, and Barry Smith, with key input from Todd Gamblin. We thank xSDK software developers and the IDEAS team for insightful discussion about issues and approaches. ## Acknowledgement This material is based upon work supported by the U.S. Department of Energy Office of Science, Advanced Scientific Computing Research and Biological and Environmental Research programs. ----- [//]: # "Main body footnotes" <sup>1</sup> Packages are free to support their own additional options, but using the standard options should be all that is needed to get correct builds. <sup>2</sup> A subset of these standard behaviors is implemented in the XSDKDefaults.cmake module and is demonstrated and tested in the CMake project https://github.com/bartlettroscoe/XSDKCMakeProj. <sup>3</sup> This standard is related only to arguments to CMake and GNU Autoconf; there is no requirement regarding the make system used (for example, that it be GNU make) nor that the make system accepts any particular arguments, such as `make LIBS+=-lz`. [//]: # "Links go here" [1]: https://ideas-productivity.org/wordpress/wp-content/uploads/2016/04/IDEAS-ConfigurationWhatIsSoftwareConfiguration-V0.2.pdf [2]: https://ideas-productivity.org/wordpress/wp-content/uploads/2016/12/IDEAS-ConfigurationHowToConfigureSoftware-V0.2.pdf [3]: http://www.ideas-productivity.org [4]: http://dx.doi.org/10.6084/m9.figshare.4495136
C++
UTF-8
879
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = (int)l; i <= (int)r; i++) const int MAXN = 1e5 + 5; int n; int arr[MAXN]; int main(){ cin>>n; fore(i,1,n){ cin>>arr[i]; } vector<int> res; bool flag = true; res.push_back(arr[1]); fore(i,2,n){ if (flag){ if (arr[i] <= res.back()) { res.pop_back(); res.push_back(arr[i]); } else{ res.push_back(arr[i]); flag = false; } } else{ if (arr[i] >= res.back()) { res.pop_back(); res.push_back(arr[i]); } else{ res.push_back(arr[i]); flag = true; } } } cout<<res.size()<<endl; }
PHP
UTF-8
2,551
2.90625
3
[]
no_license
<?php namespace Prokl\CollectionExtenderBundle\Services\Extenders; use Illuminate\Support\Arr; use Illuminate\Support\Collection; /** * Class Pick * @package Prokl\CollectionExtenderBundle\Extenders * Расширение Collections: pluck по нескольким полям. * * @since 16.09.2020 * @since 20.09.2020 Проверка на существование макроса. */ class Pick implements ExtenderCollectionInterface { /** * @inheritDoc */ public function registerMacro() : void { /** * Similar to pluck, with the exception that it can 'pluck' more than one column. * This method can be used on either Eloquent models or arrays. * * @param string|array $cols Set the columns to be selected. * @return Collection A new collection consisting of only the specified columns. */ if (Collection::hasMacro('pick')) { return; } Collection::macro('pick', // @phpstan-ignore-next-line function ($cols = ['*']) { $cols = is_array($cols) ? $cols : func_get_args(); /** @var Collection $obj */ $obj = clone $this; // Just return the entire collection if the asterisk is found. if (in_array('*', $cols, true)) { return $this; } return $obj->transform(static function ($value) use ($cols) : Collection { $ret = []; foreach ($cols as $col) { // This will enable us to treat the column as a if it is a // database query in order to rename our column. $name = $col; if (preg_match('/(.*) as (.*)/i', $col, $matches)) { $col = $matches[1]; $name = $matches[2]; } // If we use the asterisk then it will assign that as a key, // but that is almost certainly **not** what the user // intends to do. $name = str_replace('.*.', '.', $name); // We do it this way so that we can utilise the dot notation // to set and get the data. Arr::set($ret, $name, data_get($value, $col)); } return $ret; }); }); } }
Java
UTF-8
2,729
2.25
2
[]
no_license
package com.iamcure.ui.servlet; import java.io.IOException; import java.util.Calendar; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.iamcure.bo.listener.MedicalStoreListener; import com.iamcure.util.DateUtil; /** * Servlet implementation class MedicalStoreServelet */ public class MedicalStoreServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String Operation = null; /** * @see HttpServlet#HttpServlet() */ public MedicalStoreServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String u_ID=request.getParameter(""); String medicalstoreName=request.getParameter(""); String country=request.getParameter(""); String stateName=request.getParameter(""); String city=request.getParameter(""); String pinCode=request.getParameter(""); String streetName=request.getParameter(""); String phoneNumber=request.getParameter(""); String medicalStorePhoto=request.getParameter(""); String descripition=request.getParameter(""); String storeTimings=request.getParameter(""); String storeRating=request.getParameter(""); String storeReview=request.getParameter(""); String medicalPrescription=request.getParameter(""); String createdDate=request.getParameter(""); String lastModifiedDate=request.getParameter(""); String createdBy=request.getParameter(""); String lastModifiedBy=request.getParameter(""); String Operation=request.getParameter("operation"); if(streetName!=null && streetName.contains("^''''^")) streetName=streetName.replace("^''''^", "#"); if(medicalstoreName!=null && medicalstoreName.contains("^''''^")) medicalstoreName=medicalstoreName.replace("^''''^", "#"); Calendar createdDateCal=DateUtil.getCalFromDbFormatString(createdDate); MedicalStoreListener.createOrUpdateMedicalStore(u_ID, medicalstoreName, country, stateName, city, pinCode, streetName, phoneNumber, medicalStorePhoto, descripition, storeTimings, storeRating, storeReview, medicalPrescription, createdDate, lastModifiedDate, createdBy,lastModifiedBy , Operation); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
C
UTF-8
2,181
2.6875
3
[ "Unlicense" ]
permissive
/* DannyNiu/NJF, 2018-02-01. Public Domain. */ #include "rijndael.h" #include <x86intrin.h> #define NI_Define_AES_Cipher(name,Nr) \ void name(void const *in, void *out, \ void const *restrict w) \ { \ NI_Rijndael_Nb4_Cipher(in, out, w, Nr); \ } static void NI_Rijndael_Nb4_Cipher( uint8_t const in[16], uint8_t out[16], uint8_t const *restrict w, int Nr) { register __m128i state = _mm_loadu_si128((const void*)in), rk; rk = _mm_loadu_si128((const void*)(w)); state = _mm_xor_si128(state, rk); for(register int i=1; i<Nr; i++) { rk = _mm_loadu_si128((const void*)(w+i*16)); state = _mm_aesenc_si128(state, rk); } rk = _mm_loadu_si128((const void*)(w+Nr*16)); state = _mm_aesenclast_si128(state, rk); _mm_storeu_si128((void*)out, state); return; } #define NI_Define_AES_InvCipher(name,Nr) \ void name(void const *in, void *out, \ void const *restrict w) \ { \ NI_Rijndael_Nb4_InvCipher(in, out, w, Nr); \ } static void NI_Rijndael_Nb4_InvCipher( uint8_t const in[16], uint8_t out[16], uint8_t const *restrict w, int Nr) { register __m128i state = _mm_loadu_si128((const void*)in), rk; rk = _mm_loadu_si128((const void*)(w+Nr*16)); state = _mm_xor_si128(state, rk); for(register int i=Nr; --i>0; ) { rk = _mm_loadu_si128((const void*)(w+i*16)); rk = _mm_aesimc_si128(rk); state = _mm_aesdec_si128(state, rk); } rk = _mm_loadu_si128((const void*)(w)); state = _mm_aesdeclast_si128(state, rk); _mm_storeu_si128((void*)out, state); return; } /* Even though "Intel(R) Advanced Encryption Standard (AES) New Instruction Set" * by Shay Gueron, * - Intel Architecture Group, * - Isreal Development Center, * - Intel Corporation. * had sample key expansion code, it causes alignment warnings during compilation, * so I dropped it in favor of C-based version. */ #include "rijndael.c"
Swift
UTF-8
1,100
2.96875
3
[]
no_license
import SwiftUI struct MatchView: View { let teamShieldSize: CGFloat = 45.0 let xSymbolSize: CGFloat = 20.0 var match: Match! var body: some View { HStack() { HStack() { Text(match.homeTeam) .font(.system(size: 20.0)) Image(match.homeTeam) .resizable() .frame(width: teamShieldSize, height: teamShieldSize) } Spacer() Image("XSymbol") .resizable() .frame(width: xSymbolSize, height: xSymbolSize) Spacer() HStack() { Image(match.awayTeam) .resizable() .frame(width: teamShieldSize, height: teamShieldSize) Text(match.awayTeam) .font(.system(size: 20.0)) } } .padding(.horizontal, 25.0) .padding(.vertical, 20.0) } } struct MatchView_Previews: PreviewProvider { static var previews: some View { MatchView(match: matches[0]) } }
JavaScript
UTF-8
2,306
2.640625
3
[ "MIT" ]
permissive
const db = require( './database' ) const brcypt = require( 'bcrypt' ) const saltRounds = process.env.SALT const create = ( username, email, password ) => { bcrypt.hash( password, saltRounds ) .then( hash => { return db.query(` INSERT INTO member ( username, email, password ) VALUES ( $1, $2, $3 ) RETURNING * `, [ username, email, password ] ) }) .catch( error => { console.err({ message: 'Error occurred when creating member', arguments: arguments }) throw error }) } const isValidPassword = (id, password) => { return findById(id) .then( member => { return bcrypt.compare( password, member.password ) }) } const findById = id => { return db.oneOrNone( ` SELECT * FROM member WHERE id=$1`, [ id ] ) .catch( error => { console.err({ message: 'Error occurred when trying to find id', arguments: arguments }) throw error }) } const findByEmail = email => { return db.oneOrNone( ` SELECT * FROM member WHERE email=$1`, [ email ] ) .catch( error => { console.err({ message: 'Error occurred when trying to find email', arguments: arguments }) throw error }) } const findByUsername = username => { return db.oneOrNone( ` SELECT * FROM member WHERE username=$1`, [ username ] ) .catch( error => { console.err({ message: 'Error occurred when trying to find username', arguments: arguments }) throw error }) } const getUsername = id => { return db.oneOrNone( ` SELECT username FROM member WHERE id=$1`, [ id ] ) .catch( error => { console.err({ message: 'Error occurred when trying to find email', arguments: arguments }) throw error }) } const destroy = id => { return db.query( ` DELETE FROM member WHERE id=$1 RETURNING *`, [ id ] ) .catch( error => { console.err({ message: 'Error occurred when trying to find email', arguments: arguments }) throw error }) } module.exports = { create, isValidPassword, findById, findByEmail, findByUsername, getUsername, destroy }
Java
UTF-8
1,914
1.53125
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2016, The IKANOW Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.ikanow.aleph2.analytics.hadoop.utils; import org.apache.hadoop.mapreduce.InputFormat; import com.ikanow.aleph2.data_model.interfaces.data_analytics.IAnalyticsAccessContext; /** Collection of constants used in various Hadoop batch enrichment related places * @author Alex * */ public class HadoopBatchEnrichmentUtils { @SuppressWarnings("rawtypes") public static interface HadoopAccessContext extends IAnalyticsAccessContext<InputFormat> {} // Batch enrichment constants public static final String BATCH_SIZE_PARAM = "aleph2.batch.batchSize"; public static final String BE_CONTEXT_SIGNATURE = "aleph2.batch.beContextSignature"; //(one of context signature or bucket signature must be filled in) public static final String BE_BUCKET_SIGNATURE = "aleph2.batch.beBucketSignature"; //(one of context signature or bucket signature must be filled in) public static final String BE_BUCKET_INPUT_CONFIG = "aleph2.batch.inputConfig"; //(one of context signature or bucket signature must be filled in) public static final String BE_DEBUG_MAX_SIZE = "aleph2.batch.debugMaxSize"; }
PHP
UTF-8
750
2.828125
3
[]
no_license
<?php use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\PHPMailer; class MailSender { public static function sendMessage($email, $subject, $message) { $mail = new PHPMailer(true); try { //Server settings $mail->isSMTP(); $mail->Host = 'smtp.mailtrap.io'; $mail->SMTPAuth = true; $mail->Username = '8a9e12ba0abd65'; $mail->Password = '9d33a703a4a791'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; //Recipients $mail->setFrom('saganroman@example.com', 'WebDeveloper'); $mail->addAddress($email); // Content $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $message; $mail->send(); } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } } }
SQL
UTF-8
766
2.5625
3
[ "MIT" ]
permissive
create database glycol; use glycol; create table orderTable ( log_date char(10) not null, log_time char(8) not null, side varchar(4) not null, amount double not null, outstanding_size double not null, average_price int not null, child_order_acceptance_id varchar(32) not null, child_order_state varchar(10) not null, sold boolean not null ); create table collateral ( log_date char(10) not null, log_time char(8) not null, rest_position double not null, collateral int not null, open_position_pnl int not null, require_collateral int not null, keep_rate double not null ); create table log ( log_date char(10) not null, log_time char(8) not null, cost int not null, sell_rate int not null );
TypeScript
UTF-8
944
2.640625
3
[ "MIT" ]
permissive
interface FirestoreOptionsData { aiScoreMultiplier: number; animationDuration: number; hintLineWidth: number; hintRadius: number; hintTime: number; roundDuration: number; roundsNumber: number; } interface FirestoreImageData { clicks: { clickCount: number; x: number; y: number }[]; correctClicks: number; hintCount: number; wrongClicks: number; } type Month = | "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"; interface FirestoreScoreData { ai_score: number; correct_ai_answers: number; correct_player_answers: number; day: number; month: Month; score: number; usedHints: boolean; user: string; year: number; } interface ImageNumbersData { easy: number; easy_area: number; medium: number; medium_area: number; hard: number; hard_area: number; } interface AnnotationData { truth: number[]; predicted: number[]; }
Swift
UTF-8
1,237
2.9375
3
[ "MIT" ]
permissive
// // Constants.swift // RBTreeUI // // Created by LiLi Kazine on 2019/3/5. // Copyright © 2019 LiLi Kazine. All rights reserved. // import UIKit class Colors { static let red = hex2Color(hex: "cf3030")! static let red_light = hex2Color(hex: "f67280")! static let blue = hex2Color(hex: "35477d")! static let black = hex2Color(hex: "141414")! static let orange = hex2Color(hex: "e88a1a")! static let grey = hex2Color(hex: "d9d9d9")! static func hex2Color(hex val: String) -> UIColor? { if val.count != 6 { return nil } let vals: [String] = [val.substring(include: 0, nonclude: 2), val.substring(include: 2, nonclude: 4), val.substring(include: 4, nonclude: 6)] if let decR = UInt8(vals[0], radix: 16), let decG = UInt8(vals[1], radix: 16), let decB = UInt8(vals[2], radix: 16) { return UIColor(red: CGFloat(decR)/255.0, green: CGFloat(decG)/255.0, blue: CGFloat(decB)/255.0, alpha: 1.0) } else { return nil } } } extension String { func substring(include start: Int, nonclude end: Int) -> String { return String(self[String.Index(encodedOffset: start)..<String.Index(encodedOffset: end)]) } }
Java
UTF-8
186
2.15625
2
[]
no_license
package com.platzhaltr.util.date.result; import java.util.Date; /** * An event without the specification of a time. */ public interface Event { Date getStart(); Date getEnd(); }
Markdown
UTF-8
12,539
2.640625
3
[ "MIT" ]
permissive
--- title: skill description: categories: - skill tags: --- <!-- TOC --> - [1. skill系统](#1-skill%E7%B3%BB%E7%BB%9F) - [1.1. 指向性skill](#11-%E6%8C%87%E5%90%91%E6%80%A7skill) - [1.2. 范围性skill](#12-%E8%8C%83%E5%9B%B4%E6%80%A7skill) - [1.3. 无锁定skill](#13-%E6%97%A0%E9%94%81%E5%AE%9Askill) - [2. skill_effect](#2-skill_effect) - [3. buff系统](#3-buff%E7%B3%BB%E7%BB%9F) - [3.1. buff由一个或者多个buff_effect实现](#31-buff%E7%94%B1%E4%B8%80%E4%B8%AA%E6%88%96%E8%80%85%E5%A4%9A%E4%B8%AAbuff_effect%E5%AE%9E%E7%8E%B0) - [3.2. buff由枚举及参数 调用其他模块提供功能 例如 物品, 召唤系统](#32-buff%E7%94%B1%E6%9E%9A%E4%B8%BE%E5%8F%8A%E5%8F%82%E6%95%B0-%E8%B0%83%E7%94%A8%E5%85%B6%E4%BB%96%E6%A8%A1%E5%9D%97%E6%8F%90%E4%BE%9B%E5%8A%9F%E8%83%BD-%E4%BE%8B%E5%A6%82-%E7%89%A9%E5%93%81-%E5%8F%AC%E5%94%A4%E7%B3%BB%E7%BB%9F) - [3.3. buff参数构成](#33-buff%E5%8F%82%E6%95%B0%E6%9E%84%E6%88%90) - [4. buff_effect](#4-buff_effect) - [5. Operation](#5-operation) - [6. Buff](#6-buff) - [7. BuffEffect buff效果表,描述怎样调用operation 效果的生效对象,触发条件,是否生效判定(当释放者身上有某类buff或者拥有者身上有某类buff,生效概率等等),传给operation的参数](#7-buffeffect--buff%E6%95%88%E6%9E%9C%E8%A1%A8%E6%8F%8F%E8%BF%B0%E6%80%8E%E6%A0%B7%E8%B0%83%E7%94%A8operation--%E6%95%88%E6%9E%9C%E7%9A%84%E7%94%9F%E6%95%88%E5%AF%B9%E8%B1%A1%E8%A7%A6%E5%8F%91%E6%9D%A1%E4%BB%B6%E6%98%AF%E5%90%A6%E7%94%9F%E6%95%88%E5%88%A4%E5%AE%9A%E5%BD%93%E9%87%8A%E6%94%BE%E8%80%85%E8%BA%AB%E4%B8%8A%E6%9C%89%E6%9F%90%E7%B1%BBbuff%E6%88%96%E8%80%85%E6%8B%A5%E6%9C%89%E8%80%85%E8%BA%AB%E4%B8%8A%E6%9C%89%E6%9F%90%E7%B1%BBbuff%E7%94%9F%E6%95%88%E6%A6%82%E7%8E%87%E7%AD%89%E7%AD%89%E4%BC%A0%E7%BB%99operation%E7%9A%84%E5%8F%82%E6%95%B0) - [8. 案例](#8-%E6%A1%88%E4%BE%8B) <!-- /TOC --> # 1. skill系统 <a id="markdown-skill%E7%B3%BB%E7%BB%9F" name="skill%E7%B3%BB%E7%BB%9F"></a> ## 1.1. 指向性skill <a id="markdown-%E6%8C%87%E5%90%91%E6%80%A7skill" name="%E6%8C%87%E5%90%91%E6%80%A7skill"></a> ## 1.2. 范围性skill <a id="markdown-%E8%8C%83%E5%9B%B4%E6%80%A7skill" name="%E8%8C%83%E5%9B%B4%E6%80%A7skill"></a> ## 1.3. 无锁定skill <a id="markdown-%E6%97%A0%E9%94%81%E5%AE%9Askill" name="%E6%97%A0%E9%94%81%E5%AE%9Askill"></a> ``` skill系统由多个skill_effect 配合条件与节奏控制实现 ``` # 2. skill_effect <a id="markdown-skill_effect" name="skill_effect"></a> ``` 职责 ``` # 3. buff系统 <a id="markdown-buff%E7%B3%BB%E7%BB%9F" name="buff%E7%B3%BB%E7%BB%9F"></a> ## 3.1. buff由一个或者多个buff_effect实现 <a id="markdown-buff%E7%94%B1%E4%B8%80%E4%B8%AA%E6%88%96%E8%80%85%E5%A4%9A%E4%B8%AAbuff_effect%E5%AE%9E%E7%8E%B0" name="buff%E7%94%B1%E4%B8%80%E4%B8%AA%E6%88%96%E8%80%85%E5%A4%9A%E4%B8%AAbuff_effect%E5%AE%9E%E7%8E%B0"></a> ## 3.2. buff由枚举及参数 调用其他模块提供功能 例如 物品, 召唤系统 <a id="markdown-buff%E7%94%B1%E6%9E%9A%E4%B8%BE%E5%8F%8A%E5%8F%82%E6%95%B0-%E8%B0%83%E7%94%A8%E5%85%B6%E4%BB%96%E6%A8%A1%E5%9D%97%E6%8F%90%E4%BE%9B%E5%8A%9F%E8%83%BD-%E4%BE%8B%E5%A6%82-%E7%89%A9%E5%93%81%2C-%E5%8F%AC%E5%94%A4%E7%B3%BB%E7%BB%9F" name="buff%E7%94%B1%E6%9E%9A%E4%B8%BE%E5%8F%8A%E5%8F%82%E6%95%B0-%E8%B0%83%E7%94%A8%E5%85%B6%E4%BB%96%E6%A8%A1%E5%9D%97%E6%8F%90%E4%BE%9B%E5%8A%9F%E8%83%BD-%E4%BE%8B%E5%A6%82-%E7%89%A9%E5%93%81%2C-%E5%8F%AC%E5%94%A4%E7%B3%BB%E7%BB%9F"></a> ## 3.3. buff参数构成 <a id="markdown-buff%E5%8F%82%E6%95%B0%E6%9E%84%E6%88%90" name="buff%E5%8F%82%E6%95%B0%E6%9E%84%E6%88%90"></a> # 4. buff_effect <a id="markdown-buff_effect" name="buff_effect"></a> ``` buff_effect分为三类 控制类, 增益类, 减益类, 其他 ``` # 5. Operation <a id="markdown-operation" name="operation"></a> 原子操作,技能,buff都可以调用,每个操作传入参数的意义不同 操作方式:增加,减少,直接修改,按百分比,按数值 添加buff,参数是buff模板id,buff持续时间,层数 增减hp,mp等等 添加某个状态,在buff消失时要移除该状态 临时增加或者减少某个属性 根据属性枚举,可以修改任何属性 驱散buff 驱散方式传入参数 按大类,按小类,按id等 召唤陷阱,怪物等等 使技能进入cd 取消技能cd 打断技能释放 等等 状态 存储时按位: 束缚 沉默 昏迷 昏睡 位移过程中 必然闪避 必然暴击 必然命中 等等 免疫 免疫控制 在添加控制类buff时判定 免疫debuff 添加debuff时判定 免疫减速 免疫物理攻击 免疫魔法攻击 等等 # 6. Buff <a id="markdown-buff" name="buff"></a> BuffTemplate表 buff基础信息,大类,小类,最大层数,持续时间,触发次数,跳场景是否保留,下线是否保留,死亡是否保留,是否可以被手动移除等等 分类: 增益类 减益类 控制类 每个大类再分小类 # 7. BuffEffect buff效果表,描述怎样调用operation 效果的生效对象,触发条件,是否生效判定(当释放者身上有某类buff或者拥有者身上有某类buff,生效概率等等),传给operation的参数 <a id="markdown-buffeffect--buff%E6%95%88%E6%9E%9C%E8%A1%A8%EF%BC%8C%E6%8F%8F%E8%BF%B0%E6%80%8E%E6%A0%B7%E8%B0%83%E7%94%A8operation--%E6%95%88%E6%9E%9C%E7%9A%84%E7%94%9F%E6%95%88%E5%AF%B9%E8%B1%A1%EF%BC%8C%E8%A7%A6%E5%8F%91%E6%9D%A1%E4%BB%B6%EF%BC%8C%E6%98%AF%E5%90%A6%E7%94%9F%E6%95%88%E5%88%A4%E5%AE%9A%EF%BC%88%E5%BD%93%E9%87%8A%E6%94%BE%E8%80%85%E8%BA%AB%E4%B8%8A%E6%9C%89%E6%9F%90%E7%B1%BBbuff%E6%88%96%E8%80%85%E6%8B%A5%E6%9C%89%E8%80%85%E8%BA%AB%E4%B8%8A%E6%9C%89%E6%9F%90%E7%B1%BBbuff%EF%BC%8C%E7%94%9F%E6%95%88%E6%A6%82%E7%8E%87%E7%AD%89%E7%AD%89%EF%BC%89%EF%BC%8C%E4%BC%A0%E7%BB%99operation%E7%9A%84%E5%8F%82%E6%95%B0" name="buffeffect--buff%E6%95%88%E6%9E%9C%E8%A1%A8%EF%BC%8C%E6%8F%8F%E8%BF%B0%E6%80%8E%E6%A0%B7%E8%B0%83%E7%94%A8operation--%E6%95%88%E6%9E%9C%E7%9A%84%E7%94%9F%E6%95%88%E5%AF%B9%E8%B1%A1%EF%BC%8C%E8%A7%A6%E5%8F%91%E6%9D%A1%E4%BB%B6%EF%BC%8C%E6%98%AF%E5%90%A6%E7%94%9F%E6%95%88%E5%88%A4%E5%AE%9A%EF%BC%88%E5%BD%93%E9%87%8A%E6%94%BE%E8%80%85%E8%BA%AB%E4%B8%8A%E6%9C%89%E6%9F%90%E7%B1%BBbuff%E6%88%96%E8%80%85%E6%8B%A5%E6%9C%89%E8%80%85%E8%BA%AB%E4%B8%8A%E6%9C%89%E6%9F%90%E7%B1%BBbuff%EF%BC%8C%E7%94%9F%E6%95%88%E6%A6%82%E7%8E%87%E7%AD%89%E7%AD%89%EF%BC%89%EF%BC%8C%E4%BC%A0%E7%BB%99operation%E7%9A%84%E5%8F%82%E6%95%B0"></a> 效果调用时机: 开始生效 周期性生效 结束时生效 时间耗尽 死亡 被驱散 触发次数消耗尽 手动取消 无条件(只要结束就生效) 根据结束方式判断是否生效 触发生效 有条件触发(当血量低于多少百分比时触发等),无条件触发(被控制时触发等) 层数叠满时生效 效果生效对象: Buff拥有者,buff释放者,效果触发者或者aoe方法pick到的对象 Buff可以直接调用伤害公式进行伤害,跟技能一样,在buff产生时会初始化buff释放者的伤害计算相关数据 Buff添加 判断免疫 判断层数 Buff替换规则,高等级替换低等级,多buff共存等等 调用开始时生效的效果 添加buff触发生效条件,在程序各处添加触发接口,使用技能时触发,被控制时触发,收到伤害时触发,使用某个技能时触发(带参数 技能id)等等 Buff update 调用buff周期生效效果 buff被触发 调用触发effect,根据配置决定对buff释放者,buff拥有者或者buff触发者使用效果 Buff 结束 调用结束生效效果,根据buff结束方式调用对应的生效效果,结束方式有:时间耗尽结束,触发次数被耗尽,被驱散,玩家主动点击取消 等 Skill Skillconfig表通用信息 主动技能,被动技能(由buff实现) 触发类技能,在自身或者选中对象在某种状态下时可以释放的主动技能 吟唱 void OnSkillIntonate(const CS_SKILL_INTONATE_REQ* pData); 技能吟唱使用的动作,吟唱时间,显示的文字,都可以配置,配置在Intonate表中 状态判断,技能在某些状态下才可以释放或者在某些状态下不能释放 释放者,目标都需要判断 释放消耗判断 释放距离 释放对象判断 敌军,友军等 释放位置合法性等 开始吟唱时需要判断此时是否有其他效果需要调用 比如给自己加个buff 特殊处理 瞬发技能不需要吟唱直接释放 在吟唱完成准备释放时,大部分条件都需要再判断一次 比如技能,状态限制,敌对关系等可能发生变化的条件 地图传送技能,直接打断当前技能,然后执行传送技能 使用物品的技能,某些物品直接出效果,避免战斗过程中无法使用物品,物品走自己的cd,不走技能cd,某些带使用动作的物品,物品自己决定使用哪个Intonateid的效果 释放技能 扣除消耗 开始施法时判断是否有效果调用,跟开始吟唱时一样 通知客户端开始释放技能 如果该技能有主动位移,在开始释放包内带上计算好的终点给到客户端,并启动定时器,强制设定客户端位置。每个hit点都可能会有位移,如果开始位置一致,后面客户端和服务端计算得到的位置肯定一致,所以客户端可以先行计算,但是最终位置服务端将会判断 开始计算hit点 一个技能可能存在多个hit点 在每个hit点都可以计算伤害和效果 void OnSkillHit(const CS_SKILL_HIT_REQ* pData); hit点时间到时,客户端拾取目标发送到服务端,并且先表现受击动画和受击特效,服务端进行伤害计算,效果计算,如果该技能需要服务端拾取,则服务端会自己拾取攻击目标并进行伤害计算和效果计算 每个hit点的伤害计算方式由damage表决定,效果则由skilleffect表决定,每个hit点可以不一样 拾取目标的方式由pick表决定 延迟伤害,先下发,客户端攻击到后通知服务端扣血,服务端也会设一个最大延迟时间 位移技能 1 无吟唱直接位移,客户端先行,计算出终点位置,服务端检验,不通过直接强拉 2 吟唱后位移,等服务端下发终点位置 对于有吟唱的技能,服务器可以完全控制技能的节奏 对于没有吟唱的技能,因为是客户端先行,服务器无法控制节奏,因为会出现网络波动 释放技能的消息和hit点消息可能同时到来。也可以改成服务端计算hit直接下发的方式 增加正在释放技能状态 此状态下,无法移动,无法释放其他技能 结束技能 可以提前结束 void CBattleSkill::OnSkillStop(const CS_SKILL_STOP_REQ* pData) 或者服务端的总时间到了,也会自动结束 # 8. 案例 <a id="markdown-%E6%A1%88%E4%BE%8B" name="%E6%A1%88%E4%BE%8B"></a> 以技能北斗七星阵为例 北斗是由天枢、天璇、天玑、天权、玉衡、开阳、瑶光七星组成 范围型技能 创建北斗七星对象及一个阵法对象 瑶光, 开阳, 对范围内敌人 造成三次 40%法术伤害 命中对象 降低50点怒气 基础伤害功能+基础debuff功能 玉衡, 天权, 对范围内敌人 造成三次 40%物理伤害 恢复所造成伤害300% 基础伤害功能+脚本追加功能 天玑, 天璇, 天枢 对范围内敌人 造成一次 120%法术伤害 基础伤害功能 并为范围内己方添加 时光回溯 状态 持续3秒. 该状态记录当前生命值及怒气值 基础buff功能+脚本追加功能 如果当前不处于禁疗状态, 若己方血量低于记录值的60% 则恢复至60%, 高于则不变化 基础buff功能+脚本条件判断功能+脚本追加功能 如果当前不处于禁怒状态, 那么己方怒气低于记录值的40% 则恢复至40%, 高于则不变化 基础buff功能+脚本条件判断功能+脚本追加功能 北斗七星阵法对象 对范围内敌人 造成3次 50%法术伤害 并额外造成当前生命20%的伤害. 最大值为法攻(200%). 基础伤害功能+脚本追加功能 免疫中断 基础buff功能
Ruby
UTF-8
1,733
4.4375
4
[]
no_license
#sets the people variable to 30 people = 30 #sets the cars variable to 40 cars = 40 #sets the trucks variable to 15 trucks = 15 #If cars are greater than people print a statement if cars > people #The statement that would printed if the conditions are right puts "We should take the cars." # if the above statement is false then check if cars is less than people elsif cars < people #Prints a string puts "We should not take the cars." #If nether of the statements above are true do the following else #print a string puts "We can't decide." #Ends the block of if statements end #If a trucks are greater than cars then print a string if trucks > cars #prints a string puts "That's too many trucks." #If the above statement is false than check if trucks are less then cars then print a string elsif trucks < cars #prints a string puts "Maybe we could take the trucks." #If neither of the statements are true then print a string else #prints a string puts "We still can't decide." #Ends the if else block end #If people is greater than trucks than print a string if people > trucks #prints a string puts "Alright, let's just take the trucks." #If the above condition is false then print the following string else #prints a string puts "Fine, let's stay home then." #Ends the if else block end #if cars is greater than trucks and if people are greater than trucks print a string if cars > trucks && people > trucks #prints a string puts "We should sell the trucks" #If the above statement is false then check if trucks are greater than cars && people are greater than cars print a string elsif trucks > cars && people > cars #prints a string puts "We should sell the cars" end
C++
UTF-8
6,889
3.15625
3
[]
no_license
#include <algorithm> #include <cstdint> #include <fstream> #include <iostream> #include <unordered_map> #include <utility> enum class PositionState { INVALID, FLOOR, AVAILABLE, OCCUPIED, }; class Coord { int16_t x; int16_t y; public: Coord(int16_t x, int16_t y) noexcept : x{x}, y{y} {} [[nodiscard]] int16_t X() const noexcept { return x; } [[nodiscard]] int16_t Y() const noexcept { return y; } bool operator==(const Coord& rhs) const noexcept { return x == rhs.x && y == rhs.y; } struct Hash { auto operator()(const Coord& coord) const noexcept { return std::hash<int32_t>{}((static_cast<int32_t>(coord.x) << 16) | coord.y); } }; }; class SpaceArrangement { std::unordered_map<Coord, PositionState, Coord::Hash> positions; int16_t xMax; int16_t yMax; template <class Predicate> [[nodiscard]] uint8_t IsInState(int16_t x, int16_t y, Predicate& pred) const noexcept { auto pos = positions.find(Coord{x, y}); return pred(pos == positions.end() ? PositionState::INVALID : pos->second) ? 1 : 0; } [[nodiscard]] auto RaycastToChair(int16_t x, int16_t y, int16_t xDiff, int16_t yDiff, int16_t xLimit, int16_t yLimit) const noexcept { while (x != xLimit && y != yLimit) { x += xDiff; y += yDiff; if (auto pos = positions.find(Coord{x, y}); pos != positions.end()) return pos; } return positions.end(); } template <class Predicate> [[nodiscard]] bool CountRaycastsInState(int16_t x, int16_t y, int8_t target, Predicate&& pred) const noexcept { auto count = 0; std::initializer_list<std::tuple<int16_t, int16_t, int16_t, int16_t>> consider = {{0, -1, -1, 0}, // up {0, 1, -1, yMax}, // down {-1, 0, 0, -1}, // left {1, 0, xMax, -1}, // right {-1, -1, 0, 0}, // up&left {1, -1, xMax, 0}, // up&right {-1, 1, 0, yMax}, // down&left {1, 1, xMax, yMax}, // down&right }; for (auto& [xdt, ydt, xLim, yLim] : consider) { auto pos = RaycastToChair(x, y, xdt, ydt, xLim, yLim); count += pred(pos == positions.end() ? PositionState::INVALID : pos->second) ? 1 : 0; if (count == target) return true; } return false; } template <class Predicate> [[nodiscard]] bool CountNeighboursInState(int16_t x, int16_t y, int8_t target, Predicate&& pred) const noexcept { std::initializer_list<std::pair<int16_t, int16_t>> consider = {{x, y - 1}, {x, y + 1}, {x - 1, y}, {x + 1, y}, {x - 1, y - 1}, {x + 1, y - 1}, {x - 1, y + 1}, {x + 1, y + 1}}; auto count = 0; for (auto& [x, y] : consider) { count += IsInState(x, y, pred); if (count == target) return true; } return false; } [[nodiscard]] bool AllUnoccupied(int16_t x, int16_t y, bool raycast) const noexcept { constexpr auto pred = [] (auto state) { return state != PositionState::OCCUPIED; }; return raycast ? CountRaycastsInState(x, y, 8, pred) : CountNeighboursInState(x, y, 8, pred); } [[nodiscard]] bool ShouldBecomeEmpty(const auto& kvp, bool raycast, int8_t target) const noexcept { auto& [coord, state] = kvp; constexpr auto pred = [] (auto state) { return state == PositionState::OCCUPIED; }; return state == PositionState::OCCUPIED && (raycast ? CountRaycastsInState(coord.X(), coord.Y(), target, pred) : CountNeighboursInState(coord.X(), coord.Y(), target, pred)); } [[nodiscard]] bool ShouldBecomeOccupied(const auto& kvp, bool raycast) const noexcept { auto& [coord, state] = kvp; return state == PositionState::AVAILABLE && AllUnoccupied(coord.X(), coord.Y(), raycast); } [[nodiscard]] std::pair<decltype(positions), bool> Simulate(bool raycast) { auto newPositions = positions; auto changed = false; for (auto& kvp : positions) { auto& [coord, state] = kvp; if (ShouldBecomeOccupied(kvp, raycast)) { newPositions[coord] = PositionState::OCCUPIED; changed = true; } else if (ShouldBecomeEmpty(kvp, raycast, raycast ? 5 : 4)) { newPositions[coord] = PositionState::AVAILABLE; changed = true; } } return {std::move(newPositions), changed}; } public: explicit SpaceArrangement(std::istream& in) { char c; int16_t x = 0, y = 0; while (c = in.get(), in) { if (c == 'L') positions.emplace(Coord{x++, y}, PositionState::AVAILABLE); else if (c == '\n') x = 0, ++y; else ++x; } yMax = y; xMax = x - 1; } [[nodiscard]] int16_t SolvePart(bool isPart1) { auto savedState = positions; while (true) { auto&& [newPos, changed] = Simulate(isPart1); if (!changed) break; positions = std::move(newPos); } auto ret = std::ranges::count_if(positions, [] (auto& pos) { return pos.second == PositionState::OCCUPIED; }); positions = std::move(savedState); return ret; } }; int main(int argc, const char* argv[]) { if (argc != 2) return 1; std::ifstream file{argv[1]}; SpaceArrangement arrangement{file}; std::cout << arrangement.SolvePart(false) << '\n'; std::cout << arrangement.SolvePart(true) << '\n'; }
JavaScript
UTF-8
827
4.84375
5
[]
no_license
/* Acccessing array[-1] In some programming languages, we can access array elements using negative indexes, counted from the end. Like this: let array = [1, 2, 3]; array[-1]; // 3, the last element array[-2]; // 2, one step from the end array[-3]; // 1, two steps from the end In other words, array[-N] is the same as array[array.length - N]. Create a proxy to implement that behavior. That’s how it should work: */ let array = [1, 2, 3]; array = new Proxy(array, { get(target, prop, receiver) { let numericProp = Number(prop); if (numericProp < 0) { numericProp = numericProp + target.length; } return Reflect.get(target, numericProp, receiver); } }); console.log(array[2]) console.log( array[-1] ); // 3 console.log( array[-2] ); // 2 // Other array functionality should be kept "as is"
Python
UTF-8
1,016
2.578125
3
[ "MIT" ]
permissive
from sklearn.metrics import mean_squared_error from scipy.stats.stats import pearsonr from copy import copy def ForwardPropFeatureImp(model, X_true, Y_true, mp): ''' Leave one feature out importance ''' try: df_grid = mp.df_grid except: H_grid = mp.plot_grid() df_grid = mp.df_grid df_grid = df_grid.sort_values(['y', 'x']).reset_index(drop=True) Y = model.predict(X_true) mse = mean_squared_error(Y_true, Y) N, W, H, C = X_true.shape results = [] for i in tqdm(range(len(df_grid)), ascii= True): ts = df_grid.iloc[i] y = ts.y x = ts.x X1 = copy(X_true) X1[:, y, x,:] = np.zeros(X1[:, y, x,:].shape) Y1 = model.predict(X1) mse_mutaion = mean_squared_error(Y_true, Y1) res = mse_mutaion - mse # if res > 0, important, othervise, not important results.append(res) S = pd.Series(results, name = 'importance') df = df_grid.join(S) return df
Python
UTF-8
837
3.515625
4
[]
no_license
# coding: utf8 # 两个单链表生成相加链表 class Node(object): def __init__(self,data,_next = None): self.data = data self._next = _next def addList(head1,head2): s1 = [] s2 = [] while head1: s1.append(head1.data) head1 = head1._next while head2: s2.append(head2.data) head2 = head2._next ca = 0 n1 = 0 n2 = 0 n = 0 node = None pre = None while s1 or s1 : n1 = s1.pop() if s1 else 0 n2 = s2.pop() if s2 else 0 n = n1 + n2 + ca pre = node node = Node(n%10) node._next = pre ca = n/10 if ca == 1: pre = node node = Node(1) node._next = pre return node head1 = Node(9,Node(3,Node(7))) head2 = Node(6,Node(3)) a = addList(head1,head2) print a
Python
UTF-8
269
2.65625
3
[ "MIT" ]
permissive
import importlib import unittest solver = importlib.import_module('2020_17_2') class Test2020Day17Part2(unittest.TestCase): def test_example1(self): input = ( '.#.\n' '..#\n' '###\n' ) self.assertEqual(solver.solve(input), 848)
Markdown
UTF-8
949
2.6875
3
[]
no_license
## Project List: ### 1. hs-dbms: Housing Society - Database Management System #### About this project: An application that provides a GUI to access a database. In this particular application, the database is a Housing Society Database Management System (HSDbMS). #### Libraries used: Swing, AWT for the GUI and MySQL for the database alongwith it's java connectors. ### 2. hs-dbms-testing: Housing Society - Database Management System [A testing project] #### About this project: Programs written to test the hsdbms project. ### Libraries used: JUnit. ### 3. med-exp-system: Medical Expert System #### About this project: An AI project that implements a basic Medical Expert System. ### 4. diffie-hellman: Diffie-Hellman Key Exchange #### About this project: This project implements the Diffie-Hellman key exchange in Java. ### 5. school-assignments: #### About this collection: This is a collection of my assignments from school.
Java
UTF-8
1,963
2.421875
2
[ "Apache-2.0" ]
permissive
package com.andreas.main.stages.themeSelectorStage; import java.io.File; import com.andreas.main.App; import com.andreas.main.FileUtils; import com.andreas.main.app.AppController; import com.andreas.main.stages.StageUtils; import org.jdom2.Element; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.stage.FileChooser; public class ThemeSelectorController extends AppController { @FXML public ComboBox<String> themeSelector; @Override public void init() { FileUtils.forEachFile("data/themes", path -> { themeSelector.getItems().add(path.getFileName().toString()); }); Element root = FileUtils.readXmlFile("data/data.xml"); themeSelector.getEditor().setText(root.getChildText("theme")); } @FXML private void importTheme() { FileChooser fc = new FileChooser(); File file = fc.showOpenDialog(null); String suffix = FileUtils.splitPrefixAndSuffix(file.getName())[1]; if (!suffix.toLowerCase().equals(".css")){ StageUtils.pushNotification("Theme must be a .css file!"); return; } FileUtils.copyFile(file.getAbsolutePath(), "data/themes"); getScene().getStage().stop(); } @FXML private void applyTheme() { setTheme(themeSelector.getSelectionModel().getSelectedItem()); getScene().getStage().stop(); } private void setTheme(String name) { Element root = FileUtils.readXmlFile("data/data.xml"); Element theme = root.getChild("theme"); if (theme == null) { theme = new Element("theme"); root.getChildren().add(theme); } theme.setText(name); App.stages.forEach(stage -> { stage.applyStylesheet(name); }); FileUtils.createXmlFile("data/data.xml", root); } @FXML private void cancel() { getScene().getStage().stop(); } }
C#
UTF-8
2,343
3.203125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MahjongApp { class Game { private Field Field; private Tuple<int, int> DicePointer; private Tuple<int, int> ChosenDices; public Game(Field field) => Field = field; public Game(int length, int width, int count) { Field = new Field(length, width); Field.FillField(count); } private bool Takely(Tuple<int, int> coordinate) => Field[coordinate].Count != 0 && (Field.Extreme(coordinate) || Field.Higher(coordinate)); public void PressKey(Keys key) { switch (key) { case Keys.Down: MoveDicePointer(0, -1); break; case Keys.Up: MoveDicePointer(0, 1); break; case Keys.Left: MoveDicePointer(-1, 0); break; case Keys.Right: MoveDicePointer(1, 0); break; case Keys.Enter: ChooseDice(); break; } } private void MoveDicePointer(int dx, int dy) => DicePointer = Tuple.Create( SumMod(DicePointer.Item1, dx, Field.Length), SumMod(DicePointer.Item2, dy, Field.Width)); private int SumMod(int x, int y, int mod) => (x + y + mod) % mod; private void DeleteDices() { Field.Delete(DicePointer); Field.Delete(ChosenDice.Item2); ChosenDice = null; if (Field.PairCount == 0) Console.WriteLine("Game Over, You Win"); } private void ChooseDice() { if (Takely(DicePointer)) if (ChosenDice.Item1) { if (ChosenDice == DicePointer) ChosenDice = null; else if (Field[ChosenDice].Peek().Equals(Field[DicePointer].Peec())) DeleteDices(); else ChosenDice = null; } else ChosenDice = DicePointer; } } }
Markdown
UTF-8
3,592
2.890625
3
[ "Apache-2.0" ]
permissive
--- title: Built-in Functions --- ## panic # ```cadence fun panic(_ message: String): Never ``` Terminates the program unconditionally and reports a message which explains why the unrecoverable error occurred. ```cadence let optionalAccount: AuthAccount? = // ... let account = optionalAccount ?? panic("missing account") ``` ## assert ```cadence fun assert(_ condition: Bool, message: String) ``` Terminates the program if the given condition is false, and reports a message which explains how the condition is false. Use this function for internal sanity checks. The message argument is optional. ## unsafeRandom ```cadence fun unsafeRandom(): UInt64 ``` Returns a pseudo-random number. NOTE: Smart contract developers should be mindful about the limitations of unsafeRandom. The stream of random numbers produced is potentially unsafe in the following two regards: 1. The sequence of random numbers is potentially predictable by transactions within the same block and by other smart contracts calling into your smart contract. 2. A transaction calling into your smart contract can potentially bias the sequence of random numbers which your smart contract internally generates. We are working towards removing these limitations incrementally. Once these points are addressed, Flow’s randomness is safe and we will remove the "unsafe" qualifier. Nevertheless, there is an additional safety-relevant aspect that developers need to be mindful about: * A transaction can atomically revert all its action at any time. Therefore, it is possible for a transaction calling into your smart contract to post-select favourable results and revert the transaction for unfavourable results. ([example](https://consensys.github.io/smart-contract-best-practices/development-recommendations/general/public-data/)) This limitation is inherent to any smart contract platform that allows transactions to roll back atomically and cannot be solved through safe randomness alone. Providing additional Cadence language primitives to simplify this challenge for developers is on our roadmap as well. Nevertheless, with safe randomness (points 1 and 2 above resolved), developers can prevent clients from post-select favourable outcomes using approaches such as described in the [example](https://consensys.github.io/smart-contract-best-practices/development-recommendations/general/public-data/). ## RLP RLP (Recursive Length Prefix) serialization allows the encoding of arbitrarily nested arrays of binary data. Cadence provides RLP decoding functions in the built-in `RLP` contract, which does not need to be imported. - ```cadence fun decodeString(_ input: [UInt8]): [UInt8] ``` Decodes an RLP-encoded byte array (called string in the context of RLP). The byte array should only contain of a single encoded value for a string; if the encoded value type does not match, or it has trailing unnecessary bytes, the program aborts. If any error is encountered while decoding, the program aborts. ```cadence fun decodeList(_ input: [UInt8]): [[UInt8]]` ``` Decodes an RLP-encoded list into an array of RLP-encoded items. Note that this function does not recursively decode, so each element of the resulting array is RLP-encoded data. The byte array should only contain of a single encoded value for a list; if the encoded value type does not match, or it has trailing unnecessary bytes, the program aborts. If any error is encountered while decoding, the program aborts.
C#
UTF-8
794
3.078125
3
[]
no_license
public static BaseTypeFactory { public enum Types { DerType1, DerType2, DerType3 } public static BaseType CreateInstance(Types type) { switch(type) { case Types.DerType1: return (BaseType) Activator. CreateInstance(Type.GetType("DerType1")); case Types.DerType2: return (BaseType) Activator. CreateInstance(Type.GetType("DerType2")); case Types.DerType3: return (BaseType) Activator. CreateInstance(Type.GetType("DerType3")); default: thrown new ArgumentException("Invalid Type specified"); } } }
Java
UTF-8
1,023
2.546875
3
[]
no_license
/* * Author: Wing Cheang Mok * Student Number: s3697904 * Course: ISYS1118 Software Engineering Fundamentals * Assignment: Supermarket Support System */ package consoleMenu; import java.sql.SQLException; import org.junit.After; import org.junit.Before; import org.junit.Test; import data.DatabaseManager; import model.IntegerException; import store.LoginManager; public class ConsoleMenuTest { private ConsoleMenu menu; private LoginManager loginManager; private DatabaseManager dbManager; @Before public void setUp() throws IntegerException{ menu = new ConsoleMenu(); dbManager = new DatabaseManager(); loginManager = new LoginManager(dbManager.getEmployees(), dbManager.getCustomers()); } /** * Warehouse Staff - Replenish Stock * Manager - Set Promotion * Manager - Set Discount (Bulk) */ @Test (expected = IntegerException.class) public void negativeQuantity() throws IntegerException, SQLException{ menu.printMenu(); } @After public void tearDownClass() throws Exception{ } }
Python
UTF-8
6,179
3.171875
3
[]
no_license
""" XTEA Block Encryption Algorithm Original Code: http://code.activestate.com/recipes/496737/ Algorithm: http://www.cix.co.uk/~klockstone/xtea.pdf >>> import os >>> x = xtea.xtea() >>> iv = 'ABCDEFGH' >>> z = x.crypt('0123456789012345','Hello There',iv) >>> z.encode('hex') 'fe196d0a40d6c222b9eff3' >>> x.crypt('0123456789012345',z,iv) 'Hello There' Modified to use CBC - Steve K: >>> import xtea >>> x = xtea.xtea() >>> #set up your key and IV then... >>> x.xtea_cbc_decrypt(key, iv, data, n=32, endian="!") """ import struct TEA_BLOCK_SIZE = 8 TEA_KEY_SIZE = 16 def xtea_encrypt(key, block, n=64, endian="!"): """ Encrypt 64 bit data block using XTEA block cypher * key = 128 bit (16 char) * block = 64 bit (8 char) * n = rounds (default 32) #changed to 64 * endian = byte order (see 'struct' doc - default big/network) >>> z = xtea_encrypt('0123456789012345','ABCDEFGH') >>> z.encode('hex') 'b67c01662ff6964a' Only need to change byte order if sending/receiving from alternative endian implementation >>> z = xtea_encrypt('0123456789012345','ABCDEFGH',endian="<") >>> z.encode('hex') 'ea0c3d7c1c22557f' """ v0, v1 = struct.unpack(endian + "2L", block) # print ("v0 and v1 are " + str(v0) + " " + str(v1)) # print ("Key is " + key) # key = b'key' k = struct.unpack(endian + "4L", key) sum, delta, mask = 0, 0x9e3779b9, 0xffffffff # removed trailing L from all values for round in range(n): v0 = (v0 + (((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + k[sum & 3]))) & mask sum = (sum + delta) & mask v1 = (v1 + (((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + k[sum >> 11 & 3]))) & mask return struct.pack(endian + "2L", v0, v1) def crypt(key, data, iv='\00\00\00\00\00\00\00\00', n=32): """ Encrypt/decrypt variable length string using XTEA cypher as key generator (OFB mode) * key = 128 bit (16 char) * iv = 64 bit (8 char) * data = string (any length) >>> import os >>> key = os.urandom(16) >>> iv = os.urandom(8) >>> data = os.urandom(10000) >>> z = crypt(key,data,iv) >>> crypt(key,z,iv) == data True """ def keygen(key, iv, n): """ encrypt the key and create a generator for all 8 bit blocks in the 64 bit block of the encrypted key """ while True: # encrypt 64 bit block # encrypt the key with initialization vector # use the partially(64bit) encrypted key as initialization vector # for the next block after the first iteration of the while loop iv = xtea_encrypt(key, iv, n) # for 8 bit in 64 bit for k in iv: yield ord(k) # map - get list of ordinals for all chars in data # keygen - create a generator(8 bit steps) of the encrypted key # zip - crate tuples for a char(8bit) and 8bit of the key # x^y xor the created tuples and cast them to 8 bit xor = [chr(x ^ y) for (x, y) in zip(list(map(ord, data)), keygen(key, iv, n))] return "".join(xor) def xtea_decrypt(key, block, n=32, endian="!"): """ Decrypt 64 bit data block using XTEA block cypher * key = 128 bit (16 char) * block = 64 bit (8 char) * n = rounds (default 32) * endian = byte order (see 'struct' doc - default big/network) >>> z = 'b67c01662ff6964a'.decode('hex') >>> xtea_decrypt('0123456789012345',z) 'ABCDEFGH' Only need to change byte order if sending/receiving from alternative endian implementation >>> z = 'ea0c3d7c1c22557f'.decode('hex') >>> xtea_decrypt('0123456789012345',z,endian="<") 'ABCDEFGH' """ v0, v1 = struct.unpack(endian + "2L", block) k = struct.unpack(endian + "4L", key) delta, mask = 0x9e3779b9, 0xffffffff #removed trailing L from both values sum = (delta * n) & mask for round in range(n): v1 = (v1 - (((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + k[sum >> 11 & 3]))) & mask sum = (sum - delta) & mask v0 = (v0 - (((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + k[sum & 3]))) & mask return struct.pack(endian + "2L", v0, v1) def xtea_cbc_decrypt(key, iv, data, n=32, endian="!"): """ Decrypt a data buffer using cipher block chaining mode Written by Steve K """ global TEA_BLOCK_SIZE size = len(data) if (size % TEA_BLOCK_SIZE != 0): raise Exception("Size of data is not a multiple of TEA \ block size (%d)" % (TEA_BLOCK_SIZE)) decrypted = "" i = 0 while (i < size): result = xtea_decrypt(key, data[i:i + TEA_BLOCK_SIZE], n, endian) j = 0 while (j < TEA_BLOCK_SIZE): decrypted += chr(ord(result[j]) ^ ord(iv[j])) j += 1 iv = data[i:i + TEA_BLOCK_SIZE] i += TEA_BLOCK_SIZE return decrypted.strip(chr(0)) def xtea_cbc_encrypt(key, iv, data, n=32, endian="!"): """ Encrypt a data buffer using cipher block chaining mode Written by ztwaker """ global TEA_BLOCK_SIZE size = len(data) # alignment if (size % TEA_BLOCK_SIZE != 0): data += chr(0) * (TEA_BLOCK_SIZE - (size % TEA_BLOCK_SIZE)) encrypted = "" i = 0 while (i < size): block = "" j = 0 while (j < TEA_BLOCK_SIZE): block += chr(ord(data[i + j]) ^ ord(iv[j])) j += 1 encrypted += xtea_encrypt(key, block, n, endian) iv = encrypted[i:i + TEA_BLOCK_SIZE] i += TEA_BLOCK_SIZE return encrypted # testing if __name__ == '__main__': import os import random data = os.urandom(random.randint(0x000000001, 0x00001000)) key = os.urandom(TEA_KEY_SIZE) iv1 = iv2 = os.urandom(TEA_BLOCK_SIZE) data == xtea_cbc_decrypt(key, iv2, xtea_cbc_encrypt(key, iv1, data))
Python
UTF-8
229
2.84375
3
[]
no_license
def countBitsFlip(a,b): ##Your code here ans = 0 while a != 0 or b != 0: if a%2 != b%2: ans += 1 a //= 2 b //= 2 return ans
Java
UTF-8
2,356
3.65625
4
[]
no_license
package com.codeChefMedium.Sieve; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; public class NumberOfFactorsSieve { public static void main(String args[]) throws Exception { int i,j,k; boolean prime[] = new boolean[1000001]; for(i=2;i*i<=1000000;i++)//http://stackoverflow.com/questions/5811151/why-do-we-check-upto-the-square-root-of-a-prime-number-to-determine-if-it-is-pri { if(prime[i]==false) { k=0; j=i*i; while(j<=1000000) { prime[j]=true; j=i*i+k*i; k++; } } } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int A,t = Integer.parseInt(br.readLine()); while(t--!=0) { int N = Integer.parseInt(br.readLine()); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); String s[] = br.readLine().split(" "); /*for(j=2;j<10;j++) System.out.println(j+ " " + prime[j]+" "); System.out.println();*/ int count; for(i=0;i<N;i++) { // System.out.println(); A = Integer.parseInt(s[i]); //System.out.println(" A " + A); for(j=2;j<=A;j++) { if(prime[j]==false) { if(A%j==0) { count=0; while(A%j==0) { A/=j; count++; } if(map.get(j)!=null) { map.put(j,map.get(j)+count); //System.out.println("m1 j " +j+" " + map.get(j)); } else { map.put(j,count); //System.out.println("m2 j " +j+" " + map.get(j)); } } } } } long ans=1; for(int key : map.keySet()) { ans*=((int)map.get(key)+1); } System.out.println(ans); } } /*A simple modification of Sieve of Erastothenes will also prove to be helpful. The following is what I used. f[i] == 0 if i is prime, and if i is prime, then f[i] will have the smallest prime that will divide it. for (int i = 2; i <= N; i++) if (!f[i]) for (int j = i+i; j <= N; j += i) if (!f[j]) f[j] = i; f[i] will help a lot to find all the prime divisors of a number. f[42]=2 increment map[2]by 1 42/2=21 f[21]=3 increment map[3] by 1 21/3=7 f[7]=0 increment map[7] by1*/ /*old way to check if a number is prime * for (int a = 2; a * a <= n; a++) { if (n % a == 0) { return false; } } */ }
C++
UHC
336
3.15625
3
[]
no_license
#include <stdio.h> int main(){ //10. Ҽ(prime-number) ˻ ϰ ڰ Է μ ϴ α׷ ۼϽÿ. int a, n; printf(" Էϼ :"); scanf_s("%d", &a); for(n=1; n<=a; n=n+1){ if (a%n==0) { printf ("%d %d\n",a,n); } } }
JavaScript
UTF-8
1,236
2.640625
3
[]
no_license
const express = require('express'); const router = express.Router(); const data = require("../data"); const locaitonData = data.locations; // Single Location Page router.get("/:id", (req, res) => { // Find a location by the provided id, // then display its information // As well as listing all events that will be at this location // Each of these events need to link to the event page and show the event name // If a location is not found, display the 404 error page locaitonData.getLocation(parseInt(req.params.id)).then(location => { res.render('Location/single', { location: location }); }).catch( err =>{ res.render("misc/debug", { err:err }); }); }); // Location Index Page router.get("/", (req, res) => { // Display a list of all locations; it can be in an unordered list, or a table // Each of these locations need to link to the single location page locaitonData.getAllLocations().then(location => { res.render('Location/index', { location: location }); }).catch( err =>{ res.render("misc/debug", { err:err }); }); // res.render("misc/debug", { debug: true, modelData: { something: "SomeValue" } }); }); module.exports = router;
C++
UTF-8
752
3.03125
3
[]
no_license
#include <iostream> #include <string> #include <deque> using namespace std; const int SIZE = 5; char arr[SIZE] = { 'a', 'e', 'i', 'o', 'u' }; int main() { string str; cin >> str; while (str != "#") { int flag = 0; int str_sz = str.size(); deque <char> dq; for (int i = 0;i < str_sz;i++) dq.push_back(str[i]); for (int i = 0;i < str_sz;i++) { bool fg = false; for (int idx = 0;idx < SIZE;idx++) { if(dq[i] == arr[idx]){ fg = true; // 모음이면 true break; } } if (fg) break; else { flag++; } } while (flag--) { dq.push_back(dq.front()); dq.pop_front(); } for (auto it = dq.begin(); it < dq.end();it++) cout << *it; cout << "ay" << endl; cin >> str; } return 0; }
Markdown
UTF-8
5,538
3.0625
3
[ "Apache-2.0" ]
permissive
# CppCon 2018: Parallel Programming with Modern C++: from CPU to GPU This repository provides set up instructions and the exerises for the CppCon parallel programing class. ## Pre-requisites The majority of the exercises will require a only standard C++17 compliant compiler, however if for any reason you cannot use a C++17 compiler, using online compilers such as https://godbolt.org/ and https://wandbox.org/ will suffice. Some later exercises, those which involve programming for the GPU will have some further dependencies. You will need to install OpenCL drivers for the GPU on your laptop and ComputeCpp SYCL (see instructions below). If you do not have a GPU on your laptop or cannot find suitable OpenCL drivers for your GPU then the CPU will suffice. If you have trouble setting this up or for any reason are unable to install the requirements on your laptop we are providing a docker image which will provide OpenCL drivers for Intel CPU and ComputeCpp SYCL (see instructions below). ## SYCL Exercises | Exercise | Source | Solution | |----------|--------|----------| | [SYCL 00: Installing ComputeCpp ][exercise-sycl-00] | NA | NA | | [SYCL 01: Configuring a Queue ][exercise-sycl-01] | [source][source-sycl-01] | [solution][solution-sycl-01] | | [SYCL 02: Hello World ][exercise-sycl-02] | [source][source-sycl-02] | [solution][solution-sycl-02] | | [SYCL 03: Vector Add ][exercise-sycl-03] | [source][source-sycl-03] | [solution][solution-sycl-03] | | [SYCL 04: Image Grayscale ][exercise-sycl-04] | [source][source-sycl-04] | [solution][solution-sycl-04] | | [SYCL 05: Transpose ][exercise-sycl-05] | [source][source-sycl-05] | [solution][solution-sycl-05] | ## Instructions ### Installing OpenCL drivers: * You will need the OpenCL drivers for your GPU: * Intel OpenCL drivers: https://software.intel.com/en-us/articles/opencl-drivers. * AMD OpenCL drivers: https://www.amd.com/en/support. * NVidia OpenCL drivers: https://developer.nvidia.com/cuda-toolkit-32-downloads ### Installing ComputeCpp: * You can download ComputeCpp SYCL and find many useful resources at https://developer.codeplay.com/. * Set the environment variable `COMPUTECPP_DIR` to point to the root directory of the ComputeCpp installation. * For help getting setup and verifying your installation see https://developer.codeplay.com/computecppce/latest/getting-started-guide. * In general ComputeCpp supports Windows 7/10 and Ubuntu 16.04/18.04, and we support Intel CPU/GPU, AMD GPU and have experimental support for NVidia GPU on Ubunutu. For a full list of the supported platforms see https://developer.codeplay.com/computecppce/latest/supported-platforms. * Note that ComputeCpp currently only supports the earlier Radeon Software Crimson Edition AMD drivers. ### Setting up docker image: * Install Docker CE from https://docs.docker.com/install/. * Pull the computecpp_ubunutu1604 docker image: `docker pull aerialmantis/computecpp_ubuntu1604` * Run the computecpp_ubuntu1604 docker image: `docker run --rm -it aerialmantis/computecpp_ubuntu1604` ### Preparing this repository * Once you've got OpenCL and ComputeCpp SYCL setup or you have the docker image setup you can clone this repository to verify your setup and prepare yourself for the class. * Pull this repository: `git clone https://github.com/AerialMantis/cppcon-parallelism-class.git` * Create a build directory: `cd cppcon2018-parallelism-class/` `mkdir build` `cd build` * Run CMake to configure solution (local setup): `cmake ../ -G[Generator] -DCMAKE_BUILD_TYPE=[Debug/Release]` * Run CMake to configure solution (docker image): `cmake ../ -GNinja -DCMAKE_BUILD_TYPE=Debug -DOpenCL_LIBRARY=${OCL_LIB}/libOpenCL.so -DOpenCL_INCLUDE_DIR=${OCL_INC}` * Note that if you are using an NVidia GPU, in order to use the experimental ComputeCpp SYCL support you must include the following in the above CMake command: `-DCOMPUTECPP_BITCODE=ptx64` * Note that you can enable building the solutions by adding the following in the above CMake command: `-DCPPCON_ENABLE_SOLUTIONS=ON` * Note that you can disable the SYCL tests in the case you are not able to use ComputeCpp by adding the following in the above CMake command: `-DCPPCON_ENABLE_SYCL=OFF` * Build your solution: `cmake --build .` * Verify your setup by running the `verify_sycl` sample: `./examples/example_verify_sycl` ### Installing GCC 8 (Ubuntu 16.04) * To install GCC 8 on Ubuntu 16.04 you need update the apt-get repository: `RUN apt-get install software-properties-common` `RUN add-apt-repository ppa:ubuntu-toolchain-r/test` `RUN apt-get update` `RUN apt-get install g++-8` [exercise-sycl-00]: ./docs/sycl_00_setting_up_computecpp.md [exercise-sycl-01]: ./docs/sycl_01_configuring_a_queue.md [exercise-sycl-02]: ./docs/sycl_02_hello_world.md [exercise-sycl-03]: ./docs/sycl_03_vector_add.md [exercise-sycl-04]: ./docs/sycl_04_image_grayscale.md [exercise-sycl-05]: ./docs/sycl_05_transpose.md [source-sycl-01]: ./source/sycl_01_configuring_a_queue.cpp [source-sycl-02]: ./source/sycl_02_hello_world.cpp [source-sycl-03]: ./source/sycl_03_vector_add.cpp [source-sycl-04]: ./source/sycl_04_image_grayscale.cpp [source-sycl-05]: ./source/sycl_05_transpose.cpp [solution-sycl-01]: ./solutions/sycl_01_configuring_a_queue.cpp [solution-sycl-02]: ./solutions/sycl_02_hello_world.cpp [solution-sycl-03]: ./solutions/sycl_03_vector_add.cpp [solution-sycl-04]: ./solutions/sycl_04_image_grayscale.cpp [solution-sycl-05]: ./solutions/sycl_05_transpose.cpp
PHP
UTF-8
1,819
2.875
3
[]
no_license
<?php namespace App\Service; use Symfony\Component\HttpFoundation\Session\SessionInterface; class CartService { private $session; /** * CartService constructor. */ public function __construct(SessionInterface $session) { $this->session = $session; } public function getAll() { return $this->session->has('cart') ? $this->session->get('cart') : []; } public function addItem($item) { $cart = $this->getAll(); $message = 'Produto adicionado com sucesso!'; if (count($cart)) { $slug = array_column($cart, 'slug'); if (in_array($item['slug'], $slug)) { $cart = $this->incrementCartSlug($cart, $item); $message = sprintf('Quantidade do Produto %s aumentada com sucesso!', $item['name']); } else { array_push($cart, $item); } } else { $cart[] = $item; } $this->session->set('cart', $cart); return $message; } public function removeItem($item) { $cart = $this->getAll(); $cart = array_filter($cart, function ($items) use ($item) { return $items['slug'] != $item; }); if (!$cart) { return $this->session->remove('cart'); } $this->session->set('cart', $cart); } public function destroyCart(): bool { $this->session->remove('cart'); return true; } private function incrementCartSlug($cart, $item) { $arrayMap = array_map(function ($line) use ($item) { if ($line['slug'] == $item['slug']) { $line['amount'] += $item['amount']; } return $line; }, $cart); return $arrayMap; } }
TypeScript
UTF-8
920
3.25
3
[]
no_license
import PVector from './p-vector' export default class Brain { step: number directions: PVector[] constructor(size: any) { this.step = 0; this.directions = [...Array(size)].map(() => { const randomAngle = random(2 * Math.PI) const vec = PVector.fromAngle(randomAngle) return vec }) } clone() { const clone = new Brain(this.directions.length) clone.directions.forEach((_, idx) => { clone.directions[idx] = this.directions[idx].copy() }) return clone } mutate() { const mutationRate = 0.01 this.directions = this.directions.map(direction => { const rand = Math.random() if (rand < mutationRate) { const randomAngle = Math.random() * 0.5 * Math.PI const currentAngle = direction.getAngle() return PVector.fromAngle(currentAngle + randomAngle) } return direction.copy() }) } } function random(max = 1, min = 0) { return Math.random() * (max - min) + min }
Java
UTF-8
390
2.171875
2
[]
no_license
package com.ciuc.andrii.daggertest.model.custom_garage.car.engine; import javax.inject.Inject; public class Engine { Block block; Cylinders cylinders; SparkPlugs sparkPlugs; @Inject public Engine(Block block, Cylinders cylinders, SparkPlugs sparkPlugs) { this.block = block; this.cylinders = cylinders; this.sparkPlugs = sparkPlugs; } }
Java
UTF-8
17,998
1.835938
2
[]
no_license
package com.guiji.robot.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.guiji.common.model.process.ProcessInstanceVO; import com.guiji.process.model.ProcessReleaseVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.guiji.component.lock.DistributedLockHandler; import com.guiji.component.lock.Lock; import com.guiji.component.result.Result.ReturnData; import com.guiji.process.api.IProcessSchedule; import com.guiji.robot.constants.RobotConstants; import com.guiji.robot.exception.AiErrorEnum; import com.guiji.robot.exception.RobotException; import com.guiji.robot.model.AiCallApplyReq; import com.guiji.robot.model.UserResourceCache; import com.guiji.robot.service.IAiResourceManagerService; import com.guiji.robot.service.IUserAiCfgService; import com.guiji.robot.service.vo.AiInuseCache; import com.guiji.robot.service.vo.AiPoolInfo; import com.guiji.robot.service.vo.HsReplace; import com.guiji.robot.util.DataLocalCacheUtil; import com.guiji.robot.util.ListUtil; import com.guiji.utils.DateUtil; import com.guiji.utils.RedisUtil; import com.guiji.utils.StrUtils; import com.guiji.utils.SystemUtil; /** * @ClassName: AiResourceManagerServiceImpl * @Description: 机器人资源管理 * @date 2018年11月16日 下午2:19:33 * @version V1.0 */ @Service public class AiResourceManagerServiceImpl implements IAiResourceManagerService{ private final Logger logger = LoggerFactory.getLogger(getClass()); private final int AI_NUM = 10000; //这里需要获取所有机器人资源,后续需要单独提供接口,现在先用10000来获取全部 @Autowired RedisUtil redisUtil; @Autowired AiAsynDealService aiAsynDealService; @Autowired AiCacheService aiCacheService; @Autowired IUserAiCfgService iUserAiCfgService; @Autowired IProcessSchedule iProcessSchedule; @Autowired DistributedLockHandler distributedLockHandler; @Autowired DataLocalCacheUtil dataLocalCacheUtil; //需要为sellbot mock的话术模板 @Value("#{'${template.mock:}'.split(',')}") private List<String> mockTemplateList; /** * 初始化机器人资源池 * 将机器人从进程管理中初始化到缓存机器人池中 */ public List<AiInuseCache> aiPoolInit() { Lock lock = new Lock(RobotConstants.LOCK_ROBOT_AIPOOL_INIT, RobotConstants.LOCK_ROBOT_AIPOOL_INIT); if (distributedLockHandler.tryLock(lock)) { try { //从进程管理申请sellbot资源 List<ProcessInstanceVO> instanceList = applyAiResouceFromProcess(this.AI_NUM); List<AiInuseCache> aiPoolList = new ArrayList<AiInuseCache>(); for(int i=0;i<instanceList.size();i++) { AiInuseCache aiInuse = new AiInuseCache(); aiInuse.setAiNo(this.genAiNo(instanceList.get(i).getIp(), String.valueOf(instanceList.get(i).getPort()))); //机器人临时编号 aiInuse.setAiStatus(RobotConstants.AI_STATUS_F); //新申请机器人默认空闲状态 aiInuse.setInitDate(DateUtil.getCurrentymd()); //初始化日期 aiInuse.setInitTime(DateUtil.getCurrentTime()); //初始化时间 aiInuse.setIp(instanceList.get(i).getIp()); //机器IP aiInuse.setPort(String.valueOf(instanceList.get(i).getPort())); //机器人port aiPoolList.add(aiInuse); } //放入redis缓存 aiCacheService.initAiPool(aiPoolList); //3、异步记录历史 aiAsynDealService.initAiCycleHis(aiPoolList); return aiPoolList; } catch (RobotException e) { throw e; } catch (Exception e1) { logger.error("机器人资源池初始化异常!",e1); throw new RobotException(AiErrorEnum.AI00060033.getErrorCode(),AiErrorEnum.AI00060033.getErrorMsg()); }finally { //释放锁 distributedLockHandler.releaseLock(lock); } }else { logger.warn("用户机器人资源池未能获取资源锁!!!"); throw new RobotException(AiErrorEnum.AI00060034.getErrorCode(),AiErrorEnum.AI00060034.getErrorMsg()); } } /** * 重新加载sellbot资源 * 1、如果资源池中没有sellbot,那么重新初始化 * 2、如果资源池中已经有sellbot,那么增量处理 */ @Override public void reloadSellbotResource() { //查询目前缓存中的机器人资源 List<AiInuseCache> poolAiInuseCacheList = this.queryAiPoolList(); if(ListUtil.isNotEmpty(poolAiInuseCacheList)) { //如果资源池中已经有了机器人,那么增量增加 //继续从进程管理申请sellbot资源 List<ProcessInstanceVO> instanceList = applyAiResouceFromProcess(this.AI_NUM); if(ListUtil.isNotEmpty(instanceList)) { logger.info("又申请到了{}个sellbot机器人",instanceList.size()); //如果又申请到了新的机器 List<AiInuseCache> aiNewPoolList = new ArrayList<AiInuseCache>(); for(int i=0;i<instanceList.size();i++) { AiInuseCache aiInuse = new AiInuseCache(); aiInuse.setVersion(RobotConstants.HS_VERSION_SB); //sellbot机器人 aiInuse.setAiNo(this.genAiNo(instanceList.get(i).getIp(), String.valueOf(instanceList.get(i).getPort()))); //机器人临时编号 aiInuse.setAiStatus(RobotConstants.AI_STATUS_F); //新申请机器人默认空闲状态 aiInuse.setInitDate(DateUtil.getCurrentymd()); //初始化日期 aiInuse.setInitTime(DateUtil.getCurrentTime()); //初始化时间 aiInuse.setIp(instanceList.get(i).getIp()); //机器IP aiInuse.setPort(String.valueOf(instanceList.get(i).getPort())); //机器人port aiNewPoolList.add(aiInuse); //逐条放资源池 aiCacheService.changeAiPool(aiInuse); } //3、异步记录历史 aiAsynDealService.initAiCycleHis(aiNewPoolList); } }else { logger.info("全量更新"); aiPoolInit(); } } /** * 从AI资源池中获取所有机器人 * @return */ @Override public List<AiInuseCache> queryAiPoolList(){ return aiCacheService.queryAiPools(); } /** * 查询机器人资源池概况 * 查询资源池中总共多少机器人、在忙的有多少,每个用户分配了多少 * @return */ @Override public AiPoolInfo queryAiPoolInfo() { AiPoolInfo aiPoolInfo = new AiPoolInfo(); List<AiInuseCache> allAiList = this.queryAiPoolList(); if(ListUtil.isNotEmpty(allAiList)) { aiPoolInfo.setTotalNum(allAiList.size()); //资源池中机器人总数 int aiBusiNum = 0; for(AiInuseCache ai:allAiList) { if(RobotConstants.AI_STATUS_B.equals(ai.getAiStatus())) { aiBusiNum++; } } aiPoolInfo.setBusiNum(aiBusiNum); } //查询所有用户已分配的机器人列表 Map<String,List<AiInuseCache>> allUserAiInUserMap = aiCacheService.queryAllAiInUse(); if(allUserAiInUserMap != null && !allUserAiInUserMap.isEmpty()) { Map<String,Integer> userAiMap = new HashMap<String,Integer>(); for(Map.Entry<String, List<AiInuseCache>> allUserAiInuseEntry : allUserAiInUserMap.entrySet()) { String userId = allUserAiInuseEntry.getKey(); //用户ID List<AiInuseCache> userAiList = allUserAiInuseEntry.getValue(); //用户已分配的机器人 if(ListUtil.isNotEmpty(userAiList)) { userAiMap.put(userId, userAiList.size()); } } aiPoolInfo.setUserAssignMap(userAiMap); } return aiPoolInfo; } /** * 从机器人资源池中分配一个机器人给本次申请 * @param aiCallApplyReq * @param userResourceCache * @return */ @Override public AiInuseCache aiAssign(AiCallApplyReq aiCallApplyReq) { Lock lock = new Lock(RobotConstants.LOCK_ROBOT_AIPOOL_ASSIGN, RobotConstants.LOCK_ROBOT_AIPOOL_ASSIGN); if (distributedLockHandler.tryLock(lock)) { try { AiInuseCache assignAi = null; String templateId = aiCallApplyReq.getTemplateId(); //获取模板 HsReplace hsReplace = dataLocalCacheUtil.queryTemplate(templateId); if(RobotConstants.HS_VERSION_FL==hsReplace.getVersion() || (mockTemplateList!=null&&mockTemplateList.contains(templateId))) { //如果是飞龙的话术模板或者是测试需要mock的模板分配飞龙机器人 //分配一个飞龙机器人 assignAi = new AiInuseCache(); assignAi.setVersion(RobotConstants.HS_VERSION_FL); //新版本飞龙机器人 assignAi.setAiNo(SystemUtil.getBusiSerialNo(null,20)); //生成20位的机器人编号 assignAi.setUserId(aiCallApplyReq.getUserId()); //用户号 assignAi.setTemplateIds(aiCallApplyReq.getTemplateId()); //模板号 assignAi.setAiStatus(RobotConstants.AI_STATUS_B); //忙 assignAi.setCallingPhone(aiCallApplyReq.getPhoneNo()); //正在拨打的电话 assignAi.setCallingTime(DateUtil.getCurrentTime()); //开始拨打时间 assignAi.setSeqId(aiCallApplyReq.getSeqId()); //会话id }else { //分配一个sellbot的机器人 assignAi = this.getSellbotAi(aiCallApplyReq); } //将这个机器人分配给用户 aiCacheService.changeAiInUse(assignAi); return assignAi; } catch (RobotException e) { throw e; } catch (Exception e1) { logger.error("从机器人资源池捞机器人异常!",e1); throw new RobotException(AiErrorEnum.AI00060033.getErrorCode(),AiErrorEnum.AI00060033.getErrorMsg()); }finally { //释放锁 distributedLockHandler.releaseLock(lock); } }else { logger.warn("[从机器人资源池捞机器人]未能获取资源锁!!!"); throw new RobotException(AiErrorEnum.AI00060034.getErrorCode(),AiErrorEnum.AI00060034.getErrorMsg()); } } /** * 获取sellbot ai * 其他地方不可直接调用,只为机器人资源分配使用 * @param aiCallApplyReq * @return */ private AiInuseCache getSellbotAi(AiCallApplyReq aiCallApplyReq) { //获取AI机器人资源池 List<AiInuseCache> aiPoolList = this.queryAiPoolList(); if(aiPoolList == null || aiPoolList.isEmpty()) { //如果缓存中没有数据,初始化下 aiPoolList = this.aiPoolInit(); } AiInuseCache assignAi = null; if(aiPoolList != null && !aiPoolList.isEmpty()) { for(AiInuseCache aiInuseCache : aiPoolList) { if(RobotConstants.AI_STATUS_F.equals(aiInuseCache.getAiStatus())) { //找到1个空闲的机器人 assignAi = aiInuseCache; break; } } } if(assignAi==null) { //没有空闲机器人 logger.error("本地机器人资源池机器人总数{},没有空闲机器人",aiPoolList == null ? 0:aiPoolList.size()); throw new RobotException(AiErrorEnum.AI00060002.getErrorCode(),AiErrorEnum.AI00060002.getErrorMsg()); } //设置分配后的部分信息 assignAi.setVersion(RobotConstants.HS_VERSION_SB); //sellbot机器人 assignAi.setUserId(aiCallApplyReq.getUserId()); //用户号 assignAi.setTemplateIds(aiCallApplyReq.getTemplateId()); //模板号 assignAi.setAiStatus(RobotConstants.AI_STATUS_B); //忙 assignAi.setCallingPhone(aiCallApplyReq.getPhoneNo()); //正在拨打的电话 assignAi.setCallingTime(DateUtil.getCurrentTime()); //开始拨打时间 assignAi.setSeqId(aiCallApplyReq.getSeqId()); //会话id assignAi.setCallNum(assignAi.getCallNum()+1); //拨打数量 //将资源池中机器人状态更新为忙 aiCacheService.changeAiPool(assignAi); return assignAi; } /** * 机器人资源释放还回进程资源池 * 1、将用户inuse缓存清理掉 * 2、将机器人资源池中的机器人状态置为闲 * @param aiInuse */ @Override public void aiRelease(AiInuseCache aiInuse) { if(aiInuse != null) { //从用户缓存中也清理掉该用户的找个机器人 aiCacheService.delUserAi(aiInuse.getUserId(), aiInuse.getAiNo()); if(RobotConstants.HS_VERSION_SB==aiInuse.getVersion()) { //如果是sellbot的机器人,那么才需要还回资源池,其他直接干掉 //将机器人资源池中的机器人状态置为闲 aiInuse.setAiStatus(RobotConstants.AI_STATUS_F); aiInuse.setCallingPhone(null); aiInuse.setCallingTime(null); aiCacheService.changeAiPool(aiInuse); } } } /** * 机器人资源批量释放还回进程资源池 * @param aiList */ @Override public void aiBatchRtnProcess(List<AiInuseCache> aiList) { //调用进程管理,释放机器人资源 if(ListUtil.isNotEmpty(aiList)) { List<ProcessInstanceVO> processList = new ArrayList<ProcessInstanceVO>(); for(AiInuseCache ai : aiList) { if(StrUtils.isNotEmpty(ai.getIp())) { ProcessInstanceVO vo = new ProcessInstanceVO(); vo.setIp(ai.getIp()); vo.setPort(Integer.valueOf(ai.getPort())); processList.add(vo); } } if(processList!=null && !processList.isEmpty()) { //调用进程管理释放资源 logger.info("调用进程管理释放:{}个sellbot机器人",processList.size()); ProcessReleaseVO processReleaseVO = new ProcessReleaseVO(); processReleaseVO.setProcessInstanceVOS(processList); iProcessSchedule.release(processReleaseVO); //异步记录日志--这个日志没有用,不再记录了 // aiAsynDealService.releaseAiCycleHis(aiList); } } } /** * 设置机器人忙-正在打电话 * @param aiInuseCache */ @Override public void aiBusy(AiInuseCache aiInuseCache) { if(aiInuseCache != null) { aiInuseCache.setAiStatus(RobotConstants.AI_STATUS_B); aiCacheService.changeAiInUse(aiInuseCache); } } /** * 设置机器人空闲 * @param aiInuseCache */ @Override public void aiFree(AiInuseCache aiInuseCache) { if(aiInuseCache != null) { aiInuseCache.setAiStatus(RobotConstants.AI_STATUS_F); aiCacheService.changeAiInUse(aiInuseCache); } } /** * 设置机器人暂停不可用 * @param aiInuseCache */ @Override public void aiPause(AiInuseCache aiInuseCache) { if(aiInuseCache != null) { aiInuseCache.setAiStatus(RobotConstants.AI_STATUS_P); aiCacheService.changeAiInUse(aiInuseCache); } } /** * 查询用户已分配的AI列表 * @param userId * @return */ @Override public List<AiInuseCache> queryUserInUseAiList(String userId){ if(StrUtils.isNotEmpty(userId)) { return aiCacheService.queryUserAiInUseList(userId); } return null; } /** * 查询用户正在忙的AI列表 * @param userId * @return */ @Override public List<AiInuseCache> queryUserBusyUseAiList(String userId){ if(StrUtils.isNotEmpty(userId)) { List<AiInuseCache> list = aiCacheService.queryUserAiInUseList(userId); if(ListUtil.isNotEmpty(list)) { for(int i=0;i<list.size();i++) { list.get(i).setAiName("硅语"+(i+1)+"号"); //机器人名字 list.get(i).setSortId(i); //排序ID } } return list; } return null; } /** * 查询用户在休息的AI列表(空闲/暂停不可以用) * @param userId * @return */ @Override public List<AiInuseCache> queryUserSleepUseAiList(String userId){ if(StrUtils.isNotEmpty(userId)) { List<AiInuseCache> sleepList = new ArrayList<AiInuseCache>(); UserResourceCache userResourceCache = aiCacheService.getUserResource(userId); int aiNum = 0; //用户总机器人 int aiInuseNum = 0; //用户在忙的机器人 if(userResourceCache!=null) { aiNum = userResourceCache.getAiNum(); //用户总机器人 } List<AiInuseCache> aiInuseList = aiCacheService.queryUserAiInUseList(userId); if(ListUtil.isNotEmpty(aiInuseList)) { aiInuseNum = aiInuseList.size(); } if(aiNum-aiInuseNum>0) { //总机器人-在忙的机器人 = 空闲的机器人 for(int i=0;i<(aiNum-aiInuseNum);i++) { //拼装用户空闲的机器人 AiInuseCache aiInuseCache = new AiInuseCache(); int seqNo = aiInuseNum + i +1; //空闲的机器人顺着忙的机器人排序下来 aiInuseCache.setAiNo("AI"+seqNo); //机器人编号 aiInuseCache.setAiName("硅语"+(seqNo)+"号"); //机器人名字 aiInuseCache.setSortId(i); //排序ID aiInuseCache.setAiStatus(RobotConstants.AI_STATUS_F); //空闲 aiInuseCache.setCallNum(0); aiInuseCache.setUserId(userId); sleepList.add(aiInuseCache); } } return sleepList; } return null; } /** * 从进程管理申请机器人 * @param applyAiNum * @return */ private List<ProcessInstanceVO> applyAiResouceFromProcess(int applyAiNum){ //调用进程管理服务申请sellbot机器人资源 ReturnData<List<ProcessInstanceVO>> processInstanceListData = iProcessSchedule.getSellbot(10000); if(processInstanceListData == null) { logger.error("调用进程管理申请资源,返回数据为空.."); throw new RobotException(AiErrorEnum.AI00060007.getErrorCode(),AiErrorEnum.AI00060007.getErrorMsg()); }else if(!RobotConstants.RSP_CODE_SUCCESS.equals(processInstanceListData.getCode())) { logger.error("调用进程管理申请全部机器人资源异常..."); throw new RobotException(processInstanceListData.getCode(),processInstanceListData.getMsg()); } List<ProcessInstanceVO> instanceList = processInstanceListData.getBody(); if(instanceList == null || instanceList.isEmpty() || instanceList.size()==0) { logger.error("调用进程管理申请全部机器人异常,无空余可用机器人..."); throw new RobotException(AiErrorEnum.AI00060008.getErrorCode(),AiErrorEnum.AI00060008.getErrorMsg()); }else { logger.info("初始化机器人资源池,申请到{}个机器人",instanceList.size()); } return instanceList; } /** * 查询用户某个机器人 * @param userId 用户id * @param aiNo 机器人编号 * @return */ @Override public AiInuseCache queryUserAi(String userId,String aiNo){ if(StrUtils.isNotEmpty(userId) && StrUtils.isNotEmpty(aiNo)) { return aiCacheService.queryAiInuse(userId, aiNo); } return null; } /** * ip/port生成机器人 * ipportyyyyMMdd * @param ip * @param port * @return */ private String genAiNo(String ip,String port) { String aiNo = ip+port; aiNo = aiNo.replaceAll("\\.",""); return DateUtil.getStringDate(new Date())+aiNo; } }
Markdown
UTF-8
1,212
2.859375
3
[]
no_license
# Alt Fuel Finder Simple app to view alternative fuel stations within 6 miles of a given zip code, limited to 10 results. Completed in a 2 hr period as a mid-mod assessment for mod 3 at Turing. It uses the NREL alternative fuel station API data found [here](https://developer.nrel.gov/docs/transportation/alt-fuel-stations-v1/nearest/). ## Setup ``` $ bundle install $ rake db:{create,migrate} $ rails s ``` Navigate to `http://localhost:3000` ## Tech 1. Rails 1. Faraday to make API requests 1. VCR to record request data to avoid making real API calls during each test ## Testing Testing is done with rspec and tests the station model, facade, service, and view. It utilizes feature and model testing. To run tests: ``` bundle exec rspec ``` ## User Story As a user When I visit "/" And I fill in the search form with 80203 (Note: Use the existing search form) And I click "Locate" Then I should be on page "/search" Then I should see a list of the 10 closest stations within 6 miles sorted by distance And the stations should be limited to Electric and Propane And for each of the stations I should see Name, Address, Fuel Types, Distance, and Access Times
C
UTF-8
413
2.640625
3
[ "MIT" ]
permissive
#pragma once #include "Main.h" enum { FULL_WINDOW, ASPECT_1_1, EXIT }; int Aspect = FULL_WINDOW; void Menu(int value) { switch (value) { case FULL_WINDOW: Aspect = FULL_WINDOW; Reshape(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)); break; case ASPECT_1_1: Aspect = ASPECT_1_1; Reshape(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)); break; case EXIT: exit(0); } }
Java
UTF-8
729
2.859375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package akatkar.exam03.makeupQuestions; /** * * @author akatkar */ public class Question7 { public int getMax(int a, int b) { if (a > b) { return a; } else { return b; } } public static void main(String[] args) { boolean b = false; byte byt = 2; short sh = 3; char ch = 'A'; int i = 5; long lo = 25676; float f = 2.45f; double d = 2.1; sh = (short) i; } }
Python
UTF-8
3,081
2.53125
3
[]
no_license
import unittest from selenium import webdriver from django.test import TestCase import time URL = "http://raplev.com:8080" class SellVisitorTest (TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_user_signup_and_login(self): # Omar needs to use Raplev for his job. He goes # to check out its homepage self.browser.get(URL) # He notices the page title and header mention Raplev self.assertIn('Homepage', self.browser.title) # He notices a registration button signup_button = self.browser.find_element_by_xpath('/html/body/header/div/div[1]/nav/ul/li[3]/button') signup_button.click() # The Registration pane is opened # where he enters a username and a password username_field = self.browser.find_element_by_id('email') name_field = self.browser.find_element_by_id('full_name') password1_field = self.browser.find_element_by_id('password1') password2_field = self.browser.find_element_by_id('password2') # He wants to sell sign_up_button = self.browser.find_element_by_id('buy_button') # He fills in the details for a new user and clicks on the "Sign Up" button username_field.send_keys('test1@example.com') name_field.send_keys('test test') password1_field.send_keys('test1test1') password2_field.send_keys('test1test1') sign_up_button.click() time.sleep(3) class BuyVisitorTest (TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_user_signup_and_login(self): # Omar needs to use Raplev for his job. He goes # to check out its homepage self.browser.get(URL) # He notices the page title and header mention Raplev self.assertIn('Homepage', self.browser.title) # He notices a registration button signup_button = self.browser.find_element_by_xpath('/html/body/header/div/div[1]/nav/ul/li[3]/button') signup_button.click() # The Registration pane is opened # where he enters a username and a password username_field = self.browser.find_element_by_id('email') name_field = self.browser.find_element_by_id('full_name') password1_field = self.browser.find_element_by_id('password1') password2_field = self.browser.find_element_by_id('password2') # He wants to sell sign_up_button = self.browser.find_element_by_id('sell_button') # He fills in the details for a new user and clicks on the "Sign Up" button username_field.send_keys('test1@example.com') name_field.send_keys('test test') password1_field.send_keys('test1test1') password2_field.send_keys('test1test1') sign_up_button.click() time.sleep(3) if __name__ == '__main__': unittest.main(warnings='ignore') if __name__ == '__main__': unittest.main(warnings='ignore')
C++
UTF-8
1,151
2.84375
3
[ "MIT" ]
permissive
#ifndef __PLAYER__ #define __PLAYER_ #include <SFML/Graphics.hpp> #include <array> #include <map> enum class PlayerSide { left, right }; enum class PaddleMoveDiretion { UP = -1, DOWN = 1 }; struct Paddle { const float y_width_center = 128 / 2; const float x_width = 8; const float y_width = 128; float y_position; float x_position; float y_speed; bool move; sf::RectangleShape shape; Paddle(float x_position) : x_position(x_position), y_position(y_position), shape({x_width, y_width}), move(false) { y_position = 384 - y_width_center; shape.setPosition({x_position, y_position}); shape.setFillColor(sf::Color::White); } void set_position_y(float pos) { shape.setPosition({x_position, pos}); } operator sf::RectangleShape &(void) { return shape; } }; struct Player { int id; PlayerSide side; Paddle paddle; Player(int id, PlayerSide side) : id(id), side(side), paddle(side == PlayerSide::left ? 8 : 1004) {} void set_paddle_y_position(float pos) { paddle.set_position_y(pos); } ~Player(void) = default; operator sf::RectangleShape &(void) { return paddle; } }; #endif
Java
UTF-8
9,881
2.84375
3
[]
no_license
package mksinterface.mksitem.src; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import com.mks.api.response.Field; import com.mks.api.response.Item; /** * This special field class represents a full field of an item in Integrity. * You are able to feed the class with an "Field" element which is given directly * from Integrity or feed it with your own parameters. Internal the fields will be * saved with their correct types and values. * @author ckaltenboeck * */ public class Mksinterface_mksfield { //Variable definitions private String stringValue_; private int intValue_; private Calendar calendarValue_; private double doubleValue_; private boolean booleanValue_; private ArrayList<Object> listValue_; private long longValue_; private int type_; private String name_; //Constants for all at the moment available Types of fields public static final int MKSINTERFACE_MKSFIELD_TYPE_NO_TYPE = 0; public static final int MKSINTERFACE_MKSFIELD_TYPE_STRING = 1; public static final int MKSINTERFACE_MKSFIELD_TYPE_INT = 2; public static final int MKSINTERFACE_MKSFIELD_TYPE_BOOLEAN = 3; public static final int MKSINTERFACE_MKSFIELD_TYPE_DOUBLE = 4; public static final int MKSINTERFACE_MKSFIELD_TYPE_CALENDAR = 5; public static final int MKSINTERFACE_MKSFIELD_TYPE_OBJECTLIST = 6; public static final int MKSINTERFACE_MKSFIELD_TYPE_LONG = 7; /** * Constructor to create an internal field from a mksfield * @param field mksfield object */ public Mksinterface_mksfield(Field field) throws Mksinterface_fieldException { if(field == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_FIELD_NULL); if (field.getDisplayName() == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_TYPE_NOT_AVAILABLE); else name_ = field.getDisplayName(); if (field.getDataType() == null) { type_ = MKSINTERFACE_MKSFIELD_TYPE_NO_TYPE; return; } if (field.getDataType().equals(Field.BOOLEAN_TYPE)) { booleanValue_ = field.getBoolean(); type_ = MKSINTERFACE_MKSFIELD_TYPE_BOOLEAN; } else if (field.getDataType().equals(Field.DATE_TYPE)) { calendarValue_ = Calendar.getInstance(); calendarValue_.setTime(field.getDateTime()); type_ = MKSINTERFACE_MKSFIELD_TYPE_CALENDAR; } else if (field.getDataType().equals(Field.DOUBLE_TYPE)) { doubleValue_ = field.getDouble(); type_ = MKSINTERFACE_MKSFIELD_TYPE_DOUBLE; } else if (field.getDataType().equals(Field.FLOAT_TYPE)) { doubleValue_ = (double)field.getFloat(); type_ = MKSINTERFACE_MKSFIELD_TYPE_DOUBLE; } else if (field.getDataType().equals(Field.INTEGER_TYPE)) { intValue_ = field.getInteger(); type_ = MKSINTERFACE_MKSFIELD_TYPE_INT; } else if (field.getDataType().equals(Field.LONG_TYPE)) { longValue_ = field.getLong(); type_ = MKSINTERFACE_MKSFIELD_TYPE_LONG; } else if (field.getDataType().equals(Field.ITEM_LIST_TYPE)) { @SuppressWarnings("unchecked") List<Item> list = field.getList(); listValue_ = new ArrayList<Object>(); for(int i=0; i < list.size(); i++) { listValue_.add(new Integer(list.get(i).getId())); } type_ = MKSINTERFACE_MKSFIELD_TYPE_OBJECTLIST; } else if(field.getDataType().equals(Field.STRING_TYPE)) { stringValue_ = field.getString(); type_ = MKSINTERFACE_MKSFIELD_TYPE_STRING; } else if(field.getDataType().equals(Field.ITEM_TYPE)) { if (field.getItem().toString() == null) stringValue_ = ""; stringValue_ = field.getItem().toString(); type_ = MKSINTERFACE_MKSFIELD_TYPE_STRING; } else if(field.getDataType().equals(Field.VALUE_LIST_TYPE)) { stringValue_ = field.getItem().toString(); type_ = MKSINTERFACE_MKSFIELD_TYPE_STRING; } else { throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_TYPE_NOT_AVAILABLE); } } /** * Constructor to create an internal field with a String value and a name * @param value Value of the field * @param name Name of the field */ public Mksinterface_mksfield(String value, String name) throws Mksinterface_fieldException { if (value == null || name == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_PARAMETER_NULL); stringValue_ = value; name_ = name; type_ = MKSINTERFACE_MKSFIELD_TYPE_STRING; } /** * Constructor to create an internal field with an int value and a name * @param value Value of the field * @param name Name of the field */ public Mksinterface_mksfield(int value, String name) throws Mksinterface_fieldException { if (name == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_PARAMETER_NULL); intValue_ = value; name_ = name; type_ = MKSINTERFACE_MKSFIELD_TYPE_INT; } /** * Constructor to create an internal field with an boolean value and a name * @param value Value of the field * @param name Name of the field */ public Mksinterface_mksfield(boolean value, String name) throws Mksinterface_fieldException { if (name == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_PARAMETER_NULL); booleanValue_ = value; name_ = name; type_ = MKSINTERFACE_MKSFIELD_TYPE_BOOLEAN; } /** * Constructor to create an internal field with an double value and a name * @param value Value of the field * @param name Name of the field */ public Mksinterface_mksfield(double value, String name) throws Mksinterface_fieldException { if (name == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_PARAMETER_NULL); doubleValue_ = value; name_ = name; type_ = MKSINTERFACE_MKSFIELD_TYPE_DOUBLE; } /** * Constructor to create an internal field with an Calendar value and a name * @param value Value of the field * @param name Name of the field */ public Mksinterface_mksfield(Calendar value, String name) throws Mksinterface_fieldException { if (name == null || value == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_PARAMETER_NULL); calendarValue_ = value; name_ = name; type_ = MKSINTERFACE_MKSFIELD_TYPE_CALENDAR; } /** * Constructor to create an internal field with an long value and a name * @param value Value of the field * @param name Name of the field */ public Mksinterface_mksfield(long value, String name) throws Mksinterface_fieldException { if (name == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_PARAMETER_NULL); longValue_ = value; name_ = name; type_ = MKSINTERFACE_MKSFIELD_TYPE_CALENDAR; } /** * Constructor to create an internal field with an List Object value and a name * @param value Value of the field * @param name Name of the field */ public Mksinterface_mksfield(ArrayList<Object> value, String name) throws Mksinterface_fieldException { if (name == null) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_PARAMETER_NULL); if (value.size() == 0) throw new Mksinterface_fieldException(Mksinterface_fieldException.MKSINTERFACE_FIELD_EXCEPTION_PARAMETER_NULL); listValue_ = value; name_ = name; type_ = MKSINTERFACE_MKSFIELD_TYPE_BOOLEAN; } /** * Returns the value of the field as string * @return value */ public String getStringValue() { return stringValue_; } /** * Returns the value of the field as int * @return value */ public int getIntValue() { return intValue_; } /** * Returns the value of the field as double * @return value */ public double getDoubleValue() { return doubleValue_; } /** * Returns the value of the field as boolean * @return value */ public boolean getBooleanValue() { return booleanValue_; } /** * Returns the value of the field as Calendar object * @return value */ public Calendar getCalendarValue() { return calendarValue_; } /** * Returns the value of the field as a List Object * @return value */ public List<Object> getListValue() { return listValue_; } public long getLongValue() { return longValue_; } /** * Converts a list of mks fields to a list of internal java fields * @param fields input fields of the interface * @return java representation fields */ public static ArrayList<Mksinterface_mksfield> convertField(ArrayList<Field> fields) throws Mksinterface_fieldException { ArrayList<Mksinterface_mksfield> mksfields = new ArrayList<Mksinterface_mksfield>(); for(int i= 0; i < fields.size(); i++) { mksfields.add(new Mksinterface_mksfield(fields.get(i))); } return mksfields; } /** * Returns the name of the field * @return Name */ public String getName() { return name_; } /** * Returns the type of the field as an integer value. * Look at the constants for type definition * @return Type of the field */ public int getType() { return type_; } /** * Returns value as string */ public String toString() { switch(type_) { case MKSINTERFACE_MKSFIELD_TYPE_STRING: return stringValue_; case MKSINTERFACE_MKSFIELD_TYPE_INT: return intValue_+""; case MKSINTERFACE_MKSFIELD_TYPE_BOOLEAN: if (booleanValue_) return "true"; else return "false"; case MKSINTERFACE_MKSFIELD_TYPE_DOUBLE: return doubleValue_+""; case MKSINTERFACE_MKSFIELD_TYPE_CALENDAR: return calendarValue_.toString(); case MKSINTERFACE_MKSFIELD_TYPE_OBJECTLIST: return listValue_.toString(); case MKSINTERFACE_MKSFIELD_TYPE_LONG: return longValue_+""; default: return ""; } } }
Python
UTF-8
1,511
3.203125
3
[]
no_license
import random import string days = ['Nov 12 2018 ', 'Nov 13 2018 ', 'Nov 14 2018 '] s = "" def random_string(string_length=10): letters = string.ascii_lowercase return ''.join(random.choice(letters) for _ in range(string_length)) def add_edge(mail1, mail2): global s s += mail1 + "," + mail2 + "," + days[random.randint(0, 10000) % len(days)] + str(random.randint(0, 23)).zfill( 2) + ":" + str(random.randint(0, 59)).zfill(2) + ":" + str(random.randint(0, 59)).zfill(2) + "\n" def generate_edges(data_size=1000000): emails = [] f = open('nodes.csv', 'r') for line in f: x = line.split(",") emails.append(x[6].strip()) for i in range(0, data_size): int_or_ext = random.randint(0, 100000000) if int_or_ext % 25 == 0: ext_email = random_string(8) + "@ext.com" int_email = emails[random.randint(0, 100000000) % len(emails)] if random.randint(0, 1000000) % 2 == 0: add_edge(int_email, ext_email) else: add_edge(ext_email, int_email) else: email1 = emails[random.randint(0, 100000000) % len(emails)] email2 = emails[random.randint(0, 100000000) % len(emails)] while email1 == email2: email2 = emails[random.randint(0, 100000000) % len(emails)] add_edge(email1, email2) f1 = open('edges.csv', 'w') f1.write(s) f1.close() if __name__ == '__main__': generate_edges()
Python
UTF-8
4,318
2.53125
3
[]
no_license
# -*- coding:utf-8 -*- from __future__ import print_function import codecs import numpy as np import math import heapq import random import sys import os negNum = 100 def get_hit_ratio(rank_list, target_item): for item in rank_list: if item == target_item: return 1 return 0 def get_ndcg(rank_list, target_item): for i, item in enumerate(rank_list): if item == target_item: return math.log(2) / math.log(i + 2) return 0 def eval_one_rating(i_gnd, i_pre, K): if sum(i_pre) == 0: return 0, 0 map_score = {} for item, score in enumerate(i_pre): map_score[item] = score target_item = i_gnd.index(1.0) rank_list = heapq.nlargest(K, map_score, key=map_score.get) hit = get_hit_ratio(rank_list, target_item) ndcg = get_ndcg(rank_list, target_item) return hit, ndcg if __name__ == "__main__": # read pos user ids user_id_list = [] user_id_reader = codecs.open("user_id.txt", mode="r", encoding="utf-8") for line in user_id_reader: user_id_list.append(line.strip()) user_id_reader.close() alpha = float(sys.argv[1]) print("eval with alpha:", alpha) not_enough_num = 0 # generate test samples score_reader = codecs.open(sys.argv[2], mode="r", encoding="utf-8") sample_reader = codecs.open("test_samples/test_samples_"+str(alpha)+".txt", mode="r", encoding="utf-8") score_line = score_reader.readline() sample_line = sample_reader.readline() debug_num = 0 hit_k_score = [] ndcg_k_score = [] pos_error_pairs = [] neg_error_pairs = [] for user_id in user_id_list: print("user id:", user_id) user_item_score_dict = dict() while score_line: score_line_list = score_line.strip().split("\t") if score_line_list[0] == user_id: score_line = score_reader.readline() user_item_score_dict[(score_line_list[0], score_line_list[1])] = (score_line_list[-2], score_line_list[-1]) else: break print("user item len:", len(user_item_score_dict)) test_sample_list = [] # read test samples while sample_line: sample_line_list = sample_line.strip().split("\t") if sample_line_list[0] == user_id: test_sample_list.append(sample_line_list) sample_line = sample_reader.readline() else: break # samples for test_object in test_sample_list: pos_pair = (user_id, test_object[1]) neg_pair_list = [] for neg_idx in test_object[2].split("#"): neg_pair_list.append((user_id, neg_idx)) ground_truth_labels = [] predict_labels = [] ground_truth_labels.append(1.0) predict_labels.append(float(user_item_score_dict[pos_pair][1])) for neg_pair in neg_pair_list: _scores = user_item_score_dict[neg_pair] ground_truth_labels.append(0.0) predict_labels.append(float(_scores[1])) temp_hit = [] temp_ndcg = [] for k in range(1, 16): hit, ndcg = eval_one_rating(i_gnd=ground_truth_labels, i_pre=predict_labels, K=k) temp_hit.append(hit) temp_ndcg.append(ndcg) hit_k_score.append(temp_hit) ndcg_k_score.append(temp_ndcg) sample_reader.close() score_reader.close() total_hit_res_array = np.asarray(hit_k_score) total_ndcg_res_array = np.asarray(ndcg_k_score) print(total_hit_res_array.shape) print(total_ndcg_res_array.shape) hit_average = [] ndcg_average = [] for i in range(15): hit_average.append("%.5f" % np.mean(total_hit_res_array[:, i])) ndcg_average.append("%.5f" % np.mean(total_ndcg_res_array[:, i])) print("hit score:", hit_average) print("ndcg score:", ndcg_average) score_dir = sys.argv[3] score_writer = codecs.open(os.path.join(score_dir, "eval_res_%.1f.txt" % alpha), mode="w", encoding="utf-8") score_writer.write("hit scores\t:" + "\t".join(hit_average) + "\n") score_writer.write("ndcg scores\t:" + "\t".join(ndcg_average) + "\n") score_writer.close()
Java
UTF-8
558
3.21875
3
[]
no_license
package arrays; import java.util.Arrays; public class Person { public static void main(String[] args) { int []ages=new int[5]; ages[0]=12; ages[1]=22; ages[2]=32; ages[3]=42; ages[4]=52; System.out.println(Arrays.toString(ages)); String[]names=new String[4]; names[0]="can"; names[1]="ali"; names[2]="nur"; names[3]="su"; System.out.println(names[1]); System.out.println(names[2]); double[]prices= {45.99,23.5,11.50,33.33,99.99}; prices[4]=112.89; System.out.println(Arrays.toString(prices)); } }
C#
UTF-8
5,293
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Timers; using System.Xml.Serialization; using LotteryVoteMVC.Models; using System.Web; namespace LotteryVoteMVC.Core { public class TodayLotteryCompany { private static object _lockHelper = new object(); private static TodayLotteryCompany _todayCompany; private readonly string _configName = "TodayLotteryCompany.config"; private const string M_COMPANYSTR = "PersonalCompany"; private DateTime _lastUpdateTime; public DateTime LastUpdateTime { get { if (_lastUpdateTime == default(DateTime)) { FileInfo config = new FileInfo(ConfigPath); _lastUpdateTime = config.LastWriteTime; } return _lastUpdateTime; } private set { _lastUpdateTime = value; } } private string _configPath; public string ConfigPath { get { if (string.IsNullOrEmpty(_configPath)) { string folderPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + "Config\\"; if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath); _configPath = folderPath + _configName; } return _configPath; } } private CompanyManager _comManager; public CompanyManager ComManager { get { if (_comManager == null) _comManager = new CompanyManager(); return _comManager; } } Timer todayCompanyTime = new Timer(600000); //十分钟检查更新 private TodayLotteryCompany() { todayCompanyTime.AutoReset = true; todayCompanyTime.Enabled = true; todayCompanyTime.Elapsed += new ElapsedEventHandler(todayCompanyTime_Elapsed); todayCompanyTime.Start(); CheckUpdate(); } private void todayCompanyTime_Elapsed(object sender, ElapsedEventArgs e) { CheckUpdate(); } private void CheckUpdate() { if (LastUpdateTime.Date != DateTime.Today) UpdateTodayLotteryCompany(); } public static TodayLotteryCompany Instance { get { if (_todayCompany == null) { lock (_lockHelper) { if (_todayCompany == null) _todayCompany = new TodayLotteryCompany(); } } return _todayCompany; } } public IList<LotteryCompany> GetTodayCompany() { IList<LotteryCompany> companys = null; if (HttpContext.Current != null) companys = HttpContext.Current.Items[M_COMPANYSTR] as IList<LotteryCompany>; if (companys == null) { if (!File.Exists(ConfigPath)) throw new FileNotFoundException(ConfigPath); companys = Deserialize(); if (HttpContext.Current != null) HttpContext.Current.Items[M_COMPANYSTR] = companys; } return companys; } /// <summary> /// 获取还在接受投注的公司. /// </summary> /// <returns></returns> public IList<LotteryCompany> GetOpenCompany() { List<LotteryCompany> returnValue = new List<LotteryCompany>(); var companyList = GetTodayCompany(); foreach (var company in companyList) { var openTime = DateTime.Today.Add(company.OpenTime); var closeTime = DateTime.Today.Add(company.CloseTime); var now = DateTime.Now; if (now >= openTime && now <= closeTime) returnValue.Add(company); } return returnValue; } /// <summary> /// 更新今日开奖公司. /// </summary> public void UpdateTodayLotteryCompany() { var companys = ComManager.GetTodayLotteryCompany().ToList(); ; Serialiaze(companys); } private void Serialiaze(IList<LotteryCompany> source) { XmlSerializer xs = new XmlSerializer(source.GetType()); Stream stream = new FileStream(ConfigPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); xs.Serialize(stream, source); stream.Close(); } private IList<LotteryCompany> Deserialize() { XmlSerializer xs = new XmlSerializer(typeof(List<LotteryCompany>)); Stream stream = new FileStream(ConfigPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); List<LotteryCompany> companys = (List<LotteryCompany>)xs.Deserialize(stream); return companys; } } }
Python
UTF-8
6,482
2.671875
3
[]
no_license
import numpy as np import pandas as pd import os import cv2 import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score import torch from torch.utils.data import TensorDataset, DataLoader,Dataset import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.models as models import torchvision.transforms as transforms import torch.optim as optim from torch.optim import lr_scheduler import time import tqdm from PIL import Image from torch.utils.data.sampler import SubsetRandomSampler from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, CosineAnnealingLR train_on_gpu = True num_epochs = 8 num_classes = 2 batch_size = 128 learning_rate = 0.1 # Device configuration device = torch.device('cuda:0') labels = pd.read_csv('data/train_labels.csv') train_path = 'data/train/' test_path = 'data/test/' print(f'{len(os.listdir(train_path))} pictures in train.') print(f'{len(os.listdir(test_path))} pictures in test.') class MyDataset(Dataset): def __init__(self, df_data, data_dir = './', transform=None): super().__init__() self.df = df_data.values self.data_dir = data_dir self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, index): img_name,label = self.df[index] img_path = os.path.join(self.data_dir, img_name+'.tif') image = cv2.imread(img_path) if self.transform is not None: image = self.transform(image) return image, label train, val = train_test_split(labels, stratify=labels.label, test_size=0.1) trans_train = transforms.Compose([transforms.ToPILImage(), transforms.Pad(64, padding_mode='reflect'), transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip(), transforms.RandomRotation(20), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5, 0.5, 0.5])]) trans_valid = transforms.Compose([transforms.ToPILImage(), transforms.Pad(64, padding_mode='reflect'), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5, 0.5, 0.5])]) dataset_train = MyDataset(df_data=train, data_dir=train_path, transform=trans_train) dataset_valid = MyDataset(df_data=val, data_dir=train_path, transform=trans_valid) train_loader = DataLoader(dataset = dataset_train, batch_size=batch_size, shuffle=True, num_workers=0) valid_loader = DataLoader(dataset = dataset_valid, batch_size=batch_size//2, shuffle=False, num_workers=0) def train(model, loss_fn, device, train_loader, optimizer): #training of model model.train() samples_trained = 0 training_loss = 0 #for data set for data, target in train_loader: data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = loss_fn(output, target) training_loss += loss.item() loss.backward() optimizer.step() samples_trained += data.size()[0] print('Trained %d samples, loss: %10f' %(samples_trained, training_loss/samples_trained), end="\r") del data del target training_loss /= samples_trained return training_loss def test(model, loss_fn, device, test_loader): #evaluating model on validation/test dataset model.eval() correct_pred = 0 samples_tested = 0 test_loss = 0 with torch.no_grad(): for data,target in test_loader: data, target = data.to(device), target.to(device) output = model(data) test_loss += loss_fn(output, target).item() pred = output.argmax(dim=1) correct_pred += torch.sum(pred==target).item() samples_tested += data.size()[0] print('Tested %d samples, loss: %10f' %(samples_tested, test_loss/samples_tested), end="\r") accuracy = correct_pred/samples_tested test_loss /= samples_tested return accuracy, test_loss def train_val_test(model, loss_fn, device, optimizer, epoch, name): #function to train model, valdidate data against validation set and finally running the model on the test dataset training_loss_list = [] val_loss_list = [] val_accuracy_list = [] highest_val_loss = 1 test_loss_list = [] #training and validating across epochs for t in range(epoch): print ('Current epoch: ', t+1) training_loss = train(model, loss_fn, device, train_loader, optimizer) print ('') accuracy, val_loss = test(model, loss_fn, device, valid_loader) print ('') if val_loss < highest_val_loss: highest_val_loss = val_loss torch.save(model.state_dict(), name + '.pt') val_accuracy_list.append(accuracy) training_loss_list.append(training_loss) val_loss_list.append(val_loss) #plot and save graph plt.plot(val_loss_list, label='val loss') plt.legend(loc='upper left') plt.savefig(name + '_val_loss.png') plt.clf() plt.plot(training_loss_list, label='training loss') plt.legend(loc='upper left') plt.savefig(name + '_training_loss.png') plt.clf() plt.plot(val_accuracy_list, label='val accuracy') plt.legend(loc='upper left') plt.savefig(name + '.png') plt.clf() #torch.save(model.state_dict(), 'model.ckpt') #run on test set model.load_state_dict(torch.load(name + '.pt')) test_accuracy, test_loss = test(model, loss_fn, device, test_loader) test_loss_list.append(test_loss) print ("Accuracy is: ", test_accuracy) with open(name + '.txt', 'w') as txtfile: txtfile.write("Accuracy is: "+ str(test_accuracy)) plt.plot(test_loss_list, label ='test loss') plt.legend(loc='upper left') plt.savefig(name + '_test_loss.png') plt.clf() isdev = True torch.cuda.empty_cache() device = torch.device('cuda:0') loss_fn = F.cross_entropy epoch = 1 if isdev else 8 learningrate = 0.01 model3 = models.inception_v3(pretrained=True) optimizer = torch.optim.Adamax(model3.parameters(), lr=learning_rate) model3.to(device) train_val_test(model3, loss_fn, device, optimizer, epoch, 'model3')
JavaScript
UTF-8
6,331
2.921875
3
[ "MIT" ]
permissive
'use strict'; var _ = require('lodash'); var expect = require('must'); var Cache = require('../cache'); function loadTests(cb) { cb(null, [ { id: 1, name: 'test 1' }, { id: 2, name: 'test 2' }, { id: 3, name: 'test 3' }, ]); } describe('Cache Tests', function() { it('loads and gets when calling get even before load', function(done) { var cache = new Cache({ loader: loadTests, getter: function(tests, id, cb) { cb(null, _.find(tests, function(test) { return test.id === id; })); } }); // call get with key that the getter function uses return cache.get(2, function(err, testValue) { expect(err).to.be.null(); expect(testValue.id).to.equal(2); expect(testValue.name).to.equal('test 2'); done(); }); }); it('calling load then get pulls from cache without calling load again', function(done) { var callCount = 0; // usedto count function calls function countingLoader(cb) { callCount++; return loadTests(cb); } var cache = new Cache({ loader: countingLoader, getter: function(tests, id, cb) { cb(null, _.find(tests, function(test) { return test.id === id; })); } }); return cache.reload(function(err) { expect(err).to.be.null(); return cache.get(2, function(err, testValue) { expect(err).to.be.null(); expect(testValue.id).to.equal(2); expect(testValue.name).to.equal('test 2'); expect(callCount).to.equal(2); done(); }); }); }); it('once load is called it calls load ever refresh time', function(done) { var count = 0; var currentData = []; function appendTestLoader(cb) { count++; currentData.push({ id: count, name: 'Test ' + count }); cb(null, currentData); } var cache = new Cache({ loader: appendTestLoader, ttl: 10 //sets refrest to 20 ms }); setTimeout(function() { return cache.get(function(err, testData) { expect(err).to.be.null(); expect(testData.length).to.be.gte(4); done(); }); }, 50); }); it('if load takes to long the error callback is called but data stays', function(done) { var firstRun = true; var callCount = 0; function timeoutAfterFirstRunLoad(cb) { loadTests(function(err, data) { expect(err).to.be.null(); if (!firstRun) { // delay call 50 ms setTimeout(function() { cb(null, data); }, 50); } else { // first run return data firstRun = false; cb(null, data); } }); } var cache = new Cache({ loader: timeoutAfterFirstRunLoad, ttl: 10, // 10 ms refresh timeout: 10, // timeout after 10 ms errorCallback: function() { callCount++; } }); setTimeout(function() { expect(callCount).to.be.gt(0); done(); }, 50); }); it('erroring loader calls errorCallback and calls to get return the err', function(done) { var testerror; var cache = new Cache({ loader: function(cb) { cb(new Error('I have an issue.')); }, errorCallback: function(err) { testerror = err; } }); return cache.get(function(err, data) { expect(err).is.error('I have an issue.'); expect(testerror).is.error('I have an issue.'); done(); }); }); it('if load happened without an error at least once will return data on get', function(done) { var callCount = 0; // usedto count function calls function errorAfterFirstLoadLoader(cb) { callCount++; if (callCount == 1) { return loadTests(cb); } else { throw new Error('We have issues.'); } } var cache = new Cache({ loader: errorAfterFirstLoadLoader, ttl: 10 }); setTimeout(function() { return cache.get(function(err, data) { expect(err).to.be.null(); expect(data).to.be.an.array(); done(); }); }, 50); }); /* Working on this it('calling reload mutiple times only reloads once', function(done) { var cache = new Cache({ loader: loadTests, getter: function(tests, id, cb) { cb(null, _.find(tests, function(test) { return test.id === id; })); } }); // call get with key that the getter function uses return cache.get(2, function(err, testValue) { expect(err).to.be.null(); expect(testValue.id).to.equal(2); expect(testValue.name).to.equal('test 2'); done(); }); }); */ it('not passing loader throws expection', function() { var error; try { new Cache(); } catch(ex) { error = ex; } expect(error).is.error('You must pass in an options with a loader function.'); }); it('passing a non number for ttl throws expection', function() { var error; try { new Cache({ loader: loadTests, ttl: 'bad' }); } catch(ex) { error = ex; } expect(error).is.error('The ttl option must be a number and greater than or equal to 0.'); }); it('passing a negitive number for ttl throws expection', function() { var error; try { new Cache({ loader: loadTests, ttl: -1 }); } catch(ex) { error = ex; } expect(error).is.error('The ttl option must be a number and greater than or equal to 0.'); }); it('passing a non number for timeout throws expection', function() { var error; try { new Cache({ loader: loadTests, timeout: 'bad' }); } catch(ex) { error = ex; } expect(error).is.error('The timeout option must be a number and greater than or equal to 0.'); }); it('passing a negitive number for timeout throws expection', function() { var error; try { new Cache({ loader: loadTests, timeout: -1 }); } catch(ex) { error = ex; } expect(error).is.error('The timeout option must be a number and greater than or equal to 0.'); }); it('passing a non function for getter throws expection', function() { var error; try { new Cache({ loader: loadTests, getter: 'bad' }); } catch(ex) { error = ex; } expect(error).is.error('The getter option must be a function.'); }); });
Ruby
UTF-8
211
3.453125
3
[]
no_license
# while not <condition> # <code> # end # until <condition> # <code> # end # <code> until <condition> i = 0 # while not 10 , runs from 0 to 9 until i >= 10 puts "#{i} is the value" i += 1 end
C++
UTF-8
1,792
3.296875
3
[ "MIT" ]
permissive
//UVa - 10660 - Citizen attention offices //Iterative complete search - Generate all possible combinations 25C5 //Coordinate x, y becomes p = x*5 + y, get back x = p / 5, y = p % 5 #include <iostream> #include <cstring> using namespace std; constexpr int INF{ 999999999 }; int dist( int a, int b) { return abs(a/5 - b/5) + abs(a%5 - b%5); } int main() { int t, n; //Problem parameters int pop[25]; //Population int off[5]; //Office locations scanf("%d", &t); while( t-- ) { memset( pop, 0, sizeof(pop) ); scanf("%d", &n); int r, c, p; //Row, column, population while( n-- ) { scanf( "%d %d %d", &r, &c, &p ); pop[r*5 + c] = p; } int minimum{INF}; //Enumerate all 25C5 combinations to choose 5 offices for( int of1{0}; of1 < 21; ++of1) for( int of2{of1 + 1}; of2 < 22; ++of2) for( int of3{of2 + 1}; of3 < 23; ++of3) for( int of4{of3 + 1}; of4 < 24; ++of4) for( int of5{of4 + 1}; of5 < 25; ++of5) { int distance{ 0 }; for( int r{0}; r < 5; ++r ) for( int c{0}; c < 5; ++c ) { int near{ INF }; int loc{r*5 + c}; //Find nearest office near = min(near, dist(of1, loc)); near = min(near, dist(of2, loc)); near = min(near, dist(of3, loc)); near = min(near, dist(of4, loc)); near = min(near, dist(of5, loc)); distance += near * pop[r*5 + c]; } if( distance < minimum ) { minimum = distance; //Store 5 offices off[0] = of1; off[1] = of2; off[2] = of3; off[3] = of4; off[4] = of5; } } for( int i{0}; i < 4; ++i ) cout << off[i] << ' '; cout << off[4] << '\n'; } }
C++
UTF-8
1,460
2.90625
3
[]
no_license
#include <algorithm> #include <iostream> #include <queue> #include <string> #include <time.h> #include <vector> using namespace std; using ll = long long; using pll = pair<ll, ll>; int bfs(vector<vector<int>> &map, vector<vector<bool>> &vertex) { queue<pll> q; int di[] = {-1, 0, 1, 0}, dj[] = {0, 1, 0, -1}; int h = map.size(), w = map[0].size(); vertex[0][0] = true; q.push({0, 0}); while (!q.empty()) { pll now = q.front(); q.pop(); int i = now.first, j = now.second; for (int k = 0; k < 4; k++) { int pi = i + di[k], pj = j + dj[k]; if (pi >= 0 && pi <= h - 1 && pj >= 0 && pj <= w - 1 && !vertex[pi][pj]) { vertex[pi][pj] = true; q.push({pi, pj}); map[pi][pj] = map[i][j] + 1; } } } return map[h-1][w-1]; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); clock_t _start = clock(); int tc; // cin >> tc; tc = 1; for (int i = tc; i--;) { int n, m; cin >> n >> m; vector<vector<int>> map(n, vector<int>(m)); vector<vector<bool>> vertex(n, vector<bool>(m, false)); for (int i = 0; i < n; i++) { string str; cin >> str; for (int j = 0; j < m; j++) { map[i][j] = str[j] - '0'; if (str[j] == '0') vertex[i][j] = true; } } cout << bfs(map, vertex) << '\n'; } float _time = (float)(clock() - _start) / CLOCKS_PER_SEC; // cout << "\ntime : " << _time; }
C++
UTF-8
289
2.796875
3
[]
no_license
#include "CardGampe.h" #include <iostream> using namespace std; CardGampe::CardGampe(int p) { players = p; totalparticipants += p; cout << p << " players have started a new game. there are now " << totalparticipants << " players in total" << endl; } CardGampe::~CardGampe(void) { }
Swift
UTF-8
634
2.78125
3
[]
no_license
// // PicsumCell.swift // Picsum // // Created by Hari Krishna Bikki on 4/12/20. // import UIKit class PicsumCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var author: UILabel! func configure(with picsum: Picsum){ // assign the value to the appropriate cell author.text = picsum.author picsum.image { (image) in self.imageView.image = image } } // To avoid replacing the image and text when scrolling override func prepareForReuse() { author.text = nil imageView.image = nil } }
C
UTF-8
224
2.578125
3
[]
no_license
#include "./include/btree.h" void btree_apply_infix(btree_t *root, int (*applyf)(void *)) { if(root == 0) return ; btree_apply_infix(root->left, *applyf); applyf(root->item); btree_apply_infix(root->right, *applyf); }
C++
UTF-8
1,636
2.546875
3
[]
no_license
#include "TimeClient.h" #include <arale/base/Logging.h> #include <arale/net/EventLoop.h> #include <functional> using namespace arale; using namespace arale::net; using namespace arale::base; TimeClient::TimeClient(EventLoop *loop, const InetAddress &addr) : loop_(loop), client_(loop, "Time Client", addr) { using namespace std::placeholders; client_.setConnectionCallback(std::bind(&TimeClient::onConnection, this, _1)); client_.setMessageCallback(std::bind(&TimeClient::onMessage, this, _1, _2, _3)); } void TimeClient::connect() { client_.connect(); } void TimeClient::onConnection(const TcpConnectionPtr &conn) { LOG_INFO << "TimeClient - " << conn->localAddr().toIpPort() << " -> " << conn->remoteAddr().toIpPort() << " is " << (conn->isConnected() ? "UP" : "DOWN"); if (!conn->isConnected()) { loop_->quitLoop(); } } void TimeClient::onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp receiveTime) { if (buf->readableBytes() >= sizeof(uint32_t)) { const void *data = buf->peek(); uint32_t be32 = *static_cast<const uint32_t *>(data); buf->retrieve(sizeof(uint32_t)); time_t time = sockets::networkToHost32(be32); Timestamp ts(implicit_cast<uint64_t>(time) * Timestamp::kMicroSecondsPerSecond); LOG_INFO << "Server time = " << time << ", " << ts.toFormattedString(); } else { LOG_INFO << conn->getName() << " no enough data " << buf->readableBytes() << " at " << receiveTime.toFormattedString(); } }
PHP
UTF-8
364
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Repositories; interface ClientesRepository { public function find($id); public function findAll(); public function create($data); public function update($id, $data); public function save($object); public function delete($object); public function searchAndPaginate($queryString, $perPage = 15, $pageName = 'page'); }
C
UTF-8
5,624
3.15625
3
[]
no_license
#include<stdio.h> #include<conio.h> #include <malloc.h> #include<math.h> #include<windows.h> int i,j; int n1,m1,n2,m2; int getInt(int* a) //ввод целого числа { int n; do { n=scanf("%d",a); if (n==0 || (*a<=0) ) { printf ("Error"); scanf ("%*[^\n]"); n=0; } }while (n==0); return 1; } int getDouble(float *a) //ввод вещественного числа { float n; do{ n = scanf("%f", a, sizeof(float)); if (n < 0) return 0; if (n == 0) { printf("%s\n", "Error! Repeat input"); scanf("%*c", 0); } } while (n == 0); return 1 ; } typedef struct complex_num { float Re; float Im; }num; void output_matrix( num **p,int n,int m) { for(i=0;i<n;i++) { for(j=0;j<m;j++) if (p[i][j].Im==0.0) printf("\t%-9.1f",p[i][j].Re); else if (p[i][j].Re==0.0) printf ("\t%-0.1fi\t",p[i][j].Im); else printf ("\t%-0.1f + %0.1fi",p[i][j].Re,p[i][j].Im); printf("\n"); } } void input_matrix_complex( num **p,int n,int m) { for(i=0;i<n;i++) { for(j=0;j<m;j++) { printf("Enter[%d][%d]:\t ",i+1,j+1); printf ("Re= "); getDouble(&p[i][j].Re); printf ("\t\tIm= "); getDouble(&p[i][j].Im); } } } void input_matrix_real(num **p,int n,int m) { for(i=0;i<n;i++) { for(j=0;j<m;j++) { printf("Enter [%d][%d]= ",i+1,j+1); getDouble(&p[i][j].Re); p[i][j].Im=0.0; } } } void transpose_matrix( num **p4,num **p,int n,int m) { for(i=0;i<n;i++) { for(j=0;j<m;j++) { p4[i][j].Re=p[j][i].Re; p4[i][j].Im=-p[j][i].Im; } } } void plus_matrix( num **p,num **p1,num **p2,int n,int m) { for(i=0;i<n;i++) { for(j=0;j<m;j++) { p[i][j].Re = p1[i][j].Re + p2[i][j].Re; p[i][j].Im = p1[i][j].Im + p2[i][j].Im; } } } void multiplication_matrix( num **p,num **p1, num **p2,int n,int m, int q) { int k; for(i=0;i<n;i++) for(j=0;j<m;j++) { p[i][j].Re=0.0; p[i][j].Im=0.0; for(k=0;k<q;k++) { p[i][j].Re+=p1[i][k].Re*p2[k][j].Re-p1[i][k].Im*p2[k][j].Im; p[i][j].Im+=p1[i][k].Re*p2[k][j].Im+p1[i][k].Im*p2[k][j].Re; } } } void main() { int a; num **p,**p1,**p2; printf ("Elements are complex or real number?\n"); printf ("1. Complex number\n"); printf ("2. Real number\n"); do{ getInt(&a); switch (a) { case 1:system("cls");printf ("\n------------------------Complex num-------------------------\n"); break; case 2:system("cls");printf ("\n------------------------Real num-------------------------\n"); break; default: printf ("Error! Repeat!");a=0; } }while (a==0); printf ("How many lines of matrix1? n1="); getInt(&n1); printf ("How many columns of matrix1? m1="); getInt(&m1); p1=(num**)malloc(n1*m1*sizeof(num)); printf ("\nMatrix 1:\n"); if (a==1) input_matrix_complex(p1,n1,m1); if (a==2) input_matrix_real(p1,n1,m1); output_matrix(p1,n1,m1); printf ("\nHow many lines of matrix2? n2="); getInt(&n2); printf ("How many columns of matrix2? m2="); getInt(&m2); p2=(num**)malloc(n2*m2*sizeof(num)); printf ("\nMatrix 2:\n"); if (a==1) input_matrix_complex(p2,n2,m2); if (a==2) input_matrix_real(p2,n2,m2); output_matrix(p2,n2,m2); printf ("\n------------------------------------------------------------\n"); if (n1==m1) { printf ("Transpose matrix1:\n"); p=(num**)malloc(n1*sizeof(num)); for (i=0;i<n1;i++) { p[i]=(num*)malloc(m1*sizeof(num)); } transpose_matrix(p,p1,n1,m1); output_matrix(p,n1,m1); free(p); } else printf ("Matrix1 cannot transpose (ne mozhet transponirovat)"); printf ("\n------------------------------------------------------------\n"); if (n2==m2) { printf ("Transpose matrix2:\n"); p=(num**)malloc(n2*sizeof(num)); for (i=0;i<n2;i++) { p[i]=(num*)malloc(m2*sizeof(num)); } transpose_matrix(p,p2,n2,m2); output_matrix(p,n2,m2); free(p); } else printf ("Matrix2 cannot transpose (ne mozhet transponirovat)"); printf ("\n------------------------------------------------------------\n"); if (n1!=n2 || m1!=m2) printf ("Can not plus matrix1 and matrix2"); else { printf ("\nSum matrix1 + matrix2:\n"); p=(num**)malloc(n1*sizeof(num)); for (i=0;i<n1;i++) { p[i]=(num*)malloc(m1*sizeof(num)); } plus_matrix(p,p1,p2,n1,m1); output_matrix(p,n1,m1); free(p); } printf ("\n------------------------------------------------------------\n"); if (m1==n2) { printf ("\nMultiplication matrix1 X matrix2:\n"); p=(num**)malloc(n1*sizeof(num)); for (i=0;i<n1;i++) { p[i]=(num*)malloc(m2*sizeof(num)); } multiplication_matrix(p,p1,p2,n1,m2,m1); output_matrix(p,n1,m2); } else printf ("\nMatrix1 can not multiply by matrix2 (ne mozhet umnozhit)"); free(p1); free(p2); getch(); }
Swift
UTF-8
4,032
3.171875
3
[ "Apache-2.0", "Swift-exception", "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* This source file is part of the Swift.org open source project Copyright (c) 2019 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// A resource to bundle with the Swift package. /// /// If a Swift package declares a Swift tools version of 5.3 or later, it can include resource files. /// Similar to source code, the Swift Package Manager scopes resources to a target, so you must put them /// into the folder that corresponds to the target they belong to. /// For example, any resources for the `MyLibrary` target must reside in `Sources/MyLibrary`. /// Use subdirectories to organize your resource files in a way that simplifies file identification and management. /// For example, put all resource files into a directory named `Resources`, /// so they reside at `Sources/MyLibrary/Resources. /// By default, the Swift Package Manager handles common resources types for Apple platforms automatically. /// For example, you don’t need to declare XIB files, storyboards, Core Data file types, and asset catalogs /// as resources in your package manifest. /// However, you must explicitly declare other file types—for example image files—as resources /// using the `process(_:localization:)`` or `copy(_:)`` rules. Alternatively, exclude resource files from a target /// by passing them to the target initializer’s `exclude` parameter. public struct Resource: Encodable { /// Defines the explicit type of localization for resources. public enum Localization: String, Encodable { /// A constant that represents default internationalization. case `default` /// A constant that represents base internationalization. case base } /// The rule for the resource. private let rule: String /// The path of the resource. private let path: String /// The explicit type of localization for the resource. private let localization: Localization? private init(rule: String, path: String, localization: Localization?) { self.rule = rule self.path = path self.localization = localization } /// Applies a platform-specific rule to the resource at the given path. /// /// Use the `process` rule to process resources at the given path /// according to the platform it builds the target for. For example, the /// Swift Package Manager may optimize image files for platforms that /// support such optimizations. If no optimization is available for a file /// type, the Swift Package Manager copies the file. /// /// If the given path represents a directory, the Swift Package Manager /// applies the process rule recursively to each file in the directory. /// /// If possible use this rule instead of `copy(_:)`. /// /// - Parameters: /// - path: The path for a resource. /// - localization: The explicit localization type for the resource. public static func process(_ path: String, localization: Localization? = nil) -> Resource { return Resource(rule: "process", path: path, localization: localization) } /// Applies the copy rule to a resource at the given path. /// /// If possible, use `process(_:localization:)`` and automatically apply optimizations /// to resources. /// /// If your resources must remain untouched or must retain a specific folder structure, /// use the `copy` rule. It copies resources at the given path, as is, to the top level /// in the package’s resource bundle. If the given path represents a directory, Xcode preserves its structure. /// /// - Parameters: /// - path: The path for a resource. public static func copy(_ path: String) -> Resource { return Resource(rule: "copy", path: path, localization: nil) } }
Swift
UTF-8
406
2.609375
3
[]
no_license
// // Declarations.swift // // // Created by // import UIKit func mainThread(_ code: @escaping (() -> ())) { DispatchQueue.main.async { code() } } func secondThread(_ code: @escaping (() -> ())) { DispatchQueue.global(qos: .background).async { code() } } func getScreenWidthPercentage(_ percentage: CGFloat) -> CGFloat { UIScreen.main.bounds.width * percentage }
Python
UTF-8
1,998
3.078125
3
[]
no_license
from django.shortcuts import render # render will use for showing the html file on browser from .models import Prime #Prime is models that is requre to import data to database from here import datetime def checkprime(x): #it is function that check is it prime or not if x<=1: return 0 else: for y in range(2,x): if x%y==0: return 0 return 1 def index(request): #it is the index function when directory in main that function can run using urls in urls.py return render(request, 'index.html') def calculate(request): if request.method == "POST": totalprime = "" a = request.POST.get('f_int','') b = request.POST.get('s_int','') try: # we have use try except when we can not change into int and it is give error when type conversion str to int int(a) int(b) except ValueError: return render(request,'error.html') # when something is missing then run error.html c=int(a) d=int(b) timea = datetime.datetime.now() for i in range(c,d): if checkprime(i)==1: totalprime +=str(i) + " " timeb = datetime.datetime.now() totaltime=(int(timeb.strftime("%H"))-int(timea.strftime("%H")))*60.0*60.0+(int(timeb.strftime("%M"))-int(timea.strftime("%M")))*60.0+(int(timeb.strftime("%S"))-int(timea.strftime("%S")))+(int(timeb.strftime("%f"))-int(timea.strftime("%f")))*0.000001 timelaps = str(totaltime) #total time calculate using diffrence in starting time and ending time of this program contact = Prime(prime_f=a, prime_s=b, times=timea,timelaps=timelaps, totalprime=totalprime) contact.save() #we have save the data in database else : return render(request, 'index.html') params = {'purpose': totalprime,'a':a,'b':b} #these parameters we have use to show the total prime no. in html page return render(request,'calculate.html',params)
Java
UTF-8
14,043
2.453125
2
[]
no_license
/** * */ package au.edu.anu.dspace.client.swordv2.digitisation.crosswalk; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import au.edu.anu.dspace.client.swordv2.digitisation.iiirecord.IIIRECORD; import au.edu.anu.dspace.client.swordv2.digitisation.iiirecord.MARCSUBFLD; import au.edu.anu.dspace.client.swordv2.digitisation.iiirecord.VARFLD; /** * @author Rahul Khanna * */ public abstract class AbstractCrosswalk implements Crosswalk { private static final String SUBFIELDS_A_TO_Z = "abcdefghijklmnopqrstuvwxyz"; protected static final String PARAGRAPH_BREAK = System.lineSeparator() + System.lineSeparator(); private String concatenateSubfields(List<MARCSUBFLD> marcSubFields, String subfieldIndicators, String subfieldSeparator) { StringBuilder conc = new StringBuilder(); char[] siChars = subfieldIndicators.toCharArray(); for (int iSubFldIndicator = 0; iSubFldIndicator < siChars.length; iSubFldIndicator++) { for (int iMarcSubField = 0; iMarcSubField < marcSubFields.size(); iMarcSubField++) { if (marcSubFields.get(iMarcSubField).getSUBFIELDINDICATOR() .equals(String.valueOf(siChars[iSubFldIndicator]))) { conc.append(marcSubFields.get(iMarcSubField).getSUBFIELDDATA()); if (iMarcSubField < marcSubFields.size() - 1) { conc.append(subfieldSeparator); } // not breaking as there may be multiple subfields with // same subfieldindicator } } } return conc.toString().trim(); } private String getIndicator1(VARFLD marcTagVarField) { return marcTagVarField.getMarcInfo().getINDICATOR1(); } private String getIndicator2(VARFLD marcTagVarField) { return marcTagVarField.getMarcInfo().getINDICATOR2(); } private List<VARFLD> getVarFields(IIIRECORD iiiRecord, String... marcTags) { List<VARFLD> marcTagVarFields = new ArrayList<>(); for (VARFLD varFld : iiiRecord.getVarFields()) { String curMarcTag = varFld.getMarcInfo().getMARCTAG(); for (String iMarcTag : marcTags) { if (curMarcTag.equals(iMarcTag)) { marcTagVarFields.add(varFld); } } } sortTagFieldsBySequence(marcTagVarFields); return marcTagVarFields; } private int parseInt(String str) { return Integer.parseInt(str); } private void sortTagFieldsBySequence(List<VARFLD> marcTagVarFields) { marcTagVarFields.sort(new Comparator<VARFLD>() { @Override public int compare(VARFLD o1, VARFLD o2) { int o1SeqNum = parseInt(o1.getHEADER().getSEQUENCENUM()); int o2SeqNum = parseInt(o2.getHEADER().getSEQUENCENUM()); if (o1SeqNum < o2SeqNum) { return -1; } else if (o1SeqNum > o2SeqNum) { return 1; } else { return 0; } } }); } private String stripLeadingTrailingChars(String original, String leadingChars, String trailingChars) { StringBuilder sb = new StringBuilder(original); // strip leading chars boolean repeat = false; do { char firstChar = sb.charAt(0); repeat = false; for (char c : leadingChars.toCharArray()) { if (firstChar == c) { sb.deleteCharAt(0); repeat = true; break; } } } while (repeat); // strip trailing chars repeat = false; do { char lastChar = sb.charAt(sb.length() - 1); repeat = false; for (char c : trailingChars.toCharArray()) { if (lastChar == c) { sb.deleteCharAt(sb.length() - 1); repeat = true; break; } } } while (repeat); return sb.toString(); } // ================================= protected List<String> extractAccessRights(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "506")) { if (getIndicator1(marcTagVarField).equals("1")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } } return values; } protected List<String> extractAccrualMethods(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "541")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "cd", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } return values; } protected List<String> extractAlternativeTitles(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "130", "210", "240", "242", "246", "730", "740")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " /")); } } return values; } protected List<String> extractAuthors(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "100")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "a", ""); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ,")); } } for (VARFLD marcTagVarField : getVarFields(iiiRecord, "700")) { if (concatenateSubfields(marcTagVarField.getMarcSubfld(), "e", "").equalsIgnoreCase("author")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "a", ""); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ,")); } } } return values; } protected String extractBNumber(IIIRECORD iiiRecord) { String bNumber = iiiRecord.getRecordInfo().getRECORDKEY().trim(); return bNumber; } protected List<String> extractColleges(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "710")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "ab", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } return values; } protected List<String> extractDatesCopyrighted(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "260", "264")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "c", ""); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " [", " .]")); } } return values; } protected List<String> extractDatesPublished(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "260", "264")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "c", ""); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " [", " .]")); } } return values; } protected List<String> extractDissertationNotes(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "502")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "a", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } return values; } protected List<String> extractFormatExtents(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "300")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "a", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " +:")); } } return values; } protected List<String> extractFormatMediums(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "340")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "a", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " +")); } } return values; } protected List<String> extractLanguages(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "546")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } return values; } protected List<String> extractPublishers(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "260", "264")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "ab", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ,")); } } return values; } protected List<String> extractSubjectClassifications(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "084")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } return values; } protected List<String> extractSubjectsDdc(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "082")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } return values; } protected List<String> extractSubjectsLcc(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "050", "090")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } return values; } protected List<String> extractSubjectsLcsh(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "600", "610", "611", "630", "650")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } for (VARFLD marcTagVarField : getVarFields(iiiRecord, "651")) { if (getIndicator2(marcTagVarField).equalsIgnoreCase("0")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } } return values; } protected List<String> extractAbstracts(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "520")) { if (getIndicator1(marcTagVarField).equals("3")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "ab", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } } if (values.size() > 0) { // concatenate all summaries into one value separated by a line separator StringBuilder concatenatedSummary = new StringBuilder(); for (int i = 0; i < values.size(); i++) { concatenatedSummary.append(values.get(i)); if (i < values.size() - 1) { concatenatedSummary.append(PARAGRAPH_BREAK); } } values = new ArrayList<>(1); values.add(concatenatedSummary.toString()); } return values; } protected List<String> extractSummaries(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "520")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } if (values.size() > 0) { // concatenate all summaries into one value separated by a line separator StringBuilder concatenatedSummary = new StringBuilder(); for (int i = 0; i < values.size(); i++) { concatenatedSummary.append(values.get(i)); if (i < values.size() - 1) { concatenatedSummary.append(PARAGRAPH_BREAK); } } values = new ArrayList<>(1); values.add(concatenatedSummary.toString()); } return values; } protected List<String> extractSupervisors(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "700")) { if (concatenateSubfields(marcTagVarField.getMarcSubfld(), "e", "").equalsIgnoreCase("degree supervisor")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "a", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ,")); } } } return values; } protected List<String> extractTableOfContents(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "505")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), SUBFIELDS_A_TO_Z, " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " ")); } } return values; } protected List<String> extractTitles(IIIRECORD iiiRecord) { List<String> values = new ArrayList<>(); for (VARFLD marcTagVarField : getVarFields(iiiRecord, "245")) { String value = concatenateSubfields(marcTagVarField.getMarcSubfld(), "ab", " "); if (value != null && value.length() > 0) { values.add(stripLeadingTrailingChars(value, " ", " /")); } } return values; } }
Python
UTF-8
7,607
2.703125
3
[ "Apache-2.0" ]
permissive
import math import numpy as np import torch from torch import nn from butterfly.complex_utils import complex_mul, conjugate def toeplitz_krylov_transpose_multiply(v, u, f=0.0): """Multiply Krylov(Z_f, v_i)^T @ u. Parameters: v: (nstack, rank, n) u: (batch_size, n) f: real number Returns: product: (batch, nstack, rank, n) """ _, n = u.shape _, _, n_ = v.shape assert n == n_, 'u and v must have the same last dimension' if f != 0.0: # cycle version # Computing the roots of f mod = abs(f) ** (torch.arange(n, dtype=u.dtype, device=u.device) / n) if f > 0: arg = torch.stack((torch.ones(n, dtype=u.dtype, device=u.device), torch.zeros(n, dtype=u.dtype, device=u.device)), dim=-1) else: # Find primitive roots of -1 angles = torch.arange(n, dtype=u.dtype, device=u.device) / n * np.pi arg = torch.stack((torch.cos(angles), torch.sin(angles)), dim=-1) eta = mod[:, np.newaxis] * arg eta_inverse = (1.0 / mod)[:, np.newaxis] * conjugate(arg) u_f = torch.ifft(eta_inverse * u[..., np.newaxis], 1) v_f = torch.fft(eta * v.unsqueeze(-1), 1) uv_f = complex_mul(u_f.unsqueeze(1).unsqueeze(1), v_f) uv = torch.fft(uv_f, 1) # We only need the real part of complex_mul(eta, uv) return eta[..., 0] * uv[..., 0] - eta[..., 1] * uv[..., 1] else: u_f = torch.rfft(torch.cat((u.flip(1), torch.zeros_like(u)), dim=-1), 1) v_f = torch.rfft(torch.cat((v, torch.zeros_like(v)), dim=-1), 1) uv_f = complex_mul(u_f.unsqueeze(1).unsqueeze(1), v_f) return torch.irfft(uv_f, 1, signal_sizes=(2 * n, ))[..., :n].flip(3) def toeplitz_krylov_multiply(v, w, f=0.0): """Multiply \sum_i Krylov(Z_f, v_i) @ w_i. Parameters: v: (nstack, rank, n) w: (batch_size, nstack, rank, n) f: real number Returns: product: (batch, nstack, n) """ _, nstack, rank, n = w.shape nstack_, rank_, n_ = v.shape assert n == n_, 'w and v must have the same last dimension' assert rank == rank_, 'w and v must have the same rank' assert nstack == nstack_, 'w and v must have the same nstack' if f != 0.0: # cycle version # Computing the roots of f mod = abs(f) ** (torch.arange(n, dtype=w.dtype, device=w.device) / n) if f > 0: arg = torch.stack((torch.ones(n, dtype=w.dtype, device=w.device), torch.zeros(n, dtype=w.dtype, device=w.device)), dim=-1) else: # Find primitive roots of -1 angles = torch.arange(n, dtype=w.dtype, device=w.device) / n * np.pi arg = torch.stack((torch.cos(angles), torch.sin(angles)), dim=-1) eta = mod[:, np.newaxis] * arg eta_inverse = (1.0 / mod)[:, np.newaxis] * conjugate(arg) w_f = torch.fft(eta * w[..., np.newaxis], 1) v_f = torch.fft(eta * v[..., np.newaxis], 1) wv_sum_f = complex_mul(w_f, v_f).sum(dim=2) wv_sum = torch.ifft(wv_sum_f, 1) # We only need the real part of complex_mul(eta_inverse, wv_sum) return eta_inverse[..., 0] * wv_sum[..., 0] - eta_inverse[..., 1] - wv_sum[..., 1] else: w_f = torch.rfft(torch.cat((w, torch.zeros_like(w)), dim=-1), 1) v_f = torch.rfft(torch.cat((v, torch.zeros_like(v)), dim=-1), 1) wv_sum_f = complex_mul(w_f, v_f).sum(dim=2) return torch.irfft(wv_sum_f, 1, signal_sizes=(2 * n, ))[..., :n] def toeplitz_mult(G, H, x, cycle=True): """Multiply \sum_i Krylov(Z_f, G_i) @ Krylov(Z_f, H_i) @ x. Parameters: G: Tensor of shape (nstack, rank, n) H: Tensor of shape (nstack, rank, n) x: Tensor of shape (batch_size, n) cycle: whether to use f = (1, -1) or f = (0, 0) Returns: product: Tensor of shape (batch_size, nstack, n) """ # f = (1,-1) if cycle else (1,1) f = (1, -1) if cycle else (0, 0) transpose_out = toeplitz_krylov_transpose_multiply(H, x, f[1]) return toeplitz_krylov_multiply(G, transpose_out, f[0]) class ToeplitzlikeLinear(nn.Module): def __init__(self, in_size, out_size, rank=4, bias=True, corner=False): super().__init__() self.in_size = in_size self.out_size = out_size self.nstack = int(math.ceil(out_size / self.in_size)) self.rank = rank assert not corner, 'corner not currently supported' self.corner = corner init_stddev = math.sqrt(1. / (rank * in_size)) self.G = nn.Parameter(torch.randn(self.nstack, rank, in_size) * init_stddev) self.H = nn.Parameter(torch.randn(self.nstack, rank, in_size) * init_stddev) self.G._is_structured = True # Flag to avoid weight decay self.H._is_structured = True self.register_buffer('reverse_idx', torch.arange(in_size - 1, -1, -1)) if bias: self.bias = nn.Parameter(torch.Tensor(out_size)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): """Initialize bias the same way as torch.nn.Linear.""" if self.bias is not None: bound = 1 / math.sqrt(self.in_size) nn.init.uniform_(self.bias, -bound, bound) def forward(self, input): """ Parameters: input: (batch, *, in_size) Return: output: (batch, *, out_size) """ u = input.view(np.prod(input.size()[:-1]), input.size(-1)) batch = u.shape[0] # output = toeplitz_mult(self.G, self.H, input, self.corner) # return output.reshape(batch, self.nstack * self.size) n = self.in_size v = self.H # u_f = torch.rfft(torch.cat((u.flip(1), torch.zeros_like(u)), dim=-1), 1) u_f = torch.rfft(torch.cat((u[:, self.reverse_idx], torch.zeros_like(u)), dim=-1), 1) v_f = torch.rfft(torch.cat((v, torch.zeros_like(v)), dim=-1), 1) uv_f = complex_mul(u_f.unsqueeze(1).unsqueeze(1), v_f) # transpose_out = torch.irfft(uv_f, 1, signal_sizes=(2 * n, ))[..., :n].flip(3) transpose_out = torch.irfft(uv_f, 1, signal_sizes=(2 * n, ))[..., self.reverse_idx] v = self.G w = transpose_out w_f = torch.rfft(torch.cat((w, torch.zeros_like(w)), dim=-1), 1) v_f = torch.rfft(torch.cat((v, torch.zeros_like(v)), dim=-1), 1) wv_sum_f = complex_mul(w_f, v_f).sum(dim=2) output = torch.irfft(wv_sum_f, 1, signal_sizes=(2 * n, ))[..., :n] output = output.reshape(batch, self.nstack * self.in_size)[:, :self.out_size] if self.bias is not None: output = output + self.bias return output.view(*input.size()[:-1], self.out_size) def extra_repr(self): return 'in_size={}, out_size={}, bias={}, rank={}, corner={}'.format( self.in_size, self.out_size, self.bias is not None, self.rank, self.corner ) class Toeplitzlike1x1Conv(ToeplitzlikeLinear): def forward(self, input): """ Parameters: input: (batch, c, h, w) Return: output: (batch, nstack * c, h, w) """ # TODO: this is for old code with square Toeplitzlike, need to be updated batch, c, h, w = input.shape input_reshape = input.view(batch, c, h * w).transpose(1, 2).reshape(-1, c) output = super().forward(input_reshape) return output.view(batch, h * w, self.nstack * c).transpose(1, 2).view(batch, self.nstack * c, h, w)
SQL
UTF-8
196
3.546875
4
[]
no_license
SELECT sum(salary) FROM developers as dev LEFT JOIN dev_skills AS dsk ON dev.id = dsk.developer_id LEFT JOIN skills AS sk ON dsk.skills_id = sk.skill_id WHERE sk.skill_description LIKE 'java';
Java
UTF-8
495
1.828125
2
[]
no_license
package com.wuhan_data.mapper; import java.util.List; import java.util.Map; import com.wuhan_data.pojo.ColPlate; import com.wuhan_data.pojo.IndiCorrelative; public interface ColPlateMapper { public int add(ColPlate colPlate); public void delete(int id); public int update(ColPlate colPlate); public List<ColPlate> getlist(Map map);//根据栏目id查找所有指标 public int total(int cid);//查询数量 public int updateShow(ColPlate colPlate); //管理显示与否 }