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
|
---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 1,184 | 2.53125 | 3 |
[] |
no_license
|
using System;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.IO;
using System.Text;
using System.Xml.Linq;
using OpenXmlPowerTools;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
public class DocxToHtml {
static void Main(string[] args) {
}
public static string Convert(string inputPath) {
var fi = new FileInfo(inputPath);
byte[] byteArray = File.ReadAllBytes(fi.FullName);
using (MemoryStream memoryStream = new MemoryStream()) {
memoryStream.Write(byteArray, 0, byteArray.Length);
using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true)) {
HtmlConverterSettings settings = new HtmlConverterSettings() {
FabricateCssClasses = true,
RestrictToSupportedLanguages = false,
RestrictToSupportedNumberingFormats = false
};
XElement html = HtmlConverter.ConvertToHtml(wDoc, settings);
return html.ToString(SaveOptions.DisableFormatting);
}
}
}
}
|
Python
|
UTF-8
| 9,704 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
import cv2 as cv
import numpy as np
from sklearn.feature_extraction.image import extract_patches_2d
from raisr.utils import is_image, build_goal_func
import os
import pickle
from raisr.hash_key_gen import gen_hash_key
from raisr.processor import UNSHARP_MASKING_5x5_KERNEL
from datetime import datetime
import time
from pathos import multiprocessing as mp
from scipy.optimize import minimize
class RAISR:
def __init__(self, upscale_factor=2,
angle_base=24, strength_base=9, patch_size=9):
"""RAISR model
:param upscale_factor: upsampling factor;
:param angle_base: factor for angle
"""
self.up_factor = upscale_factor
self.angle_base = angle_base
self.strength_base = strength_base
self.patch_size = patch_size
self.H = None
def __repr__(self):
return f"<RAISR up_factor={self.up_factor}>"
def train(self, lr_path: str, hr_path: str, sharpen: bool = True, dst="./model"):
"""The train step of RAISR model, where RAISR learn a set of filters from data
:param sharpen: If true, use unsharp masking kernel to enhance HR images,
:param lr_path: LR images' dir path,
:param hr_path: HR images' dir path,
:param dst: Where to save the model,
:return: void, use pickle to write H to `dst`.
"""
# initialization
QS_DIR = os.path.join(dst, "Qs")
VS_DIR = os.path.join(dst, "Vs")
if not os.path.exists(dst):
os.mkdir(dst)
if not os.path.exists(QS_DIR):
os.mkdir(QS_DIR)
if not os.path.exists(VS_DIR):
os.mkdir(VS_DIR)
d2 = self.patch_size ** 2
t2 = self.up_factor ** 2
Q = np.zeros((self.angle_base, self.strength_base, t2, d2, d2))
V = np.zeros((self.angle_base, self.strength_base, t2, d2, 1))
H = np.zeros((self.angle_base, self.strength_base, t2, d2, 1))
# compute pad pixel
# left is same as top, and right is same as bottom
top_pad = (self.patch_size - 1) // 2
if self.patch_size % 2 == 0:
bottom_pad = top_pad + 1
else:
bottom_pad = top_pad
lr_files = sorted(filter(is_image, os.listdir(lr_path)))
hr_filrs = sorted(filter(is_image, os.listdir(hr_path)))
total = len(lr_files)
start = datetime.now()
print(f"*****START TO TRAIN RAISR FOR {total} IMAGE PAIRS*****\n")
def f(item):
idx, lr_fname = item
print("*****START TO PROCESS {}/{} IMAGE PAIR AT {}*****".format(
idx + 1, total, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
hr_fname = hr_filrs[idx]
lr = cv.imread(os.path.join(lr_path, lr_fname))
hr = cv.imread(os.path.join(hr_path, hr_fname))
h, w = hr.shape[:2]
lr_upscaled = cv.resize(lr, (w, h))
# Extrat the luminance in YCrCb mode of a image
lr_y = cv.cvtColor(lr_upscaled, cv.COLOR_BGR2YCrCb)[:, :, 0]
hr_y = cv.cvtColor(hr, cv.COLOR_BGR2YCrCb)[:, :, 0]
# normalize
lr_y = (lr_y - lr_y.min()) / (lr_y.max() - lr_y.min())
# Pad the image
lr_y = cv.copyMakeBorder(lr_y, top_pad, bottom_pad, top_pad, bottom_pad, borderType=cv.BORDER_REPLICATE)
# optionally sharpen
if sharpen:
hr_y = cv.filter2D(hr_y, -1, UNSHARP_MASKING_5x5_KERNEL, borderType=cv.BORDER_REPLICATE)
hr_y = (hr_y - hr_y.min()) / (hr_y.max() - hr_y.min())
patches = extract_patches_2d(lr_y, (self.patch_size, self.patch_size))
for idx1, patch in enumerate(patches):
# origin coordinate
x = idx1 // w
y = idx1 % w
# compute pixel type
t = x % self.up_factor * self.up_factor + y % self.up_factor
# conpute hash key j
angle, strength = gen_hash_key(patch, self.angle_base, self.strength_base)
patch: np.ndarray
# compute p_k
a = patch.ravel().reshape((1, -1))
# compute x_k, the true HR pixel
b = hr_y[x, y]
a_T_a = a.T.dot(a)
a_T_b = a.T.dot(b)
# increase date by flip and rotate
rot90 = self.angle_base // 4
for i in range(4):
angle1 = (angle + i * rot90) % self.angle_base
Q[angle1, strength, t] += a_T_a
V[angle1, strength, t] += a_T_b
a_T_a = np.rot90(a_T_a)
a_T_a = np.flipud(a_T_a)
flipud = self.angle_base - angle
for i in range(4):
angle1 = (flipud + i * rot90) % self.angle_base
Q[angle1, strength, t] += a_T_a
V[angle1, strength, t] += a_T_b
a_T_a = np.rot90(a_T_a)
with open(f"{QS_DIR}/Q_{lr_fname}.dat", "wb") as Q_f:
pickle.dump(Q, Q_f)
with open(f"{VS_DIR}/V_{lr_fname}.dat", "wb") as V_f:
pickle.dump(V, V_f)
print("*****END TO PROCESS {}/{} IMAGE PAIR AT {}*****".format(
idx + 1, total, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
with mp.Pool() as ps:
ps.map(f, enumerate(lr_files))
print(f"*****START TO SOLVE THE OPTIMIZATION PROBLEM AT {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*****")
for Q_f in os.listdir(f"{QS_DIR}"):
with open(f"{QS_DIR}/{Q_f}", "rb") as f:
Q += pickle.load(f)
for V_f in os.listdir(f"{VS_DIR}"):
with open(f"{VS_DIR}/{V_f}", "rb") as f:
V += pickle.load(f)
# compute H
for angle in range(self.angle_base):
for strength in range(self.strength_base):
for t in range(t2):
# solve the optimization problem by a conjugate gradient solver
print(Q[angle, strength, t], V[angle, strength, t])
goal_func = build_goal_func(Q[angle, strength, t],
V[angle, strength, t])
res = minimize(goal_func, np.random.random((d2, 1)), method='CG')
H[angle, strength, t] = res.x[:, np.newaxis]
print(f"*****END TO SOLVE THE OPTIMIZATION PROBLEM AT {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*****\n")
# write the filter
end = datetime.now()
timestamp = time.mktime(end.timetuple())
dump_path = os.path.join(dst, "raisr_filter_{}x{}_{}x{}x{}_{:.0f}.pkl".format(
self.patch_size, self.patch_size,
self.angle_base, self.strength_base, t2,
timestamp))
with open(dump_path, "wb") as f:
pickle.dump(H, f)
self.H = H
print("*****FINISH TRAIN, COSTS {}s, RESULT DUMP TO {}*****\n".format((end - start).total_seconds(), dump_path))
def cheap_upscale(self, image: np.ndarray, interpolation=cv.INTER_LINEAR) -> np.ndarray:
hight, width = image.shape[:2]
return cv.resize(image, (width * self.up_factor, hight * self.up_factor), interpolation=interpolation)
def up_scale(self, image: np.ndarray, H=None) -> np.ndarray:
""" Use raisr algorithm to upscale the image.
The raisr algorithm only process the y channel of image's ycrcb mode, the other two channel still use cheap
upscale method.
:param H: pre-trained filters
:param image: Image with BGR mode
:return: Upscaled image with BGR mode
"""
if H is not None and self.H is None:
with open(H, "rb") as f:
self.H = pickle.load(f)
h, w = image.shape[:2]
h *= self.up_factor
w *= self.up_factor
img_upscaled = cv.resize(image, (w, h), interpolation=cv.INTER_LINEAR)
if self.H is None:
raise Exception("The model have not learned the filters")
# cheap upscale and pad
top_pad = (self.patch_size - 1) // 2
if self.patch_size % 2 == 0:
bottom_pad = top_pad + 1
else:
bottom_pad = top_pad
img_upscaled_ycrcb = cv.cvtColor(img_upscaled, cv.COLOR_BGR2YCrCb)
y = img_upscaled_ycrcb[:, :, 0]
crcb = img_upscaled_ycrcb[:, :, 1:]
# normalize
m = y.max()
n = y.min()
y = (y - n) / (m - n)
y_padded = cv.copyMakeBorder(y, top_pad, bottom_pad, top_pad, bottom_pad, cv.BORDER_REPLICATE)
start = datetime.now()
# fit the HR y channel
patches = extract_patches_2d(y_padded, (self.patch_size, self.patch_size))
def f(item):
idx, patch = item
x = idx // w
y = idx % w
# compute pixel type
t = x % self.up_factor * self.up_factor + y % self.up_factor
# conpute hash key j
angle, strength = gen_hash_key(patch, self.angle_base, self.strength_base)
filter1d = self.H[angle, strength, t]
return patch.ravel().T.dot(filter1d)
with mp.Pool() as ps:
ret = ps.map(f, enumerate(patches))
hr_y = np.array(ret).reshape((h, w))
# de-normalize
hr_y = hr_y * (m - n) + n
# cheap upscale the left two channel
hr_ycrcb = np.dstack((hr_y.astype(np.uint8), crcb))
end = datetime.now()
print(f"*****FINISH UPSCALE, TOTAL COSTS {(end - start).total_seconds()}s*****")
return cv.cvtColor(hr_ycrcb, cv.COLOR_YCrCb2BGR)
|
Markdown
|
UTF-8
| 4,578 | 2.8125 | 3 |
[] |
no_license
|
---
title: 'MySQL general log'
category: mysql
excerpt: 'Let''s run through how you can setup and configure the MySQL general log.'
updated_by: 197c1509-8dff-4d72-9898-334084519619
updated_at: 1609787181
video: 'https://www.youtube.com/watch?v=fyZPlC6iSXI'
id: a2fb5146-0af3-4923-ac25-2b9d98ecc154
content:
-
type: paragraph
content:
-
type: text
text: 'The general log records every query that the MySQL database processes, with the parameters visible. This means you are able to see the values used in a bound query.'
-
type: paragraph
content:
-
type: text
text: 'There are two ways to enable the MySQL general log:'
-
type: ordered_list
attrs:
order: 1
content:
-
type: list_item
content:
-
type: paragraph
content:
-
type: text
text: 'Enable it in the configuration file. This will enable the general log when MySQL starts.'
-
type: list_item
content:
-
type: paragraph
content:
-
type: text
text: 'You can run a global query to enable the general log while the MySQL server is running.'
-
type: heading
attrs:
level: 3
content:
-
type: text
text: 'Enable via configuration file'
-
type: paragraph
content:
-
type: text
text: 'To enable the general log via the configuration file, add the following to your configuration file (example path is '
-
type: text
marks:
-
type: code
text: /etc/my.cnf
-
type: text
text: '):'
-
type: set
attrs:
values:
type: gist_content
gist_id: 1e12d01d52d2334d52ee4eca37bb12b6
gist_filename: af1a034f-95f6-4a29-9ecd-29f78cadaa5d.cnf
code: |
// my.cnf
[mysqld]
general_log = 1
log_output = 'table'
extension: cnf
-
type: paragraph
content:
-
type: text
text: 'You must restart the MySQL server after editing the configuration file.'
-
type: heading
attrs:
level: 3
content:
-
type: text
text: 'Enable via a global query'
-
type: paragraph
content:
-
type: text
text: 'To enable the general log via a global query, you can run this query:'
-
type: set
attrs:
values:
type: gist_content
gist_id: 1e12d01d52d2334d52ee4eca37bb12b6
gist_filename: 894f97b0-b220-42d1-92cf-3d9134326982.sql
code: 'SET global general_log = 1;'
extension: sql
-
type: heading
attrs:
level: 3
content:
-
type: text
text: 'General query log location'
-
type: paragraph
content:
-
type: text
text: 'Now that the general log is enabled, you have a couple options on where the log is written to. By default, it’s written to a log file located at: '
-
type: text
marks:
-
type: code
text: /var/log/mysql/mysql.log
-
type: paragraph
content:
-
type: text
text: 'However, when I enable the general log for debugging, I often have the output written to a table, so I can query it easily. To write the output to a table, you can run this global query:'
-
type: set
attrs:
values:
type: gist_content
gist_id: 1e12d01d52d2334d52ee4eca37bb12b6
gist_filename: c1995a7d-b9d9-4120-b8d2-f447ae323912.sql
code: 'SET global log_output = ''table'';'
extension: sql
-
type: paragraph
content:
-
type: text
text: 'You can query the general log table via:'
-
type: set
attrs:
values:
type: gist_content
gist_id: 1e12d01d52d2334d52ee4eca37bb12b6
gist_filename: 117e2331-6878-4a75-8e18-d2126b494cb0.sql
code: 'SELECT * FROM mysql.general_log;'
extension: sql
-
type: paragraph
content:
-
type: text
text: 'The results returned can be filtered, sorted, etc:'
-
type: set
attrs:
values:
type: gist_content
gist_id: 1e12d01d52d2334d52ee4eca37bb12b6
gist_filename: 1699c0b5-4467-4600-bef7-3968891f39bc.sql
code: 'SELECT * FROM mysql.general_log ORDER BY event_time DESC LIMIT 100;'
extension: sql
---
|
JavaScript
|
UTF-8
| 3,302 | 2.53125 | 3 |
[] |
no_license
|
// 导出 文章相关的API函数
import request from '@/utils/request'
/**
* 获取文章列表
* @param {Integer} channelId - 频道ID
* @param {Integer} timestamp - 时间戳
*/
export const getArticles = (channelId, timestamp) => {
return request('/app/v1_1/articles', 'get', {
channel_id: channelId,
timestamp,
with_top: 1
})
}
/**
*不感兴趣
* @param {string} articleId -对文章不感兴趣
*/
export const disLike = articleId => {
return request('/app/v1_0/article/dislikes', 'post', {
target: articleId
})
}
export const report = (articleId, type) => {
return request('/app/v1_0/article/reports', 'post', {
target: articleId,
type
})
}
/**
*联想建议的词条
* @param {String} q -请求的前缀词句
*/
export const suggest = (q) => {
return request('/app/v1_0/suggestion', 'get', {
q
})
}
/**
*搜索文章
* @param {int} page -页码
* @param {int} perPage -每页多少条
* @param {string} q -搜索关键字
*
*/
export const searchArticles = ({ page = 1, perPage = 20, q }) => {
return request('/app/v1_0/search', 'get', {
page,
per_page: perPage,
q
})
}
/**
*获取文章详情
* @param {String} articleId -文章ID
*/
export const getArticleDetail = (articleId) => {
return request(`/app/v1_0/articles/${articleId}`, 'get')
}
/**
*关注
* @param {int} userId -用户ID
*/
export const followed = (userId) => {
return request('/app/v1_0/user/followings', 'post', {
target: userId
})
}
/**
*取消关注
* @param {int} userId -用户ID
*/
export const unFollowed = (userId) => {
return request(`/app/v1_0/user/followings/${userId}`, 'delete')
}
/**
* 对文章不喜欢
* @param {String} articleId - 文章ID
*/
export const disLikes = (articleId) => {
return request('/app/v1_0/article/dislikes', 'post', {
target: articleId
})
}
/**
* 取消对文章不喜欢
* @param {String} articleId - 文章ID
*/
export const unDisLikes = (articleId) => {
return request('/app/v1_0/article/dislikes/' + articleId, 'delete')
}
/**
* 对文章点赞
* @param {String} articleId - 文章ID
*/
export const likings = (articleId) => {
return request('/app/v1_0/article/likings', 'post', {
target: articleId
})
}
/**
* 取消对文章点赞
* @param {String} articleId - 文章ID
*/
export const unLikings = (articleId) => {
return request('/app/v1_0/article/likings/' + articleId, 'delete')
}
/**
* 获取评论或回复
* @param {String} type - a 评论列表 c 回复列表
* @param {String} source - 评论列表 文章ID 回复列表 评论ID
* @param {String} offset - 上一次数据最后一个ID
* @param {Integer} limit - 每次加载的数据条数,默认是10条
*/
export const getCommentsOrReplys = ({ type, source, offset, limit = 10 }) => {
return request('/app/v1_0/comments', 'get', {
type, source, offset, limit
})
}
/**
*提交评论或回复
* @param {String} target -当你是评论操作时是:文章ID 当你是回复操作时是:评论ID
* @param {*} content -内容
* @param {*} artId -文章ID(当你是回复操作时)
*/
export const commentOrReply = (target, content, artId = null) => {
return request('/app/v1_0/comments', 'post', {
target,
content,
art_id: artId
})
}
|
Java
|
UTF-8
| 724 | 3.828125 | 4 |
[] |
no_license
|
package Second.JavaLearning.JavaLearning;
public class GetNumberOfUpperAndSmallAndDigits {
public static void main(String[] args) {
String aa = "India is my country 100%";
int totalChar = aa.length();
int upperCase = 0;
int lowerCase = 0;
int digits = 0;
int others = 0;
for (int i = 0; i < totalChar; i++) {
char a = aa.charAt(i);
if (Character.isUpperCase(a)) {
upperCase++;
} else if (Character.isLowerCase(a)) {
lowerCase++;
} else if (Character.isDigit(a)) {
digits++;
} else {
others++;
}
}
System.out.println("Cap: "+upperCase);
System.out.println("Small: "+lowerCase);
System.out.println("Num: "+digits);
System.out.println("others: "+others);
}
}
|
Python
|
UTF-8
| 1,796 | 3.03125 | 3 |
[] |
no_license
|
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))
# Detect object in video stream using Haarcascade Frontal Face
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# For each person, one face id
face_id = 1
# Initialize sample face image
count = 0
# allow the camera to warmup
time.sleep(0.1)
# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
image_frame = frame.array
# Convert frame to grayscale
gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY)
# Detect frames of different sizes, list of faces rectangles
faces = face_detector.detectMultiScale(gray, 1.3, 5)
#Loops for each faces
for (x,y,w,h) in faces:
# Crop the image frame into rectangle
cv2.rectangle(image_frame, (x,y), (x+w,y+h), (255,0,0), 2)
# Increment sample face image
count += 1
# Save the captured image into the datasets folder
cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
# Display the video frame, with bounded rectangle on the peerson's face
cv2.imshow('frame', image_frame)
key = cv2.waitKey(1) & 0xFF
# clear the stream in preparation for the next frame
rawCapture.truncate(0)
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
# If image taken reach 100, stop taking video
elif count>100:
break
|
SQL
|
UTF-8
| 2,071 | 3.84375 | 4 |
[
"Apache-2.0"
] |
permissive
|
CREATE OR REPLACE PROCEDURE vstat(idVin INTEGER) AS
--DECLARE
--Selection des regions de production du vin demande (idVin) et le nombre de producteurs/region
cursor V_REGIONSPROD is Select distinct P.region,count(P.np) as nombreProducteurs from Producteurs P, Recoltes, Vins
where P.NP=RECOLTES.NP and VINS.NV=RECOLTES.NV and VINS.NV=idVin
group by P.REGION ;
-- Selection des villes classées par ordre décroissant de nombre bouteille d'idVin vendues
cursor V_VILLESCLASSEMENTTOTAL is Select distinct lieu,sum(qte) as totalParVille from Achats
where nv=idVin group by lieu order by sum(qte) desc;
-- Selection par année des villes classées par ordre décroissant de nombre bouteille d'idVin vendues
cursor V_VILLESCLASSEMENTANNEE is Select distinct lieu,sum(qte) as totalParVille,extract(year from dates) as annee from Achats
where nv=idVin group by lieu,extract(year from dates) order by sum(qte) desc;
BEGIN
dbms_output.new_line;
dbms_output.put_line('Regions de production du vin numero ' || idVin);
for V_REGION in V_REGIONSPROD loop
dbms_output.new_line; --retour à la ligne <=> \n
dbms_output.put_line(chr(9) || V_REGION.region || ' ( ' || V_REGION.nombreProducteurs || ' producteurs)');
end loop;
dbms_output.new_line; --retour à la ligne <=> \n
dbms_output.put_line('Vente du vin numero ' || idVin);
for V_VILLETOTAL in V_VILLESCLASSEMENTTOTAL loop
dbms_output.new_line; --retour à la ligne <=> \n
dbms_output.put_line(chr(9) || V_VILLETOTAL.lieu || ' ( ' || V_VILLETOTAL.totalParVille || ' bouteilles)');
for V_VILLETOTALPARANNEE in V_VILLESCLASSEMENTANNEE loop
IF V_VILLETOTALPARANNEE.lieu = V_VILLETOTAL.lieu THEN
dbms_output.new_line; --retour à la ligne <=> \n
dbms_output.put_line( chr(9) || chr(9) || V_VILLETOTALPARANNEE.annee || ' : ' || V_VILLETOTALPARANNEE.totalParVille);
end IF;
end loop;
end loop;
END;
/
|
Java
|
UTF-8
| 1,719 | 3.125 | 3 |
[] |
no_license
|
package tcp;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer implements Runnable {
private final ServerSocket serverSocket;
private final int port;
public FileServer(int port){
this.port=port;
ServerSocket serverInterm = null;
try {
serverInterm = new ServerSocket(this.port);
} catch (IOException e) {
System.out.println("Can't setup server on this port number. ");
e.printStackTrace();
}
this.serverSocket = serverInterm;
}
public void run() {
while(true) {
InputStream in = null;
OutputStream out = null;
Socket socket=null;
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
out = new FileOutputStream("fichierreçu");
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[16*1024];
int count;
try {
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void startServer() {
new Thread(this).start();
}
}
|
Python
|
UTF-8
| 1,346 | 2.765625 | 3 |
[] |
no_license
|
#################################################
# Google SafeBrowsing console client #
# Using the standalone Python3 request library #
# Coded by: Macariola Ace H #
# #
#################################################
import requests
from time import sleep
try:
mainurl = "https://safebrowsing.googleapis.com/v4/threatMatches:find?"
url = input('Enter URL here:')
querystring = {'key':"AIzaSyCua037xQknK7sMR3CRBmHpxTLJKmRNbnc"}
# PAYLOAD HERE
payload = """
{
"client": {
"clientId" : "Kuro Macariola",
"clientVersion" : "1.5.2",
},
"threatInfo" : {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes": ["WINDOWS"],
"threatEntryTypes": ["URL"],
"threatEntries" : [
{"url": "https://stackoverflow.com"}
]
}
}
"""
## CHANGE THE URL FIELD TO THE URL YOU WANT TO CHECK
headers = {
'content-type' : 'application/json',
'accept' : 'application/json',
'cache-control' : 'no-cache',
}
response = requests.request("POST",mainurl,data=payload,headers=headers,params=querystring)
print(response.text)
except:
print('Error Occured')
|
TypeScript
|
UTF-8
| 624 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
import Client from './client';
import Driver from './driver';
export default class Node {
driver: Driver;
client: Client;
constructor(node?: any) {
this.driver = node && node.driver ? new Driver(node.driver) : undefined;
this.client = node && node.client ? new Client(node.client) : undefined;
}
get id(): string {
let id = '';
if (this.driver) {
id += this.driver.id;
}
id += '-';
if (this.client) {
id += this.client.id;
}
return id;
}
isEqual(node: Node): boolean {
return this.driver.id === node.driver.id && this.client.id === node.client.id;
}
}
|
Markdown
|
UTF-8
| 1,394 | 2.75 | 3 |
[] |
no_license
|
# ✈ Alura Intercâmbios - Tema Wordpress
Este projeto é o resultado do curso [WordPress: Criação de um tema personalizado](https://unibb.alura.com.br/course/wordpress-criacao-tema-personalizado).
Trata-se de um tema para o wordpress, baseado em uma empresa fictícia chamada "Alura Intercâmbios".
Neste curso, foi possível aprender a customizar diversos aspectos do tema, tais como:
- Aparência da página (utilizando CSS e Bibliotecas)
- Inclusão de scripts personalizados
- Alterações no menu admin do wordpress, permitindo que outros usuários realizem a atualização do conteúdo sem necessitar de conhecimentos em programação
- Filtros de postagens e páginas
Utilizando as funcionalidades fornecidas pelo wordpress e seguindo as boas práticas da comunidade e mercado, com um código limpo e organizado.
## 📸 Screenshots:

## 💻 Utilizando o código
Para utilizar este tema, você deve utilizar uma instalação do wordpress.
Clone o repositório dentro da pasta `wp-content/themes/`, e o tema estará disponível para seleção no painel administrativo de seu aplicativo wordpress.
## 🧪 Tecnologias utilizadas
- [PHP](https://www.php.net/)
- [Wordpress](https://wordpress.com/pt-br/)
- [Bootstrap](https://getbootstrap.com/)
- [Typed.js](https://mattboldt.com/demos/typed-js/)
|
Java
|
UTF-8
| 1,143 | 2.1875 | 2 |
[] |
no_license
|
package org.noahsark.client.manager;
import org.noahsark.client.heartbeat.HeartbeatFactory;
import org.noahsark.client.heartbeat.HeartbeatStatus;
import org.noahsark.server.remote.RetryPolicy;
/**
* 连接管理类
* @author zhangxt
* @date 22021/4/4
*/
public class ConnectionManager {
private HeartbeatFactory<?> heartbeatFactory;
private HeartbeatStatus heartbeatStatus;
private RetryPolicy retryPolicy;
public ConnectionManager() {
heartbeatStatus = new HeartbeatStatus();
}
public HeartbeatFactory<?> getHeartbeatFactory() {
return heartbeatFactory;
}
public void setHeartbeatFactory(HeartbeatFactory<?> heartbeatFactory) {
this.heartbeatFactory = heartbeatFactory;
}
public HeartbeatStatus getHeartbeatStatus() {
return heartbeatStatus;
}
public void setHeartbeatStatus(HeartbeatStatus heartbeatStatus) {
this.heartbeatStatus = heartbeatStatus;
}
public RetryPolicy getRetryPolicy() {
return retryPolicy;
}
public void setRetryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
}
}
|
JavaScript
|
UTF-8
| 1,347 | 2.6875 | 3 |
[] |
no_license
|
import React, { useState } from 'react';
import TodoFrom from './components/TodoFrom';
import TodoList from './components/TodoList';
function TodoRemove() {
const [todoList, setTodoList] = useState(() => {
const initTodoList = [
{
id: 1,
title: 'code',
},
{
id: 2,
title: 'eat',
},
{
id: 3,
title: 'sleep',
},
];
return initTodoList;
});
function handleTodoClickItem(item) {
console.log(item);
const index = todoList.findIndex(x => x.id === item.id);
if (index < 0) return;
const newTodoList = [...todoList];
newTodoList.splice(index, 1);
setTodoList(newTodoList);
}
function handleOnSubmit(fromValues) {
const newTodoList = [...todoList];
const newTodoItem = {
id: newTodoList.length + 1,
title: fromValues.title,
}
newTodoList.push(newTodoItem);
setTodoList(newTodoList);
console.log(todoList);
}
return (
<div>
<TodoFrom onSubmit={handleOnSubmit} />
<TodoList todoList={todoList} todoClickItem={handleTodoClickItem} />
</div>
);
}
export default TodoRemove;
|
Markdown
|
UTF-8
| 2,911 | 3.59375 | 4 |
[] |
no_license
|
# NOIP课程第一讲:编程入门
## 教学目标
### 0、认识C++编程
### 1、认识NOIP编程比赛
## 教学重点
### 0、【起步】
以Scratch的图形化编程作为入口,转化到代码形式的编程,使学生对编程形成最基本的概念理解
### 1、【基础】
通过上机演练的方式,让学生把课堂教学内容按照原样复现结果
### 2、【提升】
变化课堂教学所用的案例,测试学生理解情况,进一步引导学生对编程概念的理解
### 3、【习惯】
编程的核心是**输入**、**计算**、**输出**。所有课堂案例,都需要关注让学生形成解题的基本思维。
## 教学难点
C++编程中的知识点不能引入太多,减少到不能再减少为止,让学生先对代码编程有一个最原始的概念理解
## 教学过程
### 0、【讲述】简单介绍下NOIP:获奖情况
### 1、【入手点】用Scratch计算梯形面积
* 输入:上边长、底边长、高
* 计算:加法、乘法、除法、赋值
* 输出:显示面积
### 2、 【引导转化】用C++来计算梯形面积,并和Scratch的实现方式进行对比,对代码编程的软件使用做介绍
### 3、【知识点解析】讲解上面C++案例中出现的语法内容
### 4、【简单测试】让学生用上面已经讲解的知识点实现一个简单的乘法和加法的混合运算问题:已知一位小朋友的电影票价是10元,计算x位小朋友的总票价是多少?
* 输入:小朋友的数目x
* 计算:总票价y=10*x
* 输出:总票价y
### 5、【知识点解析】再次重复讲解C++语法知识
### 6、【输出控制】【案例】给定一个字符,用它构造一个底边长5个字符,高3个字符的等腰字符三角形。掌握对于输出的控制,让学生找到对于代码编程的掌控感
#
###
#####
### 7、【课堂练习】用C++输出一句话:Hello,World!
### 8、【课堂练习】输入三个整数,然后依次输出它们,并用逗号分隔
### 9、【课堂练习】输入四个整数,然后用两行输出它们,每行两个数字,同一行的数字之间用8个空格分隔
### 10、【课堂练习】小明今年12岁,爸爸37岁,妈妈36岁,请计算今年全家年龄总和,然后计算当小明16岁的时候,爸爸和妈妈各是几岁
### 11、【课堂练习】假设地球上的新生资源安恒定的速度增长。照此测算,地球上现有资源加上新生资源可供x亿人生活a年,或供y亿人生活b年。为了能够实现可持续发展,避免资源枯竭,地球最多能养活多少亿人?
* 输入:一行,包括四个正整数x、a、y、b,两个整数之间用单个空格隔开。x>y,a<b, a*x<by,它们都不大于10000
* 输出:一个实数z,表示地球最多养活z亿人,输出结果精确到小数点后两位
|
Markdown
|
UTF-8
| 24,525 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "An introduction to conditional (in)dependence, causality and probabilistic graphical models"
excerpt: "For the purpose of feature selection in prediction or characterization"
modified: 2018-07-17
tags: [causality, pgm, statistics]
comments: false
---
<!-- Inline math replace: -->
<!-- \$(.*?)\$ -->
<!-- \\\\($1\\\\) -->
\\(
\newcommand{\CI}{\mathrel{\perp\mspace{-10mu}\perp}}
\\)
This post summarizes my notes of a brief detour during my PhD to study conditional independence and causality. At the time, we had just finished a piece of research on identifying the *most relevant* and *least redundant* set of features for a prediction problem related to fluid flow in porous media[^fn1]. I then wondered if probabilistic graphical models (PGMs) could provide even more rigorous (perhaps even causal) statistical relationships. I concluded, in the end, that establishing causality was beyond our reach, due to a lack of *causal sufficiency* in our data. Establishing conditional independence (the next best thing) through PGMs and *structure learning* might have been feasible, but at the time I found that most established methods could not handle my non-Gaussian and continuous data very well. There have been some exciting developments in this area since then (using [additive noise models](https://arxiv.org/abs/1309.6779), for example) which may prompt me to revisit this approach to feature selection in the future.
### Introduction
#### Prediction or explanation?
Probabilistic graphical models (PGMs) aid in the discovery of marginal, conditional and (under strict assumptions) even causal relations between a set of variables. Before delving into the details of PGMs, it is important to ask the underlying question: are we dealing with a *prediction* problem or an *inference* (*discovery*) problem? Given a set of features, do we aim to predict the target variable of interest, or "explain" it? Understanding the difference is crucial, it turns out, in order to avoid erroneous inductions (See Aliferis et al.[^fn2] and [To Explain or To Predict?](https://projecteuclid.org/euclid.ss/1294167961)). In a supervised machine learning prediction problem, a predictive model is developed, including a choice of features, learning algorithm and performance metric. The model is trained on labeled instances and used to predict the target variable on unlabeled instances. An inference task, on the other hand, is more focused on testing causal relations between variables, accepting or rejecting hypotheses and understanding conditional (in)dependencies in the data.
At first sight, feature selection (for the purpose of prediction) seems to transcend the boundary between prediction and inference problems. After all, shouldn't we able to use the prediction performance of a chosen feature set to infer the (causal) dependence of these features on the permeability? It turns out that this is not the case. Aliferis et al.[^fn2] show that *good prediction performance can be completely misleading as a criterion for the quality of causal hypotheses* IF non-causal feature selection algorithms are used. The authors list a number of existing studies that made this error. As an alternative, Aliferis et al. highlight the existence of principled causal feature selection algorithms, in the form of structure learning methods for probabilistic graphical models. These algorithms *do* do allow "safe" feature selection both for prediction and inference tasks. The difference between non-causal and causal feature selection algorithms relates to the ability of the latter to identify both the most relevant and the least redundant features. Non-causal feature selection algorithms cannot distinguish between redundant features, and may end up selecting features that have no direct (causal) relation with the target variable.
#### Causality or conditional independence?
While discovering causal relations is highly desirable from a research perspective, in practice the required assumptions for discovery of such relations are not satisfied. In this case, conditional (in)dependence may be the "next-best" inference mechanism. That being said, some of the causal feature selection algorithms can be used to discover conditional dependencies, without drawing any conclusions about the causality involved. One such method is structure learning for probabilistic graphical models.
In the remainder of this note, an introduction of the mathematical concepts relevant for structure learning and PGMs is presented, including conditional (in)dependence, graphical models, relevant assumptions for (in)dependence and causality, and (briefly) structure learning.
#### Notation
The uppercase letters \\(X,Y,Z\\) denote (random) variables with the lowercase letters \\(x\in Val(X),\ y\in Val(Y),\ z\in Val(Z)\\) denoting their respective values. For sets of variables, we use the bold notation \\(\mathbf{X},\mathbf{Y},\mathbf{Z}\\) with values \\(\mathbf{x}\in Val(\mathbf{X}),\ \mathbf{y}\in Val(\mathbf{Y}),\ \mathbf{z}\in Val(\mathbf{Z})\\). The target variable is denoted as \\(T\\) and a set of variables \\(\mathbf{X}\\) has a joint probability distribution \\(J\\).
For graphs, we use \\(\mathbf{V}\\) to denote the set of vertices (nodes) and \\(\mathbf{E}\\) to denote the set of edges (connections). \\(G = (V,E)\\) denotes a graph, either directed or undirected. An edge is usually denoted \\((u,v)\in E,\ u,v\in V\\). We say that two vertices \\(u\\) and \\(v\\) are *adjacent* (or *neighbors*) if there is an edge that directly connects them, i.e. \\((u,v)\in E\\). Furthermore, in directed graphs, we define \\(Parents(u)\\) as the set of vertices that directly point to \\(u\\) and \\(Children(u)\\) as the set of vertices that \\(u\\) directly points to. Because, as we will see, variables are assigned to vertices in a graphical model, we will use the terms vertices, nodes, variables and features interchangeably.
### Conditional independence
Formally, conditional independence is defined as follows. Variables \\(X\\) and \\(Y\\) are conditionally independent given a set of variables \\(\mathbf{Z}\\) if and only if
$$
P(X=x,Y=y\mid\mathbf{Z}=\mathbf{z}) = P(X=x\mid\mathbf{Z}=\mathbf{z})P(Y=y\mid\mathbf{Z}=\mathbf{z}),\\
\forall x\in Val(X),\ y\in Val(Y),\ \mathbf{z}\in Val(\mathbf{Z})\ \text{where}\ P(\mathbf{Z}=\mathbf{z}) > 0 \nonumber
$$
If this equation holds, we write \\(X\CI Y\mid\mathbf{Z}\\). Conditional independence implies that given the knowledge of \\(\mathbf{Z}\\), there is no additional evidence that \\(X\\) has any influence on \\(Y\\) and vice-versa. For example[^fn3], let \\(X\\) be the variable stating whether or not a child is a member of a scouting club, and let \\(Y\\) be the variable stating whether or not a child is a delinquent. Survey data might show that \\(X\\) and \\(Y\\) are *marginally* dependent, i.e. members of a scouting club have a lower probability of being a delinquent. What if, however, we consider the socio-economic status of the child, measured by a variable \\(Z\\)? Survey data could now show that, given knowledge of \\(Z\\), there is no additional effect of \\(X\\) on \\(Y\\). In other words, the socio-economic status fully explains any relationship we observe between scouting membership and delinquency. This relationship between \\(X\\), \\(Y\\) and \\(Z\\) can be represented in a *graphical model*, as illustrated in the next figure.
<figure>
<a href="/images/pgm_conditional_independence.png"><img src="/images/pgm_conditional_independence.png"></a>
</figure>
Nodes represent variables and edges (links) represent influence. Graphical models will be explained in further detail after the concept of *conditional dependence* is introduced.
### Conditional dependence
If the equation presented in the previous section does not hold, we say that \\(X\\) and \\(Y\\) are conditionally dependent given \\(\mathbf{Z}\\). Intuitively, conditional dependence can be understood as a "competing" explanation by \\(X\\) and \\(Y\\), for a phenomenon \\(\mathbf{Z}\\). For example[^fn4], let \\(X\\) by a variable stating whether or not the sprinkler is on, let \\(Y\\) be a variable stating whether or not it is raining, and let \\(Z\\) be a variable stating whether or not the grass is wet. If we know that the grass is wet and we know that it is raining, then the probability that the sprinkler is on goes down. In other words, \\(X\\) has *explained away* \\(Z\\). The conditional dependence described here can be graphically represented as follows:
<figure>
<a href="/images/pgm_conditional_dependence.png"><img src="/images/pgm_conditional_dependence.png"></a>
</figure>
Note that, in this example, the (likely) marginal dependence between \\(X\\) and \\(Y\\) is ignored.
### Graphical models
The simple networks in the previous two figures are examples of *Bayesian networks*, or directed graphical models, in which the edges have a direction assigned to them. In contrast, the edges in *Markov networks*, or undirected graphical models, are undirected. Both Bayesian and Markov networks can be used to visualize the factorization of the joint probability distribution \\(J\\) for a set of variables \\(\mathbf{X}\\).
Formally, a Bayesian network is a graphical model that encodes the conditional dependencies of a set of random variables in a directed acyclic graph (DAG). Under certain assumptions, which will be discussed in the next section, Bayesian networks can be used to capture causal structures[^fn6]. The joint probability distribution of a set of variables in a Bayesian network is readily derived by considering the parents of each variable:
$$
P(\mathbf{X}) = \prod_{X\in \mathbf{X}} P(X\mid Parents(X))
$$
For example, from the conditional independence (scouting/delinquency) example, we know that \\(P(X,Y,Z)\\) factorizes as \\(P(X\mid Z)P(Y\mid Z)P(Z)\\). The *Markov condition* states that every variable \\(X\\) is conditionally independent of all other variables that are neither parents nor children of \\(X\\), given the parents of \\(X\\). The Markov condition generalizes to the criterion of *d-separation* for conditional independence, for which the full details are beyond the scope of this note (see Pearl[^fn5]). It is sufficient to know, at this point, that d-separation is a set of rules that allow us to infer the conditional independencies from a DAG.
A Markov network captures the conditional (in)dependencies in an undirected graph. Inferring these dependencies is straightforward, using the following three *Markov properties*:
- **Pairwise Markov property**. Two non-adjacent variables are conditionally independent given all other variables.
- **Local Markov property**. A single variable is conditionally independent of all other variables given its neighbors. The local Markov property is the Markov network-equivalent of the Markov condition in Bayesian networks.
- **Global Markov property**. Two sets of variables \\(\mathbf{X}\\) and \\(\mathbf{Y}\\) are conditionally independent given a third set \\(\mathbf{Z}\\) if \\(\mathbf{Z}\\) is a *separating* subset.
The term "separating subset" can be understood in the intuitive sense, i.e. a set \\(\mathbf{Z}\\) is a separating set of \\(\mathbf{X}\\) and \\(\mathbf{Y}\\) if every path between \\(\mathbf{X}\\) and \\(\mathbf{Y}\\) passes through one or more variables in \\(\mathbf{Z}\\). For example, \\(Z\\) would be a separating subset of \\(X\\) and \\(Y\\) in the examples shown in previous sections, if both networks were undirected.
The *Markov blanket* \\(MB(T)\\) of the target variable \\(T\\) in a Bayesian network is the union of \\(Children(T)\\), \\(Parents(T)\\) and \\(Parents(Children(T))\\). In a Markov network, \\(MB(T)\\) is the set of nodes adjacent to \\(T\\). The Markov blanket has the useful property that for every set of variables \\(\mathbf{X}\\) with no members in \\(MB(T)\\), we know that \\(\mathbf{X}\CI T \mid MB(T)\\)[^fn5]. This implies that the Markov blanket contains all necessary information to describe and predict \\(T\\), and any other variables are essentially redundant (feature selection!). Before further discussing how the Markov blanket can be used for feature selection, let's check our assumptions for independence and causality first.
### Assumptions for independence and causality
In his introduction to causal inference, Scheines[^fn7] explains the difference between the assumptions required to infer probabilistic independence and the assumptions required to infer causality, a theory developed by Spirtes et al.[^fn6]. To understand these assumptions, we first introduce the concept of *latent variables*. In practice, there may be many unmeasured, or even unknown, variables. Such variables are called latent variables. Among the latent variables, there may be variables that induce relations between pairs of variables that do not correspond to causal relations between them[^fn8]. These variables are called *confounding factors*. For example, had we not measured \\(Z\\) in the conditional independence example, then socio-economic background would have been a confounding factor for the observed relation between boy scout membership and delinquency.
If we are content with inferring conditional independence, then \\(d\\)-separation (for Bayesian networks) and the Markov properties (for Markov networks) provide us with all the necessary tools. To do so, though, we have to assume that the graphical model we obtained (through structure learning, discussed later) is an accurate representation of the true data, entailing the correct conditional independencies. Assuming that the conditional independencies encoded in the true distribution exactly equal the ones encoded in a DAG (via d-separation) is referred to as the *faithfulness assumption*. More specifically, the graph \\(G\\) is *faithful* to the joint distribution \\(J\\) of a set of variables \\(\mathbf{X}\\), meaning that every (conditional) independence in \\(J\\) can be derived from \\(G\\) using d-separation. The faithfulness assumptions also guarantees that the Markov blanket is unique[^fn10].
Inferring causality using Bayesian networks requires two additional assumptions, in addition to faithfulness. Firstly, *causal sufficiency* has to hold for the observed set of variables \\(\mathbf{X}\\), meaning that for every pair of variables in \\(\mathbf{X}\\), all common causes are also measured[^fn6]. In other words, there should not be any confounding factors. Secondly, the Bayesian network \\(G\\) and joint probability distribution \\(J\\) needs to satisfy the *causal Markov condition*, which implies (1) that \\(G\\) contains an edge from \\(X\\) to \\(Y\\) if and only if \\(X\\) is a direct cause of \\(Y\\), and (2) that the set of variables \\(\mathbf{X}\\) giving rise to \\(J\\) is causally sufficient. Under the causal sufficiency and faithfulness assumptions, the Markov blanket in a Bayesian network contains the direct causes, direct effects and the direct causes of the direct effects of \\(T\\)[^fn2].
As noted, the causal sufficiency assumption does not hold in many applications (including ours[^fn1]). It may not be feasible to measure *all* known parameters and even if we could, there is no guarantee that there are undiscovered parameters that may act as confounding factors. As a result, *correlation does not imply causation* in our data and we are very limited in our ability to draw conclusions regarding causality. The "next best" inference we can do is conditional (in)dependence, which is what we will focus on in the remaining sections. We will assume faithfulness, which is widely embraced[^fn7].
### Feature Selection
The feature selection problem is defined as follows[^fn2]: Given a \\(N\\) instances of a variable set \\(\mathbf{X}\\) drawn from the true distribution \\(D\\), a prediction algorithm \\(C\\) and a *loss* (model-performance) function \\(L\\), find the smallest subset of variables \\(\mathbf{F} \subseteq \mathbf{X}\\) such that \\(\mathbf{F}\\) minimizes the expected loss \\(L(M,D)\\), where \\(M\\) is the model trained using algorithm \\(C\\) and the feature set \\(\mathbf{F}\\). Informally, we aim to find the feature set \\(\mathbf{F}\\) that "optimally" characterizes the target variable \\(T\\)[^fn13].
In the previous section, we discussed the inference of conditional (in)dependence from Bayesian and Markov networks. The question is now: how do we utilize these tools for the purpose of feature selection and inference? Aliferis et al.[^fn2] center their discussion on this topic around the Markov blanket. Indeed, given the fact that \\(\mathbf{X}\CI T \mid MB(T)\\), members of \\(MB(T)\\) intuitively seem like promising candidates for our maximally relevant and minimally redundant feature set.
The theoretical link between feature selection, Markov blankets and the definition of feature "relevance" is rigorously examined by Tsamardinos et al.[^fn12], connecting their insights with the classical relevance definition by Kohavi and John[^fn11]. Tsamardinos et al. find, among other insights, that feature relevance is always dependent on the choice of prediction algorithm and model-performance metric. There is no universally applicable definition of relevancy for prediction. Moreover:
- *Strongly relevant* features, which contain information about \\(T\\) not found in any other features, are members of \\(MB(T)\\).
- *Weakly relevant* features, which contain information about \\(T\\) also found in other features, are not members of \\(MB(T)\\) but have an undirected path to \\(T\\)
- *Irrelevant* features, which contain no information about \\(T\\), are not members of \\(T\\) and have no undirected path to \\(T\\).
Assuming that a prediction method can learn the distribution \\(P(T\mid MB(T))\\) and the model-performance metric is such that the perfect estimation (optimal score of the metric) is attained with the smallest number of variables, then the Markov blanket of \\(T\\) is the *optimal* solution of the feature selection problem. We also know from the previous section that we can infer conditional (in)dependencies from the Markov blanket and the surrounding Bayesian/Markov network, providing insight into the relation structure.
### Structure learning
So far, we have motivated the use of graphical models for feature selection by defining feature relevance and by introducing the Markov blanket. Moreover, we demonstrated the usefulness of graphical models for inference of conditional dependency and causality in previous sections. Throughout this discussion, we assumed the graphical model was known. In practice, we need to construct the model based on a set of observations.
To this end, *structure learning* for Markov and Bayesian networks has been the subject of extensive research in the last two decades [^fn6] [^fn14] [^fn15]. The main objective is to learn the structure of the graphical model, based on a dataset of observations of the variables involved. Although some algorithms (see e.g. Koller and Mehran[^fn9]) have been designed to only learn the Markov blanket, we focus on the more general problem of learning the structure between all variables. Several approaches to structure learning can be distinguished, including score-based structure learning [^fn16], constraint-based structure learning[^fn6] and other methods (hybrid, restricted structural equation models, additive noise models).
Structure learning using score-based methods proceeds in two steps[^fn8]. First, we define a scoring function that evaluates how well the model structure matches the observations (e.g. *Likelihood score*, *Akaike's Information Criterion* (AIC) or *Bayesian Information Criterion* (BIC)). Second, we employ an algorithm that searches the combinatorial space of all possible model structures for the particular model structure that optimizes the scoring function. To move through the search space, we can add edges, delete edges, and, in the case of Bayesian networks, reverse the direction of edges. A number of search algorithms have been proposed, including:
- **Stepwise methods** for Markov networks start with an empty network and add edges (forward search) or start with a fully saturated network and delete edges (backward search) that result in the largest decrease in the scoring function.
- **Hill-climbing methods** start with an empty network, random network, or an initial network based on prior (expert) knowledge, and proceed to iteratively compute the score for all possible perturbations. The algorithm then picks the perturbation (i.e. edge addition/removal/reversal) that results in the largest score improvement. To avoid local optima, hill-climbing algorithms are often combined with random restarts and/or tabu lists. The latter prevents the algorithm from reversing the \\(k\\) most recent perturbations.
For a more detailed overview of structure learning, refer to the work by Koller and Friedman [^fn8].
### Conclusion
We have described causality, conditional independence, feature selection and Markov blankets. Theoretically, the Markov blanket of the variable to predict is a perfect solution for the feature selection problem, as outlined in the previous two section. In practice, however, (structure) learning the required graphical model of a set of random variables can be rather challenging. In my case, the random variables were all continuous and non-Gaussian, for which most existing structure learning methods (at the time) did not work. There have been some exciting developments in this area since then (using [additive noise models](https://arxiv.org/abs/1309.6779), for example) which may prompt me to revisit this approach to feature selection in the future.
### References
[^fn1]: van der Linden, J. H., Narsilio, G. A., & Tordesillas, A. (2016). Machine learning framework for analysis of transport through complex networks in porous, granular media: a focus on permeability. Physical Review E, 94(2), 022904.
[^fn2]: Aliferis, C. F., Statnikov, A., Tsamardinos, I., Mani, S., & Koutsoukos, X. D. (2010). Local causal and markov blanket induction for causal discovery and feature selection for classification part ii: Analysis and extensions. Journal of Machine Learning Research, 11(Jan), 235-284.
[^fn3]: Example based on [STAT504 - Analysis of Discrete Data](https://onlinecourses.science.psu.edu/stat504/node/112)
[^fn4]: Example based on [Wikipedia](https://en.wikipedia.org/wiki/Bayesian_network)
[^fn5]: Pearl, J. (1988). Probabilistic reasoning in intelligent systems: networks of plausible inference. Morgan Kaufmann Publishers Inc.
[^fn6]: Spirtes, P., Glymour, C. N., Scheines, R., Heckerman, D., Meek, C., Cooper, G., & Richardson, T. (2000). Causation, prediction, and search. MIT press.
[^fn7]: Scheines, R. (1997). An introduction to causal inference. In McKim, V. R. and Turner, S. P. (Eds.), Causality in Crisis? Statistical Methods and the Search for Causal Knowledge in the Social Sciences (pp. 185-200). University of Notre Dame Press.
[^fn8]: Koller, D., & Friedman, N. (2009). Probabilistic graphical models: principles and techniques. MIT press.
[^fn9]: Koller, D., & Mehran, S. (1996). Toward Optimal Feature Selection. In Lorenza, S. (Eds.), Proceedings of the Thirteenth International Conference on Machine Learning (ICML) (pp. 284-292). Morgan Kaufmann Publishers.
[^fn10]: Tsamardinos, I., Aliferis, C. F., & Statnikov, A. (2003, August). Time and sample efficient discovery of Markov blankets and direct causal relations. In Proceedings of the ninth ACM SIGKDD international conference on Knowledge discovery and data mining (pp. 673-678). ACM.
[^fn11]: Kohavi, R., & John, G. H. (1997). Wrappers for feature subset selection. Artificial intelligence, 97(1-2), 273-324.
[^fn12]: Tsamardinos, I., & Aliferis, C. F. (2003, January). Towards principled feature selection: relevancy, filters and wrappers. In Proceedings of the Ninth International Workshop on Artificial Intelligence and Statistics. Morgan Kaufmann Publishers.
[^fn13]: Peng, H., Long, F., & Ding, C. (2005). Feature selection based on mutual information criteria of max-dependency, max-relevance, and min-redundancy. IEEE Transactions on pattern analysis and machine intelligence, 27(8), 1226-1238.
[^fn14]: Neapolitan, R. E. (2004). Learning bayesian networks (Vol. 38). Upper Saddle River, NJ: Pearson Prentice Hall.
[^fn15]: Pearl, J. (2000). Causality: Models, Reasoning, and Inference. Cambridge University Press.
[^fn16]: Cooper, G. F., & Herskovits, E. (1992). A Bayesian method for the induction of probabilistic networks from data. Machine learning, 9(4), 309-347.
|
Shell
|
UTF-8
| 1,231 | 3.34375 | 3 |
[] |
no_license
|
#!/bin/bash
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
SCOLOR='\033[0m'
echo -e "${GREEN}Choose Connection Method:"
echo "0 - SSH Direct "
echo "1 - PAYLOAD "
echo "2 - SSL "
echo -e "3 - SSL+PAYLOAD \nEnter choice number :${SCOLOR}"
read mode
find=`cat settings.ini | grep "connection_mode = " |awk '{print $3}'`
sed -i "s/connection_mode = $find/connection_mode = $mode/g" settings.ini
sleep 1
screen -AmdS nohub python tunnel.py
sleep 1
if [ "$mode" = '0' ] || [ "$mode" = '1' ]
then
screen -AmdS nohub python ssh.py 1
elif [ "$mode" = '2' ] || [ "$mode" = '3' ]
then
screen -AmdS nohub python ssh.py 2
else
echo -e "${RED}wrong choice\ntry again${SCOLOR}"
python pidkill.py
exit
fi
echo -e "${YELLOW}---logs----${SCOLOR}"
sleep 10
cat logs.txt
var=`cat logs.txt | grep "CONNECTED SUCCESSFULLY"|awk '{print $4}'`
if [ "$var" = "SUCCESSFULLY" ];then
echo -e "${GREEN}---Tunneling starts-----"
chmod +x proxification.sh
./proxification.sh
echo -e "${SCOLOR}"
iptables --flush
else
echo -e "${RED}failed! , check settings.ini file again ${SCOLOR}"
fi
echo -e "${RED} vpn service stopped"
python pidkill.py
fuser 1080/tcp -k
fuser 1080/udp -k
rm logs.txt
echo -e "exiting ${SCOLOR}"
|
Java
|
UTF-8
| 2,335 | 2.625 | 3 |
[] |
no_license
|
package io.mqttpush.mqttclient.handle;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.log4j.Logger;
import io.mqttpush.mqttclient.conn.CancelbleExecutorService;
import io.mqttpush.mqttclient.conn.Connetor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttQoS;
/**
* 发送心跳
*
* @author tianzhenjiu
*
*/
public class PingRunnable implements Runnable {
Logger logger = Logger.getLogger(getClass());
final Channel channel;
/**
* 发送ping之后是否回复pong
*/
final AtomicBoolean hasResp;
final Connetor connetor;
final CancelbleExecutorService executorService;
final Integer pingTime;
public PingRunnable(Channel channel, Connetor connetor,
Integer pingTime,
CancelbleExecutorService executorService) {
super();
this.channel = channel;
this.connetor = connetor;
this.pingTime=pingTime;
this.executorService = executorService;
this.hasResp = new AtomicBoolean(false);
}
@Override
public void run() {
/**
* 只要链路不可用,或者没有收到心跳回复就重新连接
*/
if(!channel.isActive()) {
logger.warn("链路不可用了");
return;
}
if (!hasResp.get()) {
connetor.reconnection(channel);
logger.warn("规定时间内未收到PONG报文,将会重新连接");
return;
}
channel.writeAndFlush(
new MqttMessage(new MqttFixedHeader(MqttMessageType.PINGREQ, false, MqttQoS.AT_MOST_ONCE, false, 0)))
.addListener((ChannelFuture future) -> {
/**
* 只要心跳发出去了就设置了 没收到心跳
*/
if (updatehasResp(false)) {
executorService.schedule(PingRunnable.this, pingTime, TimeUnit.SECONDS);
}
if (logger.isDebugEnabled()) {
logger.debug("发送心跳");
}
});
}
/**
* 更新hasResp
* @param updateVal
* @return
*/
public boolean updatehasResp(boolean updateVal) {
if(!hasResp.compareAndSet(!updateVal, updateVal)) {
return hasResp.get()==updateVal;
}
return true;
}
}
|
PHP
|
UTF-8
| 250 | 3.359375 | 3 |
[] |
no_license
|
<?php
$a = 10;
echo $a++; //adiciona mais 1 após a mostrar a variavel a
echo "<br>";
echo ++$a; //adiciona mais 1 antes de mostrar a variavel a
echo "<br>";
echo --$a;
echo "<br>";
echo $a--;
echo "<br>";
?>
|
Java
|
UTF-8
| 1,531 | 2.15625 | 2 |
[] |
no_license
|
package compta.core.presentation.handlers.handler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.PlatformUI;
import compta.core.application.manager.TrimestreManager;
import compta.core.common.ComptaException;
import compta.core.presentation.dialogs.template.EditTemplateTrimestreDialog;
public class EditTrimestreTemplateHandler implements IHandler {
@Override
public void addHandlerListener(IHandlerListener handlerListener) {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
final EditTemplateTrimestreDialog diag = new EditTemplateTrimestreDialog();
diag.open();
try {
TrimestreManager.getInstance().setTrimestreTemplate();
} catch (final ComptaException e) {
MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Erreur", "Impossible de sauver le template");
}
return null;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isHandled() {
// TODO Auto-generated method stub
return true;
}
@Override
public void removeHandlerListener(IHandlerListener handlerListener) {
// TODO Auto-generated method stub
}
}
|
Markdown
|
UTF-8
| 1,300 | 2.671875 | 3 |
[] |
no_license
|
# 基础架构
架构说明:主数据管理包括主数据标准、主数据管理规范、主数据技术产品,主数据产品落地主数据标准和管理规范,集中管理主数据,建立 唯一视图,并由主数据管理平台统一分发;产品的功能主要包括四大块:
1、模型管理:落地数据模型标准,为主数据管理建立结构,配置编码规则,为主数据自动生成编码,界面建模为主数据管理定义操
作界面,根据需求也可为主数据维护配置流程、权限模型,模型管理是主数据管理的基础。
2、数据清洗:数据清洗主要是汇集主数据,并对汇集的数据进行清洗,如排重、合并、完善等,数据清洗保证有一份干净的、高质
量的主数据。
3、主数据维护:主数据维护为企业业务人员提供数据维护的功能,数据维护严格按标准进行校验。
4、主数据共享:落地到主数据管理系统中的主数据,最终的目的是为了给各业务系统使用,主数据共享提供系统注册,系统订阅,
服务分发,数据推送,分发监控等,主数据在企业各系统之间实现共享,并数出一处。

|
Markdown
|
UTF-8
| 5,805 | 2.546875 | 3 |
[] |
no_license
|
---
published: true
organization_id: '2016170'
year_submitted: 2016
category: play
body_class: strawberry
project_id: '6102215'
challenge_url: >-
https://challenge.la2050.org/entry/explore-los-angeless-past-present-and-future-in-augmented-reality-through-perceptoscope
title: >-
Explore Los Angeles's past, present, and future in augmented reality through
Perceptoscope
project_summary: >-
Perceptoscopes are public augmented reality viewers in the form of coin
operated binoculars. They can expose the hidden past, present points of
interest, or future potentials of a place.
project_image: >-
https://skild-prod.s3.amazonaws.com/myla2050/images/custom540/1517216783741-team89.jpeg
project_video: 'https://www.youtube.com/embed/GCBLHUIW9FI?rel=0&showinfo=0'
Are any other organizations collaborating on this proposal?: ''
Please describe your project proposal.: >-
Perceptoscope, an interactive public arts initiative, will temporarily deploy
augmented reality pedestal viewers at strategic locations around the city
taking into account the context, communities and histories of the spaces in
which they're dropped. We will work with local organizations towards permanent
deployments, and along the way document our process of design and public
deployment through online video.
Which metrics will your proposal impact?:
- Access to open space and park facilities
- Number (and quality) of informal spaces for play
- Number of parks with intergenerational play opportunities
- Number of residents with easy access to a “vibrant” park
In what areas of Los Angeles will you be directly working?:
- Central LA
- County of Los Angeles
- City of Los Angeles
- There is global interest. We want to pilot in LA.
Describe in greater detail how your proposal will make LA the best place.: >-
Perceptoscope is about encouraging the act of discovery around a place. The
shape of our viewers in particular has an immense magnetism for children and
the curious. By adding this new surprise to something familiar, people will
walk away from a place changed and encouraged to explore somewhere new.
The interactive content on the viewers themselves opens up a variety of
exciting opportunities to explore how to make places engaging and fun. It's
easy to imagine digital scavenger hunts, interactive informational
visualizations, and being transported to a different point in time at the
location you're standing.
We're just starting to explore the array of interactions possible with
Perceptoscopes, and our open source platform is designed so that the digital
creative culture already present in this city can create content quickly and
easily.
Playtesting has played a prominent role in the development of the project.
Observing the behavior of users at our various deployments has led to the
development of new features we never would have expected. We noticed kids
often assumed Perceptoscopes had the potential to also act as cameras, so
we've been developing photography features like the ability to take 360 degree
panoramic photos, or act as a 3D photo booth.
The fact that we're an open platform means collaborators will always be
pushing the project in new and exciting ways. Having them deployed broadly
across Los Angeles will give the omnipresent arts and humanities culture here
a new voice that's separate from the traditional media we're known for.
We hope that deployments can be long lasting, and that each deployment's
experiences will be dynamic and novel to encourage the revisitation of a space
for years to come.
Please explain how you will define and measure success for your project.: >-
Success for the project is measured more in trajectories than the achievement
of fixed goals. Our hybrid nature gives us a unique set of tools to help us
improve and learn.
As a hardware technology project, we're always looking to better our
technology to make it more engaging and intuitive to use. We typically look
towards design thinking practices as a means to this end, such as cycles of
prototyping and playtesting.
As a creative placemaking project, we hope to use techniques like pedestrian
counts and foot traffic studies to measure our impact on a location in hard
data. By understanding how a Perceptoscope is placed in a space, we can not
only optimize how people come to discover it but also take advantage of the
way it might draw people to an otherwise empty spot.
As a media project, we measure our impact in impressions. How many people were
we able to impact in an given amount of time deployed at that location?. How
effectively did we convey the story we were trying to tell? Did we represent
the perspectives of that space broadly?
Our ultimate goal for the project is to achieve sustainability and feed back
revenue generated from the project into more units and deployments. The idea
is to create a feedback loop between communities and the project that deepens
our roots and broadens our footprint.
How can the LA2050 community and other stakeholders help your proposal succeed?:
- 'Money '
- Volunteers
- Advisors/board members
- 'Staff '
- Publicity/awareness
- Infrastructure (building/space/vehicles etc.)
- 'Education/training '
- Technical infrastructure (computers etc.)
- 'Community outreach '
- Network/relationship support
- Quality improvement research
cached_project_image: >-
https://archive-assets.la2050.org/images/2016/explore-los-angeless-past-present-and-future-in-augmented-reality-through-perceptoscope/skild-prod.s3.amazonaws.com/myla2050/images/custom540/1517216783741-team89.jpeg
organization_name: Perceptoscope
organization_website: www.perceptoscope.com
---
|
JavaScript
|
UTF-8
| 2,860 | 2.734375 | 3 |
[
"CC-BY-SA-3.0",
"CC-BY-SA-4.0"
] |
permissive
|
captiontext = [
"11014 Gemeinden, davon 2 bewohnte gemeindefreie Gebiete (Stand 31.12.2018)",
"4511 Verwaltungsgemeinschaften, davon 1254 Gemeindeverbände (Stand 31.12.2018)",
"401 Kreise, davon 107 kreisfreie Städte (Stand 31.12.2018)",
"19 Regierungsbezirke (Stand 31.12.2018)",
"16 Bundesländer (Stand 31.12.2018)",""];
adetext = [
"ADE 6: Gemeinden",
"ADE 5: Verwaltungsgemeinschaften",
"ADE 4: Kreise",
"ADE 3: Regierungsbezirke",
"ADE 2: Länder",
"ADE 1: Staat"];
var id_vwgeb = "vwgeb_ch";
var id_vwgl = "vwgl_ch";
var vwgeb_path = "adm_ch/vwgeb_ch/Rplot";
var vwgl_path = "adm_ch/vwgl_ch/ch_vwgl";
//preload images
var images_vwgeb = new Array();
var images_vwgl = new Array();
var num_images = 4;
function preloadImages (){
for (i = 0; i < num_images; i++) {
images_vwgeb[i] = new Image();
images_vwgeb[i].src = vwgeb_path+(i+1)+".png";
images_vwgl[i] = new Image();
images_vwgl[i].src = vwgl_path+(i+1)+".png";
console.log(images_vwgl[i].src);
console.log(images_vwgeb[i].src);
}
}
preloadImages();
var id = setInterval(frame, 3000);
var pos = 0;
// 4 states: 0 = ready; 1 = started loading images; 2/3 = first/second image loaded
var imageLoaded = 0;
//console.log("pos: " + pos +"imageLoaded: "+imageLoaded);
//alert("test");
function imageOnload(){
console.log("pos: " + pos +" imageLoaded: "+imageLoaded+" loaded image "+(imageLoaded));
imageLoaded++;
if(imageLoaded == 3){
loadDescription();
imageLoaded = 0;
}
};
function frame() {
console.log("pos: " + pos +" imageLoaded: "+imageLoaded);
if(imageLoaded != 0) // skip iteration if images from previous were not loaded
return;
imageLoaded = 1;
console.log("pos: " + pos +" imageLoaded: "+imageLoaded);
var img1 = document.getElementById(id_vwgeb);
img1.onload = imageOnload;
img1.src=vwgeb_path+(pos+1)+".png";
var img2 = document.getElementById(id_vwgl);
img2.onload = imageOnload;
img2.src=vwgl_path+(pos+1)+".png";
}
function loadDescription(){
var array = document.getElementsByClassName("division_"+pos);
for (var index = 0; index < array.length; index++) {
var textElement = array[index];
textElement.style.color="blue";
}
array = document.getElementsByClassName("division_"+(pos+num_images) % (num_images+1));
for (var index = 0; index < array.length; index++) {
var textElement = array[index];
textElement.style.color="inherit";
}
/* var e1 = document.getElementById("description");
if(num_images-pos==num_images)
e1.innerHTML = "<b>"+adetext[num_images - pos ]+"</b>";
else
e1.innerHTML = "<b>"+adetext[num_images - pos ]+"</b> - "+captiontext[num_images - pos ];
console.log("loaded description "+(num_images-pos)+": "+adetext[num_images - pos ]); */
if(pos >= num_images-1)
pos=0;
else
pos++;
}
|
Java
|
UTF-8
| 2,816 | 2.09375 | 2 |
[] |
no_license
|
package com.example.nmsm.sta.config.auth;
import com.example.nmsm.dyn.dao.UserDAO;
import com.example.nmsm.sta.config.oauth.*;
import com.example.nmsm.sta.model.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class PrincipalOauth2UserService extends DefaultOAuth2UserService {
@Autowired
private UserDAO userDAO;
private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);
System.out.println(oAuth2User.getAttributes());
String provider = userRequest.getClientRegistration().getRegistrationId(); // google
OAuth2UserInfo oAuth2UserInfo = null;
switch (provider){
case "google":
oAuth2UserInfo = new GoogleUserInfo(oAuth2User.getAttributes());
break;
case "facebook":
oAuth2UserInfo = new FacebookUserInfo(oAuth2User.getAttributes());
break;
case "naver":
oAuth2UserInfo = new NaverUserInfo((Map<String, Object>) oAuth2User.getAttributes().get("response"));
break;
case "kakao":
oAuth2UserInfo = new KakaoUserInfo(oAuth2User.getAttributes());
break;
default:
System.out.println("지원하지 않는 로그인");
}
// 회원 정보 받아오기 + 회원가입 하기
String providerId = oAuth2UserInfo.getProviderId();
String username = oAuth2UserInfo.getName();
String email = oAuth2UserInfo.getEmail();
String password = bCryptPasswordEncoder.encode(username+providerId);
String role = "ROLE_USER";
UserEntity user = userDAO.selectByEmail(email);
if(user == null){
user = new UserEntity();
user.setU_email(email);
user.setU_nm(username);
user.setU_pw(password);
user.setU_birth(null);
user.setU_tel(null);
user.setAuth(role);
System.out.println(user);
userDAO.insertUser(user);
}else {
}
return new PrincipalDetails(user,oAuth2User.getAttributes());
}
}
|
Python
|
UTF-8
| 1,527 | 2.890625 | 3 |
[] |
no_license
|
import csv
import tkinter
from tkinter import messagebox
with open('AvocadoPrice.csv') as csv_file:
csv_reader = csv.reader(csv_file)
head_row = next(csv_reader)
dic = {}
for row in csv_reader:
combo = (row[0], row[1])
dic[combo] = format(float(row[2]), '.2f')
def compare_price(tuple ,price):
average = float(dic[tuple])
root = tkinter.Tk()
if price >= average:
root.withdraw()
messagebox.showinfo("Information", "Unfair")
elif price < average:
root.withdraw()
messagebox.showinfo("Information", "Fair")
def readinuser(region='TotalUS', Type='None', userPrice=None):
region = str(region)
Type = str(Type)
root = tkinter.Tk()
if type(userPrice) != int and type(userPrice) != float:
root.withdraw()
messagebox.showerror("Error", "Please input a valid number for price")
if userPrice <= 0.00:
root.withdraw()
messagebox.showerror("Error", "This only for single avocado price check. Your input is unreasonable :/")
if userPrice > 5.00:
root.withdraw()
messagebox.showerror("Error", "This only for single avocado price check. Your input is unreasonable :/")
output = {}
userPrice = round(userPrice, 2)
keys = (region, Type)
output[keys] = userPrice
return region, Type
#Please input a valid number for price
#This only for single avocado price check. Your input is unreasonable :/
#This only for single avocado price check. Your input is unreasonable :/
|
Python
|
UTF-8
| 251 | 3.140625 | 3 |
[] |
no_license
|
import sys
sys.stdin = open("input.txt", "r")
T = int(input())
res = []
for tc in range(T):
n = input()
if(int(n[-1]) % 2 == 0):
res.append("Even")
else:
res.append("Odd")
for i in range(T):
print(f"#{i+1} {res[i]}")
|
C++
|
UTF-8
| 1,791 | 3.15625 | 3 |
[] |
no_license
|
#include <array>
#include <functional>
#include <queue>
#include <string>
#include <unordered_set>
#include <vector>
int openLock(std::vector<std::string>& deadends, const std::string& target) {
const std::array<char, 10> NEXT{
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'
};
const std::unordered_set<std::string> DEADENDS(deadends.begin(), deadends.end());
// CORNER CASE: "0000" is one of deadends!
if (DEADENDS.find("0000") != DEADENDS.end()) return -1;
// Typical BFS -- BFS will always find the shortest path while DFS requires
// visiting the whole search space.
std::unordered_set<std::string> visited;
std::queue<std::pair<int, std::string>> queue;
queue.push(std::make_pair(0, std::string("0000")));
visited.insert(queue.front().second);
while(!queue.empty()) {
auto v = queue.front();
queue.pop();
if (v.second == target) {
return v.first;
}
for(int i = 0; i < 4; ++i) {
// next
v.second[i] = NEXT[v.second[i] - '0'];
if (visited.find(v.second) == visited.end() &&
DEADENDS.find(v.second) == DEADENDS.end()) {
queue.push(std::make_pair(v.first + 1, v.second));
visited.insert(v.second);
}
// prev, note the NEXT operation is cyclic
v.second[i] = NEXT[(v.second[i] - '0' + 7) % 10];
if (visited.find(v.second) == visited.end() &&
DEADENDS.find(v.second) == DEADENDS.end()) {
queue.push(std::make_pair(v.first + 1, v.second));
visited.insert(v.second);
}
// Reset
v.second[i] = NEXT[v.second[i] - '0'];
}
}
return -1;
}
|
Python
|
UTF-8
| 2,205 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
from matplotlib import pyplot
import numpy
from scipy.optimize import curve_fit
def function(x, A1, B1, C1, A2, B2, C2):
return A1 * numpy.exp(-B1 * (x - C1)**2) + \
A2 * numpy.exp(-B2 * (x - C2)**2)
def main():
lengths = [10, 20, 30, 40, 50]
V1_max_mean = []
V2_max_mean = []
for length in lengths:
V1_max_arr = []
V2_max_arr = []
Chi_max_arr = []
for i in range(1, 6):
T, E, Cv, M, Chi, V1, V2 = numpy.loadtxt("length_%i_sim_%i_.mean" % (length, i), unpack=True)
params, _ = curve_fit(function, T, V1,
p0=(
1.0, 1.0, T[numpy.argmax(V1)],
1.0, 1.0, T[numpy.argmax(V1)],
), maxfev=10000000)
xnew = numpy.linspace(min(T), max(T), 1000)
ynew = function(xnew, *params)
V1_max = numpy.max(ynew)
params, _ = curve_fit(function, T, V2,
p0=(
1.0, 1.0, T[numpy.argmax(V2)],
1.0, 1.0, T[numpy.argmax(V2)],
), maxfev=10000000)
xnew = numpy.linspace(min(T), max(T), 1000)
ynew = function(xnew, *params)
V2_max = numpy.max(ynew)
V1_max_arr.append(V1_max)
V2_max_arr.append(V2_max)
V1_max_mean.append(numpy.mean(V1_max_arr))
V2_max_mean.append(numpy.mean(V2_max_arr))
X = numpy.log(lengths)
Y1 = numpy.log(V1_max_mean)
Y2 = numpy.log(V2_max_mean)
m1, B1 = numpy.polyfit(X, Y1, 1)
nu1 = 1 / m1
m2, B2 = numpy.polyfit(X, Y2, 1)
nu2 = 1 / m2
pyplot.figure()
pyplot.plot(X, Y1, "or", label=r"$\ln V_{1}$")
pyplot.plot(X, numpy.polyval((m1, B1), X), "--r")
pyplot.plot(X, Y2, "sb", label=r"$\ln V_{2}$")
pyplot.plot(X, numpy.polyval((m2, B2), X), "--b")
pyplot.grid()
pyplot.xlabel(r"$\ln L$", fontsize=20)
pyplot.ylabel(r"$\ln V_1, \ \ln V_2$", fontsize=20)
pyplot.legend(loc="best")
pyplot.savefig("Vn.png")
pyplot.close()
nu = (nu1 + nu2) * 0.5
print("nu1 = ", nu1)
print("nu2 = ", nu2)
print("nu = ", nu)
if __name__ == '__main__':
main()
|
JavaScript
|
UTF-8
| 3,885 | 2.53125 | 3 |
[] |
no_license
|
import React, { useState, useEffect } from "react";
import { Link } from 'react-router-dom';
import { Form, FormInput, FormGroup, Button } from "shards-react";
import { AddBundleToCart } from '../services/common';
export default function PreviousOrderInput() {
const [ bubbles, updateBubbles ] = useState([]);
const [ phoneNumber, updatePhoneNumber ] = useState('');
const [ error, updateError ] = useState('');
const [ previousOrders, updatePreviousOrders ] = useState([]);
useEffect(() => {
getBubbles();
}, []);
function getBubbles() {
fetch('http://localhost:3500/api/bubbles')
.then(response => response.json())
.then(function(data) {
updateBubbles(data);
});
}
function handlePrevOrderSearch(phoneNumber) {
fetch('http://localhost:3500/api/orders/' + phoneNumber)
.then((response) => {
if (response.ok) {
updateError('');
return response.json();
} else {
updatePreviousOrders([]);
updateError('Not found.');
}
})
.then((data) => {
if (data){
let prevOrders = convertPrevOrderSearchToBundle(data);
updatePreviousOrders(prevOrders);
return data;
}
});
}
function convertPrevOrderSearchToBundle(response) {
let bundles = [];
for (let i = 0; i < response.length; i++) {
let currBubbles = [];
for (let n = 0; n < response[i].cartItems.length; n++) {
let bubble = bubbles.find(b => b.id == response[i].cartItems[n][0]);
let quantity = response[i].cartItems[n][1];
bubble.quantity = quantity;
currBubbles.push(bubble);
}
bundles.push({id: i, items: currBubbles});
}
return bundles;
}
function handleAddBundleToCart(bubbles, bundleName) {
AddBundleToCart(bubbles);
window.location.href = "/cart";
}
return (
<div className="cart-prev-order">
<h2 className="cart-prev-order-title">Previous orders</h2>
<Form onSubmit={e => { e.preventDefault(); }} >
<FormGroup>
<label htmlFor="name">Telephone</label>
<FormInput
name="telephone"
onChange={(e) => updatePhoneNumber(e.target.value)}
placeholder="Enter telephone" />
</FormGroup>
<Button className="btn btn-light px-5" onClick={() => handlePrevOrderSearch(phoneNumber)}>Search</Button>
<p>{error}</p>
{previousOrders.map((data) => {
return (
<div className="bundle text-center my-3" key={data.id}>
<div className="card-deck justify-content-center">
{data.items.map((bubble) => {
return (
<Link to={`/bubbles/${bubble.id}`} key={bubble.id}>
<div className="bubble-card card bundle-card text-center text-dark" id={bubble.id} >
<h4 className="card-header">{bubble.name}</h4>
<img className="img-fluid" src={bubble.image} />
<p>Quantity: {bubble.quantity}</p>
<p>{bubble.price} ISK</p>
</div>
</Link>
)})
}
</div>
<div className="w-100 d-flex">
<button className="btn btn-lg btn-outline-success bundle-button addToCart" onClick={() => handleAddBundleToCart(data.items, data.name)}>Add to Cart</button>
</div>
</div>
)
})}
</Form>
</div>
)
}
|
Markdown
|
UTF-8
| 1,076 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
# Lab07-Collections
**Author**: Benjamin Taylor
**Version**: 1.0.0
## Overview
An application that creates a deck of 52 cards and shuffles it.
## Getting Started
1. Create a fork of this repository, and clone your fork to your device.
2. Open the solution file (Cards.sln) in Visual Studio.
3. To run the app, click the green arrow button labeled "Start".
4. For testing, navigate to the TestDeck project using the Solution Explorer.
5. To run the tests, press CTRL+R or navigate to Tests > Run > All Tests in the top-level menu.
## Using The Application

1. Upon starting the application, the screen will be filled by two lists of cards: One showing the deck before the shuffle, and one showing the deck after the shuffle. You can use the scroll bar on the right to view both lists. Pressing any key will exit the application.
## Architecture
**Languages Used**: C# 7.0 (.NET Core 2.1)
Written with Visual Studio Community 2017.
## Change Log
06-23-2018 4:53pm - Initial version.
|
Markdown
|
UTF-8
| 840 | 2.875 | 3 |
[] |
no_license
|
#### 弹窗模板
添加了关闭弹窗时的回调
####8.23
添加了图片预加载的方法,向外暴露
1.向外暴露一个js文件,会暴露出一个构造函数
```javascript
var prop = new Baitai.Popup({
body:".test" //弹窗模板需要放置的地方
});
//弹窗图片预加载(可以选择性的调用)
prop.preImgLoad();
```
2.向外暴露的方法:
```javascript
sendMessage(DATA) //传入弹窗的展示数据
toggleState(ACTION) //弹窗的展示和隐藏,显示:‘show’,隐藏:‘hidden’
```
3.模板的具体使用流程(具体可以参考各个模板中的demo):
* 1.该弹窗模板不会直接被引入到游戏中,而是通过`middle.js`去引入,直接引入到页面的是`middle.js`
* 2.通过middle.js引入成功后,其中new实例对象middle.js会直接做了
|
Python
|
UTF-8
| 11,517 | 2.703125 | 3 |
[] |
no_license
|
#Circle Neighborhood using GDAL and PP
# Parallel Processing- dividing image with border zones, moving window across each piece then recombines
# Calculating the density over circles with radii from 1 to 20 miles
# Circular moving window is approximated using a regular-shaped octagon following Glasbey and Jones (1997)
# and the average is calculated recursively.
# Reading data in subprocess
import os, sys, time, math, numpy, pp
import osgeo.gdal as gdal
from osgeo.gdalconst import *
gdal.AllRegister()
startTime = time.time()
def image_process(startj, starti, rows, cols, offsetX, offsetY, pixelWidth, pixelHeight, originLat, originLon, miles):
try:
gdal
except:
import osgeo.gdal
# print 'Rows: ', rows
# print 'Cols: ', cols
# print 'Startj: ', startj
# print 'Starti: ', starti
fn = 'C:\\Users\\wcj\\Documents\\test\\pop_parallel\\file_0'
inImg = osgeo.gdal.Open(fn, osgeo.gdalconst.GA_ReadOnly)
if inImg is None:
print 'Could not open file ' + fn
sys.exit(1)
band = inImg.GetRasterBand(1)
r = offsetX
p = int(round((1.414213562*(r+1)-1)/3.414213562))
windowSum = 0
count = 0
try:
data = band.ReadAsArray(startj, starti, cols, rows).astype(numpy.int32) # read the subset block of data into memory
except:
print 'Error reading image (subprocess): ' + str(starti) + ', ' + str(startj) + ', ' + str(cols) + ', ' + str(rows)
print sys.exc_info()
sys.exit(1)
outArray = numpy.zeros((rows - (2*offsetY), cols - (2*offsetX)), dtype=long) # output array removes overlapping regions
#f.write(str(startj) + ' ' + str(starti) + ' ' + str(rows) + ' ' + str(cols))
for i in range (offsetY, rows - offsetY):
# loop through all rows, start in from the edge of the grid by offset no. of cells
for j in range (offsetX, cols - offsetX):
# loop through all columns, starting from the offset cell
if j == offsetX: # and i == offsetY: # first row and column location
windowSum = 0 # reset the sum (no recursive calculation)
count = 0
for x in range((i - offsetX), (i + offsetX+1)):
# at each cell, loop through a square centered on i,j
for y in range((j - offsetY), (j + offsetY+1)):
if abs((x-i)+(y-j)) <= offsetX + p and abs((x-i)-(y-j)) <= offsetX + p:
windowSum += data[x,y]
count += 1
## if j == offsetX and i == offsetY:
## f.write('windowSum: ' + str(windowSum) + ' ' + str(i) + ', ' + str(j) + ' \n')
## if j== offsetX and i ==offsetY:
## f.write(str(x) + ', ' + str(y) + '\n')
#print str(i) + ', ' + str(j) + ' - ' + str(x) + ',' + str(y) + ' ' + str(data[x,y])
#windowSum=-2
## elif j == offsetX and i > offsetY: # first column location in the rest of the image
## TL = TC = TR = BL = BC = BR = 0
##
## for k in range(-r,-p+1):
## TR += data[i+k-1, j+r+p+k-1] #
## TL += data[i+k-1, j-r-p-k-1]
## if (i == offsetY + 1):
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j+r+p+k-1) + '\n')
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j-r-p-k-1) + '\n')
##
## for k in range(p, r+1):
## BR += data[i+k-1, j+r+p-k-1] #
## BL += data[i+k-1, j-r-p+k-1]
## if (i == offsetY + 1):
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j+r+p-k-1) + '\n')
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j-r-p+k-1) + '\n')
##
## for k in range(-p+1, j+p):
## BC += data[i+r, k]
## TC += data[i-r, k]
## if (i == offsetY + 1):
## f.write(str(k) + ' ' + str(i+r) + ', ' + str(k) + '\n')
## f.write(str(k) + ' ' + str(i-r) + ', ' + str(k) + '\n')
##
## windowSum = windowSum + BR + BL + BC - TR - TL - TC
## #windowSum = -1
else: # do recursively
A = B = C = D = E = F = 0
try:
try:
for k in range(-r,-p+1):
A += data[i+k-1, j+r+p+k] #j+r+p+k+1
D += data[i+k-1, j-r-p-k-1] #j-r-p-k-1
## if (j == offsetX + 1 and i == offsetY + 1) or (j == offsetX + 2 and i == offsetY + 1):
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j+r+p+k) + '\n')
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j-r-p-k-1) + '\n')
except:
errorMsg = 'loop 1'
raise Exception
try:
for k in range(-p+1,p): #(-p,p) adjusted for range inclusion
B += data[i+k-1, j+r] # j+r
E += data[i+k-1, j-r-1] #i+k-1, j-r
## if (j == offsetX + 1 and i == offsetY + 1) or (j == offsetX + 2 and i == offsetY + 1):
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j+r) + '\n')
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j-r-1) + '\n')
except:
errorMsg = 'loop 2'
raise Exception
try:
for k in range(p,r+1):
C += data[i+k-1, j+r+p-k] # j+r+p-k
F += data[i+k-1, j-r-p+k-1]
## if (j == offsetX + 1 and i == offsetY + 1) or (j == offsetX + 2 and i == offsetY + 1):
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j+r+p-k) + '\n')
## f.write(str(k) + ' ' + str(i+k-1) + ', ' + str(j-r-p+k-1) + '\n')
except:
errorMsg = 'loop 3'
raise Exception
except:
print 'Error in recursive sum at ' + str(i) + ', ' + str(j)
print 'Error in loop: ' + errorMsg
print 'r: ' + str(r)
print 'p: ' + str(p)
print 'k: ' + str(k)
print sys.exc_info()
sys.exit(1)
#print str(A) + ',' + str(B) + ',' + str(C) + ',' + str(D) + ',' + str(E) + ',' + str(F)
#f.write('before: ' + str(windowSum) + '\n')
windowSum = windowSum + (A + B + C - D - E - F)
## if i == offsetY:
## f.write(str(A) + ',' + str(B) + ',' + str(C) + ',' + str(D) + ',' + str(E) + ',' + str(F) + '\n')
## f.write('after: ' + str(windowSum) + ' ' + str(i) + ', ' + str(j) + '\n')
#if windowSum < 0: windowSum = 0
#print str(windowSum)
#if j == 20:
#sys.exit(1)
try:
#print 'WindowSum: ' + str(windowSum)
if windowSum < 0: windowSum = 0
outArray[i-offsetY,j-offsetX] = windowSum #/ (math.pi * miles**2) # sum of all cells in 'circle' / area of circle in sq. miles
except:
print 'Error at ' + str(i) + ', ' + str(j)
print 'Sum = ' + str(sum)
print sys.exc_info()
sys.exit(1)
data = None
band = None
inImg = None
#f.close()
return outArray, startj+offsetX, starti+offsetY
# tuple of all parallel python servers to connect with
ppservers = ()
#ppservers = ("10.0.0.1",)
if len(sys.argv) > 1:
ncpus = int(sys.argv[1])
# Creates jobserver with ncpus workers
job_server = pp.Server(ncpus, ppservers=ppservers)
else:
# Creates jobserver with automatically detected number of workers
job_server = pp.Server(ppservers=ppservers)
print "Starting pp with", job_server.get_ncpus(), "workers"
# open the file
#fn = 'L:\\Chris\\Reactors_Siting\\Pop\\version2\\lsusa08day'
#fn = 'P:\\demos\\pop_parallel\\file_0'
fn = 'C:\\Users\\wcj\\Documents\\test\\pop_parallel\\file_0'
#fn = 'P:\\demos\\pop_parallel\\pt_pop'
inImg = gdal.Open(fn, GA_ReadOnly)
if inImg is None:
print 'Could not open file ' + fn
sys.exit(1)
# get image size
cols = inImg.RasterXSize
rows = inImg.RasterYSize
bands = inImg.RasterCount
print 'Img: cols=' + str(cols) + ', rows=' + str(rows)
#band = inImg.GetRasterBand(1)
# get image properties
geotransform = inImg.GetGeoTransform()
originX = geotransform[0]
originY = geotransform[3]
pixelWidth = geotransform[1]
pixelHeight = geotransform[5]
originLat = originY + (pixelHeight / 2)
originLon = originX + (pixelWidth / 2)
# divide the image into subsets and send to PP jobs
for radius in range (1,2): # *** Change range for choice of radii ***
print 'Radius: ' + str(radius)
miles = radius * 1609.344 # radius in meters -- pixel size in meters
offsetX = int(miles / pixelWidth) # convert the radius into the number of cells
offsetY = int(miles / (-1*pixelHeight))
print 'Pixel Width=' + str(pixelWidth) + ', Pixel Height=' + str(pixelHeight)
print 'Offset X:' + str(offsetX) + ' Y:' + str(offsetY)
jobs = []
#Read data by block - *** test different block sizes
xBlockSize = 400
yBlockSize = 400
for i in range(0, rows, yBlockSize): # starting at origin (upper-left)
if i == 0:
starti = 0
numRows = yBlockSize + offsetY
else:
starti = i - offsetY
if i + yBlockSize + offsetY < rows:
numRows = yBlockSize + (2*offsetY)
else:
numRows = rows - starti
for j in range(0, cols, xBlockSize):
if j == 0:
startj = 0
numCols = xBlockSize + offsetX
else:
startj = j - offsetX
if j + xBlockSize + offsetX < cols:
numCols = xBlockSize + (2*offsetX)
else:
numCols = cols - startj
try:
print str(startj) + ', ' + str(starti) + ', ' + str(numCols) + ', ' + str(numRows)
# send to the job server: coordinates of the image process
jobs.append(job_server.submit(image_process, (startj, starti, numRows, numCols, offsetX, offsetY, pixelWidth, pixelHeight, originLat, originLon, miles,), (), ("math", "numpy", "osgeo.gdal", "osgeo.gdalconst",)))
data = None
except:
print 'Error!'
print sys.exc_info()
#raw_input('Press a key ...')
# create output image
print ' ... creating output image'
#driver = inImg.GetDriver()
driver = gdal.GetDriverByName('HFA')
driver.Register()
#out_fn = 'C:\\Temp\\loop\\output2\\loop10_' + str(radius) + '.img'
out_fn = 'C:\\Users\\wcj\\Documents\\test\\ParallelPop\\loop10_' + str(radius) + '.img'
#outImg = driver.Create(out_fn, cols, rows, 1, GDT_Byte)
outImg = driver.Create(out_fn, cols, rows, 1, GDT_Int32)
if outImg is None:
print 'Could not create output image ' + out_fn
sys.exit(1)
outBand = outImg.GetRasterBand(1)
# write output data
for job in jobs: # loop through returned PP tasks
outData, j, i = job()
try:
outBand.WriteArray(outData, j, i)
print '.... output ....'
print j, i
print outData.size
#print outData
outData = None
#break
except:
print 'Error writing output image: ' + str(i) + ', ' + str(j)
print outData.size
print outData
print sys.exc_info()
sys.exit(1)
outBand.FlushCache()
stats = outBand.GetStatistics(0,1)
outImg.SetGeoTransform(inImg.GetGeoTransform())
outImg.SetProjection(inImg.GetProjection())
outImg = None
# clean up and finish
inImg = None
#data = None
#band = None
#outBand = None
job_server.print_stats()
endTime = time.time()
print 'Finished! ' + str(endTime - startTime)
|
C++
|
UTF-8
| 509 | 3.671875 | 4 |
[] |
no_license
|
#include<iostream>
using namespace std;
void maximum_difference_problem(int a[],int n)
{
int res = a[1] - a[0];
int k = a[0];
for(int i=1;i<n;i++)
{
res = max(res,a[i]-k);
k = min(k,a[i]);
}
cout<<"The max difference is : "<<res<<endl;
}
int main(void)
{
int n;
cout<<"Size of array : ";
cin>>n;
int a[n];
cout<<"Enter the elements of array : "<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
maximum_difference_problem(a,n);
}
|
Java
|
UTF-8
| 2,327 | 2.234375 | 2 |
[] |
no_license
|
package com.luwei.dubbo_provider.rocketmq.producer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.BrokerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @projectName: GitHub
* @packageName: com.luwei.rocketmq.producer
* @auther: luwei
* @description: RocketMQ 生产者配置
* @date: 2020/2/23 19:15
* @alert: This document is private to luwei
* @version: 1.8.00_66
*/
@Configuration
public class ProducerConfig {
private static final Logger LOG = LoggerFactory.getLogger(ProducerConfig.class) ;
@Value("${rocketmq.producer.groupName}")
private String groupName;
@Value("${rocketmq.producer.namesrvAddr}")
private String namesrvAddr;
@Value("${rocketmq.producer.maxMessageSize}")
private Integer maxMessageSize ;
@Value("${rocketmq.producer.sendMsgTimeout}")
private Integer sendMsgTimeout;
@Value("${rocketmq.producer.retryTimesWhenSendFailed}")
private Integer retryTimesWhenSendFailed;
@Bean
public DefaultMQProducer getRocketMQProducer() {
BrokerConfig brokerConfig = new BrokerConfig();
brokerConfig.setNamesrvAddr(this.namesrvAddr);
DefaultMQProducer producer = new DefaultMQProducer(this.groupName);
producer.setNamesrvAddr(this.namesrvAddr);
//如果需要同一个jvm中不同的producer往不同的mq集群发送消息,需要设置不同的instanceName
if(this.maxMessageSize!=null){
producer.setMaxMessageSize(this.maxMessageSize);
}
if(this.sendMsgTimeout!=null){
producer.setSendMsgTimeout(this.sendMsgTimeout);
}
//如果发送消息失败,设置重试次数,默认为2次
if(this.retryTimesWhenSendFailed!=null){
producer.setRetryTimesWhenSendFailed(this.retryTimesWhenSendFailed);
}
try {
producer.start();
System.err.println("生产者启动成功");
} catch (MQClientException e) {
e.printStackTrace();
}
return producer;
}
}
|
C#
|
UTF-8
| 3,547 | 2.96875 | 3 |
[] |
no_license
|
using SpeechLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading;
namespace LB.Common
{
public class LBSpeakHelper
{
public static string SpeakString="";
private static SpeechSynthesizer speak = new SpeechSynthesizer();
private static Prompt prompt = null;
//public static void AddSpeak(string strMsg)
//{
// lock (LstSpeak)
// {
// if (!LstSpeak.Contains(strMsg))
// {
// LstSpeak.Add(strMsg);
// }
// }
//}
public static void Speak(enSpeakType eSpeakType)
{
string strSpeak = "";
switch (eSpeakType)
{
case enSpeakType.FinishWeight:
strSpeak = "称重完毕,请离开秤台";
break;
case enSpeakType.ToWeightCenter:
strSpeak = "请停到秤台中间";
break;
case enSpeakType.UpToWeight:
strSpeak = "请上秤";
break;
case enSpeakType.UpDownWeight:
strSpeak = "请下秤";
break;
case enSpeakType.PleaseCard:
strSpeak = "请刷卡";
break;
case enSpeakType.ReadCardSuccess:
strSpeak = "刷卡成功,请离开!";
break;
}
if (strSpeak != "")
{
try
{
SpeakString = strSpeak;
//speak.Rate = -3;
//speak.SpeakAsync(strSpeak);
}
catch (Exception ex)
{
}
//speak.Speak(strSpeak);
//speak.Dispose(); //释放之前的资源
}
}
public static bool Speak(string strSpeak)
{
bool bolIsCompleted = false;
if (strSpeak != "")
{
try
{
if (prompt == null || prompt.IsCompleted)
{
bolIsCompleted = true;
speak.Rate = -3;
speak.Volume = 100;
//speak.SelectVoice("Microsoft Lili");
//speak.SelectVoiceByHints(VoiceGender.Neutral, VoiceAge.Adult, 2, System.Globalization.CultureInfo.CurrentCulture);
prompt = speak.SpeakAsync(strSpeak);
}
//speak.Dispose(); //释放之前的资源
}
catch (Exception ex)
{
}
}
return bolIsCompleted;
}
}
public enum enSpeakType
{
/// <summary>
/// 称重完毕,请离开秤台
/// </summary>
FinishWeight,
/// <summary>
/// 请停到秤台中间
/// </summary>
ToWeightCenter,
/// <summary>
/// 请上秤
/// </summary>
UpToWeight,
/// <summary>
/// 请下秤
/// </summary>
UpDownWeight,
/// <summary>
/// 请刷卡
/// </summary>
PleaseCard,
/// <summary>
/// 刷卡成功,请离开
/// </summary>
ReadCardSuccess
}
}
|
JavaScript
|
UTF-8
| 1,216 | 3.875 | 4 |
[] |
no_license
|
// Array with 3 of my favorite games as objects, each object should have the same 4 properties
const games = [
{name: 'Cards Against Humanity', numberOfPlayers: 4, rating:5, type:'card game'},
{name: 'Taboo Midnight', numberOfPlayers: 4, rating:4, type:'buzzer game'},
{name: 'The Game of Life Quarter Life Crisis', numberOfPlayers:2, rating:4, type:'board game'},
];
//Prompt user to select a random number
let randomIdx = prompt('I have 3 games in my collection. Pick a number between 1 and 3 and I will tell you about that game');
if (randomIdx > 3) {
window.alert('Please choose a number between 1 and 3');
} else {
console.log('You selected' + ' ' + games[randomIdx - 1].name + ', ' + 'which is a' + ' ' + games[randomIdx - 1].type + ' ' + 'that has a rating of' + ' ' + games[randomIdx - 1].rating + ' ' + 'and that needs at least' + ' ' + games[randomIdx -1].numberOfPlayers + ' ' + 'players' + '.');
window.alert ('You selected' + ' ' + games[randomIdx - 1].name + ', ' + 'which is a' + ' ' + games[randomIdx - 1].type + ' ' + 'that has a rating of' + ' ' + games[randomIdx -1].rating + ' ' + 'and that needs at least' + ' ' + games[randomIdx - 1].numberOfPlayers + ' ' + 'players' + '.')
}
|
JavaScript
|
UTF-8
| 532 | 2.75 | 3 |
[] |
no_license
|
let numOfSegments;
let stepAngle;
let radius;
function setup() {
createCanvas(500,500);
colorMode(HSB,360,100,100);
}
function draw() {
numOfSegments = map(mouseX,0,width,10,40);
stepAngle = (TWO_PI)/numOfSegments;
radius = 200;
push();
translate(250,250);
beginShape(TRIANGLE_FAN);
vertex(0,0);
//vertex(mouseX,mouseY);
for(let i=0; i<=360; i+=stepAngle) {
let vx = (radius * cos(i));
let vy = (radius * sin(i));
vertex(vx,vy);
}
endShape();
pop();
}
|
Java
|
UTF-8
| 635 | 2.046875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package si.opkp;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import si.opkp.model.MySQLDatabase;
import si.opkp.model.NodeSuccessResult;
import si.opkp.util.Pojo;
@Component
@Primary
class DatabaseMock extends MySQLDatabase {
@Override
public NodeSuccessResult callFunction(String function, Object... args) {
List<Pojo> result = new ArrayList<>();
if (function.equals("ping")) {
result.add(new Pojo.Builder()
.property("ping", "pong")
.build());
}
return new NodeSuccessResult(result, 1);
}
}
|
TypeScript
|
UTF-8
| 239 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
export default class NumberUtils {
static roundRange(val: number, min: number, max: number) {
if (val > max) {
val = max;
} else if (val < min) {
val = min;
}
return val;
}
}
|
JavaScript
|
UTF-8
| 2,746 | 2.890625 | 3 |
[] |
no_license
|
const S_UP = 0;
const S_DOWN = 1;
const S_LEFT = 2;
const S_RIGHT = 3;
const S_WIDTH = 320;
const S_HEIGHT = 240;
const S_BODYSIZE = 16;
var arrow = S_DOWN;
var bodyarr = new Array();
var foodarr = new Array();
init = function() {
for (i = 0; i<9; i++) {
var tmp = new Object();
tmp.x = i*S_BODYSIZE;
tmp.y = 0;
bodyarr.push(tmp);
}
}
drawcan = {
test: function(canvas) {
if (canvas) {
var context = elem.getContext('2d');
if(context){
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 4;
context.shadowColor = 'rgba(122,122,122, 0.5)';
context.fillStyle = '#0000ff';
context.fillRect(0, 0, S_WIDTH, S_HEIGHT);
context.font = 'italic 40px sans-serif';
context.textBaseline = 'top';
context.fillStyle = 'rgba(222, 122, 122, 0.5)';
context.fillText('DrawCan Test!', 5, 5);
}
}
else {
alert('canvas element is null');
}
} ,
drawbody: function(canvas) {
drawcan.drawrect(canvas, 0, 0, S_WIDTH, S_HEIGHT, '#fff');
for (i in bodyarr) {
body=bodyarr[i];
drawcan.drawrect(canvas, body.x, body.y, S_BODYSIZE, S_BODYSIZE, '#000');
}
} ,
drawfood: function(canvas) {
for (i in foodarr) {
food=foodarr[i];
drawcan.drawrect(canvas, food.x, food.y, S_BODYSIZE, S_BODYSIZE, '#0a0');
}
} ,
drawrect: function(canvas, x, y, w, h, color) {
if (canvas) {
var context = canvas.getContext('2d');
if(context) {
context.save();
context.fillStyle = color;
context.fillRect(x, y, w, h);
context.restore();
}
}
} ,
}
mainwhile = function() {
cur = bodyarr[bodyarr.length-1];
x=y=0;
switch(arrow) {
case S_UP:
x = cur.x;
y = cur.y-S_BODYSIZE;
break;
case S_DOWN:
x = cur.x;
y = cur.y+S_BODYSIZE;break;
case S_LEFT:
x = cur.x-S_BODYSIZE;
y = cur.y;
break;
case S_RIGHT:
x = cur.x+S_BODYSIZE;
y = cur.y;
break;
default:break;
}
if (x<0) x += S_WIDTH; else x %= S_WIDTH;
if (y<0) y += S_HEIGHT; else y %= S_HEIGHT;
var body = new Object;
body.x = x;
body.y = y;
bodyarr.push(body);
bodyarr.shift();
canvas = document.getElementById('snakCanvas');
drawcan.drawbody(canvas);
drawcan.drawfood(canvas);
}
window.addEventListener('load', function() {
$(document).bind('keypress', function(event) {
key = event.keyCode||event.which||event.charCode;
//alert(key);
switch(key) {
case 119:
case 38: arrow=S_UP; return;
case 115:
case 40: arrow=S_DOWN; return;
case 97:
case 37: arrow=S_LEFT; return;
case 100:
case 39: arrow=S_RIGHT; return;
default: return;
}
});
init();
setInterval(mainwhile, 150);
},100);
|
C++
|
UTF-8
| 5,089 | 3.390625 | 3 |
[] |
no_license
|
#include <iostream>
#include <map>
template<typename K>
class Key
{
public:
Key(K val) : _val(val) {}
// copyable
Key(K& k) : _val(k._val) {}
// assignable
void operator=(const Key<K>& k) { _val = k._val; }
// less than
bool operator<(const Key<K>& k) const { return _val < k._val; }
private:
K _val;
Key() = delete;
};
template<typename V>
class Value
{
public:
Value(V val) : _val(val) {}
// copyable
Value(V& v) : _val(v._val) {}
// assignable
void operator=(const Value<V>& v) { _val = v._val; }
// comparable via operator==
bool operator==(const Value<V>& v) const { return _val == v._val; }
private:
V _val;
Value() = delete;
};
template<typename K, typename V>
class interval_map {
V m_valBegin;
std::map<K, V> m_map;
public:
// constructor associates whole range of K with val
interval_map(V const& val)
: m_valBegin(val)
{}
// Assign value val to interval [keyBegin, keyEnd).
// Overwrite previous values in this interval.
// Conforming to the C++ Standard Library conventions, the interval
// includes keyBegin, but excludes keyEnd.
// If !( keyBegin < keyEnd ), this designates an empty interval,
// and assign must do nothing.
void assign(K const& keyBegin, K const& keyEnd, V const& val) {
// INSERT YOUR SOLUTION HERE
if (!(keyBegin < keyEnd)) return;
if (m_map.empty()) {
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, m_valBegin));
return;
}
//canonical?
bool isCanonical = true;
//cases for keyEnd
if (!(m_map.rbegin()->first < keyEnd) && !(keyEnd < m_map.rbegin()->first)) isCanonical &= !(val == m_valBegin);
else if (m_map.rbegin()->first < keyEnd) isCanonical &= !(val == m_valBegin);
else if (!(keyEnd < m_map.begin()->first) && !(m_map.begin()->first < keyEnd)) {
isCanonical &= !(val == m_map.begin()->second);
}
else if (keyEnd < m_map.begin()->first) {
isCanonical &= !(val == m_valBegin);
}
else {
//to be
auto b = m_map.find(keyEnd);
if (b != m_map.end()) {
isCanonical &= !(val == b->second);
}
else {
isCanonical &= !(val == m_valBegin);
}
}
// cases for keyBegin
if (!(keyBegin < m_map.begin()->first) && !(m_map.begin()->first < keyBegin)) isCanonical &= !(val == m_valBegin);
else if (keyBegin < m_map.begin()->first) isCanonical &= !(val == m_valBegin);
else if (!(m_map.rbegin()->first < keyBegin) && !(keyBegin < m_map.rbegin()->first)) {
auto b = m_map.rbegin();
isCanonical &= !((++b)->second == val);
}
else if (m_map.rbegin()->first < keyBegin) {
isCanonical &= !(val == m_valBegin);
}
else {
if(m_map.find(keyBegin) == m_map.end()) {
//key is not there but still inside
isCanonical &= !(val == m_valBegin);
}
else {
auto b = m_map.begin();
b = m_map.lower_bound(keyBegin);
if (--b != m_map.end()) isCanonical &= !(val == (--b)->second);
}
}
//if canonical
if (isCanonical) {
m_map.erase(m_map.lower_bound(keyBegin), m_map.lower_bound(keyEnd));
V keyEndValue = operator[](keyEnd); //
m_map.insert_or_assign(keyBegin, val);
m_map.insert_or_assign(keyEnd, keyEndValue);
}
}
// look-up of the value associated with key
V const& operator[](K const& key) const {
auto it = m_map.upper_bound(key);
if (it == m_map.begin()) {
return m_valBegin;
}
else {
return (--it)->second;
}
}
void IntervalMapTest() {
//m_map.assign(8, 10, 'k');
//imap.assign(8, 12, 'k');
}
void show() {
std::cout << "\nshow" << std::endl;
for (auto entry : m_map) {
std::cout << entry.first << "," << entry.second << std::endl;
}
}
};
// Many solutions we receive are incorrect. Consider using a randomized test
// to discover the cases that your implementation does not handle correctly.
// We recommend to implement a test function that tests the functionality of
// the interval_map, for example using a map of int intervals to char.
int main(void) {
interval_map<int, char> imap('A');
imap.assign(8, 10, 'k');
imap.show();
imap.assign(8, 10, 'b');
imap.show();
imap.assign(10, 15, 'b');
imap.show();
imap.assign(0, 4, 'b');
imap.show();
return 0;
}
|
Markdown
|
UTF-8
| 660 | 2.625 | 3 |
[
"MIT",
"CC-BY-NC-4.0",
"CC-BY-NC-SA-3.0"
] |
permissive
|
<!-- title: Les souvenirs du 15 août -->
<!-- category: Humeur -->
Mon parrain a toujours aimé le 15 août et sa fête annuelle au village. Le gros de la journée était rythmé par le tournoi de pétanque, en doublette ou en triplette, avec ses beau-frères. Je me souviens de la franche camaraderie et de la bonne humeur même si on perdait le point, du pastis payé par les perdants à chaque fin de partie. Et la journée se clôturait par une bonne bouffe et le tirage du feu d'artifice.

Quatre ans déjà que tu nous as quitté. Tu nous manques toujours autant, nous nous souvenons des bons moments.
|
Markdown
|
UTF-8
| 2,599 | 2.75 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
[环境类问题](#1)
[ 1、项目初始构建出现 Could not get resource 'https:xxxxx'](#1.1)
[配置类问题](#2)
[ 1、使用系统组件加载异常](#2.1)
[ 2、manifest allowBackup 问题](#2.2)
[ 3、运行启动插件异常——Excution failed for task ':app:phInstallPluginDebug'](#2.3)
[代码实现问题](#3)
------------
<h2 id='1'> 环境类问题</h2>
<h3 id='1.1'>1、项目初始构建出现 Could not get resource 'https:xxxxx'</h3>
**问题描述:** https 访问地址受限,导致工程无法运行。
**原因:** 工程配置所需的 lib 在 https 上可能没有个,需要重配置工程。
**举例:**
> 暂无
**解决方法:**
> 参考:https://blog.csdn.net/shenjinalin123/article/details/84235187
------------
<h2 id='2'> 配置类问题</h2>
<h3 id='2.1'>1、使用系统组件加载异常</h3>
**问题描述:** 在插件中使用部分系统组件加载不出来,达不到预期效果。
**原因:** 可能使用到的系统组件未在宿主中进行权限声明。
**举例:** 如下场景
> *在插件中调用相机,扫描二维码,surfaceView 无任何图像展示。*
**解决方法:** 权限的声明是以宿主为主的,因为在检测应用权限的时候,标识是以宿主权限为参考。所以上述场景中,使用相机时,如果未在宿主中进行权限声明,那么在插件中,仍然无法使用相应的系统组件。所以,此类问题的解决方法,只需要再宿主中申请相应的权限即可。
<h3 id='2.2'>2、manifest allowBackup 问题</h3>
**问题描述:** 如图:

**原因:** 插件运行需要配置是否支持后台响应
**举例:** 如下场景
> 无
**解决方法:**
在 manifest 中配置加入 `tools:replace="anroid:allowBackup"`
<h3 id='2.3'>3、运行启动插件异常——Excution failed for task ':app:phInstallPluginDebug'</h3>
**问题描述:** 如图:

**原因:** 要从 AS 直接启动或调试目标插件,插件是运行在宿主的,所以在启动插件的时候,必须保证宿主处于启动状态,否则启动任务无法完成插件安装和启动操作。
**举例:**
> 无
**解决方法:**
启动调试插件之前,先启动宿主。保证宿主在前台。
------------
<h2 id='3'> 代码实现问题</h2>
|
Python
|
UTF-8
| 3,450 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
import math
class Tile:
#a tile of the map and its properties
def __init__(self, blocked, block_sight=None):
self.blocked = blocked
self.explored = False
#by default, if a tile is blocked, it also blocks sight
if block_sight is None:
block_sight = blocked
self.block_sight = block_sight
class Rect:
#a rectangle on the map. used to characterize a room.
def __init__(self, x, y, w, h):
self.x1 = x
self.y1 = y
self.x2 = x + w
self.y2 = y + h
def center(self):
center_x = (self.x1 + self.x2) / 2
center_y = (self.y1 + self.y2) / 2
return (center_x, center_y)
def intersect(self, other):
#returns true if this rectangle intersects with another one
return (self.x1 <= other.x2 and self.x2 >= other.x1 and
self.y1 <= other.y2 and self.y2 >= other.y1)
class Object:
#this is a generic object: the player, a monster, an item, the stairs...
#it's always represented by a character on screen.
def __init__(self, x, y, char, name, blocks=False, fighter=None, ai=None, item=None):
self.x = x
self.y = y
self.char = char
self.name = name
self.blocks = blocks
self.fighter = fighter
self.ai = ai
self.item = item
if self.fighter: # let the fighter component know who owns it
self.fighter.owner = self
if self.ai: # let the AI component know who owns it
self.ai.owner = self
if self.item: # let the Item component know who owns it
self.item.owner = self
def move(self, dx, dy, dungeon):
#move by the given amount, if the destination is not blocked
if not is_blocked(self.x + dx, self.y + dy, dungeon):
self.x += dx
self.y += dy
def get(self, player):
if (self.x, self.y) in player.fov_coords:
return self
def clear(self):
del self
def move_towards(self, target_x, target_y, dungeon):
#vector from this object to the target, and distance
dx = target_x - self.x
dy = target_y - self.y
distance = math.sqrt(dx ** 2 + dy ** 2)
#normalize it to length 1 (preserving direction), then round it and
#convert to integer so the movement is restricted to the map grid
dx = int(round(dx / distance))
dy = int(round(dy / distance))
self.move(dx, dy, dungeon)
def distance_to(self, other):
#return the distance to another object
dx = other.x - self.x
dy = other.y - self.y
return math.sqrt(dx ** 2 + dy ** 2)
def send_to_back(obj, objects):
# make this object be drawn first, so all others appear above it if
# they're in the same tile.
objects.remove(obj)
objects.insert(0, obj)
def is_blocked(x, y, dungeon):
#first test the map tile
if dungeon.map[x][y].blocked:
return True
#now check for any blocking objects
for object in dungeon.objects:
if object.blocks and object.x == x and object.y == y:
return True
return False
class Item:
def pickUp(self, objects, console):
objects.remove(self.owner)
console.printStr('You picked up ' + self.owner.name + '!')
if self.owner.name == 'Cone of Dunshire':
return True
else:
return False
|
C#
|
UTF-8
| 3,115 | 3.09375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
using static System.Console;
namespace Factory
{
//public class NYStyleChessPizza: Pizza
// {
// public NYStyleChessPizza()
// {
// name = "NY Style Sauce and Cheese Pizza";
// dough = "Thin Crust Dough";
// sauce = "Marinara Sauce";
// topping.Add("Grated Reggiano Cheese");
// }
// }
// public class ChicagoStyleCheesePizza: Pizza
// {
// public ChicagoStyleCheesePizza()
// {
// name = "Chicago Style Deep Dish Cheese Pizza";
// dough = "Extra Thick Crust Dough";
// sauce = "Plum Tomato Sauce";
// topping.Add("Shredded Mozzarella Cheese");
// }
// public override void cut()
// {
// WriteLine("Cutting the pizza into square slices");
// }
// }
public class CheesePizza : Pizza
{
PizzaIngredientFactory ingredientFactory;
public CheesePizza(PizzaIngredientFactory PizzaingredientFactory) //原料工厂
{
ingredientFactory = PizzaingredientFactory;
}
public override void prepare()
{
WriteLine("Perparing " + name);
dough = ingredientFactory.createDough();
sauce = ingredientFactory.createSauce();
cheese = ingredientFactory.createCheese();
}
}
public class ClamPizza : Pizza
{
PizzaIngredientFactory ingredientFactory;
public ClamPizza(PizzaIngredientFactory PizzaingredientFactory) //原料工厂
{
ingredientFactory = PizzaingredientFactory;
}
public override void prepare()
{
WriteLine("Perparing " + name);
dough = ingredientFactory.createDough();
sauce = ingredientFactory.createSauce();
cheese = ingredientFactory.createCheese();
clam = ingredientFactory.createClam();
}
}
public class VeggiePizza : Pizza
{
PizzaIngredientFactory ingredientFactory;
public VeggiePizza(PizzaIngredientFactory PizzaingredientFactory) //原料工厂
{
ingredientFactory = PizzaingredientFactory;
}
public override void prepare()
{
WriteLine("Perparing " + name);
dough = ingredientFactory.createDough();
sauce = ingredientFactory.createSauce();
veggies = ingredientFactory.createVeggies();
}
}
public class PepperoniPizza : Pizza
{
PizzaIngredientFactory ingredientFactory;
public PepperoniPizza(PizzaIngredientFactory PizzaingredientFactory) //原料工厂
{
ingredientFactory = PizzaingredientFactory;
}
public override void prepare()
{
WriteLine("Perparing " + name);
dough = ingredientFactory.createDough();
sauce = ingredientFactory.createSauce();
pepperoni = ingredientFactory.createPepperoni();
}
}
}
|
C++
|
UTF-8
| 1,224 | 3.15625 | 3 |
[] |
no_license
|
//
// Created by Ahmed Al Mahrooqi on 2019-02-28.
//
#include "gtest/gtest.h"
#include "IntHashTable.h"
#include "EmployeeDirectory.h"
TEST(inthashtable, iterator_functions) { //test begin(),end() and increment(), and getData() functions
IntHashTable t(6);
t.insert(1);
t.insert(3);
t.insert(5);
int i = -1;
for(auto it = t.begin(); !it.end(); ++it) {
i+=2; // produces odd numbers: 1,3,5
EXPECT_EQ(it.getData(), i );
}
}
TEST(inthashtable, resize_function) { //test begin(),end() and increment(), and getData() functions
IntHashTable t(3);
t.insert(3);
auto it = t.begin();
EXPECT_EQ(it.getData(),3); //at begining (location 0), the bucket should contain 3 (3%3=0)
t.resize(5);
t.insert(0);
it=t.begin();
++it;
EXPECT_EQ(it.getData(),3);
}
TEST(employeeDirectory, public_functions) {
EmployeeDirectory d(4);
Employee e;
d.insert(Employee("Johns","Adam","Mr.","IT","31881"));
EXPECT_TRUE(d.search("Johns",e));
EXPECT_TRUE(d.peek("Johns"));
EXPECT_EQ(d.search("Johns",e)->first_name,"Adam");
d.remove("Johns");
EXPECT_FALSE(d.peek("Johns"));
}
|
Java
|
UTF-8
| 2,691 | 2.40625 | 2 |
[] |
no_license
|
package com.ab.cryptoportfolio.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
/**
* @author Arpit Bhardwaj
*/
/*@Configuration
//@Order(2)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
//byu default the framework uses formLogin() -> usernamePasswordFilter
//to configure only basicAuthenticationFilter
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.logout();
//to allow framing in same domain
http.headers().frameOptions().sameOrigin().and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.logout();
//to allow framing in wide domain
http.headers().frameOptions().disable()
.addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "ALLOW-FROM yourdomain.com")).and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.logout();
//to disable content type header
http.headers().contentTypeOptions().disable().and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.logout();
//to disable csrf
http.csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.logout();
//to place csrf in request instead of cookie
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.logout();
}
}*/
public class SecurityConfiguration{}
|
Python
|
UTF-8
| 786 | 2.90625 | 3 |
[] |
no_license
|
import yagmail
string1 = 'portal'
# opening a text file
file1 = open("ymail.txt", "r")
# read file content
readfile = file1.read()
# checking condition for string found or not
if string1 in readfile:
sender_email = 'abdmail799@gmail.com'
receiver_email = ['habhilash3@gmail.com','manikantar281@gmail.com']
subject = "Check THIS out"
sender_password ='L6JXLkAxnFxDiV4'
yag = yagmail.SMTP(user=sender_email, password=sender_password)
contents = ["This is the first paragraph in our email","As you can see, we can send a list of strings,","being this our third one",]
attachments=['Desktop/File 1/image1.png','Desktop/File 1/gantt2.png','Desktop/File 1/gantt3.png']
yag.send(receiver_email, subject, contents, attachments)
else:
print('No Government Land Records Found in the area.')
# closing a file
file1.close()
|
C
|
UTF-8
| 757 | 4 | 4 |
[
"MIT"
] |
permissive
|
/*
A alocação dinâmica é feita via funções malloc, realloc, calloc e free da biblioteca stdlib.h
*/
# include <stdio.h>
# include <stdlib.h>
int main(void) {
// A função malloc irá alocar memória e retornar o ponteiro do primeiro espaço alocado retornando um ponteiro do tipo "void".
int *ptr_mDinamica = malloc(sizeof(int));
//algumas vezes pode ocorrer erro por conta do tipo, então basta fazer o casting para o tipo do ponteiro
//*ptr_mDinamica = (int *) malloc(sizeof(int));
*ptr_mDinamica = 5;
printf("Endereço apontado pelo ponteiro: %x\n", ptr_mDinamica);
printf("Valor apontado pelo ponteiro: %d\n", *ptr_mDinamica);
// free() Desaloca a memória
free(ptr_mDinamica);
return 0;
}
|
C#
|
UTF-8
| 1,161 | 2.75 | 3 |
[] |
no_license
|
using System.Collections.Generic;
using Cosmetics.Contracts;
namespace Cosmetics.Handlers
{
public class AddToShoppingCartHandler : ProcessingCommnadHandler
{
private const string ProductAddedToShoppingCart = "Product {0} was added to the shopping cart!";
public AddToShoppingCartHandler(ICosmeticsFactory cosmeticsFactory)
: base(cosmeticsFactory)
{
}
protected override bool CanHandle(string commandName)
{
return commandName == "AddToShoppingCart";
}
protected override string Handle(ICommand command, IShoppingCart shoppingCart, IDictionary<string, ICategory> categories, IDictionary<string, IProduct> products)
{
var productToAddToCart = command.Parameters[0];
if (!products.ContainsKey(productToAddToCart))
{
return string.Format(ProductDoesNotExist, productToAddToCart);
}
var product = products[productToAddToCart];
shoppingCart.AddProduct(product);
return string.Format(ProductAddedToShoppingCart, productToAddToCart);
}
}
}
|
C#
|
UTF-8
| 1,070 | 2.96875 | 3 |
[] |
no_license
|
using BLInterfaces;
using System;
using System.Collections.Generic;
namespace ConsolePL
{
public class AwardPL
{
private ILogicLayer _BL;
public AwardPL(ILogicLayer bl)
{
_BL = bl;
}
public void AddAward()
{
List<string> userInfo = new List<string>();
userInfo.Add(_BL.GetEntities().Count.ToString());
Console.WriteLine("Введите название награды");
userInfo.Add(Console.ReadLine());
Console.WriteLine($"{Environment.NewLine}Выберите пользователей," +
$" представленных к награждению:{Environment.NewLine}");
Console.WriteLine(_BL.AddEntity(userInfo, AddAwardedUsers(), string.Empty));
Console.WriteLine();
}
List<int> AddAwardedUsers()
=> new CommonConsoleLogic().AddConnectedEntities(_BL);
public void DeleteAward()
=> new CommonConsoleLogic().DeleteEntity(_BL);
}
}
|
C
|
UTF-8
| 594 | 2.515625 | 3 |
[] |
no_license
|
#include "loading.h"
#include "common.h"
#include "resource.h"
#include "env.h"
SDL_Surface* loading_bg;
SDL_Surface* loading_status_bg;
SDL_Surface* loading_status_fg;
SDL_Surface* loading_screen;
void loading_init(SDL_Surface* screen)
{
loading_screen = screen;
loading_bg = load_global_image("loading.png");
loading_start();
}
void loading_start()
{
SDL_BlitSurface(loading_bg, NULL, loading_screen, NULL);
SDL_Flip(loading_screen);
}
void loading_deinit()
{
free_surface(loading_bg);
free_surface(loading_status_bg);
free_surface(loading_status_fg);
}
|
C#
|
UTF-8
| 15,780 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using org.apache.zookeeper;
using org.apache.zookeeper.data;
namespace Org.Apache.CuratorNet.Client.Utils
{
public class ZKPaths
{
/**
* Zookeeper's path separator character.
*/
public const String PATH_SEPARATOR = "/";
private static readonly CreateMode NON_CONTAINER_MODE = CreateMode.PERSISTENT;
/**
* @return {@link CreateMode#CONTAINER} if the ZK JAR supports it. Otherwise {@link CreateMode#PERSISTENT}
*/
public static CreateMode getContainerCreateMode()
{
return CreateModeHolder.containerCreateMode;
}
/**
* Returns true if the version of ZooKeeper client in use supports containers
*
* @return true/false
*/
public static bool hasContainerSupport()
{
return getContainerCreateMode() != NON_CONTAINER_MODE;
}
private static class CreateModeHolder
{
internal static readonly Logger log = LogManager.GetCurrentClassLogger();
internal static readonly CreateMode containerCreateMode;
static CreateModeHolder()
{
CreateMode localCreateMode;
try
{
//localCreateMode = CreateMode.valueOf("CONTAINER");
localCreateMode = NON_CONTAINER_MODE;
}
catch ( Exception)
{
localCreateMode = NON_CONTAINER_MODE;
log.Warn("The version of ZooKeeper being used doesn't support Container nodes. " +
"CreateMode.PERSISTENT will be used instead.");
}
containerCreateMode = localCreateMode;
}
}
/**
* Apply the namespace to the given path
*
* @param namespace namespace (can be null)
* @param path path
* @return adjusted path
*/
public static String fixForNamespace(String ns, String path)
{
return fixForNamespace(ns, path, false);
}
/**
* Apply the namespace to the given path
*
* @param namespace namespace (can be null)
* @param path path
* @param isSequential if the path is being created with a sequential flag
* @return adjusted path
*/
public static String fixForNamespace(String ns, String path, bool isSequential)
{
// Child path must be valid in and of itself.
PathUtils.validatePath(path, isSequential);
if ( ns != null )
{
return makePath(ns, path);
}
return path;
}
/**
* Given a full path, return the node name. i.e. "/one/two/three" will return "three"
*
* @param path the path
* @return the node
*/
public static String getNodeFromPath(String path)
{
PathUtils.validatePath(path);
int i = path.LastIndexOf(PATH_SEPARATOR);
if (i < 0)
{
return path;
}
if ((i + 1) >= path.Length)
{
return "";
}
return path.Substring(i + 1);
}
public class PathAndNode
{
private readonly String path;
private readonly String node;
public PathAndNode(String path, String node)
{
this.path = path;
this.node = node;
}
public String getPath()
{
return path;
}
public String getNode()
{
return node;
}
}
/**
* Given a full path, return the node name and its path. i.e. "/one/two/three" will return {"/one/two", "three"}
*
* @param path the path
* @return the node
*/
public static PathAndNode getPathAndNode(String path)
{
PathUtils.validatePath(path);
int i = path.LastIndexOf(PATH_SEPARATOR);
if (i < 0)
{
return new PathAndNode(path, "");
}
if ((i + 1) >= path.Length)
{
return new PathAndNode(PATH_SEPARATOR, "");
}
String node = path.Substring(i + 1);
String parentPath = (i > 0) ? path.Substring(0, i) : PATH_SEPARATOR;
return new PathAndNode(parentPath, node);
}
/**
* Given a full path, return the the individual parts, without slashes.
* The root path will return an empty list.
*
* @param path the path
* @return an array of parts
*/
public static List<String> split(String path)
{
PathUtils.validatePath(path);
return SplitPath(path);
// return PATH_SPLITTER.splitToList(path);
}
// private static readonly Splitter PATH_SPLITTER
// = Splitter.on(PATH_SEPARATOR).omitEmptyStrings();
private static List<string> SplitPath(string path)
{
return path.Split(new[] { PATH_SEPARATOR },
StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
/**
* Make sure all the nodes in the path are created.
* NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish
* between directories and files. So, every node in the path is created.
* The data for each node is an empty blob.
*
* @param zookeeper the client
* @param path path to ensure
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException Zookeeper errors
*/
public static void mkdirs(ZooKeeper zookeeper, String path)
{
mkdirs(zookeeper, path, true, null, false);
}
/**
* Make sure all the nodes in the path are created.
* NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish
* between directories and files. So, every node in the path is created.
* The data for each node is an empty blob.
*
* @param zookeeper the client
* @param path path to ensure
* @param makeLastNode if true, all nodes are created. If false, only the parent nodes are created
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException Zookeeper errors
*/
public static void mkdirs(ZooKeeper zookeeper,
String path,
bool makeLastNode)
{
mkdirs(zookeeper, path, makeLastNode, null, false);
}
/**
* Make sure all the nodes in the path are created. NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish
* between directories and files. So, every node in the path is created. The data for each node is an empty blob
*
* @param zookeeper the client
* @param path path to ensure
* @param makeLastNode if true, all nodes are created. If false, only the parent nodes are created
* @param aclProvider if not null, the ACL provider to use when creating parent nodes
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException Zookeeper errors
*/
public static void mkdirs(ZooKeeper zookeeper,
String path,
bool makeLastNode,
IInternalACLProvider aclProvider)
{
mkdirs(zookeeper, path, makeLastNode, aclProvider, false);
}
/**
* Make sure all the nodes in the path are created. NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish
* between directories and files. So, every node in the path is created. The data for each node is an empty blob
*
* @param zookeeper the client
* @param path path to ensure
* @param makeLastNode if true, all nodes are created. If false, only the parent nodes are created
* @param aclProvider if not null, the ACL provider to use when creating parent nodes
* @param asContainers if true, nodes are created as {@link CreateMode#CONTAINER}
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException Zookeeper errors
*/
public static async void mkdirs(ZooKeeper zookeeper,
String path,
bool makeLastNode,
IInternalACLProvider aclProvider,
bool asContainers)
{
PathUtils.validatePath(path);
int pos = 1; // skip first slash, root is guaranteed to exist
do
{
pos = path.IndexOf(PATH_SEPARATOR, pos + 1);
if ( pos == -1 )
{
if ( makeLastNode )
{
pos = path.Length;
}
else
{
break;
}
}
String subPath = path.Substring(0, pos);
if ( await zookeeper.existsAsync(subPath, false) == null )
{
try
{
IList<ACL> acl = null;
if ( aclProvider != null )
{
acl = aclProvider.getAclForPath(subPath);
if ( acl == null )
{
acl = aclProvider.getDefaultAcl();
}
}
if ( acl == null )
{
acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
}
await zookeeper.createAsync(subPath,
new byte[0],
acl.ToList(),
getCreateMode(asContainers))
.ConfigureAwait(false);
}
catch ( KeeperException.NodeExistsException)
{
// ignore... someone else has created it since we checked
}
}
}
while ( pos<path.Length );
}
/**
* Recursively deletes children of a node.
*
* @param zookeeper the client
* @param path path of the node to delete
* @param deleteSelf flag that indicates that the node should also get deleted
* @throws InterruptedException
* @throws KeeperException
*/
public static async void deleteChildren(ZooKeeper zookeeper,
String path,
bool deleteSelf)
{
PathUtils.validatePath(path);
ChildrenResult children = await zookeeper.getChildrenAsync(path, null);
foreach( String child in children.Children )
{
String fullPath = makePath(path, child);
deleteChildren(zookeeper, fullPath, true);
}
if ( deleteSelf )
{
try
{
await zookeeper.deleteAsync(path, -1);
}
catch ( KeeperException.NotEmptyException )
{
//someone has created a new child since we checked ... delete again.
deleteChildren(zookeeper, path, true);
}
catch ( KeeperException.NoNodeException )
{
// ignore... someone else has deleted the node it since we checked
}
}
}
/**
* Return the children of the given path sorted by sequence number
*
* @param zookeeper the client
* @param path the path
* @return sorted list of children
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException zookeeper errors
*/
public static async Task<List<string>> getSortedChildren(ZooKeeper zookeeper, String path)
{
ChildrenResult children = await zookeeper.getChildrenAsync(path, false);
List<string> sortedList = new List<string>(children.Children);
sortedList.Sort();
return sortedList;
}
/**
* Given a parent path and a child node, create a combined full path
*
* @param parent the parent
* @param child the child
* @return full path
*/
public static String makePath(String parent, String child)
{
StringBuilder path = new StringBuilder();
joinPath(path, parent, child);
return path.ToString();
}
/**
* Given a parent path and a list of children nodes, create a combined full path
*
* @param parent the parent
* @param firstChild the first children in the path
* @param restChildren the rest of the children in the path
* @return full path
*/
public static String makePath(String parent, String firstChild, params String[] restChildren)
{
StringBuilder path = new StringBuilder();
joinPath(path, parent, firstChild);
if (restChildren == null)
{
return path.ToString();
}
else
{
foreach(String child in restChildren)
{
joinPath(path, "", child);
}
return path.ToString();
}
}
/**
* Given a parent and a child node, join them in the given {@link StringBuilder path}
*
* @param path the {@link StringBuilder} used to make the path
* @param parent the parent
* @param child the child
*/
private static void joinPath(StringBuilder path, String parent, String child)
{
// Add parent piece, with no trailing slash.
if ((parent != null) && (parent.Length > 0))
{
if (!parent.StartsWith(PATH_SEPARATOR))
{
path.Append(PATH_SEPARATOR);
}
if (parent.EndsWith(PATH_SEPARATOR))
{
path.Append(parent.Substring(0, parent.Length - 1));
}
else
{
path.Append(parent);
}
}
if ((child == null) || (child.Length == 0) || (child.Equals(PATH_SEPARATOR)))
{
// Special case, empty parent and child
if (path.Length == 0)
{
path.Append(PATH_SEPARATOR);
}
return;
}
// Now add the separator between parent and child.
path.Append(PATH_SEPARATOR);
if (child.StartsWith(PATH_SEPARATOR))
{
child = child.Substring(1);
}
if (child.EndsWith(PATH_SEPARATOR))
{
child = child.Substring(0, child.Length - 1);
}
// Finally, add the child.
path.Append(child);
}
private ZKPaths()
{
}
private static CreateMode getCreateMode(bool asContainers)
{
return asContainers ? getContainerCreateMode() : CreateMode.PERSISTENT;
}
}
}
|
Java
|
UTF-8
| 1,349 | 1.851563 | 2 |
[] |
no_license
|
package com.kapalert.kadunastategovernment.utils;
import android.app.Application;
import android.content.Context;
import android.os.StrictMode;
import androidx.multidex.MultiDex;
import org.acra.ACRA;
import org.acra.config.ACRAConfiguration;
import org.acra.config.ConfigurationBuilder;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
//Main application class
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
// builder.detectFileUriExposure();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath(Constants.FONT_FILE)
.setFontAttrId(uk.co.chrisjenx.calligraphy.R.attr.fontPath)
.build()
);
final ACRAConfiguration config;
try {
config = new ConfigurationBuilder(this)
.setMailTo("naveen.orem@gmail.com")
.build();
ACRA.init(this, config);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
|
Java
|
UTF-8
| 2,040 | 1.71875 | 2 |
[] |
no_license
|
package defpackage;
/* renamed from: avp reason: default package */
/* compiled from: PG */
public final class avp {
public java.util.Set a = new java.util.HashSet();
private boolean b;
private boolean c;
private boolean d;
private java.lang.String e;
private android.accounts.Account f;
private java.lang.String g;
private java.util.Map h = new java.util.HashMap();
public avp() {
}
public avp(com.google.android.gms.auth.api.signin.GoogleSignInOptions googleSignInOptions) {
defpackage.azb.b((java.lang.Object) googleSignInOptions);
this.a = new java.util.HashSet(googleSignInOptions.g);
this.b = googleSignInOptions.j;
this.c = googleSignInOptions.k;
this.d = googleSignInOptions.i;
this.e = googleSignInOptions.l;
this.f = googleSignInOptions.h;
this.g = googleSignInOptions.m;
this.h = com.google.android.gms.auth.api.signin.GoogleSignInOptions.b((java.util.List) googleSignInOptions.n);
}
public final defpackage.avp a() {
this.a.add(com.google.android.gms.auth.api.signin.GoogleSignInOptions.a);
return this;
}
public final defpackage.avp a(com.google.android.gms.common.api.Scope scope, com.google.android.gms.common.api.Scope... scopeArr) {
this.a.add(scope);
this.a.addAll(java.util.Arrays.asList(scopeArr));
return this;
}
public final com.google.android.gms.auth.api.signin.GoogleSignInOptions b() {
if (this.a.contains(com.google.android.gms.auth.api.signin.GoogleSignInOptions.c) && this.a.contains(com.google.android.gms.auth.api.signin.GoogleSignInOptions.b)) {
this.a.remove(com.google.android.gms.auth.api.signin.GoogleSignInOptions.b);
}
if (this.d && (this.f == null || !this.a.isEmpty())) {
a();
}
return new com.google.android.gms.auth.api.signin.GoogleSignInOptions(3, new java.util.ArrayList(this.a), this.f, this.d, this.b, this.c, this.e, this.g, this.h);
}
}
|
Python
|
UTF-8
| 922 | 3.1875 | 3 |
[] |
no_license
|
import sys
from operator import itemgetter
from heapq import heappush, heappop
input = sys.stdin.readline
def simulate(camels):
camels.sort(key=itemgetter(0))
queue = []
ans = 0
for k, l, r in camels:
ans += l
if len(queue) < k:
# ok
heappush(queue, l - r)
else:
heappush(queue, l - r)
d = heappop(queue)
ans -= d
return ans
def solve():
n = int(input())
camels = [tuple(map(int, input().split())) for _ in range(n)]
ans = 0
camels_l = []
camels_r = []
for k, l, r in camels:
if k == n or l == r:
ans += l
elif l > r:
camels_l.append((k, l, r))
else:
# r > l
camels_r.append((n - k, r, l))
ans += simulate(camels_l)
ans += simulate(camels_r)
print(ans)
t = int(input())
for _ in range(t):
solve()
|
PHP
|
UTF-8
| 239 | 2.734375 | 3 |
[] |
no_license
|
<?php
function getName($d_id, $dbc)
{
$sql = 'SELECT Name FROM Datei WHERE D_ID = :d_id';
$get_name = $dbc->prepare($sql);
$get_name->bindParam(':d_id', $d_id);
$get_name->execute();
return $get_name->fetchColumn();
}
|
Java
|
UTF-8
| 1,621 | 2.734375 | 3 |
[] |
no_license
|
package com.serkancay.multiplerecyclerview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import com.serkancay.multiplerecyclerview.Book.Type;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView rvBooks;
private BookListAdapter mBookListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvBooks = findViewById(R.id.rvBooks);
List<Book> books = generateDummyList();
mBookListAdapter = new BookListAdapter(this, books);
rvBooks.setAdapter(mBookListAdapter);
}
private List<Book> generateDummyList() {
List<Book> books = new ArrayList<>();
books.add(new Book(
"Selahattin Eyyubi ve Aslan Yürekli Richard",
"3. Haçlı Haçlı Seferinin Filistin Safhasının Romanı",
"Yazar: Walter Scott",
"Yayınevi : Ötüken Neşriyat",
19.90,
19.90,
R.drawable.img_book_1,
Type.NORMAL));
books.add(
new Book(
"Kader Anı",
"The Click Moment",
"Yazar: Frans Johansson",
"Yayınevi : Mediacat Yayıncılık",
35.00,
21.70,
R.drawable.img_book_2,
Type.DISCOUNTED));
return books;
}
}
|
C#
|
UTF-8
| 818 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using UnityEngine;
using UnityEngine.Events;
public class ArduinoConnection : MonoBehaviour
{
// Callback signature
// Has: Return of type 'void' and 2 parameters
public delegate void TouchCallback(int pin, bool touched);
// Event declaration
public event TouchCallback OnBookTouched;
void Start()
{
}
void Update()
{
}
void OnSerialLine(string line)
{
// Parse line
char[] splitChar = {' '};
string[] splitLine = line.Split(splitChar);
int pin = int.Parse(splitLine[0]);
bool touched = int.Parse(splitLine[1]) != 0;
// Invoke the event
if (OnBookTouched != null)
OnBookTouched(pin,touched);
}
}
|
Markdown
|
UTF-8
| 2,119 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
Traditional PHP Method of Accessing Files
=========================================
Traditionally, files were accessed through a stream resource and many specialised
functions that operated on that resource.
What is a Resource?
-------------------
Resources were created to fill the gap that the lack of OOP left in early versions of PHP.
They have stayed with us since.
A resource is a primitive PHP type, just like an int or a string. The implementation of
resources is not unlike C-style pointers, with each resource variable pointing to a
data structure in memory. The structure holds properties and state of the resource.
Being a pointer allows resources to be passed around by reference. In fact,
resources have always been passed by reference.
A resource is not an object. It does not have methods or properties you can access
directly. You can only create or access or use resources through specialised functions
that operat, create or destroy those resources.
A PHP resource is a data structure that represents an external resource. An external
resource can be anything - a file or stream, a directory, a document, an image, a HTTP
connection, a Flash object, a database connection - the list goes on.
There are around 120 [resource types](http://www.php.net/manual/en/resource.php) available
in PHP in a standard install. Each one has dozens of functions that operate on them, and
that fills the global function space with well over a thousand functions that we really
don't need; we don't need, because there are better ways of handling external resources now.
TODO: example of using a stream resource and the functions involved.
The problems with resources is:
* They are not objects, so cannot be extended, serialised, dumped to a log file.
* They require many specialised functions to operate on them.
This talk is going to focus on one resource type: stream. This type handles directories
and directory structures, files and file names, and supports a number of different
protocols (not just local files). The flysystem package aims to offer an alternative
to this resource in a more OOP way.
|
PHP
|
UTF-8
| 1,852 | 2.625 | 3 |
[] |
no_license
|
<?php
//
// Created by Grégoire JONCOUR on 09/04/2015.
// Copyright (c) 2015 Grégoire JONCOUR. All rights reserved.
//
namespace App\Entity;
use App\App;
use App\Vendor\Avatar;
use Core\Entity\Entity;
class UserEntity extends Entity
{
public function getName(){
return $this->firstname.' '.$this->lastname;
}
public function getPhonenumberFormat(){
return wordwrap($this->phonenumber,2," ",true);
}
public function getCompleteAddress(){
$adresse = $this->streetAddress;
$adresse .= ', '.$this->postalcode;
$adresse .= ', '.$this->city;
return $adresse;
}
public function getGps(){
// Google Maps Geocoder
$geocoder = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false";
// Requête envoyée à l'API Geocoding
$query = sprintf($geocoder, urlencode(utf8_encode($this->getCompleteAddress())));
$result = json_decode(file_get_contents($query));
$json = $result->results[0];
$Lat = (string) $json->geometry->location->lat;
$Lng = (string) $json->geometry->location->lng;
return array('lat' => $Lat, 'lng' => $Lng) ;
}
public function getCompleteDateRegister()
{
setlocale (LC_TIME, 'fr_FR.UTF-8','fra');
$date=ucfirst(utf8_encode(strftime("%A %d %B %Y à %Hh%M", strtotime($this->date_register))));
return $date;
}
public function getDateRegister(){
return date("d/m/Y - H:i", strtotime($this->date_register));
}
public function getGroup(){
$group = App::getInstance()->getTable('group')->find($this->id_group);
return $group->name;
}
public function getAvatarUrl(){
$avatarUrl = Avatar::getGravatar($this->email, 'identicon');
return Avatar::renderAvatar($avatarUrl, $this->id);
}
}
|
Markdown
|
UTF-8
| 1,088 | 3.109375 | 3 |
[] |
no_license
|
# 웹엑스 강의
- 문제는 파이참을 통해 푼다.
## 배열 활용 예제
- 입력의 4가지 방법
```python
a = input()
b = int(input())
c = list(input().split())
d = list(map(int, input().split())) # map 을 하지 않으면 리스트로만 받고 이를 숫자로 받고싶으면 map이 필
print(a, type(a))
```
- gravity
> 상자들이 쌓여있는 방이 있다. 방이 오른쪽으로 90도 회전하여 상자들이 중력의 영향을 받아 낙하한다고 할 때, 낙차가 가장 큰 상자를 구하여 그 낙차를 리턴하는 프로그램을 작성하시오.
> 중력은 회전이 완료된 후 적용된다.
> 상자들은 모두 한쪽 벽면에 붙여진 상태로 쌓여 2차원의 형태를 이루며 벽에서 떨어져서 쌓인 상자는 없다.
> 방의 가로길이는 항상 100이며, 세로 길이도 항상 100이다.
> 즉, 상자는 최소0, 최대 100 높이로 쌓을 수 있다.
> => 여기서 낙차가 가장 큰 상자를 구하라고 했으니 A 상자겠지!
>
> => 나보다 작은 애가 몇개지?
|
C#
|
UTF-8
| 1,669 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Traffic;
namespace Traffic
{
/// <summary>
/// Script for plat.
/// </summary>
public class Plat : OnRoadObject
{
[SerializeField]
private Vector3 startPosition;
[SerializeField]
private Vector3 speed;
[SerializeField]
private GameConfig state;
[SerializeField]
private int id;
public override Vector3 Speed
{
get => speed;
set => this.speed = value;
}
public override Vector3 StartPosition
{
get => this.startPosition;
set
{
this.startPosition = value;
transform.localPosition = this.startPosition;
}
}
public override GameConfig State
{
get => this.state;
set => this.state = value;
}
public override int Id
{
get => this.id;
set => this.id = value;
}
// Start.
public override void Start()
{
this.startPosition = transform.localPosition;
}
// Fixed update.
public override void FixedUpdate() {
Move();
}
// Move.
public override void Move()
{
if (this.speed.z > 0)
{
throw new System.ArgumentException("Z component of speed value for plat should be negative");
}
var convSpeed = this.state.InstantSpeed;
transform.Translate(convSpeed);
}
}
}
|
C++
|
UTF-8
| 3,703 | 2.5625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/shm.h>
#include "data_struct.h"
#include <fcntl.h>
#include <fstream>
//消费者1
#define PRODUCER_NUM 2 //生产者数目
#define CONSUMER_NUM 2 //消费者数目
#define SHARED_SIZE 64
#define BUFFER_SIZE (SHARED_SIZE/sizeof(CommonData)) //缓冲池大小,可存放int类型数
#define P_READ bufptrs[0] //缓冲池读取指针
#define P_WRITE bufptrs[1] //缓冲池写入指针
using namespace std;
int main()
{
void *shared_memory = (void *)0;
CommonData *shared_stuff;
void *pids_memory = (void *)0;
pid_t *pids;
void *bufptr_memory = (void *)0;
int *bufptrs;
int shmid1,shmid2,shmid3;
srand((unsigned int)getpid());
shmid1 = shmget((key_t)1234, SHARED_SIZE, 0666 | IPC_CREAT);
shmid2 = shmget((key_t)12345, 2*sizeof(pid_t), 0666 | IPC_CREAT);
shmid3 = shmget((key_t)123456, 2*sizeof(int), 0666 | IPC_CREAT);
if (shmid1 == -1 || shmid2 == -1 || shmid3 == -1)
{
printf("shmget failed\n");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid1, (void *)0, 0);
pids_memory = shmat(shmid2, (void *)0, 0);
bufptr_memory = shmat(shmid3, (void *)0, 0);
if (shared_memory == (void *)-1 || pids_memory == (void *)-1 || bufptr_memory == (void *)-1)
{
printf( "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached\n");
shared_stuff = (CommonData*)shared_memory;
pids = (pid_t*)pids_memory;
bufptrs = (int*)bufptr_memory;
sem_t *room_sem = sem_open("room_sem",O_CREAT, 0644, BUFFER_SIZE); //同步信号信号量,表示缓冲区有可用空间
sem_t *product_sem = sem_open("product_sem",O_CREAT,0644, 0); //同步信号量,表示缓冲区有可用产品
sem_t *mutex = sem_open("mutex",O_CREAT,0644, 1);
if (room_sem == SEM_FAILED || product_sem == SEM_FAILED || mutex == SEM_FAILED)
{
printf("sem initial failed.");
sem_unlink("room_sem");
sem_unlink("product_sem");
sem_unlink("mutex");
exit(EXIT_FAILURE);
}
fstream file_out("a.out", fstream::out);
if(file_out.is_open())
{
for (int i = 0; i < 10000; ++i)
{
usleep(rand() % 500000 + 500000);
sem_wait(product_sem);
sem_wait(mutex);
CommonData* data = &shared_stuff[P_READ];
if (data->program_id == pids[0])
{
file_out << data->data << "\t";
P_READ= ( P_READ + 1) % BUFFER_SIZE;
int pro_num = (int)((P_WRITE-P_READ+BUFFER_SIZE)%BUFFER_SIZE);
printf("Consumer 2 read from buffer, with data %d\n", data->data);
printf("product number is %d\n",pro_num == 0? 8:pro_num);
sem_post(mutex);
sem_post(room_sem);
}
else
{
--i;
sem_post(mutex);
sem_post(product_sem);
}
}
}
else
{
printf("Open file failed.");
}
file_out.close();
sem_close(room_sem);
sem_close(product_sem);
sem_close(mutex);
sem_unlink("room_sem");
sem_unlink("product_sem");
sem_unlink("mutex");
if (shmdt(shared_memory) == -1)
{
printf("shmdt1 failed\n");
exit(EXIT_FAILURE);
}
if (shmdt(pids_memory) == -1)
{
printf("shmdt2 failed\n");
exit(EXIT_FAILURE);
}
if (shmdt(bufptr_memory) == -1)
{
printf("shmdt1 failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid1, IPC_RMID, 0) == -1)
{
printf("shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid2, IPC_RMID, 0) == -1)
{
printf("shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid3, IPC_RMID, 0) == -1)
{
printf("shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
printf("Process 3 done.");
getchar();
return 0;
}
|
Java
|
UTF-8
| 638 | 2.03125 | 2 |
[] |
no_license
|
package test;
import driver.DriverSingleton;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import util.TestListener;
import java.util.concurrent.TimeUnit;
@Listeners ({TestListener.class})
public class CommonConditions {
protected WebDriver driver;
@BeforeClass
public void browserSetUp() {
driver = DriverSingleton.getDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
@AfterClass
public void exit() {
DriverSingleton.closeDriver();
}
}
|
Java
|
UTF-8
| 734 | 3 | 3 |
[] |
no_license
|
package l28try2;
public class Application {
public static void main(String[] args) {
byte byteValue = 127;
short shortValue = 334;
int intValue = 1234;
long longValue = 342356;
float floatValue = 42.545f;
double doubleValue = 342.534534;
shortValue = byteValue;
System.out.println(shortValue);
intValue = (int) longValue;
System.out.println(intValue);
doubleValue = (double)floatValue;
System.out.println(doubleValue);
floatValue = (float)doubleValue;
System.out.println();
System.out.println(floatValue);
intValue = (int)doubleValue;
System.out.println();
System.out.println(intValue);
byte bv = (byte)128;
System.out.println(bv);
}
}
|
Shell
|
UTF-8
| 976 | 3.921875 | 4 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash
# Constants
source "$(dirname "$(realpath "$0")")/../../scripts/common.sh"
declare -ri EXIT_MISSING_BINS=110
declare -ri EXIT_UKNOWN_OPT=111
declare -ri EXIT_RSYNC=112
run_check "$EXIT_MISSING_BINS" "Missing binaries" \
"ensure_bins rsync"
# Show help text
show_help() {
cat <<EOF
upload.sh - Upload a file
USAGE
upload.sh [-h] HOST_FILE REMOTE_FILE
OPTIONS
-h Show help text
ARGUMENTS
HOST_FILE File on this host machine to upload
REMOTE_FILE Location on the remote machine at which to upload HOST_FILE
BEHAVIOR
Uploads a file to the Pi.
EOF
exit 0
}
# Options
while getopts "h" opt; do
case "$opt" in
h) show_help ;;
'?') die "$EXIT_UNKNOWN_OPT" "Unknown option" ;;
esac
done
shift $((OPTIND-1))
# Arguments
declare -r HOST_FILE="$1"
declare -r REMOTE_FILE="$2"
run_check "$EXIT_RSYNC" "Failed to upload '$HOST_FILE' to '$REMOTE_FILE'" \
"rsync "$HOST_FILE" $(ssh_conn_str):"$REMOTE_FILE""
|
PHP
|
UTF-8
| 2,021 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace WebTranslator\Utility;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\TranslatorInterface;
class TranslationHelper
{
public static function getRealCatalogueSize($primaryLocale, Translator $translator)
{
$primaryCatalogue = $translator->getCatalogue($primaryLocale);
$size = 0;
foreach ($primaryCatalogue->all() AS $domain => $translations) {
$size += sizeof($translations);
}
return $size;
}
public static function getTotalUntranslated($primaryLocale, Translator $translator,array $locales)
{
$untranslated = 0;
$primaryCatalogue = $translator->getCatalogue($primaryLocale)->all();
// iterate through the primary catalogue as our source of truth
foreach ($locales AS $locale) {
if ($locale != $primaryLocale) {
$fallbackCatalogue = $translator->getCatalogue($locale);
// loop through the primary catalogue and check to see if it's present in the fallback
foreach ($primaryCatalogue AS $domain => $translations) {
foreach ($translations AS $translationKey => $translationValue) {
if (!$fallbackCatalogue->has($translationKey, $domain)) {
$untranslated++;
}
}
}
}
}
return $untranslated;
}
public static function compareTotalTranslations(TranslatorInterface $translator, $locale1, $locale2)
{
$catalogue1 = $translator->getCatalogue($locale1)->all();
$catalogue2 = $translator->getCatalogue($locale2)->all();
$size1 = $size2 = 0;
foreach ($catalogue1 AS $domain => $translations) {
$size1 += sizeof($translations);
}
foreach ($catalogue2 AS $domain => $translations) {
$size2 += sizeof($translations);
}
return $size1 - $size2;
}
}
|
Java
|
UTF-8
| 983 | 3.1875 | 3 |
[] |
no_license
|
package hw07;
import static org.junit.Assert.assertEquals;
import controller.ImageUtils;
import java.io.IOException;
import model.image.Image;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the resize class, observing if the images are correctly resized while still maintaining
* the correct makeup of the image.
*/
public class TestResize {
Image before;
@Before
public void setup() {
try {
before = ImageUtils.read("photos/squidward.png");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testResizeSimpleImage() {
Image after = before.resize(321, 544);
assertEquals(321, after.getWidth());
assertEquals(544, after.getHeight());
}
@Test(expected = IllegalArgumentException.class)
public void testResizeIllegalArg() {
before.resize(987788765, 1349807110);
}
@Test//no exception
public void test1by1Resize() {
assertEquals(before.resize(1, 1).getHeight(), 1);
}
}
|
Java
|
UTF-8
| 143 | 1.84375 | 2 |
[] |
no_license
|
@OnCreateMountContent protected static EditTextWithEventHandlers onCreateMountContent(Context c){
return new EditTextWithEventHandlers(c);
}
|
PHP
|
UTF-8
| 2,996 | 2.765625 | 3 |
[] |
no_license
|
<?php
namespace models;
use core\Model;
class Subscription extends Model
{
private $planningId;
private $userId;
private $dateTime;
private $grade;
private $reviewed;
private $present;
private $planning;
private $user;
public function __construct()
{
parent::__construct();
}
public function setData($data)
{
$this->planningId = $data->planningID;
$this->userId = $data->gebruikerID;
$this->dateTime = $data->datumtijd;
$this->grade = $data->cijfer;
$this->reviewed = $data->beoordeling;
$this->present = $data->aanwezig;
}
/**
* @return mixed
*/
public function getPlanningId()
{
return $this->planningId;
}
/**
* @param $planningId
*
* @return $this
*/
public function setPlanningId($planningId)
{
$this->planningId = $planningId;
return $this;
}
/**
* @return mixed
*/
public function getUserId()
{
return $this->userId;
}
/**
* @param $userId
*
* @return $this
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/**
* @return mixed
*/
public function getDateTime()
{
return $this->dateTime;
}
/**
* @param $dateTime
*
* @return $this
*/
public function setDateTime($dateTime)
{
$this->dateTime = $dateTime;
return $this;
}
/**
* @return mixed
*/
public function getGrade()
{
return $this->grade;
}
/**
* @param $grade
*
* @return $this
*/
public function setGrade($grade)
{
$this->grade = $grade;
return $this;
}
/**
* @return mixed
*/
public function getReviewed()
{
return $this->reviewed;
}
/**
* @param $reviewed
*
* @return $this
*/
public function setReviewed($reviewed)
{
$this->reviewed = $reviewed;
return $this;
}
/**
* @return mixed
*/
public function getPresent()
{
return $this->present;
}
/**
* @param $present
*
* @return $this
*/
public function setPresent($present)
{
$this->present = $present;
return $this;
}
/**
* @return mixed
*/
public function getPlanning()
{
return $this->planning;
}
/**
* @param $planning
*
* @return $this
*/
public function setPlanning($planning)
{
$this->planning = $planning;
return $this;
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* @param User $user
*
* @return $this
*/
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
}
|
Java
|
UTF-8
| 332 | 2.453125 | 2 |
[] |
no_license
|
import java.applet.*;
import java.awt.*;
public class IBMChatClientApplet extends Applet {
public void init() {
String host = getParameter("host");
int port = Integer.parseInt(getParameter("port"));
setLayout(new BorderLayout());
add("Center", new IBMChatClient(host, port));
}
}
|
PHP
|
UTF-8
| 651 | 3.140625 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?
namespace rude;
class crypt
{
public static function password($password, $salt = null, $salt_length = 32)
{
if ($salt === null)
{
$salt = static::salt($salt_length);
}
$hash = md5($password . $salt);
return array($hash, $salt);
}
public static function salt($length = 32, $alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
return strings::rand($length, $alphabet);
}
public static function is_valid($password, $hash, $salt)
{
list($tmp_hash, $tmp_salt) = static::password($password, $salt);
if ($tmp_hash === $hash and $tmp_salt === $salt)
{
return true;
}
return false;
}
}
|
C
|
UTF-8
| 2,656 | 2.765625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "fantasma.h"
#include "fantasmaDos.h"
#include "utn.h"
#define QTY 100
#define QTY_PUB 1000
#include "informar.h"
int main()
{
Cliente arrayC[QTY];
Publicacion arrayP[QTY_PUB];
int menu;
int auxiliarId;
Cliente_init(arrayC,QTY);
Publicacion_init(arrayP,QTY_PUB);
do
{
getValidInt("\n1.Alta\n2.Baja\n3.Modificar\n4.Publicar\n5.Pausar Publicacion\n6.reanudar publicacion\n7.mostrar clientes\n8.mostrar publicaciones\n9.Salir\n10.El cliente con mas avisos activos\n11.El cliente con mas avisos pausados\n12.el cliente con mas avisos\n13.cant publicaciones de un rubro\n14.rubro con mas publicaciones activas\n15.rubro con menos publicaciones activas\n","\nNo valida\n",&menu,1,15,1);
switch(menu)
{
case 1:
Cliente_alta(arrayC,QTY);
break;
case 2:
getValidInt("ID?","\nNumero valida\n",&auxiliarId,0,200,2);
Cliente_baja(arrayC,QTY,auxiliarId);
break;
case 3:
getValidInt("ID?","\nNumero valida\n",&auxiliarId,0,200,2);
Cliente_modificacion(arrayC,QTY,auxiliarId);
break;
case 4:
Publicacion_alta(arrayP,QTY_PUB,arrayC, QTY );
break;
case 5:
publicacion_pausar(arrayP, QTY_PUB , arrayC, QTY);
break;
case 6:
publicacion_reanudar(arrayP, QTY_PUB,arrayC, QTY);
break;
case 7 :
Cliente_mostrar(arrayC,QTY,arrayP, QTY_PUB);
break;
case 8 :
publicaciones_mostrar(arrayC,QTY, arrayP, QTY_PUB);
break;
case 10 :
informar_clienteConMasAvisosActivos(arrayC,QTY,arrayP,QTY_PUB);
break;
case 11 :
informar_clienteConMasAvisosPausados(arrayC,QTY,arrayP,QTY_PUB);
break;
case 12 :
informar_clienteConMasAvisos(arrayC,QTY,arrayP,QTY_PUB);
break;
case 13 :
cantidadPublicacionRubroIngresado(arrayP, QTY_PUB);
break;
case 14 :
rubroMasPublicacionesActivas(arrayP, QTY_PUB);
break;
case 15 :
rubroMenosPublicacionesActivas(arrayP, QTY_PUB);
break;
}
}while(menu != 9);
return 0;
}
|
Java
|
UTF-8
| 1,069 | 2.125 | 2 |
[] |
no_license
|
package com.example.diary;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
public class MainActivity extends AppCompatActivity
{
TextInputEditText passwordTextInputEditText;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindViews();
}
public void onClickSubmit(View v)
{
if (!passwordTextInputEditText.getText().toString().equals(getString(R.string.nimi)))
{
Toast.makeText(this, R.string.wrong_password,Toast.LENGTH_SHORT).show();
}
else
{
Intent intent=new Intent(this,Diary.class);
startActivity(intent);
}
}
private void bindViews()
{
passwordTextInputEditText=findViewById(R.id.mainActivity_TextInputEditText_password);
}
}
|
C#
|
UTF-8
| 627 | 3.09375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Day4Exercise_Starting
{
class SectionH_q1
{
static void Main()
{
int num = ReadInteger();
Console.WriteLine("Entered Integer:"+num);
}
static int ReadInteger()
{
while (true)
{
Console.Write("Enter an Integer : ");
var num =int.TryParse( Console.ReadLine(),out int n);
if (num)
return n;
}
}
}
}
|
Java
|
UTF-8
| 7,763 | 2.09375 | 2 |
[] |
no_license
|
package cn.com.fero.system.service.impl;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.fero.domain.system.criteria.SysSettingClobCriteria;
import cn.com.fero.domain.system.criteria.SysSettingCriteria;
import cn.com.fero.domain.system.entity.SysSetting;
import cn.com.fero.domain.system.entity.SysSettingClob;
import cn.com.fero.domain.system.entity.UploadFile;
import cn.com.fero.domain.system.repository.SysSettingClobRepository;
import cn.com.fero.domain.system.repository.SysSettingRepository;
import cn.com.fero.domain.system.repository.UploadFileRepository;
import cn.com.fero.framework.dao.BaseCriteria.Operator;
import cn.com.fero.framework.enumpack.GroupCodeEnum;
import cn.com.fero.framework.enumpack.SettingTypeEnum;
import cn.com.fero.message.service.MailSettingManageService;
import cn.com.fero.system.service.SettingService;
import cn.com.fero.system.service.dto.SysSettingDto;
import cn.com.fero.utils.Constants;
@Service
public class SettingServiceImpl implements SettingService{
@Autowired
SysSettingRepository sysSettingRepository;
@Autowired
private SysSettingClobRepository sysSettingClobRepository;
@Autowired
private MailSettingManageService mailSettingManageService;
@Autowired
private UploadFileRepository uploadFileRepository;
@Override
public SysSettingDto findSysSettingAll(String tenantCd) {
SysSettingDto sysSettingDto = new SysSettingDto();
// 实例化统设定组集合列表
sysSettingDto.setSettingLists(new LinkedList<List<SysSetting>>());
sysSettingDto.setBiddingLists(new LinkedList<List<SysSetting>>());
// 实例化系统设定组名称集合
sysSettingDto.setSettingListName(new LinkedList<String>());
// 查询实体
SysSettingCriteria settingCriteria = new SysSettingCriteria();
SysSettingClobCriteria settingClobCriteria = new SysSettingClobCriteria();
// 图片参数对应的上传文件集合
List<UploadFile> uploadFiles = new LinkedList<UploadFile>();
// 图片参数对应的参数名
List<String> picSettingName = new LinkedList<String>();
// 图片参数对应的参数编码
List<String> picSettingCode = new LinkedList<String>();
//基本设置
settingCriteria.setGroupCode(Constants.BASIC_SETTING, Operator.equal);
List<SysSetting> basic = sysSettingRepository.findByCriteria(settingCriteria);
for(Iterator<SysSetting> iter = basic.iterator(); iter.hasNext();){
SysSetting setting = iter.next();
// 判断是否是图片参数,如果是,则加入到图片列表里
if(SettingTypeEnum.SETTING_TYPE_PICTURE.getCode().equals(setting.getSettingType())){
uploadFiles.add(uploadFileRepository.findOne(setting.getSettingValue()));
picSettingName.add(setting.getSettingTitle());
picSettingCode.add(setting.getSettingCode());
iter.remove(); // 将图片参数移除,防止重复显示
}
}
sysSettingDto.setBasicSetting(basic);
sysSettingDto.setProLogoUploadFile(uploadFiles);
sysSettingDto.setPicSettingName(picSettingName);
sysSettingDto.setPicSettingCode(picSettingCode);
// 基础费用相关参数
settingCriteria.setGroupCode(GroupCodeEnum.GROUP_CODE_COST_SETTING.getCode(), Operator.equal);
sysSettingDto.getSettingLists().add(sysSettingRepository.findByCriteria(settingCriteria));
sysSettingDto.getSettingListName().add(GroupCodeEnum.GROUP_CODE_COST_SETTING.getValue());
// 时间相关参数
settingCriteria.setGroupCode(GroupCodeEnum.GROUP_CODE_DATE_SETTING.getCode(), Operator.equal);
sysSettingDto.getSettingLists().add(sysSettingRepository.findByCriteria(settingCriteria));
sysSettingDto.getSettingListName().add(GroupCodeEnum.GROUP_CODE_DATE_SETTING.getValue());
// 合同参数
settingCriteria.setGroupCode(GroupCodeEnum.GROUP_CODE_CONTRACT_SETTING.getCode(), Operator.equal);
sysSettingDto.getSettingLists().add(sysSettingRepository.findByCriteria(settingCriteria));
sysSettingDto.getSettingListName().add(GroupCodeEnum.GROUP_CODE_CONTRACT_SETTING.getValue());
// 白拿活动设定
settingCriteria.setGroupCode(GroupCodeEnum.GROUP_CODE_ACTIVITY_SETTING.getCode(), Operator.equal);
sysSettingDto.getSettingLists().add(sysSettingRepository.findByCriteria(settingCriteria));
sysSettingDto.getSettingListName().add(GroupCodeEnum.GROUP_CODE_ACTIVITY_SETTING.getValue());
// 前端产品显示 #968 by liupin
settingCriteria.setGroupCode(GroupCodeEnum.GROUP_CODE_PRODUCE_SHOW_SETTING.getCode(), Operator.equal);
sysSettingDto.getSettingLists().add(sysSettingRepository.findByCriteria(settingCriteria));
sysSettingDto.getSettingListName().add(GroupCodeEnum.GROUP_CODE_PRODUCE_SHOW_SETTING.getValue());
// 注册相关参数 add by Wang Xin 2016-05-26
settingCriteria.setGroupCode(GroupCodeEnum.GROUP_CODE_REGISTER_SETTING.getCode(),Operator.equal);
sysSettingDto.getSettingLists().add(sysSettingRepository.findByCriteria(settingCriteria));
sysSettingDto.getSettingListName().add(GroupCodeEnum.GROUP_CODE_REGISTER_SETTING.getValue());
// 体验标参数
settingCriteria.setGroupCode("bidding", Operator.equal);
sysSettingDto.getBiddingLists().add(sysSettingRepository.findByCriteria(settingCriteria));
// 邮箱设置
sysSettingDto.setMailSetting(mailSettingManageService.getMailSetting(tenantCd));
// 项目说明书
// TODO 目前这样书写
settingClobCriteria.setGroupCode("manual_setting", Operator.equal);
settingClobCriteria.setSettingCode("manual", Operator.equal);
List<SysSettingClob> clobs = sysSettingClobRepository.findByCriteria(settingClobCriteria);
if(clobs != null && !clobs.isEmpty()){
sysSettingDto.setSysSettingClob(clobs.get(0));
}
return sysSettingDto;
}
@Override
public void updateSysSettingBySettingCode(List<SysSetting> sysSetting) {
if(sysSetting.size()>0){
for(int i=0;i<sysSetting.size();i++){
sysSettingRepository.dynamicUpdate(sysSetting.get(i));
}
}
}
@Override
public SysSetting findSysSettingBySettingCode(String settingCode) {
return sysSettingRepository.findSysSettingBySettingCode(settingCode);
}
@Override
public int updateBusiness(SysSetting sysSetting) {
return sysSettingRepository.dynamicUpdate(sysSetting);
}
@Override
public void updateAll(List<SysSetting> sysSetting) {
if(sysSetting.size()>0){
for(int i=0;i<sysSetting.size();i++){
sysSettingRepository.update(sysSetting.get(i));
}
}
}
@Override
public List<SysSetting> findSysSettingBidding(String groupcode) {
// 查询实体
SysSettingCriteria settingCriteria = new SysSettingCriteria();
//根据groupcode查询
if(groupcode != null && !groupcode.equals("")){
settingCriteria.setGroupCode(groupcode, Operator.equal);
settingCriteria.setOrderBy(SysSettingCriteria.OrderField.createTime);
}
return sysSettingRepository.findByCriteria(settingCriteria);
}
@Override
public int insert(SysSetting sysSetting) {
return sysSettingRepository.insert(sysSetting);
}
@Override
public SysSetting findOne(String id) {
return sysSettingRepository.findOne(id);
}
}
|
C
|
UTF-8
| 1,707 | 4.15625 | 4 |
[] |
no_license
|
#include "binary_trees.h"
/**
* binary_tree_is_perfect - This function checks if a binary tree is perfect
* @tree: A pointer to the root node
* Return: 1 if a tree is perfect, otherwise 0
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
/* empty tree is APPARENTLY NOT perfect */
if (!tree)
return (0);
/* single node is perfect */
if (binary_tree_is_leaf(tree))
return (1);
/* if left & right-child exist */
if (tree->left && tree->right)
{
/* check depth */
if (binary_tree_height(tree->left) != binary_tree_height(tree->right))
return (0);
}
/* recursively check depth of subtrees */
if (binary_tree_is_perfect(tree->left) == 0 ||
binary_tree_is_perfect(tree->right) == 0)
return (0);
return (1);
}
/**
* binary_tree_height - This function measures the height of a binary tree
* @tree: A pointer to the root node
* Return: Height of the tree, or 0 if tree is NULL
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t left_depth = 0, right_depth = 0;
if (!tree || (!tree->left && !tree->right))
return (0);
/* compute the depth of each subtree if they exist */
left_depth = binary_tree_height(tree->left);
right_depth = binary_tree_height(tree->right);
/* compare the values of each depth */
if (left_depth >= right_depth)
return (left_depth + 1);
else
return (right_depth + 1);
}
/**
* binary_tree_is_leaf - This function checks if a node is a leaf
* @node: A pointer to the node
* Return: 1 if node is a leaf, otherwise 0
*/
int binary_tree_is_leaf(const binary_tree_t *node)
{
if (node)
{
/* if left & right child doesn't exist--it's a leaf! */
if (!node->left && !node->right)
return (1);
}
return (0);
}
|
JavaScript
|
UTF-8
| 7,047 | 2.8125 | 3 |
[] |
no_license
|
let context // canvas实例
let direction // 点击的方位
let touchCurrentIndex = -1 // 选中的下标
// 圆饼的四个方位
const RIGHT_DOWN = 0
const LEFT_DOWN = 1
const LEFT_UP = 2
const RIGHT_UP = 3
const radius = 70 // 圆的半径
const max_radius = 80 // 选中后的那一个的半径
let axis_x = 0 // 圆心x坐标
let axis_y = 0 // 圆心y坐标
Component({
/**
* 组件的初始数据
*/
data: {
analysis: [
{
name: '吃',
num: 30,
price: 2999.68,
color: '#2ED084',
}, {
name: '喝',
num: 20,
price: 2199.50,
color: '#FDC604',
}, {
name: '玩',
num: 18,
price: 1599.50,
color: '#F5554E',
}, {
name: '乐',
num: 15,
price: 1299.50,
color: '#0EADFE',
}, {
name: '其他',
num: 10,
price: 900,
color: '#8684F2',
}, {
name: '更多类别',
num: 7,
price: 600,
color: '#0FB0FA',
},
],
},
lifetimes: {
attached: function () {
// 获取canvas的宽高,设置圆心坐标
const query = wx.createSelectorQuery().in(this)
query.selectAll('#chart_content').boundingClientRect()
query.exec(res => {
res = res[0][0]
axis_x = res.width / 2
axis_y = res.height / 2
// 开始绘制
this.drawChart()
})
},
},
/**
* 组件的方法列表
*/
methods: {
tranMonth() {
console.log('tranMonth')
},
// 计算出开始的弧度和所占比例
calPieAngle(series) {
let startAngle = 0
return series.map(item => {
item.proportion = item.num / 100
item.startAngle = startAngle
startAngle += 2 * Math.PI * item.proportion
item.endAngle = startAngle
return item
})
},
// 绘制饼图
drawChart() {
context = wx.createCanvasContext('chart', this)
let pieSeries = this.calPieAngle(this.data.analysis)
pieSeries.forEach((item, idx) => {
context.beginPath()
context.setFillStyle(item.color)
context.moveTo(axis_x, axis_y)
context.arc(axis_x, axis_y, idx === touchCurrentIndex ? max_radius : radius, item.startAngle, item.startAngle + 2 * Math.PI * item.proportion)
context.closePath()
context.fill()
})
// 选中了区块,绘制相对应的金额
if (touchCurrentIndex > -1) {
this.drawCurrentPrice()
}
context.draw()
},
// 绘制当前选中的一块的文字
drawCurrentPrice() {
let angle = 0 // 计算当前块一半的位置加上前面块一起的弧度
let arr = this.data.analysis
for (let i = 0; i < arr.length; i++) {
let prevIndex = i === 0 ? 0 : i - 1
let prevAngle = arr[prevIndex].endAngle / (Math.PI / 180)
if (i === touchCurrentIndex) {
angle = arr[i].endAngle / (Math.PI / 180)
if (i === 0) {
angle = angle / 2
} else {
angle = (angle - prevAngle) / 2
angle = angle + prevAngle
}
break
}
}
// 圆上x y轴坐标
let x = Math.round(max_radius * Math.cos(angle * Math.PI / 180)) + axis_x
let y = Math.round(max_radius * Math.sin(angle * Math.PI / 180)) + axis_y
let turning_x_one = 0
let turning_y_one = 0
let turning_x_two = 0
let turning_y_two = 0
let text_top_x =0
let text_top_y = 0
let text_bot_x = 0
let text_bot_y = 0
turning_x_one = direction === RIGHT_DOWN || direction === RIGHT_UP ? x + 10 : x - 10
turning_y_one = direction === RIGHT_DOWN || direction == LEFT_DOWN ? y + 10 : y - 10
turning_x_two = direction === RIGHT_DOWN || direction === RIGHT_UP ? x + 35 : x - 35
turning_y_two = direction === RIGHT_DOWN || direction == LEFT_DOWN ? y + 10 : y - 10
text_top_x = direction === RIGHT_DOWN || direction === RIGHT_UP ? x + 42 : x - 42
text_top_y = direction === RIGHT_DOWN || direction == LEFT_DOWN ? y + 5 : y - 15
text_bot_x = direction === RIGHT_DOWN || direction === RIGHT_UP ? x + 40 : x - 40
text_bot_y = direction === RIGHT_DOWN || direction == LEFT_DOWN ? y + 25 : y + 5
context.beginPath()
context.setStrokeStyle(arr[touchCurrentIndex].color)
context.lineTo(x, y)
context.lineTo(turning_x_one, turning_y_one)
context.lineTo(turning_x_two, turning_y_two)
context.stroke()
context.setTextAlign(direction === LEFT_DOWN || direction === LEFT_UP ? 'right' : 'left')
context.setFontSize(12)
context.setFillStyle(arr[touchCurrentIndex].color)
context.fillText(arr[touchCurrentIndex].name, text_top_x, text_top_y)
context.fillText('¥' + arr[touchCurrentIndex].price, text_bot_x, text_bot_y)
context.closePath()
},
// 饼图点击事件处理
chartTouchStart(e) {
let touches = e.touches
if (touches.length > 1) return
touches = touches[0]
let {x, y} = touches
let sx = axis_x - radius
let ex = axis_x + radius
let sy = axis_y - radius
let ey = axis_y + radius
// 点击区域不在饼状图内
if (x < sx || x > ex || y < sy || y > ey) {
touchCurrentIndex = -1
this.drawChart()
return
}
// 点击坐标的正切值,相对圆心的四个方向
let proportion = 0
// 右下
if (x > axis_x && y > axis_y) {
let a = x - axis_x
let b = y - axis_y
proportion = Math.atan(b / a)
direction = RIGHT_DOWN
}
// 左下
if (x < axis_x && y > axis_y) {
let a = axis_x - x
let b = y - axis_y
proportion = Math.atan(a / b) + (Math.PI / 2)
direction = LEFT_DOWN
}
// 左上
if (x < axis_x && y < axis_y) {
let a = axis_x - x
let b = axis_y - y
proportion = Math.atan(b / a) + Math.PI
direction = LEFT_UP
}
// 右上
if (x > axis_x && y < axis_y) {
let a = x - axis_x
let b = axis_y - y
proportion = Math.atan(a / b) + (Math.PI * 1.5)
direction = RIGHT_UP
}
// 判断是否正好点在四条正角上
proportion = x === axis_x ? y < axis_y ? Math.PI * 1.5 : Math.PI / 2 : proportion
proportion = y === axis_y ? x < axis_x ? Math.PI : 0 : proportion
if (this.getTouchCurrentIndex(proportion) !== touchCurrentIndex) {
touchCurrentIndex = this.getTouchCurrentIndex(proportion)
// 重新绘制
this.drawChart()
}
},
// 获取点击的是哪一块
getTouchCurrentIndex(proportion) {
let arr = this.data.analysis
let currentIndex = 0
for (let i = 0; i < arr.length; i++) {
if (proportion <= arr[i].endAngle) {
currentIndex = i
break
}
}
return currentIndex
},
}
});
|
C++
|
UTF-8
| 431 | 2.765625 | 3 |
[] |
no_license
|
#ifndef _ROBOT_H_
#define _ROBOT_H_
#include "point.h"
#include "angle.h"
class Robot {
public:
Robot(Point _position, Angle _frontAngle);
~Robot();
private:
Point position;
Angle frontAngle;
public:
Angle getFrontAngle(void);
Point getPosition(void);
void setFrontAngle(Angle _frontAngle);
void setPosition(Point _position);
};
#endif //_ROBOT_H_
|
C
|
UTF-8
| 1,662 | 2.78125 | 3 |
[] |
no_license
|
#include "sysutils.h"
#include "errors.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/file.h>
int write_pid(const char* file)
{
FILE *pid_file;
pid_file = fopen(file, "w");
if (!pid_file)
return ERR;
fprintf(pid_file, "%d\n", getpid());
fclose(pid_file);
return OK;
}
int read_pid_and_kill(const char* file)
{
FILE *pid_file;
pid_t pid;
int read;
int max_ms_wait = MAX_KILL_WAIT_MS;
int ms_wait_interval = 200;
int ms_waited = 0;
struct timespec ts;
ts.tv_nsec = ms_wait_interval * 1000;
ts.tv_sec = 0;
pid_file = fopen(file, "r");
if (!pid_file)
return -1;
read = fscanf(pid_file, "%d", &pid);
fclose(pid_file);
if (read < 1)
return -1;
if (kill(pid, SIGTERM) == -1)
{
perror("kill");
return -1;
}
while (ms_waited < max_ms_wait)
{
if (kill(pid, 0) == -1) /* Kill con señal 0 devuelve -1 si el proceso ya ha salido */
return 0;
nanosleep(&ts, NULL);
ms_waited += ms_wait_interval;
}
kill(pid, SIGKILL);
return 1;
}
int try_getlock(const char* file)
{
int pid_file = open(file, O_CREAT | O_RDWR, 0666);
int rc = flock(pid_file, LOCK_EX | LOCK_NB);
if (rc)
{
if (EWOULDBLOCK == errno)
return 0;
else
return -1;
}
return 1;
}
rlim_t get_soft_limit(int resource)
{
struct rlimit lim;
if(getrlimit(resource, &lim) == -1)
return -1;
else
return lim.rlim_cur;
}
|
JavaScript
|
UTF-8
| 2,105 | 2.578125 | 3 |
[] |
no_license
|
import React, {Component} from "react";
import { Container, ListGroup, ListGroupItem } from "reactstrap";
class UserViewChefList extends Component {
constructor(props) {
super(props);
this.state = {
chefs: [],
isLoading: true,
};
}
componentDidMount() {
this.setState({ isLoading: true });
fetch("api/chefs")
.then((response) => response.json())
.then((data) => this.setState({ chefs: data, isLoading: false }));
}
increaseQty = (addvalue) => {
if (addvalue.value < 10) {
const updatedValue = addvalue.value++;
this.setState({ updatedValue });
}
};
decreaseQty = (decvalue) => {
if (decvalue.value > 0) {
const updatedValue = decvalue.value--;
this.setState({ updatedValue });
}
};
render() {
const { chefs, isLoading } = this.state;
if (isLoading) {
return <p>Loading ....</p>;
}
const userviewList = chefs.map((chef) => {
return (
<ListGroupItem key={chef.chefid}>
<section className="listItem">
<div>
<img id="chefavatar" src={chef.chefavatar} alt="Avatar" />
</div>
<bold>{chef.chefname}</bold>
<p>{chef.chefspecialty}</p>
</section>
<section>
<ul className="d-flex flex-row">
{chef.chefmenus.map((item) => (
<li className="w-50" key={item.id}>
<p>{item.desc}</p>
<img id="footimage" src={item.image} alt="menu"></img>
<p>{item.value}</p>
<button onClick={() => this.decreaseQty(item)}>
-
</button>
<button onClick={() => this.increaseQty(item)}>
+
</button>
</li>
))}
</ul>
</section>
</ListGroupItem>
);
});
return (
<div>
<Container fluid>
<ListGroup>{userviewList}</ListGroup>
</Container>
</div>
);
}
}
export default UserViewChefList;
|
Shell
|
UTF-8
| 317 | 3.03125 | 3 |
[] |
no_license
|
#! /bin/sh
BASEDIR=$(dirname $0)
DEPLOY_DIR="/var/www-$1/gleebox"
rsync -qrlpgoDz -c --delete $EXCLUDES --progress $BASEDIR $DEPLOY_DIR
cd $DEPLOY_DIR
pwd
if [ $1 = "staging" ]; then
./runpaste-staging stop
./runpaste-staging start
else if [ $1 == "production" ]; then
./runpaste stop
./runpaste start
fi
fi
|
C++
|
UTF-8
| 4,490 | 3.15625 | 3 |
[] |
no_license
|
/*
ID: j316chuck
PROG: union_area_rectangles
LANG: C++
*/
#include <bits/stdc++.h>
#define Rd(r) freopen(r, "r", stdin)
#define Wt(w) freopen(w, "w", stdout)
#define deb(x) cerr << "DEBUG: "<< #x << " = " << x << endl;
#define endl '\n'
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double EPS = 1e-9;
typedef long long LL;
using namespace std;
template < typename F, typename S >
ostream& operator << ( ostream& os, const pair< F, S > & p ) {
return os << "(" << p.first << ", " << p.second << ")";
}
template < typename T >
ostream &operator << ( ostream & os, const vector< T > &v ) {
os << "{";
typename vector< T > :: const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "}";
}
template < typename T >
ostream &operator << ( ostream & os, const set< T > &v ) {
os << "[";
typename set< T > :: const_iterator it;
for ( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "]";
}
template < typename F, typename S >
ostream &operator << ( ostream & os, const map< F, S > &v ) {
os << "[";
typename map< F , S >::const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << it -> first << " = " << it -> second ;
}
return os << "]";
}
template <class T> void deb_array(T *arr, int length) {
for (int i = 0; i < length; i++) {
cout << arr[i] << ' ';
} cout << '\n';
}
struct PT {
double x, y;
PT() {}
PT(double x, double y) : x(x), y(y) {}
PT(const PT &p) : x(p.x), y(p.y) {}
PT operator + (const PT &p) const { return PT(x + p.x, y + p.y); }
PT operator - (const PT &p) const { return PT(x - p.x, y - p.y); }
PT operator * (double c) const { return PT(x * c, y * c); }
PT operator / (double c) const { return PT(x / c, y / c); }
//sorts from low to high in y;
bool operator < (const PT &p) const {
if (p.y > y) return true;
else if (p.y < y) return false;
return p.x > x;
}
bool operator == (const PT &p) const {
return make_pair(p.x, p.y) == make_pair(x, y);
}
};
ostream &operator << (ostream &os, const PT &p) {
os << "(" << p.x << "," << p.y << ")";
return os << "";
}
struct Segment {
PT s, e;
int type, index;
Segment(PT s, PT e, int type, int index) : s(s), e(e), type(type), index(index) {};
Segment(){};
};
bool xcmp(const Segment &a, const Segment &b) {
return make_pair(a.s.x, a.s.y) < make_pair(b.s.x, b.s.y);
}
bool ycmp(const Segment &a, const Segment &b) {
return make_pair(a.s.y, a.s.x) < make_pair(b.s.y, b.s.x);
}
ostream &operator << (ostream &os, const Segment &s) {
os << "Segment: " << s.s << ", " << s.e;
return os << "";
}
//v is sorted by x from small to big
//h is sorted by y from small to big
long long UnionAreaRectangles(vector<Segment> &v, vector<Segment> &h, int n) {
long long area = 0;
bool in[n];
memset(in, false, sizeof(in));
Segment c;
double xdelta, ystart, cnt;
in[v[0].index] = true;
for (int i = 1; i < v.size(); i++) {
c = v[i];
xdelta = c.s.x - v[i-1].s.x;
if (xdelta < EPS) {
in[c.index] = c.type;
continue;
}
cnt = 0;
for (int k = 0; k < h.size(); k++) {
if (!in[h[k].index]) {
continue;
} else if (!h[k].type) {
if (cnt == 0) ystart = h[k].s.y;
cnt++;
} else {
cnt--;
if (cnt == 0) area += xdelta * (h[k].s.y - ystart);
}
}
in[c.index] = c.type;
}
return area;
}
int main() {
freopen("overplanting.in", "r", stdin);
int n;
scanf("%d", &n);
vector<Segment> v(2*n);
vector<Segment> h(2*n);
double sx, sy, ex, ey;
for (int i = 0; i < n; i++) {
scanf("%lf %lf %lf %lf", &sx, &sy, &ex, &ey);
v[2*i] = {{sx, sy}, {ex, ey}, 1, i};
v[2*i+1] = {{ex, ey}, {sx, sy}, 0, i};
h[2*i] = {{sx, sy}, {ex, ey}, 1, i};
h[2*i+1] = {{ex, ey}, {sx, sy}, 0, i};
}
//sorted by x
sort(v.begin(), v.end(), xcmp);
sort(h.begin(), h.end(), ycmp);
printf("%lld\n", UnionAreaRectangles(v, h, n));
/*for (int i = 0; i < v.size(); i++) {
cout << v[i].s << endl;
}*/
}
|
C++
|
UTF-8
| 885 | 3.09375 | 3 |
[] |
no_license
|
/*
Arithmetic Number
Link: https://practice.geeksforgeeks.org/problems/arithmetic-number2815/1#
*/
#include<bits/stdc++.h>
#define int long long
using namespace std ;
//--------------------------------------------------------------------
class Solution
{
public :
int inSequence(int A, int B, int C)
{
if (A == B) return true;
if (C == 0)
return false;
if ((B - A > 0 && C < 0) || (B - A < 0 && C > 0))
return false;
return !((B - A) % C);
}
};
//--------------------------------------------------------------------
signed main()
{
int testcases = 1 ;
// cin >> testcases ;
while( testcases -- )
{
Solution obj;
int a, b, c ;
cin >> a >> b >> c;
cout << obj.inSequence(a, b, c);
cout << endl ;
}
return 0 ;
}
|
C++
|
GB18030
| 832 | 4.1875 | 4 |
[] |
no_license
|
//2дԭΪvoid index(int a[], int n,int &sub)
//ܣڴСΪnaУijsub
//ҵӦԪص±긳subûҵ-1sub
//ͨжsubֵжǷи
//sub͵IJֵá
#include<iostream>
using namespace std;
void index(int a[], int n,int &sub)
{
int i = 0;
if (NULL == a || n < 1)
{
sub = -1;
return ;
}
else
{
for(i=0; i<n; i++)
{
if(a[i] == sub)
{
sub = i;
return ;//Ϊʲôbreak У
}
}
sub = -1;
}
}
int main()
{
int arr[100]={0};
int sub = 0;
int n = 0;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
cin>>sub;
index(arr,n,sub);
cout<<sub;
return 0;
}
|
Java
|
UTF-8
| 1,072 | 2.375 | 2 |
[] |
no_license
|
package com.mdy.student.bean;
public class Student {
private String id;
private String name;
private double chinese;
private double math;
private double english;
private double per;
private double homework;
private char level;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getChinese() {
return chinese;
}
public void setChinese(double chinese) {
this.chinese = chinese;
}
public double getMath() {
return math;
}
public void setMath(double math) {
this.math = math;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
public double getPer() {
return per;
}
public void setPer(double per) {
this.per = per;
}
public double getHomework() {
return homework;
}
public void setHomework(double homework) {
this.homework = homework;
}
public char getLevel() {
return level;
}
}
|
TypeScript
|
UTF-8
| 8,723 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
import {Base, IQuestion, IConditionRunner, ISurveyData, ISurvey, HashTable, Event} from './base';
import {QuestionCustomWidget} from './questionCustomWidgets';
import {JsonObject} from './jsonobject';
import {ConditionRunner} from './conditions';
import {ILocalizableOwner} from "./localizablestring";
/**
* A base class for all questions. QuestionBase doesn't have information about title, values, errors and so on.
* Those properties are defined in the Question class.
*/
export class QuestionBase extends Base implements IQuestion, IConditionRunner, ILocalizableOwner {
private static questionCounter = 100;
private static getQuestionId(): string {
return "sq_" + QuestionBase.questionCounter++;
}
protected data: ISurveyData = null;
private surveyValue: ISurvey = null;
private conditionRunner: ConditionRunner = null;
/**
* The link to the custom widget.
*/
public customWidget: QuestionCustomWidget;
customWidgetData = { isNeedRender: true };
/**
* An expression that returns true or false. If it returns a true the Question becomes visible and if it returns false the Panel becomes invisible. The library perform the expression on survey start and on changing a question value. If the property is empty then visible property is used.
* @see visible
*/
public visibleIf: string = "";
private idValue: string;
private visibleValue: boolean = true;
private startWithNewLineValue: boolean = true;
private visibleIndexValue: number = -1;
/**
* Use it to set the specific width to the question.
*/
public width: string = "";
private renderWidthValue: string = "";
private rightIndentValue: number = 0;
private indentValue: number = 0;
/**
* The event is fired when the survey change it's locale
* @see SurveyModel.locale
*/
public localeChanged: Event<(sender: QuestionBase) => any, any> = new Event<(sender: QuestionBase) => any, any>();
focusCallback: () => void;
renderWidthChangedCallback: () => void;
rowVisibilityChangedCallback: () => void;
startWithNewLineChangedCallback: () => void;
visibilityChangedCallback: () => void;
visibleIndexChangedCallback: () => void;
readOnlyChangedCallback: () => void;
surveyLoadCallback: () => void;
constructor(public name: string) {
super();
this.idValue = QuestionBase.getQuestionId();
this.onCreating();
}
/**
* Always returns false.
*/
public get isPanel(): boolean { return false; }
/**
* Use it to get/set the question visibility.
* @see visibleIf
*/
public get visible(): boolean { return this.visibleValue; }
public set visible(val: boolean) {
if (val == this.visible) return;
this.visibleValue = val;
this.fireCallback(this.visibilityChangedCallback);
this.fireCallback(this.rowVisibilityChangedCallback);
if (this.survey) {
this.survey.questionVisibilityChanged(<IQuestion>this, this.visible);
}
}
/**
* Returns true if the question is visible or survey is in design mode right now.
*/
public get isVisible(): boolean { return this.visible || (this.survey && this.survey.isDesignMode); }
/**
* Returns true if there is no input in the question. It always returns true for html question or survey is in 'display' mode.
* @see QuestionHtmlModel
* @see SurveyModel.mode
* @see Question.readOnly
*/
public get isReadOnly() { return true; }
/**
* Returns the visible index of the question in the survey. It can be from 0 to all visible questions count - 1
*/
public get visibleIndex(): number { return this.visibleIndexValue; }
/**
* Returns true if there is at least one error on question validation.
* @param fireCallback set it to true to show error in UI
*/
public hasErrors(fireCallback: boolean = true): boolean { return false; }
/**
* Returns the number of erros on validation.
*/
public get currentErrorCount(): number { return 0; }
/**
* Returns false if the question doesn't have a title property, for example: QuestionHtmlModel
*/
public get hasTitle(): boolean { return false; }
/**
* Returns false if the question doesn't have an input element, for example: QuestionHtmlModel
*/
public get hasInput(): boolean { return false; }
/**
* Returns true, if you can have a comment for the question.
*/
public get hasComment(): boolean { return false; }
/**
* Returns the unique identificator. It is generated automatically.
*/
public get id(): string { return this.idValue; }
/**
* The Question renders on the new line if the property is true. If the property is false, the question tries to render on the same line/row with a previous question/panel.
*/
public get startWithNewLine(): boolean { return this.startWithNewLineValue; }
public set startWithNewLine(value: boolean) {
if(this.startWithNewLine == value) return;
this.startWithNewLineValue = value;
if(this.startWithNewLineChangedCallback) this.startWithNewLineChangedCallback();
}
/**
* The rendered width of the question.
*/
public get renderWidth(): string { return this.renderWidthValue; }
public set renderWidth(val: string) {
if (val == this.renderWidth) return;
this.renderWidthValue = val;
this.fireCallback(this.renderWidthChangedCallback);
}
/**
* Set it different from 0 to increase the left padding.
*/
public get indent(): number { return this.indentValue; }
public set indent(val: number) {
if (val == this.indent) return;
this.indentValue = val;
this.fireCallback(this.renderWidthChangedCallback);
}
/**
* Set it different from 0 to increase the right padding.
*/
public get rightIndent(): number { return this.rightIndentValue; }
public set rightIndent(val: number) {
if (val == this.rightIndent) return;
this.rightIndentValue = val;
this.fireCallback(this.renderWidthChangedCallback);
}
/**
* Focus the question input.
* @param onError Focus if there is an error.
*/
public focus(onError: boolean = false) { }
setData(newValue: ISurveyData) {
this.data = newValue;
if(newValue && newValue["questionAdded"]) {
this.surveyValue = <ISurvey>newValue;
}
this.onSetData();
}
/**
* Returns the survey object.
*/
public get survey(): ISurvey { return this.surveyValue; }
protected fireCallback(callback: () => void) {
if (callback) callback();
}
protected onSetData() { }
protected onCreating() { }
/**
* Run visibleIf expression. If visibleIf is not empty, then the results of performing the expression (true or false) set to the visible property.
* @param values Typically survey results
* @see visible
* @see visibleIf
*/
public runCondition(values: HashTable<any>) {
if (!this.visibleIf) return;
if (!this.conditionRunner) this.conditionRunner = new ConditionRunner(this.visibleIf);
this.conditionRunner.expression = this.visibleIf;
this.visible = this.conditionRunner.run(values);
}
//IQuestion
public onSurveyValueChanged(newValue: any) {
}
public onSurveyLoad() {
this.fireCallback(this.surveyLoadCallback);
}
protected get isLoadingFromJson(): boolean { return this.survey && this.survey.isLoadingFromJson; }
public setVisibleIndex(value: number) {
if (this.visibleIndexValue == value) return;
this.visibleIndexValue = value;
this.fireCallback(this.visibleIndexChangedCallback);
}
public supportGoNextPageAutomatic() { return false; }
public clearUnusedValues() {}
public onLocaleChanged() {
this.localeChanged.fire(this, this.getLocale());
}
onReadOnlyChanged() {}
onAnyValueChanged(){}
//ILocalizableOwner
/**
* Returns the current survey locale
* @see SurveyModel.locale
*/
public getLocale(): string { return this.data ? (<ILocalizableOwner><any>this.data).getLocale() : ""; }
public getMarkdownHtml(text: string) { return this.data ? (<ILocalizableOwner><any>this.data).getMarkdownHtml(text) : null; }
}
JsonObject.metaData.addClass("questionbase", ["!name", { name: "visible:boolean", default: true }, "visibleIf:expression",
{ name: "width" }, { name: "startWithNewLine:boolean", default: true}, {name: "indent:number", default: 0, choices: [0, 1, 2, 3]}]);
|
PHP
|
UTF-8
| 2,956 | 2.578125 | 3 |
[] |
no_license
|
#!/usr/local/bin/php
<?php
require("/home/content/48/7686848/html/includes/bv-library.php");
require("/home/content/48/7686848/html/inset/inset_includes/insetdb.php");
require("/home/content/48/7686848/html/inset/inset_includes/forms.php");
//printHeader("Welcome to Brainvoyage.com");
//check if it is first time on the page or form submited
if($id)
// print out user data by user ID
{
$table = $root."_answers";
$result = mysql_query("SELECT * FROM $table where user_id=$id") or die(mysql_error());
?>
<table border="0" align="center">
<?php
while ($data = mysql_fetch_array($result))
{
$i++;
?>
<tr bgcolor="<?php if(is_float( $i/2 )) print ("66CCFF");
else print ("CCFFFF"); ?>">
<td><?php print ($i); ?> </td>
<!-- <td><?php print ($data['id']); ?></td>
<td><?php print ($data['user_id']); ?></td> -->
<td><?php print (question($data['question'], $root)); ?> </td>
<td><?php print ($data['answer']); ?> </td>
</tr>
<?php
}?> </table> <?php
}
elseif($delete)
{
if ($delete == 1)
{
mysql_query("DELETE FROM user_answers") or die(mysql_error());
mysql_query("DELETE FROM sobin_answers") or die(mysql_error());
// mysql_query("DELETE FROM inset_answers") or die(mysql_error());
print ("<a href=list.php>List all</a>");
}
else
{
mysql_query("DELETE FROM user_answers where user_id='$delete'") or die(mysql_error());
mysql_query("DELETE FROM sobin_answers where user_id='$delete'") or die(mysql_error());
// mysql_query("DELETE FROM inset_answers where user_id='$delete'") or die(mysql_error());
print ("<a href=list.php>List all</a>");
}
}
else
{
$result = mysql_query("SELECT DISTINCT user_id FROM user_answers") or die(mysql_error());
?>
<table border="0" align="center">
<?php
while ($data = mysql_fetch_array($result))
{
$i++?>
<tr bgcolor="<?php if(is_float( $i/2 )) print ("66CCFF");
else print ("CCFFFF"); ?>">
<td><a href="list.php?id=<?= ($data['user_id']) ?>&root=user"><?= ($data['user_id']) ?></a></td>
<td><a href="list.php?id=<?= ($data['user_id']) ?>&root=sobin">SOBIN</a></td>
<!-- <td><a href="list.php?id=<?= ($data['user_id']) ?>&root=inset">INSET</a></td> -->
<td><a href="list.php?delete=<?= ($data['user_id']) ?>">Delete</a></td>
</tr>
<?php } ?>
<td><a href="list.php?delete=1">Delete All Data</a></td><td></td>
</table>
<?php
}
// validates Question id and returnd Question as str
function question($q_id, $root)
{
$intQ_id = intval($q_id);
if($intQ_id)
{
if ( $intQ_id < 10000 )
{
return get_q($intQ_id, $root);
}
else
{
$n = round($intQ_id/10000);
return get_q($n, $root);
}
}
else return ($q_id);
}
// querrees DB and returns Questions as str
function get_q($intQ_id, $root)
{
$table = $root."_questions";
$result = mysql_query("SELECT question FROM $table where id='$intQ_id'") or die(mysql_error());
$data = mysql_fetch_array($result);
return $data['question'];
}
//printFooter();
?>
|
Java
|
UTF-8
| 946 | 1.867188 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.edge.xshtsk.service.inter;
import java.util.List;
import com.edge.xshtsk.entity.ERP_Xshtsk;
import com.edge.xshtsk.entity.ERP_Xshtsk_QueryVo;
public interface XshtskService {
// 分页展现销售合同收款
public List<ERP_Xshtsk> xshtskList(ERP_Xshtsk_QueryVo vo);
// 查询销售合同收款总记录
public Integer xshtskCount(ERP_Xshtsk_QueryVo vo);
// 新增销售合同收款
public void saveXshtsk(ERP_Xshtsk xshtsk);
// 获取刚新增的销售合同收款主键
public Integer maxXshtdm();
// 根据Id获得销售合同收款对象
public ERP_Xshtsk queryXshtskById(Integer xshtskdm);
// 编辑销售合同收款
public void editXshtsk(ERP_Xshtsk xshtsk);
// 计算某一个销售合同下的所有实际收款金额
public Double querySumSjskje(Integer xsht);
// 查询当前销售合同下所有的累计开票金额
public Double querySumLjkpje(Integer xsht);
}
|
Markdown
|
UTF-8
| 4,657 | 2.8125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Project 3 - Globitek Forgery, Theft, and Hijacking Prevention
Time spent: **7** hours spent in total
## User Stories
The following **required** functionality is completed:
**(all required stories completed)**
- [x] Test for vulnerabilities
- [x] Configure sessions
- [x] Login page
- [x] Require login to access staff area pages
- [x] Logout page
- [x] Add CSRF protections to the state forms
- [x] Ensure the application is not vulnerable to XSS attacks
- [x] Ensure the application is not vulnerable to SQL Injection attacks
- [x] Run all tests from Objective 1 again and confirm that your application is no longer vulnerable to any test
The following advanced user stories are optional:
**(all optional stories completed)**
- [x] Bonus 1: Objective 4 (requiring login on staff pages) has a major security weakness because it does not follow one of the fundamental security principals. Identify the principal and write a short description of how the code could be modified to be more secure. Include your answer in the README file that accompanies your assignment submission
- [x] **(explanation in Notes section)**
- [x] Bonus 2: Add CSRF tokens and protections to all of the forms in the staff directory (new, edit, delete). Make sure the request is the same domain and that the CSRF token is valid
- [x] Bonus 3: Add code so that CSRF tokens will only be considered valid for 10 minutes after creation
- [x] Bonus 4: Only consider a session valid if the user-agent string matches the value used when the user last logged in successfully.
- [x] Advanced: Create two new pages called "public/set_secret_cookie.php" and "public/get_secret_cookie.php". The first page will set a cookie with the name "scrt" and the value "I have a secret to tell.". Before storing the cookie, you need to both encrypt it and sign it. You can use any (two-way) encryption algorithm you prefer. When the second page loads, it should read the cookie with the name "scrt", and then—if it is signed correctly—decrypt it. If it is not signed correctly then it should display an error message and skip decryption altogether.
## Video Walkthrough
Here's a walkthrough of implemented user stories:
<img src='anim_assign03.gif' title='Video Walkthrough' width='' alt='Video Walkthrough' />
GIF created with [LiceCap](http://www.cockos.com/licecap/).
## Notes
* **Bonus Objective 1:** Requiring login on staff pages violates the Fundamental Security Principal of "Prefer whitelisting over blacklisting." In order to designate that a page is secure, the current implementation requires that you specifically mark it as secure, aka blacklisting it. This approach could fail if a new page is added under the staff directory, and the developer forgets to add the blacklist to that page, allowing any user to access it. A better approach would be to designate pages that **don't** need authentication, so that the default state for any new page would be secure.
* In order to complete the set_secret_cookie advanced story, I had to download the mcrypt php plugin (sudo apt-get install php7.0-mcrypt). You may need to download it as well, if you haven't already.
* In login.php, I included separate error messages for an incorrect username vs an incorrect password, since it was explicitly noted in the requirements. In production, however, this decision would come down to the decision to prioritize security or user experience.
* In request_is_same_domain in functions.php I changed HOST_NAME to SERVER_NAME because the former included the 8080 port when accessing localhost (which doesn't appear in HTTP_REFERER).
* When I was testing the site on different browsers, I discovered a bug on the pen_tests pages when using firefox. The < script> tag would always load before the < iframe> tag (see [here](http://stackoverflow.com/questions/8996852/load-and-execute-order-of-scripts)) causing the page to infinitely reload. I included a slight modification to these pages that prevents this, as well as prevents the initial undefined error from the $msg variable.
## License
Copyright [2016] [David Maydew]
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.
|
Java
|
UTF-8
| 319 | 2.171875 | 2 |
[] |
no_license
|
package edu.temple.pihomesecuritymobile;
import android.util.Log;
public class ClientThread extends Thread{
private Client client;
public ClientThread(Client c) {
this.client = c;
}
public void run(){
Log.d("client_test","Starting Server Thread...");
client.start();
}
}
|
Python
|
UTF-8
| 1,726 | 3.734375 | 4 |
[] |
no_license
|
import random
import copy
surnames = ['cat', 'dogggggo', 'owlie']
given = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', "I", 'J']
class Student:
def __init__(self, surname, given_name, id, courses):
self.surname = surname
self.given_name = given_name
self.id = id
self.courses = courses
def __repr__(self):
return f'<{self.surname}, {self.given_name}: {self.id}>'
def __str__(self):
return f'<{self.surname}, {self.given_name}: {self.id}>'
def id_key(s):
return s.id
def surname_key(s):
return s.surname
def namelen_key(s):
return len(s.surname)
def insertion_sort(students):
for index in range(1, len(students)):
pos = index
while pos >= 1 and students[pos - 1].id > students[pos].id:
tmp = students[pos].id
students[pos].id = students[pos - 1].id
students[pos - 1].id = tmp
pos -= 1
return students
def selectionSort(students):
num = 0
smallestPos = 0
for num in range (len(students)):
smallest = 'zzzzzzz'
for pos in range(num, len(students)):
if students[pos].surname < smallest:
smallest = students[pos].surname
smallestPos = pos
tmp = copy.deepcopy(students[num])
students[num] = students[smallestPos]
students[smallestPos] = tmp
#print('during ', students)
# build a list of n students
n = 5
students = [Student(f'{surnames[i%len(surnames)]}', f'{given[i%len(given)]}', random.randint(0,1000), []) for i in range(n)]
print('before', students)
# students.sort(key=id_key)
students.sort(key= namelen_key)
#selectionSort(students)
print('after ', students)
|
PHP
|
UTF-8
| 631 | 2.578125 | 3 |
[] |
no_license
|
<?php
/**
* Content Link preparation
*
* @author Tim Lochmüller
*/
namespace HDNET\Tagger;
use TYPO3\CMS\Backend\Utility\BackendUtility;
/**
* Prepare the content Link
*/
class ContentLink implements LinkBuilderCallbackInterface
{
/**
* Prepare the link building array
*
* @param string $table
* @param int $uid
* @param array $configuration
* @param array $markers
*/
public function prepareLinkBuilding($table, $uid, &$configuration, &$markers)
{
$row = BackendUtility::getRecord($table, $uid);
$markers['###PAGE_UID###'] = $row['pid'] . '#' . $uid;
}
}
|
Java
|
UTF-8
| 19,540 | 1.976563 | 2 |
[] |
no_license
|
package hasoffer.core.product.solr;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import hasoffer.base.config.AppConfig;
import hasoffer.base.enums.SearchResultSort;
import hasoffer.base.model.PageableResult;
import hasoffer.base.utils.StringUtils;
import hasoffer.base.utils.TimeUtils;
import hasoffer.core.bo.system.SearchCriteria;
import hasoffer.core.redis.ICacheService;
import hasoffer.data.solr.*;
import jodd.util.NameValue;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.solr.client.solrj.response.PivotField;
import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
@Service
public class ProductIndex2ServiceImpl extends AbstractIndexService<Long, ProductModel2> {
private final String SOLR_CACHE_KEY = "SOLR_";
@Resource
ICacheService pageableResultcacheService;
Logger logger = LoggerFactory.getLogger(ProductIndex2ServiceImpl.class);
/*protected HttpSolrServer solrServer;
public ProductIndex2ServiceImpl() {
solrServer = new HttpSolrServer(getSolrUrl());
solrServer.setConnectionTimeout(5000);
}*/
@Override
protected String getSolrUrl() {
// return "http://solrserver:8983/solr/hasofferproduct3/";
return AppConfig.get(AppConfig.SOLR_PRODUCT_2_URL);
}
/**
* 根据关键词搜索
*
* @param title
* @param page
* @param size
* @return
*/
public PageableResult<ProductModel2> searchProductsByKey(String title, int page, int size) {
Sort[] sorts = null;
PivotFacet[] pivotFacets = new PivotFacet[1];
// cate2 distinct 提取出来所有值
pivotFacets[0] = new PivotFacet("cate2");
List<FilterQuery> fqList = new ArrayList<FilterQuery>();
FilterQuery[] fqs = fqList.toArray(new FilterQuery[0]);
SearchResult<ProductModel2> sr = searchObjs(title, fqs, sorts, pivotFacets, page <= 1 ? 1 : page, size, true);
return new PageableResult<ProductModel2>(sr.getResult(), sr.getTotalCount(), page, size);
}
/**
* 根据关键词搜索
*
* @param title
* @param page
* @param size
* @return
*/
public PageableResult<ProductModel2> searchProductsByKey(String title, int page, int size, SearchResultSort resultSort) {
Sort[] sorts = null;
if (resultSort != null) {
sorts = new Sort[1];
if (resultSort == SearchResultSort.POPULARITY) {
sorts[0] = new Sort("searchCount", Order.DESC);
} else if (resultSort == SearchResultSort.PRICEL2H) {
sorts[0] = new Sort("minPrice", Order.ASC);
} else if (resultSort == SearchResultSort.PRICEH2L) {
sorts[0] = new Sort("minPrice", Order.DESC);
}
}
PivotFacet[] pivotFacets = null;
List<FilterQuery> fqList = new ArrayList<FilterQuery>();
FilterQuery[] fqs = fqList.toArray(new FilterQuery[0]);
SearchResult<ProductModel2> sr = searchObjs(title, fqs, sorts, pivotFacets, page <= 1 ? 1 : page, size, true);
return new PageableResult<ProductModel2>(sr.getResult(), sr.getTotalCount(), page, size);
}
/**
* 根据关键词搜索
*
* @param sc
* @return
*/
public PageableResult<ProductModel2> searchProducts(SearchCriteria sc) {
String key = this.getSearchCacheKey(sc);
PageableResult<ProductModel2> model2PageableResult = null;
String pageableResultString = pageableResultcacheService.get(key, 0);
if (pageableResultString != null) {
try {
JSONObject jsonObject = JSON.parseObject(pageableResultString);
Map<String, JSONArray> pivotFieldVals = jsonObject.getObject("pivotFieldVals", Map.class);
Map<String, List<NameValue>> pivotFieldVals2 = new HashMap<String, List<NameValue>>();
Set<Map.Entry<String, JSONArray>> entries = pivotFieldVals.entrySet();
Iterator<Map.Entry<String, JSONArray>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, JSONArray> next = iterator.next();
pivotFieldVals2.put(next.getKey(), JSONArray.parseArray(next.getValue().toJSONString(), NameValue.class));
}
model2PageableResult = new PageableResult<ProductModel2>(JSONArray.parseArray(jsonObject.getString("data"), ProductModel2.class), jsonObject.getLong("numFund"), jsonObject.getLong("currentPage"), jsonObject.getLong("pageSize"), pivotFieldVals2);
return model2PageableResult;
} catch (Exception e) {
logger.error(" search products , get products from cache :" + e.getMessage());
return null;
}
} else {
List<String> pivotFields = sc.getPivotFields();
int pivotFieldSize = pivotFields == null ? 0 : pivotFields.size();
Sort[] sorts = null;
// sort by
SearchResultSort resultSort = sc.getSort();
if (resultSort != null) {
sorts = new Sort[1];
if (resultSort == SearchResultSort.POPULARITY) {
sorts[0] = new Sort(ProductModel2SortField.F_POPULARITY.getFieldName(), Order.DESC);
} else if (resultSort == SearchResultSort.PRICEL2H) {
sorts[0] = new Sort(ProductModel2SortField.F_PRICE.getFieldName(), Order.ASC);
} else if (resultSort == SearchResultSort.PRICEH2L) {
sorts[0] = new Sort(ProductModel2SortField.F_PRICE.getFieldName(), Order.DESC);
}
}
// pivot fields
PivotFacet[] pivotFacets = new PivotFacet[pivotFieldSize];
if (pivotFieldSize > 0) {
for (int i = 0; i < pivotFieldSize; i++) {
// cate2 distinct 提取出来所有值
pivotFacets[i] = new PivotFacet(pivotFields.get(i));
}
}
// filter list
List<FilterQuery> fqList = new ArrayList<FilterQuery>();
if (NumberUtils.isNumber(sc.getCategoryId())) {
long cateId = Long.valueOf(sc.getCategoryId());
fqList.add(new FilterQuery("cate" + sc.getLevel(), sc.getCategoryId()));
}
int priceFrom = sc.getPriceFrom(), priceTo = sc.getPriceTo();
String priceFromStr = "*", priceToStr = "*";
if (priceFrom < 0) {
priceFrom = 0;
}
if (priceFrom < priceTo) {
priceFromStr = String.valueOf(priceFrom);
priceToStr = String.valueOf(priceTo);
} else {
priceFromStr = String.valueOf(priceFrom);
}
fqList.add(new FilterQuery("minPrice", String.format("[%s TO %s]", priceFromStr, priceToStr)));
FilterQuery[] fqs = fqList.toArray(new FilterQuery[0]);
String keyword = sc.getKeyword();
if (StringUtils.isEmpty(keyword)) {
keyword = "*:*";
}
// search by solr
SearchResult<ProductModel2> sr = searchObjs(keyword, fqs, sorts, pivotFacets, sc.getPage() <= 1 ? 1 : sc.getPage(), sc.getPageSize(), true);
//process pivot fields
Map<String, List<NameValue>> pivotFieldVals = new HashMap<>();
if (pivotFieldSize > 0) {
NamedList<List<PivotField>> nl = sr.getFacetPivot();
for (int i = 0; i < pivotFieldSize; i++) {
String field = pivotFields.get(i);
List<PivotField> cate2List = nl.get(field);
for (PivotField pf : cate2List) {// string - object - long
System.out.println(pf.getValue() + "\t" + pf.getCount());
List<NameValue> nvs = pivotFieldVals.get(field);
if (nvs == null) {
nvs = new ArrayList<>();
pivotFieldVals.put(field, nvs);
}
nvs.add(new NameValue<Long, Long>((Long) pf.getValue(), Long.valueOf(pf.getCount())));
}
}
}
model2PageableResult = new PageableResult<ProductModel2>(sr.getResult(), sr.getTotalCount(), sc.getPage(), sc.getPageSize(), pivotFieldVals);
pageableResultcacheService.add(key, JSON.toJSONString(model2PageableResult), TimeUtils.SECONDS_OF_1_DAY);
return model2PageableResult;
}
}
/**
* 根据类目搜索商品
*/
public PageableResult<ProductModel2> searchPro(SearchCriteria criteria) {
int level = criteria.getLevel();
String cateId = criteria.getCategoryId();
int page = criteria.getPage();
int size = criteria.getPageSize();
if (level < 1 || level > 3) {
return null;
}
List<FilterQuery> fqList = new ArrayList<FilterQuery>();
int priceFrom = criteria.getPriceFrom(), priceTo = criteria.getPriceTo();
String priceFromStr = "*", priceToStr = "*";
if (priceFrom < priceTo && priceFrom >= 0) {
if (priceFrom < 0) {
priceFrom = 0;
}
priceFromStr = String.valueOf(priceFrom);
if (priceTo > 0) {
priceToStr = String.valueOf(priceTo);
}
fqList.add(new FilterQuery("minPrice", String.format("[%s TO %s]", priceFromStr, priceToStr)));
}
// Sort[] sorts = null;
Sort[] sorts = new Sort[2];
sorts[0] = new Sort("searchCount", Order.DESC);
// sort by
SearchResultSort resultSort = criteria.getSort();
if (resultSort != null) {
if (resultSort == SearchResultSort.POPULARITY) {
sorts[1] = new Sort(ProductModel2SortField.F_POPULARITY.getFieldName(), Order.DESC);
} else if (resultSort == SearchResultSort.PRICEL2H) {
sorts[1] = new Sort(ProductModel2SortField.F_PRICE.getFieldName(), Order.ASC);
} else if (resultSort == SearchResultSort.PRICEH2L) {
sorts[1] = new Sort(ProductModel2SortField.F_PRICE.getFieldName(), Order.DESC);
}
}
String q = "*:*";
PivotFacet[] pivotFacets = null;
fqList.add(new FilterQuery("cate" + level, String.valueOf(cateId)));
FilterQuery[] fqs = fqList.toArray(new FilterQuery[0]);
System.out.println(Thread.currentThread().getName() + " page " + page + " size " + size);
SearchResult<ProductModel2> sr = searchObjs(q, fqs, sorts, pivotFacets, page <= 1 ? 1 : page, size, true);
return new PageableResult<ProductModel2>(sr.getResult(), sr.getTotalCount(), page, size);
}
/**
* 类目下按关键词搜索
*
* @param cateId
* @param level
* @param title
* @param page
* @param size
* @return
*/
public PageableResult searchPro(long cateId, int level, String title, int page, int size) {
long cate1 = 0, cate2 = 0, cate3 = 0;
if (level == 1) {
cate1 = cateId;
} else if (level == 2) {
cate2 = cateId;
} else if (level == 3) {
cate3 = cateId;
}
return searchPro(cate1, cate2, cate3, title, page, size);
}
private PageableResult searchPro(long category1, long category2, long category3, String title, int page, int size) {
String q = title;
if (StringUtils.isEmpty(q)) {
q = "*:*";
}
List<FilterQuery> fqList = new ArrayList<FilterQuery>();
if (category3 > 0) {
fqList.add(new FilterQuery("cate3", String.valueOf(category3)));
} else if (category2 > 0) {
fqList.add(new FilterQuery("cate2", String.valueOf(category2)));
} else if (category1 > 0) {
fqList.add(new FilterQuery("cate1", String.valueOf(category1)));
}
FilterQuery[] fqs = fqList.toArray(new FilterQuery[0]);
Sort[] sorts = null;
PivotFacet[] pivotFacets = null;
SearchResult<Long> sr = search(q, fqs, sorts, pivotFacets, page, size);
long totalCount = sr.getTotalCount();
return new PageableResult<Long>(sr.getResult(), totalCount, page, size);
}
// public Map<String, List<String>> spellCheck(String keyword) {
// SolrQuery query = new SolrQuery();
// query.setRequestHandler("/spell");//select
// query.set("spellcheck", "true");
// query.set("spellcheck.q", keyword);
// query.set("spellcheck.build", "true");// 遇到新的检查词,会自动添加到索引里面
// query.set("spellcheck.count", 5);
//
// QueryResponse rsp = null;
// String s = "";
// List<String> suggestStrs = new ArrayList<>();
// Map<String, List<String>> map = new HashMap<>();
// try {
// rsp = solrServer.query(query);
//
// SpellCheckResponse spellres = rsp.getSpellCheckResponse();
//
// if (spellres != null) {
// if (!spellres.isCorrectlySpelled()) {
// List<SpellCheckResponse.Suggestion> suggestions = spellres.getSuggestions();
// for (SpellCheckResponse.Suggestion suggestion1 : suggestions) {
// map.put(suggestion1.getToken(), suggestion1.getAlternatives());
// }
// }
// }
// } catch (SolrServerException e) {
// throw new RuntimeException(e);
// }
//
// return map;
// }
// ************************父类实现*******************************
/*protected QueryResponse searchSolr(Query[] qs, FilterQuery[] fqs, Sort[] sorts, PivotFacet[] pivotFacets, int pageNumber, int pageSize, boolean useCache) {
SolrQuery query = new SolrQuery();
query.setRequestHandler("/select");//select
String q = this.getQ(qs);
if (!useCache) {
q = "{!cache=false}" + q;
}
query.setQuery(q);
String fq = this.getFQ(fqs);
if (!useCache) {
fq = "{!cache=false}" + fq;
}
query.setFilterQueries(fq);
query.setSorts(this.getSort(sorts));
query.setStart(pageNumber * pageSize - pageSize);
query.setRows(pageSize);
if (pivotFacets != null && pivotFacets.length > 0) {
List<String> facetFields = new LinkedList<String>();
for (PivotFacet pivotFacet : pivotFacets) {
facetFields.add(pivotFacet.getField());
}
query.setFacet(true);
query.addFacetPivotField(facetFields.toArray(new String[]{}));
}
String qStr = query.toString();
qStr = URLDecoder.decode(qStr);
QueryResponse rsp = null;
try {
rsp = solrServer.query(query);
} catch (SolrServerException e) {
throw new RuntimeException(e);
}
return rsp;
}
private String getFQ(FilterQuery[] fqs) {
if (fqs == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < fqs.length; i++) {
if (fqs[i] == null) {
continue;
}
if (i != fqs.length - 1) {
buffer.append(fqs[i].toString() + " AND ");
} else {
buffer.append(fqs[i].toString());
}
}
return buffer.toString();
}
private String getQ(Query[] qs) {
if (qs == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < qs.length; i++) {
if (qs[i] == null) {
continue;
}
if (i != qs.length - 1) {
buffer.append(qs[i].toString() + " OR ");
} else {
buffer.append(qs[i].toString());
}
}
return buffer.toString();
}
public SearchResult<ProductModel2> searchObjs(String q, FilterQuery[] fqs, Sort[] sorts, PivotFacet[] pivotFacets, int pageNumber, int pageSize, boolean useCache) {
Query[] qs = new Query[]{new Query("", q)};
QueryResponse rsp = searchSolr(qs, fqs, sorts, pivotFacets, pageNumber, pageSize, useCache);
Class clazz = (Class<ProductModel2>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
List<ProductModel2> ms = convert(rsp.getResults(), clazz);
SearchResult<ProductModel2> result = new SearchResult<ProductModel2>();
result.setResult(ms);
long numFound = rsp.getResults().getNumFound();
result.setTotalCount(numFound);
NamedList<List<PivotField>> namedFacetPivot = rsp.getFacetPivot();
result.setFacetPivot(namedFacetPivot);
return result;
}
private List<ProductModel2> convert(SolrDocumentList results, Class<ProductModel2> clazz) {
List<ProductModel2> list = new ArrayList<ProductModel2>();
Iterator<SolrDocument> iter = results.iterator();
while (iter.hasNext()) {
SolrDocument sd = iter.next();
try {
ProductModel2 m = clazz.newInstance();
for (Map.Entry<String, Object> kv : sd.entrySet()) {
BeanUtils.setProperty(m, kv.getKey(), kv.getValue());
}
list.add(m);
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}*/
public String getSearchCacheKey(SearchCriteria sc) {
StringBuilder key = new StringBuilder();
key.append(SOLR_CACHE_KEY);
if (!StringUtils.isEmpty(sc.getKeyword())) {
key.append("_").append(sc.getKeyword());
}
if (!StringUtils.isEmpty(sc.getCategoryId())) {
key.append("_").append(sc.getCategoryId());
}
if (!StringUtils.isEmpty(sc.getLevel() + "")) {
key.append("_").append(sc.getLevel());
}
if (sc.getPriceFrom() != -1) {
key.append("_").append(sc.getPriceFrom());
}
if (sc.getPriceTo() != -1) {
key.append("_").append(sc.getPriceTo());
}
if (sc.getPivotFields() != null && sc.getPivotFields().size() > 0) {
for (String pivotField : sc.getPivotFields()) {
key.append("_").append(pivotField);
}
}
if (sc.getSort() != null) {
key.append("_").append(sc.getSort());
}
key.append("_").append(sc.getPage()).append("_").append(sc.getPageSize());
return key.toString();
}
//
// public static void parseCacheString2Object(String jsonString, Class obj) {
// Method[] methods = obj.getMethods();
// for (Method method : methods) {
// if (method.getName().startsWith("set")) {
// System.out.println(method.getName());
// }
// }
// }
//
// public static void main(String[] args) {
// ProductIndex2ServiceImpl.parseCacheString2Object("", PageableResult.class);
// }
}
|
C++
|
UTF-8
| 2,843 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
/*
* ofxMask.h
*
* Created by Patricio Gonzalez Vivo on 10/1/11.
* Copyright 2011 http://PatricioGonzalezVivo.com All rights reserved.
*
* ******************************************************************
*
* tex0 -> Image
* tex1 -> LUT
*
*/
#ifndef OFXLUT
#define OFXLUT
#define STRINGIFY(A) #A
#include "ofMain.h"
#include "ofxFXObject.h"
class ofxLUT : public ofxFXObject {
public:
ofxLUT(){
passes = 1;
internalFormat = GL_RGB32F;
fragmentShader = STRINGIFY(uniform sampler2DRect tex0;
uniform sampler2DRect tex1;
float size = 32.0;
void main(void){
vec2 st = gl_TexCoord[0].st;
vec4 srcColor = texture2DRect(tex0, st);
float x = srcColor.r * (size-1.0);\n\
float y = srcColor.g * (size-1.0);
float z = srcColor.b * (size-1.0);
vec3 color = texture2DRect(tex1, vec2(floor(x)+1.0 +(floor(y)+1.0)*size, floor(z)+1.0)).rgb;
gl_FragColor = vec4( color , 1.0);
});
}
bool loadLUT(ofBuffer &buffer) {
buffer.resetLineReader();
int mapSize = 32;
float * pixels = new float[mapSize * mapSize * mapSize * 3];
textures[1].getTextureReference().allocate(mapSize * mapSize, mapSize,GL_RGB32F);
ofDirectory dir;
for(int z=0; z<mapSize ; z++){
for(int y=0; y<mapSize; y++){
for(int x=0; x<mapSize; x++){
string content = buffer.getNextLine();
int pos = x + y*mapSize + z*mapSize*mapSize;
vector <string> splitString = ofSplitString(content, " ", true, true);
if (splitString.size() >=3) {
pixels[pos*3 + 0] = ofToFloat(splitString[0]);
pixels[pos*3 + 1] = ofToFloat(splitString[1]);
pixels[pos*3 + 2] = ofToFloat(splitString[2]);
}
}
}
}
textures[1].getTextureReference().loadData( pixels, mapSize * mapSize, mapSize, GL_RGB);
return true;
}
bool loadLUT(string lutFile){
ofBuffer buffer = ofBufferFromFile(lutFile);
return loadLUT(buffer);
}
};
#endif
|
Go
|
UTF-8
| 339 | 3.484375 | 3 |
[] |
no_license
|
package main
import (
"fmt"
"sync"
)
var once sync.Once = sync.Once{}
var instanse *singler
type singler struct {
Name string
}
func NewSingler() *singler {
once.Do(func() {
instanse = new(singler)
instanse.Name = "这是一个单例"
})
return instanse
}
func main() {
singler := NewSingler()
fmt.Println(singler.Name)
}
|
Markdown
|
UTF-8
| 3,577 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
# motionEAP
The motionEAP project aims to augment workplaces with in-situ projection to support workers during manual assembly tasks. Using a depth-sensor, motionEAP is able to deliver appropriate feedback regarding the current assembly step. Correct or wrong assembly steps as well as picks from bins are detected using image processing algorithms.
## What is motionEAP
motionEAP is a software utilizing hand gestures and assembly actions as input to provide projection-based feedback whether an assembly step or a pick from a box was successful or not. The software provided at this repository is the outcome of an four year lasting research project, which was founded by the German Federal Ministry for Economic Affairs and Energy. The software utilizes a projector and a depth sensor to provide in-situ projections, while depth data is analyzed in real-time to detect hand gestures and check if assembly worksteps are performed correctly. The software was originally written to support workers at assembly workplaces by using in-situ projections to signalize from which bin has to be picked next and how to assemble picked parts on workpiece carriers.
## Supported Hardware
An arbitrary projector can be leveraged to use motionEAP. The software checks if a second screen is attached and uses it to project an editable plane on it. As for the depth sensor, motionEAP supports the following devices:
* Kinect v1 using OpenNI
* Structure Sensor using OpenNI
* Ensenso N10 using iView
* Kinect v2 using Kinect SDK 2.0
Make sure to install the correct driver for depth sensor you want to use. Try to retrieve images from the depth sensor with the delivered software from the depth sensor driver.
## System Requirements
To make use of motionEAPs, a graphics card supporting two or more screens is necessary. Depending on the depth sensor you want to use, additional hardware is necessary. For example, a USB 3.0 port and a DirectX11 compatible grapic card is necessary when a Kinect v2 should be used. Please look up the manual of the camera manufacturer to make sure your system meets the requirements. As for running the software itself, we recommend a computer with an i7 2.4 GhZ Quad Core (or similar) and 8 GB RAM. Furthermore, only Microsoft Windows 7, 8, 8.1, and 10 can be used to run the motionEAP.
## Compiling motionEAP
To compile motionEAP, just checkout the repository and open the motionEAPAdmin.sln using Visual Studio 2013. Set motionEAPAdmin as startup project and build the project.
## Why citing motionEAP
If you are using motionEAP in your research-related documents, it is recommended that you cite motionEAP. This way, other researchers can better understand your proposed-method. Your method is more reproducible and thus gaining better credibility.
## How to cite motionEAP
Below are the BibTex entries to cite motionEAP
```bibtex
@misc{Funk:2016,
author = {Markus Funk, Thomas Kosch, Sven Mayer},
title = {motionEAP},
year = {2016},
publisher = {GitHub},
journal = {GitHub repository},
howpublished = {\url{https://github.com/hcilab-org/motionEAP/}}
}
```
```bibtex
@inproceedings{funk2016motioneap,
author = {Funk, Markus and Kosch, Thomas and Kettner, Romina and Korn, Oliver and Schmidt, Albrecht},
title = {motionEAP: An Overview of 4 Years of Combining Industrial Assembly with Augmented Reality for Industry 4.0},
booktitle = {Proceedings of the 16th International Conference on Knowledge Technologies and Data-driven Business},
series = {i-KNOW '16},
year = {2016},
location = {Graz, Austria},
numpages = {4},
publisher = {ACM},
address = {New York, NY, USA}
}
```
|
Markdown
|
UTF-8
| 584 | 2.6875 | 3 |
[] |
no_license
|
# LIDAR-VR
Code and experiments to construct surfaces from point clouds and render them, as part of a hackathon.
algos - contains code to convert formats, and has a few algorithms to sparsify point clouds and construct surfaces from them. Also has some code to render point clouds in Blender.
test3 - Unity application that renders point clouds by sparsifying them and constructing solid surfaces, and allows the user to move around.

|
Python
|
UTF-8
| 4,276 | 3.140625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2023 all rights reserved
#
# triangulated surfaces
def surface(**kwds):
"""
Create a surface
"""
# get the factory
from .Surface import Surface
# make one and return it
return Surface(**kwds)
# logically cartesian grids
def grid(**kwds):
"""
Create a grid
"""
# get the factory
from .Grid import Grid
# make on and return it
return Grid(**kwds)
# corner-point grids
def cpg(**kwds):
"""
Create a corner point grid
"""
# get the factory
from .CPGrid import CPGrid
# make one and return it
return CPGrid(**kwds)
# simple representation of a simplicial mesh
def mesh(**kwds):
"""
Create a mesh
"""
# get the factory
from .Mesh import Mesh
# make one and return it
return Mesh(**kwds)
# value storage
def field(**kwds):
"""
Create a field over a one of the space discretizations
"""
# get the factory
from .Field import Field
# make one and return it
return Field(**kwds)
# converters
def triangulation(**kwds):
"""
Create a triangulation
"""
# get the factory
from .Triangulation import Triangulation
# make one and return it
return Triangulation(**kwds)
# utilities
def transfer(grid, fields, mesh):
"""
Transfer the {fields} defined over a grid to fields defined over the {mesh}
"""
# initialize the result
xfer = { property: [] for property in fields.keys() }
# get the dimension of the grid
dim = len(grid.shape)
# here we go: for every tet
for tetid, tet in enumerate(mesh.simplices):
# get the coordinates of its nodes
vertices = tuple(mesh.points[node] for node in tet)
# compute the barycenter
bary = tuple(sum(point[i] for point in vertices)/len(vertices) for i in range(dim))
# initialize the search bounds
imin = [0] * dim
imax = list(n-1 for n in grid.shape)
# as long as the two end points haven't collapsed
while imin < imax:
# find the midpoint
index = [(high+low)//2 for low, high in zip(imin, imax)]
# get that cell
cell = grid[index]
# get one corner of its bounding box
cmin = tuple(min(p[i] for p in cell) for i in range(dim))
# get the other corner of its bounding box
cmax = tuple(max(p[i] for p in cell) for i in range(dim))
# decide which way to go
for d in range(dim):
# if {bary} is smaller than that
if bary[d] < cmin[d]:
imax[d] = max(imin[d], index[d] - 1)
# if {bary} is greater than that
elif bary[d] > cmax[d]:
imin[d] = min(imax[d], index[d] + 1)
# if {bary} is within
elif cmin[d] <= bary[d] <= cmax[d]:
imin[d] = index[d]
imax[d] = index[d]
else:
assert False, 'could not locate grid cell for tet {}'.format(tetid)
# ok. we found the index; transfer the fields
for property, field in fields.items():
# store the value
xfer[property].append(field[imin])
# all done; return the map of transferred fields
return xfer
def boxUnion(b1, b2):
"""
Compute a box big enough to contain both input boxes
"""
# easy enough
return tuple(map(min, zip(b1[0], b2[0]))), tuple(map(max, zip(b1[1], b2[1])))
def boxIntersection(b1, b2):
"""
Compute a box small enough to fit inside both input boxes
"""
# easy enough
return tuple(map(max, zip(b1[0], b2[0]))), tuple(map(min, zip(b1[1], b2[1])))
def convexHull(points):
"""
Compute the convex hull of the given {points}
"""
# set up the two corners
p_min = []
p_max = []
# zip all the points together, forming as many streams of coordinates as there are
# dimensions
for axis in zip(*points):
# store the minimum value in p_min
p_min.append(min(axis))
# and the maximum value in p_max
p_max.append(max(axis))
# all done
return p_min, p_max
# end of file
|
Java
|
UTF-8
| 1,552 | 4.0625 | 4 |
[] |
no_license
|
package app;
class Person {
// Propriétés des objets de type "personne"
private String firstName;
private String lastName;
private int age;
private boolean isMale;
// Constructeur: cette méthode est appelée automatiquement lorsqu'une nouvelle instance
// de cette classe est créée (à l'aide du mot-clé new)
// Nous pouvons définir ici les paramètres que nous souhaitons demander lors de la
// création de l'objet
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.setAge(age);
}
// Renvoie le nom complet d'une personne
public String fullName() {
return firstName + " " + lastName;
}
// Détermine si une personne est majeure ou non
public boolean isLegal() {
if (this.age < 18) {
return false;
} else {
return true;
}
}
// Getter: méthode publique qui permet d'avoir accès indirectement à une propriété privée
public int getAge() {
return this.age;
}
// Setter: méthode publique qui permet de modifier indirectement une propriété privée
// On a rajouté ici de la logique préalable pour valider l'âge de la personne avant
// de modifier la propriété
// Si l'âge est invalide, on produit une erreur
public void setAge(int value) {
if (value < 0) {
throw new RuntimeException("Age must be positive");
}
this.age = value;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.