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
|
---|---|---|---|---|---|---|---|
Shell
|
UTF-8
| 515 | 3.171875 | 3 |
[] |
no_license
|
#!/bin/bash
if [ -e /etc/dynamodb/config.cfg ]; then
source /etc/dynamodb/config.cfg
else
shared=true
dbPath=/var/lib/dynamodb
port=8000
fi
librarypath=/usr/share/dynamodb/DynamoDBLocal_lib
jar=/usr/share/dynamodb/DynamoDBLocal.jar
args=("-Djava.library.path=$librarypath" "-jar $jar" "-port $port")
if [ $shared ]; then
args+=('-sharedDb')
fi
if [ $inMemory ]; then
args+=('-inMemory')
else
args+=("-dbPath $dbPath")
fi
args+=$additionalArgs
command=java
echo ${args[*]}
$command ${args[*]}
|
C
|
UTF-8
| 601 | 3.671875 | 4 |
[] |
no_license
|
//
// exercise_1.c
// Question:
//Write a C program to print your name, date of birth. and mobile number.//
//
// Created by Rob the deer on 13.04.2021.
//
#include <stdio.h>
int main(void){
//declaration of variables
int dd;
int mm;
int yyyy;
long int mobile_num;
printf("/////________WELCOME TO MY DATABASE____\\\\\n");
//assign variables
dd = 25;
mm = 06;
yyyy = 1997;
mobile_num = 89104483756;
printf("Hey, Everybody, My name is: ROBERT NYAMUGADA\n, and\n my birthdate is %d.%d.%d\n My mobile number is: %ld\n",dd,mm, yyyy, mobile_num);
puts("///////THANKS VERY MUCH\\\\\\\\\\\\");
}
|
C#
|
GB18030
| 1,669 | 2.734375 | 3 |
[] |
no_license
|
using System;
using System.Data;
namespace PMS.Model
{
/// <summary>
/// TNews(ʵ)
/// </summary>
[Serializable()]
public class News
{
/// <summary>
/// id
/// </summary>
public int NewsId { get; set; }
/// <summary>
///
/// </summary>
public string NewsTitle { get; set; }
/// <summary>
///
/// </summary>
public string NewsContent { get; set; }
/// <summary>
/// 淢ʱ
/// </summary>
public System.DateTime CreateTime { get; set; }
/// <summary>
/// 淢(ʦϢ)
/// </summary>
public Teacher teacher { get; set; }
/// <summary>
/// ԺϢԺ
/// </summary>
public College college { get; set; }
/// <summary>
/// ι캯
/// </summary>
public News() { }
/// <summary>
/// вι캯
/// </summary>
/// <param name="newsId"></param>
/// <param name="newsTitle"></param>
/// <param name="newsContent"></param>
/// <param name="createTime"></param>
/// <param name="teacher"></param>
public News(int newsId, string newsTitle, string newsContent, DateTime createTime, Teacher teacher)
{
NewsId = newsId;
NewsTitle = newsTitle;
NewsContent = newsContent;
CreateTime = createTime;
this.teacher = teacher;
}
}
}
|
Java
|
UTF-8
| 277 | 1.875 | 2 |
[] |
no_license
|
package pe.g5.upc.service;
import java.util.List;
import pe.g5.upc.entity.Autoevaluacion;
public interface iAutoevaluacionService {
public void insertar(Autoevaluacion autoevaluacion);
public List<Autoevaluacion>listar();
public void eliminar ( int idAutoevaluacion);
}
|
Markdown
|
UTF-8
| 985 | 2.96875 | 3 |
[] |
no_license
|
# blood-rage-translations
This project contains (addable) translations for the board game Blood Rage.
You can search for cards by their English titles and get translation in other Languages (In this case Georgian Or any language you add).
You can add translation of any language.
## DEMO
see here: http://blood-rage.vakho.space
## Dependencies
- node.js
## How to use?
- Run `npm install` command from project's root directory.
- Run `npm start` command and open app iside a browser.
- Type any letter to search by card title.
## How to change language?
Duplicate the file `/translations/ka.json`. For example, create `/translations/fr.json`.
Then translate contents of `fr.json`.
Then open the app in your browser with `lang` parameter. For example `http://localhost:5000?lang=fr`.
**Note: Default app language is Georgian (ka). It can be modified inside the /assets/js/script.js file**
## Resources:
Bloo Rage: https://boardgamegeek.com/boardgame/170216/blood-rage
|
Java
|
UTF-8
| 156 | 1.84375 | 2 |
[
"BSD-2-Clause"
] |
permissive
|
package cz.librarymanager.model.enums;
/**
* Created by Zdenca on 4/23/2016.
*/
public enum BookForm {
OPTICAL,PAPERBACK, HARD_COVER, MAP, ONLINE;
}
|
C#
|
UTF-8
| 4,752 | 2.78125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnigmaNet.Bus
{
public static class SubscriberUtils
{
static void Subscriber(ICommandSubscriber commandSubscriber, object commandHandler)
{
var handlerTypes = commandHandler.GetType().GetInterfaces()
.Where(m => m.IsGenericType && m.GetGenericTypeDefinition() == typeof(ICommandHandler<,>));
if (handlerTypes != null && handlerTypes.Count() > 0)
{
var subscribeMethod = typeof(ICommandSubscriber).GetMethod(nameof(ICommandSubscriber.SubscribeAsync));
foreach (var handlerType in handlerTypes)
{
var commandTypes = handlerType.GetGenericArguments();
subscribeMethod.MakeGenericMethod(commandTypes).Invoke(commandSubscriber, new object[] { commandHandler });
}
}
}
public static void Subscriber(ICommandSubscriber commandSubscriber, params object[] commandHandlers)
{
foreach (var commandHandler in commandHandlers)
{
Subscriber(commandSubscriber, commandHandler);
}
}
static void Subscriber(IEventSubscriber eventSubscriber, object eventHandler)
{
var handlerTypes = eventHandler.GetType().GetInterfaces()
.Where(m => m.IsGenericType && m.GetGenericTypeDefinition() == typeof(IEventHandler<>));
if (handlerTypes != null && handlerTypes.Count() > 0)
{
var subscribeMethod = typeof(IEventSubscriber).GetMethod("SubscribeAsync");
foreach (var handlerType in handlerTypes)
{
var eventType = handlerType.GetGenericArguments();
//subscribeMethod.MakeGenericMethod(eventType).Invoke(eventSubscriber, new object[] { eventHandler });
var task = (Task)subscribeMethod.MakeGenericMethod(eventType).Invoke(eventSubscriber, new object[] { eventHandler });
task.Wait();
}
}
}
public static void Subscriber(IEventSubscriber eventSubscriber, params object[] eventHandlers)
{
foreach (var eventHanlder in eventHandlers)
{
Subscriber(eventSubscriber, eventHanlder);
}
}
static void Subscriber(IDelayMessageSubscriber delayMessageSubscriber, object delayMessageHandler)
{
var handlerTypes = delayMessageHandler.GetType().GetInterfaces()
.Where(m => m.IsGenericType && m.GetGenericTypeDefinition() == typeof(IDelayMessageHandler<>));
if (handlerTypes != null && handlerTypes.Count() > 0)
{
var subscribeMethod = typeof(IDelayMessageSubscriber).GetMethod("SubscribeAsync");
foreach (var handlerType in handlerTypes)
{
var delayMessageType = handlerType.GetGenericArguments();
var task = (Task)subscribeMethod.MakeGenericMethod(delayMessageType).Invoke(delayMessageSubscriber, new object[] { delayMessageHandler });
task.Wait();
}
}
}
public static void Subscriber(IDelayMessageSubscriber delayMessageSubscriber, params object[] delayMessageHandlers)
{
foreach (var delayMessageHanlder in delayMessageHandlers)
{
Subscriber(delayMessageSubscriber, delayMessageHanlder);
}
}
public static void Subscriber(ICommandSubscriber commandSubscriber, IEventSubscriber eventSubscriber, params object[] handlers)
{
foreach (var eventHanlder in handlers)
{
Subscriber(eventSubscriber, eventHanlder);
}
foreach (var commandHandler in handlers)
{
Subscriber(commandSubscriber, commandHandler);
}
}
public static void Subscriber(ICommandSubscriber commandSubscriber, IEventSubscriber eventSubscriber, IDelayMessageSubscriber delayMessageSubscriber, params object[] handlers)
{
foreach (var eventHanlder in handlers)
{
Subscriber(eventSubscriber, eventHanlder);
}
foreach (var commandHandler in handlers)
{
Subscriber(commandSubscriber, commandHandler);
}
foreach (var handler in handlers)
{
Subscriber(delayMessageSubscriber, handler);
}
}
}
}
|
Java
|
UTF-8
| 191 | 2.53125 | 3 |
[] |
no_license
|
package app.exceptions;
public class InvalidCommandException extends Exception {
public InvalidCommandException(String command) {
super("Invalid command : " + command);
}
}
|
Markdown
|
UTF-8
| 3,448 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
# NumPadUltra
笔记本小键盘输入扩展(键盘钩子)
## 功能
目前主流笔记本个人电脑为节省键盘占用空间,一般不搭载数字小键盘;但是在一些情景下,小键盘按键的功能并不能被上方横排数字键所完全替代。例如:某些设计软件(如Adobe系列)和大型单机游戏的快捷键必须用到小键盘按键;以及在统计时、需要输入大量数据的情况,小键盘的九宫格布局可大幅加快输入速度。
本程序的开发动机主要是P大的一门名为“物理化学实验”的必修课:
* 经常要向Excel/Origin里输入几页的原始数据,用上方横排数字键实在太慢;
* 要在实验记录本里抄电子版讲义的原理/步骤等内容,本子压在键盘上写字容易误触按键。
本程序的主要功能便是使用(全局)键盘钩子实现了:
* 将笔记本电脑键盘的右半部分临时开辟出来作为数字小键盘的替代按键(称为`小键盘模式`),例如按下`<,`,`>.`,`?/`键后,实际输入的是`Num 1`,`Num 2`,`Num 3`(详见下图);
* 锁定键盘(即令所有键盘事件无效化),防止误触(称为`锁定模式`);
* `正常模式`(保留原始键盘布局和功能)和`小键盘模式`、`锁定模式`间可快速切换。
<p align="center">
<img src="/Keybd.jpg" width="50%" height="50%"/>
<br>小键盘模式下的实际键盘布局
</p>
## 使用方法
下载最新版本的[单个可执行文件](https://github.com/Z-H-Sun/NumPadUltra/releases/download/v3.26/NumPadUltra.exe)至任意位置,双击运行即可。
* 程序刚启动时为`小键盘模式`。默认在屏幕的左上角会出现下图所示的半透明图标,单击拖拽可改变其位置;<p align="center"><img src="/NumPadUltra/KeyboardHook/KeybdNum.ico" width="32" height="32"/></p>现在可以尝试开一个记事本,依次按下键盘上的`op[l;',./`,如果程序正常运行,实际显示的将是`789456123`
* 按下右Windows徽标键,或右键单击上述图标,可在`锁定模式`和`小键盘模式`之间切换;图标的颜色分别变为红色、黄色;<p align="center"><img src="/NumPadUltra/KeyboardHook/KeybdFbd.ico" width="32" height="32"/></p>在`锁定模式`下,计算机不会响应除了Windows徽标键以外的任何键盘事件
* 按下左Windows徽标键,或左键单击上述图标,可在上述的某个模式与`正常模式`之间切换;图标的颜色分别变为红或黄色/绿色;<p align="center"><img src="/NumPadUltra/KeyboardHook/Keybd.ico" width="32" height="32"/></p>
* 若长按Windows徽标键(长于1秒),则实现按下Windows键本身的功能,不切换模式;
* 双击上述图标可退出程序
* 鼠标中键单击上述图标,可显示如下图所示的键盘布局示意图:<p align="center"><img src="/NumPadUltra/KeyboardHook/Keyboards%20Collection.png" width="70%" height="70%"/></p>
* 单击拖拽可改变位置,滑动滚轮以改变透明度
* 点击ESC按钮或按下ESC以关闭窗口
* 在相应的按键上悬停以查看实际键盘布局,单击可模拟`小键盘模式`中相应的键盘按键事件
* Q: 是否可以自定义“数字键盘布局”?A: 目前暂时无法进行配置,只能手动更改[Form1.vb](/NumPadUltra/KeyboardHook/Form1.vb)中的`KeyBoardProc`函数,然后自行编译
|
Python
|
UTF-8
| 7,957 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/python
import sys
import os
import regret as rg
import class_Auction
import numpy as np
import regret as rg
import matplotlib.pyplot as plt
from scipy.optimize import linprog
from scipy.stats import gaussian_kde
import math
#how_much_regret is a function that takes three arguments:
# 1) filename = the name of the file where the auction is stored (the file ha to be in auction format)
# 2) player_id = the index of the player we want to calculate the regret
# 3) valuation = the valuation of the player_id
# 4) step = each time i evaluate the regret of the auctions [0,i*step]
def how_much_regret(filename,player_id,valuation,step):
#take the set of possible bids for player_id (we assume as possible bids the set of the bids he submitted)
#create the object of the auction that we want to analyze
gsp=rg.create_auction(filename)
T=len(gsp.history)
possible_bids=[]
for t in range(0,T):
b=gsp.history[t]
possible_bids.append(b[player_id])
possible_bids=set(possible_bids)
#initialie the regret as -inf
reg=-float("inf")
actions=len(possible_bids)
#maintain the history of the auction
maintain_history=gsp.history
#each time we evaluate the regret until i*step
y_axis=[]
for i in range(1,T/step):
print "iteration=", i
#i have to change a little the gsp object and maintain only the first i*step auctions
new_history=gsp.history[0:i*step]
gsp.history=new_history
#according to this modified gsp object i calculate regret
#now i calculate the regret provocated by each constant bid and i take the maximum
possible_regrets=[]
for bid in possible_bids:
possible_regrets.append(valuation*rg.DP(gsp,bid,player_id)-rg.DC(gsp,bid,player_id))
#print "theory regret:", 2*np.sqrt(actions*np.log(actions)/float(T))
#print "practice:",max(possible_regrets)
y_axis.append(max(possible_regrets))
#now it remains to reconstruct the original gsp object
gsp.history=maintain_history
#free up some space
del new_history
plt.figure()
x_axis=[i for i in range(0,len(y_axis))]
x_ticks=[ str(100*round((i+1)/float(len(y_axis)),1)) +"%" for i in range(0,len(y_axis))]
plt.xticks(x_axis,x_ticks)
plt.ylabel("regret")
plt.xlabel("auction percentage")
plt.title("Regret evolution of player "+str(player_id+1))
plt.plot(x_axis,y_axis)
plt.savefig("Regret_evolution"+str(player_id)+".png")
#avg_bid is a function that takes three arguments:
# 1) filename = the name of the file where the auction is stored (the file has to be in auction format)
# 2) player_id = the index of the player we want to calculate the regret
# 3) valuation = the valuation of the player_id
#and plots the average bid of the particular player in the particular auction
def avg_bid(filename,player_id,valuation,step):
avgs=np.array([])
#create the object of the auction that we want to analyze
gsp=rg.create_auction(filename)
T=len(gsp.history)
#average bid every 10 bids
for t in range(0,T-step,step):
#these are the bids of all bidders form 10 consecutive auctions
b=gsp.history[t:t+step]
#maintain only the bids of bidder player_id
b=[x[player_id] for x in b]
#divide by 10 to take the avg bid of the last ten auctions
avg_bid=sum(b)/float(step)
#normalize using the valuation of the bidder
avg_bid=avg_bid/float(valuation)
avgs=np.append(avgs,avg_bid)
plt.figure()
plt.xlabel("auction iteration")
plt.ylabel("bid/valuation")
x_axis=[i for i in range(0,len(avgs))]
plt.title("bid evolution of player "+str(player_id))
plt.plot(x_axis,avgs)
plt.savefig("bid_evolution"+str(player_id)+".png")
def avg_position(filename,player_id,step):
avgs=np.array([])
#create the object of the auction that we want to analyze
gsp=rg.create_auction(filename)
T=len(gsp.history)
#here i store the position that player id took in each auction iteration
positions=[]
for t in range(0,T):
positions.append(gsp.slot(player_id,gsp.history[t]))
y_axis=[]
for t in range(0,T-step,step):
#take the average position each step auctions
y_axis.append((sum(positions[t:t+step])/float(step))+1)
plt.figure()
plt.xlabel("auction iteration")
plt.ylabel("position")
plt.title("position earned of player "+str(player_id))
x_axis=[i for i in range(0,len(y_axis))]
plt.plot(x_axis,y_axis)
plt.savefig("position_evolution"+str(player_id)+".png")
def rationalizable_set(filename,player_id):
#create the auction as described in the filename (which has to be in auction format)
gsp=rg.create_auction(filename)
#take the set of possible bids for player_id (we assume as possible bids the set of the bids he submitted)
T=len(gsp.history)
possible_bids=[]
for t in range(0,T):
b=gsp.history[t]
possible_bids.append(b[player_id])
possible_bids=set(possible_bids)
#formulate the linear program that calculates the regret and the valuation supossing minimum additive error
A=[]
b=[]
cntr=0
for bid in possible_bids:
A.append([rg.DP(gsp,bid,player_id)])
b.append(rg.DC(gsp,bid,player_id))
x_coordinates=[]
y_coordinates=[]
for e in np.linspace(0,1,100):
#change the -1 with e
for i in range(0,len(b)):
b[i]+=1/float(100)
u_bounds=(0,None)
c=[1]
res = linprog(c, A_ub=A, b_ub=b, bounds=(u_bounds))
#print res
#print res.x
#print res.x[0]
if not (math.isnan(res.x)):
max_possible_u=res.x[0]
y_coordinates.append(max_possible_u)
x_coordinates.append(e)
c=[-1]
res = linprog(c, A_ub=A, b_ub=b, bounds=(u_bounds))
if not (math.isnan(res.x)):
min_possible_u=abs(res.x[0])
y_coordinates.append(min_possible_u)
x_coordinates.append(e+0.0001)
print len(x_coordinates)
print len(y_coordinates)
plt.figure()
plt.xlabel("regret")
plt.ylabel("valuation")
plt.title("rationalizable set of player "+str(player_id))
plt.plot(x_coordinates,y_coordinates,"ro")
plt.savefig("rationalizable_set"+str(player_id)+".png")
def gaussian(x,mu,sig):
return np.exp((-np.power(x-mu,2.)) / (2*np.power(sig,2.)))
def error(original_values_filename, infered_values_filename):
#collect the valuations of the first file
val_1=[]
with open(original_values_filename,'r') as f:
for line in f:
tokens=line.split()
if len(tokens)==1:
n=int(tokens[0])
if len(tokens)==2:
val_1.append(float(tokens[1]))
val_2=[]
with open(infered_values_filename,'r') as f:
for line in f:
tokens=line.split()
if len(tokens)==1:
n=int(tokens[0])
if len(tokens)==2:
val_2.append(float(tokens[1]))
if not (len(val_2)==len(val_1)):
print "error"
exit()
error=[]
#evaluate the error with respect to the magnitude of the true values
for i in range(0,len(val_1)):
error.append((val_1[i]-val_2[i])/val_1[i])
return error
#####################EDW EINAI GIA TIS PROSOMOIWSEIS
val=[]
with open("0.val",'r') as f:
for line in f:
tokens=line.split()
if len(tokens)==1:
n=int(tokens[0])
if len(tokens)==2:
val.append(float(tokens[1]))
base="../dataset/"
_error=[]
for i in range(0,100):
break
f1=str(i)+".val"
f2=str(i)+".val_infered"
_error.append(error(base+f1,base+f2))
for i in range(0,6):
break
print "-----"+str(i+1)+"------"
player_1=[x[i] for x in _error]
density=gaussian_kde(player_1)
x=np.linspace(-1,1,200)
plt.figure()
plt.xlabel("error percentage over true valuation")
plt.ylabel("pdf")
plt.title("inference method error's pdf of player "+str(i))
plt.plot(x,density(x))
plt.savefig("error_pdf"+str(i)+".png")
#print sum(player_1)/float(len(player_1))
for i in range(0,len(val)):
#rationalizable_set("0.auction",i)
#avg_bid("0.auction",i,val[i],100)
#avg_position("0.auction",i,100)
how_much_regret("0.auction",i,val[i],1000)
#exit()
|
Shell
|
UTF-8
| 522 | 2.9375 | 3 |
[] |
no_license
|
#!/bin/sh
# $Id: thump.sh 55 2008-09-30 19:26:52Z mando $
# AgentSDK
# stop/start the local agent
#
# Mike ERWIN mikee@symbiot.com
# Paco NATHAN paco@symbiot.com
# Jamie PUGH jamie@symbiot.com
nuke ()
{
ps axl | grep $1 | grep -v grep | perl -e 'while (<STDIN>) { s/\s+/ /g; @l = split(/ /); print $l[2] . "\n"; }' |
while read pid
do
printf "kill pid %6d %s\n" $pid $1
sudo kill -9 $pid
done
return 0
}
#nuke "symagent start"
killall -9 symagent
killall -9 nmap
/etc/init.d/symagent stop
sleep 3
/etc/init.d/symagent start
|
JavaScript
|
UTF-8
| 15,104 | 3.15625 | 3 |
[
"CC-BY-4.0"
] |
permissive
|
/* eslint-disable no-param-reassign */
/* eslint-disable class-methods-use-this */
import { clean } from './Utils.js';
export class MdGenerator {
/**
* Generates a markdown content from an Element.
* @param {Element} root
* @returns {string} The generated markdown.
*/
generate(root) {
clean(root);
const { childNodes } = root;
const txt = Array.from(childNodes).map(node => this.processNode(node));
return txt.join('');
}
/**
* Processes a single node.
* @param {ChildNode} node
* @returns {string} The generated code for the node.
*/
processNode(node) {
switch (node.nodeType) {
case Node.TEXT_NODE: return this.processTextNode(/** @type Text */ (node));
case Node.COMMENT_NODE: return this.processCommentNode(/** @type Comment */ (node));
case Node.ELEMENT_NODE: return this.processElementNode(/** @type Element */ (node));
default: // console.log(node);
}
return '';
}
/**
* Process a text node and returns the markup.
* @param {Text} node
* @returns {string}
*/
processTextNode(node) {
let value = node.nodeValue;
value = value.replace(/ +/g, ' ');
value = value.replace(/([*_~|`])/g, '\\$1');
value = value.replace(/^(\s*)>/g, '\\$1>');
value = value.replace(/^#/gm, '\\#');
value = value.replace(/^(\s*)([-=]{3,})(\s*)$/, '$1\\$2$3');
value = value.replace(/^( {0,3}\d+)\./gm, '$1\\.');
value = value.replace(/^( {0,3})([+-])/gm, '$1\\$2');
value = value.replace(/]([\s]*)\(/g, '\\]$1\\(');
value = value.replace(/^ {0,3}\[([\S \t]*?)]:/gm, '\\[$1]:');
return value;
}
/**
* Process a comment node and returns the markup.
* @param {Comment} node
* @returns {string}
*/
processCommentNode(node) {
return `<!--${node.data}-->\n\n`;
}
/**
* Processes an node that is an element.
* @param {Element} node
* @returns {string}
*/
processElementNode(node) {
const { localName } = node;
if (['script', 'link', 'head', 'body', 'html', 'meta', 'title', 'style'].includes(localName)) {
// we don't like them. And their children.
return '';
}
const typedHtmlElement = /** @type HTMLElement */ (node);
if (['div', 'p'].includes(localName)) {
const data = this.processParagraph(typedHtmlElement);
if (data) {
return `${data}\n\n`;
}
return data;
}
if (['section', 'header'].includes(localName)) {
let data = this.processBlockElement(typedHtmlElement);
if (data) {
data += '\n\n';
}
return data;
}
if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(localName)) {
const data = this.processHeader(typedHtmlElement);
return `${data}\n\n`;
}
if (['ul', 'ol'].includes(localName)) {
let data = this.processList(typedHtmlElement);
if (data) {
data += '\n\n';
}
return data;
}
if (localName === 'code') {
return this.processInlineCode(typedHtmlElement);
}
if (['pre'].includes(localName)) {
let data = this.processCodeBlock(typedHtmlElement);
if (data) {
data += '\n\n';
}
return data;
}
if (localName === 'a') {
return this.processAnchor(/** @type HTMLAnchorElement */ (node));
}
if (localName === 'hr') {
const data = this.processHorizontalLine();
return `${data}\n\n`;
}
if (['b', 'strong'].includes(localName)) {
return this.processBold(typedHtmlElement);
}
if (['em', 'i'].includes(localName)) {
return this.processEmphasis(typedHtmlElement);
}
if (localName === 'blockquote') {
const data = this.processBlockquote(typedHtmlElement);
return `${data}\n\n`;
}
if (localName === 'del') {
return this.processStrikeThrough(typedHtmlElement);
}
if (localName === 'img') {
return this.processImage(/** @type HTMLImageElement */ (node));
}
if (localName === 'br') {
return this.processNewLine();
}
if (localName === 'table') {
let data = this.processTable(typedHtmlElement);
if (data) {
data += '\n\n';
}
return data;
}
// console.log('Unhandled element', localName, node);
return '';
}
/**
* Processes H1-h6 elements.
* Note, this does not add new lines after the header content.
* @param {HTMLElement} node
* @returns {string}
*/
processHeader(node) {
const cnt = Number(node.localName.replace('h', ''));
if (Number.isNaN(cnt)) {
return '';
}
const keyword = new Array(cnt).fill('#').join('');
let result = `${keyword} `;
if (node.hasChildNodes()) {
const { childNodes } = node;
const content = Array.from(childNodes).map(child => this.processNode(child));
result += content.join('');
}
return result;
}
/**
* Processes the paragraph element and returns the markup.
* Note, this does not add new lines after the paragraph content.
* @param {HTMLElement} node
* @returns {string}
*/
processParagraph(node) {
let result = '';
if (node.hasChildNodes()) {
const { childNodes } = node;
const content = Array.from(childNodes).map(child => this.processNode(child)).filter(code => !!code);
result += content.join(' ').replace(/^ /gm, '');
result = result.trim();
}
return result;
}
/**
* Processes a block elements without any sematic meaning (from markdown pov) like headers, sections, etc.
* Note, this does not add new lines after the paragraph content.
* @param {HTMLElement} node
* @returns {string}
*/
processBlockElement(node) {
let result = '';
if (node.hasChildNodes()) {
const { childNodes } = node;
const content = Array.from(childNodes).map(child => this.processNode(child));
result += content.join(' ').replace(/^ /gm, '');;
result = result.trim();
}
return result;
}
/**
* Processes a <code> block.
* @param {HTMLElement} node
* @returns {string}
*/
processCodeBlock(node) {
let isBlock = false;
/** @type HTMLElement */
let block;
if (node.localName === 'pre' && node.children[0] && node.children[0].localName === 'code') {
// eslint-disable-next-line prefer-destructuring
block = /** @type HTMLElement */ (node.children[0]);
isBlock = true;
} else if (node.localName === 'code') {
block = node;
}
if (!block) {
return '';
}
const marker = isBlock ? '```' : '`';
const blockNl = isBlock ? '\n' : '';
let code = block.textContent;
if (isBlock && !code.endsWith('\n')) {
code += blockNl;
}
return `${marker}${blockNl}${code}${marker}`;
}
/**
* Processes the `<a>` element.
* @param {HTMLAnchorElement} node
* @returns {string}
*/
processAnchor(node) {
const { href, childNodes } = node;
if (!href && node.hasChildNodes()) {
// named anchors (<a name="">) count as regular stuff (?)
return this.processParagraph(node);
}
if (!node.hasChildNodes()) {
return '';
}
const parts = Array.from(childNodes).map(child => this.processNode(child));
const txt = parts.join('');
if (!txt) {
return txt;
}
const title = node.hasAttribute('title') ? ` "${node.getAttribute('title')}"` : '';
return `[${txt}](<${href}>${title})`;
}
/**
* Processes the `<ul>` and `ol` elements.
* @param {HTMLElement} node
* @returns {string}
*/
processList(node) {
let result = '';
if (!node.hasChildNodes()) {
return result;
}
const { childNodes, localName } = node;
const isOrdered = localName === 'ol';
const markerType = isOrdered ? '1. ' : '- ';
const parts = Array.from(childNodes).map((child) => {
const name = /** @type Element */ (child).localName;
if (!name || name !== 'li') {
// we ignore everything that is not a list item.
// Sub-lists are children of a list item.
return '';
}
let data = this.processListItem(/** @type HTMLElement */ (child));
if (data) {
data = `${markerType}${data}`;
}
return data;
});
result = parts.join('');
return result.trim();
}
/**
* Specializes in processing list items.
* @param {HTMLElement} node
* @returns {string}
*/
processListItem(node) {
let result = '';
if (!node.hasChildNodes()) {
return result;
}
const { childNodes } = node;
Array.from(childNodes).forEach((child) => {
const elm = /** @type HTMLInputElement */ (child);
if (elm.localName === 'input' && elm.type === 'checkbox') {
result += `[${elm.checked ? 'x' : ' '}] `;
} else if (['ul', 'ol'].includes(elm.localName)) {
const data = this.processNode(child);
if (data) {
result += `\n${data}`
}
} else {
result += this.processNode(child);
}
});
if (!/\n$/.test(result)) {
result += '\n';
} else {
// indent
result = result.split('\n').join('\n ').replace(/^ {4}$/gm, '').replace(/\n\n+/g, '\n\n');
}
return result;
}
/**
* Specializes in processing `<code>` that is not inside the `<pre>`.
* @param {HTMLElement} node
* @returns {string}
*/
processInlineCode(node) {
return `\`${node.innerHTML}\``;
}
/**
* Processes the `<em>` element.
* @param {HTMLElement} node
* @returns {string}
*/
processEmphasis(node) {
if (!node.hasChildNodes()) {
return '';
}
const { childNodes } = node;
const marker = '*';
const parts = Array.from(childNodes).map(child => this.processNode(child));
return `${marker}${parts.join('')}${marker}`;
}
/**
* Processes a `<b>` or `<strong>` block.
* @param {HTMLElement} node
* @returns {string}
*/
processBold(node) {
if (!node.hasChildNodes()) {
return '';
}
const { childNodes } = node;
const marker = '**';
const parts = Array.from(childNodes).map(child => this.processNode(child));
return `${marker}${parts.join('')}${marker}`;
}
/**
* Processes a horizontal line element.
* @returns string
*/
processHorizontalLine() {
return `---`;
}
/**
* Processes a `<blockquote>` element.
* @param {HTMLElement} node
* @returns {string}
*/
processBlockquote(node) {
const prefix = '> ';
if (!node.hasChildNodes()) {
// nothing much to do here. however, editors may want to visualize this anyway.
return prefix;
}
const { childNodes } = node;
const parts = Array.from(childNodes).map(child => this.processNode(child)).filter(txt => !!txt).map(txt => txt.trim());
return `${prefix}${parts.join(`\n${prefix}`)}`;
}
/**
* Processes a `<del>` element.
* @param {HTMLElement} node
* @returns {string}
*/
processStrikeThrough(node) {
if (!node.hasChildNodes()) {
return '';
}
const prefix = '~~';
const { childNodes } = node;
const parts = Array.from(childNodes).map(child => this.processNode(child)).filter(txt => !!txt).map(txt => txt.trim());
return `${prefix}${parts.join(' ')}${prefix}`;
}
/**
* Processes an `<img>` element.
* @param {HTMLImageElement} node
* @returns {string}
*/
processImage(node) {
const { src, alt, width, height, title } = node;
if (!src) {
return '';
}
const parts = [];
parts.push(`![${alt}]`);
parts.push(`(`);
parts.push(`<${src}>`);
if (width && height) {
parts.push(` =${width}x${height}`);
}
if (title) {
parts.push(` "${title}"`);
}
parts.push(`)`);
return parts.join('');
}
/**
* Processes the `<br/>` element.
* @returns {string}
*/
processNewLine() {
return '\n';
}
/**
* Processes a `<table>` element.
* @param {HTMLElement} node
* @returns {string}
*/
processTable(node) {
const headings = /** @type HTMLElement[] */ (Array.from(node.querySelectorAll('thead > tr > th')));
const rows = /** @type HTMLElement[] */ (Array.from(node.querySelectorAll('tbody > tr')));
/** @type string[][] */
const tableModel = [[], []];
headings.forEach((child, i) => {
let cellAlign = '---';
const content = this.processTableCell(child);
if (child.hasAttribute('style')) {
const { textAlign } = child.style;
switch (textAlign) {
case 'left': cellAlign = ':---'; break;
case 'right': cellAlign = '---:'; break;
case 'center': cellAlign = ':---:'; break;
default:
}
}
tableModel[0][i] = content.trim();
tableModel[1][i] = cellAlign;
});
rows.forEach((row) => {
const index = tableModel.push([]) - 1;
const cols = row.getElementsByTagName('td');
Array.from(cols).forEach((cell) => {
const content = this.processTableCell(cell);
tableModel[index].push(content);
});
});
const columnsSize = this.computeColumnSpace(tableModel);
const parts = [];
tableModel.forEach((cells, row) => {
cells.forEach((content, col) => {
if (row === 1) {
if (!content.startsWith(':') && content.endsWith(':')) {
cells[col] = content.padStart(columnsSize[col], '-')
} else if (content.endsWith(':')) {
cells[col] = content.slice(-1).padEnd(columnsSize[col] - 1, '-');
cells[col] += ':';
} else {
cells[col] = content.padEnd(columnsSize[col], '-');
}
} else {
const alignment = tableModel[1][col];
if (!alignment.startsWith(':') && alignment.endsWith(':')) {
cells[col] = content.padStart(columnsSize[col]);
} else if (alignment.startsWith(':') && alignment.endsWith(':')) {
cells[col] = content
.padStart(content.length + Math.floor((columnsSize[col] - content.length) / 2))
.padEnd(columnsSize[col]);
} else {
cells[col] = content.padEnd(columnsSize[col]);
}
}
});
parts.push(`| ${cells.join(' | ')} |`);
});
return parts.join('\n');
}
/**
* Processes a table cell.
* @param {HTMLElement} node
* @returns {string}
*/
processTableCell(node) {
if (!node.hasChildNodes()) {
return '';
}
const { childNodes } = node;
const parts = Array.from(childNodes).map(child => this.processNode(child)).filter(txt => !!txt).map(txt => txt.trim());
return parts.join(' ').replace(/ ([,.])/g, '$1');
}
/**
* Computes the size of each column in the table.
* @param {string[][]} tableModel
* @returns {number[]}
*/
computeColumnSpace(tableModel) {
const defaultSize = 3;
const cols = new Array(tableModel.length).fill(defaultSize);
tableModel.forEach((cells) => {
cells.forEach((content, col) => {
const { length } = content;
if (length > cols[col]) {
cols[col] = length;
}
});
});
return cols;
}
}
|
C
|
UTF-8
| 1,967 | 2.59375 | 3 |
[] |
no_license
|
#include "headers.h"
int check_pinfo(int noarg)
{
for(int i=0;i<noarg;i++)
{
if(strcmp(eachcommand[i],">") == 0)
return 0;
else if(strcmp(eachcommand[i],"<") == 0)
return 0;
else if(strcmp(eachcommand[i],">>") == 0)
return 0;
}
if(strcmp(eachcommand[0],"pinfo")==0) return 1;
return 0;
}
void dopinfo(int noarg)
{
int ret;
char* st = (char*)malloc(100*sizeof(char));
char* exe = (char*)malloc(100*sizeof(char));
char* pd = (char*)malloc(100*sizeof(char));
char* buf = (char*)malloc(1000*sizeof(char));
char* buf1 = (char*)malloc(100*sizeof(char));
char* tok=(char*)malloc(1000*sizeof(char));
char* ppid=(char*)malloc(1000*sizeof(char));
char* pmem=(char*)malloc(1000*sizeof(char));
char* pproc=(char*)malloc(1000*sizeof(char));
if(noarg>1)
{
strcpy(pd,eachcommand[1]);
strcpy(st,"/proc/");
strcat(st,pd);
strcat(st,"/status");
strcpy(exe,"/proc/");
strcat(exe,pd);
strcat(exe,"/exe");
}
else
{
int pid = getpid();
sprintf(st,"/proc/%d/status",pid);
sprintf(exe,"/proc/%d/exe",pid);
}
int fd = open(st,O_RDONLY);
if(fd==-1)
{
perror("Error");
//printf("Process with the given pid does not exist.\n");
//return;
}
read(fd,buf,500);
tok = buf;
while((tok=strtok(tok," :\t\n"))!=NULL)
{
if(strcmp(tok,"Pid")==0)
{
tok = NULL;
tok = strtok(tok," :\n\t");
strcpy(ppid,tok);
}
if(strcmp(tok,"State")==0)
{
tok = NULL;
tok = strtok(tok," :\n\t");
strcpy(pproc,tok);
}
if(strcmp(tok,"VmSize")==0)
{
tok = NULL;
tok = strtok(tok," :\n\t");
strcpy(pmem,tok);
}
tok = NULL;
}
printf("Pid -- %s\n",ppid);
printf("Process Status -- %s\n",pproc);
printf("Virtual memory -- %s\n",pmem);
close(fd);
ret = readlink(exe,buf1,100);
if(ret==-1)
{
perror("Error");
}
else
{
convertCWD(buf1);
printf("Executable path -- %s\n",buf1);
}
free(st);
free(exe);
free(buf);
free(buf1);
free(pd);
free(tok);
free(ppid);
free(pmem);
free(pproc);
}
|
Markdown
|
UTF-8
| 1,083 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
_Portfolio_
_webpage document my progress in Epicodus so far, 8.9.19_
_By Duncan Robbins_
## Description
_This webpage documents my understanding of the information taught at Epicodus. It also provides information about me and how I grew up what previous jobs I had and why I chose Epicodus as a place to learn how to code. It also includes a recent picture of me near the top of the Webpage_
## Setup/Installation Requirements
* _Clone This Repository_
* _Open the file_
* _Click on the HTML provided_
* _once on the website feel free to click on previous projects in order to open their repositories on github_
## Known Bugs
_There are no current known bugs or issues_
## Support and contact details
_if a bug occurs feel free to contact 503-819-4489 or email me at duncanrobbins19@gmail.com_
## Gh-Pages
here is a link to the gh-pages for the site https://duncan19.github.io/Independent-Project-1/
## Technologies Used
_I used bootstrap, css, html, as well as the resources provided at Epicodus_
### License
*The software is licensed under the MIT license*
Copyright (c) 2019 **_Duncan Robbins_**
|
Python
|
UTF-8
| 2,676 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
import re
from utils.form.fields import Fields
fields = Fields()
class Validate:
"""
Validator of the user input
"""
def fullValidation(self, data):
"""
It runs a full validation of all the keys in the data parameter.
It validates that matchs exactly the requested fields for an insert.
Args:
data (dict): The key<value> pair to be validated
Returns:
dict: {ok: boolean, msg: str}
"""
for key in getattr(fields, "field"):
if key not in data:
return {
"ok": False,
"msg": f"Parameter {key} missing"
}
for key in data:
config = self.getConfig(key)
if config is False:
return {
"ok": False,
"msg": f"Field {key} is invalid"
}
isValid = self.runValidations(data[key], config)
if isValid["ok"] is not True:
return isValid
return {"ok": True}
def getConfig(self, field):
"""
Returns the configuration that should be applied to the exact field
Args:
field (str): The name of the field to get the config
Returns:
dict: The configuration of the field
"""
f = getattr(fields, "field")
return f[field] if field in f else False
def runValidations(self, data, config):
"""
It runs every validation of the user input.
Args:
data (str): The user input
config (dict): The configuration for the required input
Returns:
dict: {ok: boolean, msg: str} If ok is False, some of the validations where not valid.
"""
if config["empty"] is False:
if len(data) < 1:
return {"ok": False, "msg": config["error"]}
else:
if len(data) < 1:
return {"ok": True, "msg": ""}
for check in config["checker"]:
if getattr(self, check)(data, config["checker"][check]) is not True:
return {"ok": False, "msg": config["error"]}
return {"ok": True, "msg": ""}
def regex(self, field, regex):
"""
It executes a regular expression in a string to check if it pass it
Args:
field (str): The field to be checked
regex (str): The regular expression
Returns:
boolean: If True, the regular expression match
"""
return re.search(regex, field) is not None
|
C
|
UTF-8
| 508 | 2.59375 | 3 |
[] |
no_license
|
#include<stdio.h>
void main()
{
int x;
/*char c;
char d;*/
// (eligibility test program)
printf("enter your marks\t");
scanf("%d",&x);
if(x<90 && x>20){
// printf("enter your name\t");
printf("you are qualified\t");
}
else if(x>90){
printf("you are brillient\t");
// scanf("%c",&d);
}
else{
printf("you are not eligible");
}
/*int main()
{
printf("hope!! the result is in your favour, if not so then try again later");
}*/
return 0;
getch();
}
|
Python
|
UTF-8
| 1,798 | 3.671875 | 4 |
[] |
no_license
|
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def start():
title = "Flowers don't growl"
text = """It is a warm day and you are in the woods, getting some fresh air. All of a sudden, a man jumps out of the bushes.
He starts telling you that he was picking flowers and he heard a growl. """
choices = [
('listen',"Talk to him"),
('run_away',"Run away as fast as you can!!!")
]
return render_template('adventure.html', title=title, text=text, choices=choices,picture_url="woods.jpg")
@app.route("/inside")
def listen():
title = "You stay to hear the rest of the story..."
text = """... and as he is talking, you notice that he has one hand in his pocket. You try to focus on his words, but
a bad feeling rises in your stomach. The only thing you hear from him is: 'You never know what day is going to be your last.'"""
choices = [
('freeze',"You freeze"),
('run_away',"Try to escape from him")
]
return render_template('adventure.html', title=title, text=text, choices=choices, picture_url="man.jpg")
@app.route("/escape")
def run_away():
title = "You run away!"
text = """You bolt away from the woods to safety. You hear growls in the distance."""
choices = []
return render_template('adventure.html', title=title, text=text, choices=choices,picture_url="survived.jpg")
@app.route("/stairs")
def freeze():
title = "Look out!"
text = """As you try to find the courage to escape him, you look at the pocket of his jacket and recognize the shape
of a knife...
Ooops... It is too late now."""
choices = []
return render_template('adventure.html', title=title, text=text, choices=choices,picture_url="end.jpg")
|
C#
|
UTF-8
| 857 | 3.328125 | 3 |
[] |
no_license
|
public class Solution {
public IList<int> FindAnagrams(string s, string p) {
var baseM = new int[26];
var tm = 26;
foreach(var c in p){
if(baseM[c-'a']++ == 0)
tm--;
}
var m = new int[26];
var low = 0;
var len = s.Length;
var result = new List<int>();
for(int i = 0;i<len;i++){
var c = s[i];
m[c-'a']++;
if(m[c-'a'] == baseM[c-'a'])
tm++;
while(m[c-'a'] > baseM[c-'a']){
if(m[s[low]-'a']-- == baseM[s[low]-'a'])
tm--;
low++;
}
if(tm == 26){
result.Add(i-p.Length+1);
}
}
return result;
}
}
|
Python
|
UTF-8
| 2,328 | 3.03125 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""
Copyright 2020 Tianshu AI Platform. All Rights Reserved.
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.
"""
import re
import inspect
# from ac_opf.models import ac_model
class FindClassInFile:
"""
find class in the given module
### note ###
There is only one class in the given module.
If there are more than one classes, all of them will be omit except the first
############
method: find
args:
module: object-> the given file or module
encoding: string-> "utf8" by default
output: tuple(string-> name of the class, object-> class)
usage:
# >>> import module
#
# >>> find_class_in_file = FindClassInFile()
# >>> cls = find_class_in_file.find(module)
#
# >>> cls_instance = cls[1](args)
"""
def __init__(self):
pass
def _open_file(self, path, encoding="utf8"):
with open(path, "r", encoding=encoding) as f:
data = f.readlines()
for line in data:
yield line
def find(self, module, encoding="utf8"):
path = module.__file__
lines = self._open_file(path=path, encoding=encoding)
cls = ""
for line in lines:
if "class " in line:
cls = re.findall("class (.*?)[:(]", line)[0]
if cls:
break
return self._valid(module, cls)
def _valid(self, module, cls):
members = inspect.getmembers(module)
cand = [(i, j) for i, j in members if inspect.isclass(j) and (not inspect.isabstract(j)) and (i == cls)]
if not cand:
print("class not found in {}".format(module))
return cand[0]
if __name__ == "__main__":
find_class_in_file = FindClassInFile()
# cls = find_class_in_file.find(ac_model)
# print(cls)
|
Java
|
UTF-8
| 2,796 | 2.203125 | 2 |
[] |
no_license
|
package com.baidu.shop.web;
import com.baidu.shop.base.BaseApiService;
import com.baidu.shop.base.Result;
import com.baidu.shop.config.JwtConfig;
import com.baidu.shop.dto.UserInfo;
import com.baidu.shop.entity.UserEntity;
import com.baidu.shop.service.UserOauthService;
import com.baidu.shop.status.HTTPStatus;
import com.baidu.shop.utils.CookieUtils;
import com.baidu.shop.utils.JwtUtils;
import com.baidu.shop.utils.ObjectUtil;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName UserOauthController
* @Description: TODO
* @Author cuikangpu
* @Date 2020/10/15
* @Version V1.0
**/
@RestController
public class UserOauthController extends BaseApiService {
@Autowired
private UserOauthService service;
@Autowired
@Qualifier("jwtConfig")
private JwtConfig jwtConfig;
@PostMapping("/oauth/login")
public Result<JsonObject> login(@RequestBody UserEntity userEntity,
HttpServletRequest request, HttpServletResponse response){
String token = service.login(userEntity, jwtConfig);
if (ObjectUtil.isNull(token)){
return this.setResultError(HTTPStatus.USER_USER_PASSWORD_ERROR,"用户名或密码错误");
}
CookieUtils.setCookie(request,response,jwtConfig.getCookieName(),token,
jwtConfig.getCookieMaxAge(),true);
return this.setResultSuccess();
}
@GetMapping("oauth/verify") //从cookie中获取值 value=cookie的属性名
public Result<JsonObject> verify(@CookieValue(value = "MRSHOP_TOKEN") String token,
HttpServletRequest request,HttpServletResponse response){
try {
UserInfo infoFromToken = JwtUtils.getInfoFromToken(token, jwtConfig.getPublicKey());
//解析token,证明用是登录状态, 重新刷新token
String newToken = JwtUtils.generateToken(infoFromToken, jwtConfig.getPrivateKey(), jwtConfig.getExpire());
//将新token写入cookie,延长过期时间
CookieUtils.setCookie(request,response,jwtConfig.getCookieName(),
newToken, jwtConfig.getCookieMaxAge());
return this.setResultSuccess(infoFromToken);
} catch (Exception e) {
//如果有异常 说明token有问题
//e.printStackTrace();
//应该新建http状态为用户验证失败,状态码为403
return this.setResultError(HTTPStatus.TOKEN_ERROR,"用户失效");
}
}
}
|
Java
|
UTF-8
| 560 | 2.703125 | 3 |
[] |
no_license
|
package implementation.visitor;
import implementation.visitable.Accessories;
import implementation.visitable.Clothes;
import implementation.visitable.Shoes;
import interfaces.Visitor;
import java.text.DecimalFormat;
public class NoDiscount implements Visitor {
public NoDiscount() {
}
public double visit(Clothes clothes) {
return clothes.getPrice();
}
public double visit(Shoes shoes) {
return shoes.getPrice();
}
public double visit(Accessories accessories) {
return accessories.getPrice();
}
}
|
JavaScript
|
UTF-8
| 893 | 2.828125 | 3 |
[] |
no_license
|
// Enter key for email input field
document.getElementById("email_field").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
ResetPassword();
}
});
function ResetPassword() {
// Send Reset Code
firebase.auth().sendPasswordResetEmail(document.getElementById("email_field").value).then(function() {
// Email sent.
document.getElementById("error").className = "error-green";
document.getElementById("error").innerHTML = "Email Successfully Sent! Check your inbox.";
document.getElementById("email_field").value = "";
}).catch(function(error) {
// An error happened.
document.getElementById("error").className = "error-red";
document.getElementById("error").innerHTML = error.message;
});
}
function ShowLogin() {
window.location.href = "/pages/login/";
}
|
JavaScript
|
UTF-8
| 210 | 3.015625 | 3 |
[] |
no_license
|
function tres(num, arreglo) {
var total = 0;
for (var i = 0; i < arreglo.length; i++) {
if (num === arreglo[i]) {
total++;
}
}
console.log("el numero " + num + " se repite: " + total);
}
|
Java
|
UTF-8
| 1,290 | 2.78125 | 3 |
[] |
no_license
|
package com.xk.player.uilib;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.layout.FillLayout;
public class VideoBox extends MessageBox{
protected Object result;
protected Shell shell;
/**
* Create the dialog.
* @param parent
* @param style
*/
public VideoBox(Shell parent, int style) {
super(parent, style);
createContents(280, 360);
}
/**
* Open the dialog.
* @return the result
*/
public Object open(int x,int y) {
shell.open();
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
//重要。这样就可以重写swt组件
public void checkSubclass(){}
//去掉原始open方法
public int open(){
return 0;
}
/**
* Create contents of the dialog.
*/
private void createContents(int x,int y) {
shell = new Shell(getParent(), getStyle());
shell.setSize(280, 360);
shell.setText(getText());
shell.setLayout(new FillLayout());
}
public void setText(String text){
shell.setText(text);
}
public Shell getShell(){
return shell;
}
}
|
Java
|
UTF-8
| 2,370 | 2.5625 | 3 |
[] |
no_license
|
package com.intristicmc.core.commands;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.intristicmc.core.IntristicCORE;
import com.intristicmc.core.miscellaneous.MessageManager;
import com.intristicmc.core.miscellaneous.Utils;
import ru.tehkode.permissions.bukkit.PermissionsEx;
public class CMDMsg implements CommandExecutor {
@SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(cmd.getName().equalsIgnoreCase("msg")) {
if(!(sender instanceof Player)) {
MessageManager.sendMessage(true, sender, "&cYou must be an in-game player to run this command!");
return true;
}
Player p = (Player) sender;
sender = null;
if(!p.hasPermission("intristicmc.core.message")) {
Utils.sendNoPermissionMessage(p, "intristicmc.core.message");
return true;
}
String message = null;
if(args.length == 0 || args.length == 1) {
MessageManager.sendMessage(true, p, "&7Incorrect usage for this command! &cUsage: /" + label + " <player> <message>");
return true;
} else if(args.length >= 2) {
StringBuilder messageSB = new StringBuilder();
for(int i = 1; i < args.length; i++) {
if(i == args.length) {
messageSB.append(args[i]);
} else {
messageSB.append(args[i]).append(" ");
}
}
message = messageSB.toString();
}
HashMap<String, String> replyMap = IntristicCORE.replyMap;
// Key is sender | Value is receiver.
if(Bukkit.getPlayer(args[0]) == null) {
MessageManager.sendMessage(true, p, "&c" + args[0] + " is not online!");
return true;
}
Player target = Bukkit.getPlayer(args[0]);
String targetPrefix = PermissionsEx.getUser(target).getPrefix();
String senderPrefix = PermissionsEx.getUser(p).getPrefix();
MessageManager.sendMessage(false, p, senderPrefix + "You &8&l-> &r" + targetPrefix + target.getName() + "&r&8:&r " + message);
MessageManager.sendMessage(false, target, senderPrefix + p.getName() + " &8&l-> &r" + targetPrefix + "You&r&8:&r " + message);
replyMap.put(p.getName(), target.getName());
replyMap.put(target.getName(), p.getName());
}
return true;
}
}
|
Java
|
UTF-8
| 218 | 1.554688 | 2 |
[] |
no_license
|
package com.wallet.security.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
//todo: SpringSecurity+Jwt 8.6.3 - TolkenDTO class
@Data
@AllArgsConstructor
public class TokenDTO {
private String token;
}
|
SQL
|
UTF-8
| 428 | 3.015625 | 3 |
[] |
no_license
|
CREATE TABLE IF NOT EXISTS PATIENT (
ID INT AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(50) NOT NULL,
SURNAME VARCHAR(50) NOT NULL,
BIRTHDAY DATE NOT NULL,
SECURITY_NUMBER VARCHAR(50) NOT NULL
);
CREATE TABLE IF NOT EXISTS VISIT (
ID INT AUTO_INCREMENT PRIMARY KEY,
ID_PATIENT INT NOT NULL,
VISIT_DATE DATE NOT NULL,
VISIT_TYPE VARCHAR(20) NOT NULL,
VISIT_REASON VARCHAR(20) NOT NULL,
NOTES VARCHAR(255)
);
|
Java
|
UTF-8
| 2,168 | 2.125 | 2 |
[] |
no_license
|
package ui.view;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.junit.Assert.*;
public class DeleteTest {
private static final String url = "http://localhost:8080/Volleyball_war_exploded/";
private WebDriver driver;
private String speler;
private String leeftijd;
private String positie;
private String wedstrijden;
@Before
public void setUp(){
System.setProperty("webdriver.chrome.driver", "C:\\Users\\toond\\OneDrive\\Bureaublad\\Web2\\chromedriver.exe");
driver = new ChromeDriver();
speler = "Toon Dubois";
leeftijd = "19";
positie = "Left Spiker";
wedstrijden = "5";
driver.get(url+"Servlet?command=switchNL&page=add");
driver.findElement(By.id("speler")).clear();
driver.findElement(By.id("speler")).sendKeys(speler);
driver.findElement(By.id("leeftijd")).clear();
driver.findElement(By.id("leeftijd")).sendKeys(leeftijd);
driver.findElement(By.id("positie")).clear();
driver.findElement(By.id("positie")).sendKeys(positie);
driver.findElement(By.id("wedstrijdenGespeeld")).clear();
driver.findElement(By.id("wedstrijdenGespeeld")).sendKeys(wedstrijden);
driver.findElement(By.cssSelector("input[type='submit']")).click();
}
@Test
public void verwijderTochNietVerwijdertNiet(){
driver.get(url+"Servlet?command=verwijder&naam=Toon%20Dubois");
driver.findElement(By.cssSelector("input[type='submit'][value='Toch niet']")).click();
assertTrue(driver.getPageSource().contains("Toon Dubois"));
}
@Test
public void verwijderWelVerwijdertWel(){
driver.get(url+"Servlet?command=verwijder&naam=Toon%20Dubois");
driver.findElement(By.cssSelector("input[type='submit'][value='Zeker']")).click();
assertFalse(driver.getPageSource().contains("Toon Dubois"));
}
@After
public void tearDown(){driver.quit();}
}
|
Python
|
UTF-8
| 1,060 | 2.546875 | 3 |
[] |
no_license
|
#We are using Tweepy library in order to access Twitter API.
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import time
###################
#All below tokens & consumer key& secert are from our dev. account on twitter.
access_token = ""
access_token_secret = ""
consumer_key= ""
consumer_secret = ""
####################
class Twt_listner(StreamListener):
def on_data(self, data):
try:
saveFile = open('Twtdata.json','a')
saveFile.write(data)
saveFile.write(', \n')
saveFile.close()
return True
except Except:
print ("failed ondata")
time.sleep(1)
def on_error(self, status):
print(status)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
TwtStream = Stream(auth, Twt_listner())
#Keywords we are listening for (The current theme is "#Messi")
TwtStream.filter(track=["#Barcelona,#Messi"])
|
Java
|
UTF-8
| 829 | 3.15625 | 3 |
[] |
no_license
|
package by.bsuir.lab01.actions;
public class Validators {
protected Boolean isEmpty(String value) {
if (value.length() == 0) {
return true;
}
return false;
}
protected Boolean between(String value, int from, int to) {
int len = value.length();
if (len >= from && len <= to) {
return true;
}
return false;
}
protected String Capitalize(String value) {
String result;
result = this.toUpperCase(value.substring(0, 1));
result += this.toLowerCase(value.substring(1,value.length()));
return result;
}
protected String toLowerCase(String value) {
return value.toLowerCase();
}
protected String toUpperCase(String value) {
return value.toUpperCase();
}
}
|
C#
|
UTF-8
| 1,977 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using BloggerDocuments.Database.Entities;
using BloggerDocuments.Tests.Assemblers;
using BloggerDocuments.Tests.Environment.Mocks;
using NSubstitute;
namespace BloggerDocuments.Tests.Environment.Tables
{
public class DocumentsTable
{
private readonly ProductsTable _productsTable;
private readonly ITestMocks _mocks;
private static int _currentDocId;
public List<int> SalesOrderEntities { get; }
public DocumentsTable(ProductsTable productsTable, ITestMocks mocks)
{
_productsTable = productsTable;
_mocks = mocks;
SalesOrderEntities = new List<int>();
}
public void AddSalesOrder(Action<DocumentAssembler> document)
{
var documentAssembler = new DocumentAssembler();
document(documentAssembler);
_currentDocId++;
var items = documentAssembler.DocumentItemAssemblers;
var salesOrderItems = new List<SalesOrderItemEntity>();
foreach (var item in items)
{
var prodId = _productsTable.Get(item.Name);
salesOrderItems.Add(
new SalesOrderItemEntity()
{
ProductInfo = prodId.Info,
ProductName = item.Name,
Price = item.Price,
Quantity = item.Quantity,
Value = item.Price*item.Quantity
});
}
var salesOrderEntity = new SalesOrderEntity()
{
Id = _currentDocId,
Items = salesOrderItems,
Value = salesOrderItems.Sum(x => x.Value)
};
SalesOrderEntities.Add(salesOrderEntity.Id);
_mocks.SalesOrderRepository.Get(salesOrderEntity.Id).Returns(salesOrderEntity);
}
}
}
|
PHP
|
UTF-8
| 1,459 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
require_once dirname(dirname(__FILE__)).'/vendor/autoload.php';
use Slim\App;
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;
$app = new App([
'settings' => [
'debug' => true, // On/Off whoops error
'whoops.editor' => 'sublime',
'displayErrorDetails' => true, // Display call stack in orignal slim error when debug is off
]
]);
if ($app->getContainer()->settings['debug'] === false) {
$container['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
$data = [
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => explode("\n", $exception->getTraceAsString()),
];
return $c->get('response')->withStatus(500)
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
}else{
$app->add(new WhoopsMiddleware);
}
// Throw exception, Named route does not exist for name: hello
$app->get('/', function($request, $response, $args) {
return $this->router->pathFor('hello');
});
// $app->get('/hello', function($request, $response, $args) {
// $response->write("Hello Slim");
// return $response;
// })->setName('hello');
$app->run();
|
Markdown
|
UTF-8
| 3,014 | 2.625 | 3 |
[] |
no_license
|
淘宝页面小图切换大图
```
(function () {
var box = document.getElementById('box');
//数组存放假数据
var data = [{
imgurl: ['../img/images/1.webp', '../img/images/2.webp', '../img/images/3.webp'],
title: '领带男正装商务韩版男士手打',
pingjia: 30,
shocang: 30,
xiaoliang: 50,
jiage: 300,
},
{
imgurl: ['../img/images/1.webp', '../img/images/2.webp', '../img/images/3.webp'],
title: '领带男正装商',
pingjia: 30,
shocang: 30,
xiaoliang: 50,
jiage: 300,
},
];
//拼接标签数据
var html = data.map(function (item) {
return `<li>
<div class="bipic">
<img src="../img/images/1.webp" alt="">
<span class="pic"></span>
</div>
<div class="smpic">
<img class="aaa active" src="../img/images/1.webp" alt="">
<img class="aaa" src="../img/images/2.webp" alt="">
<img class="aaa" src="../img/images/3.webp" alt="">
</div>
<div class="con">
<h4>领带男正装商务韩版男士手打</h4>
<div class="con-1">
<span>评价:30</span>
<span>收藏:30</span>
</div>
<div class="con-2">
<span>¥300</span>
<span>月销:50</span>
</div>
</div>
</li>`;
}).join('');// .join('')不可或缺的。
box.innerHTML = html;//渲染数据
var smpic = box.getElementsByClassName('smpic');//取节点
//给小图第一个添加高亮效果
for (i = 0; i < smpic.length; i++) {
smpic[i].children[0].className = 'aaa active';
} //小图换大图 var
//核心代码
var small = box.getElementsByClassName('aaa');
for (i = 0; i < small.length; i++) {//点击小图切换大图事件
small[i].onclick = function () {
//利用父元素兄弟的子元素节点控制小图和大图的src
this.parentNode.previousElementSibling.children[0].src = this.src;
//利用循环初始化
for (i = 0; i < this.parentNode.children.length; i++) {
this.parentNode.children[i].className = '';
}
this.className = 'active';//又添加class
}
}
})();
```
|
Markdown
|
UTF-8
| 6,804 | 3.15625 | 3 |
[] |
no_license
|
---
title: 在 Spring Webflux 使用 Spring Integration Redis 实现分布式锁
date: 2019-09-28 23:17:37
tags:
- java
- webflux
categories:
- Java
---
### 分布式锁
在传统单体应用中,我们用锁来保证非幂等操作在并发调用时不会产生意外的结果。最常见的应用场景应该就是 MySQL 用锁保证写表时不会重复写入或读表时读到脏数据。
进入微服务时代,整个业务系统可能是由数十个不同的服务节点组成,每个服务节点还包括多个实例确保高可用。在这样的环境下,一个写请求可能会由于负载均衡通过不同的服务实例操作数据,大多 NoSQL 实现为了并发性而牺牲了事务,则可能导致数据的正确性被破坏。这时如果有一个全局锁来对不同服务的操作进行限制,那么会一定程度解决上述问题。(对于复杂场景还需要采用分布式事务来处理回滚等等。)
与本地锁类似,分布式锁也是独立的对象,只不过存储在独立的节点上。最朴素的方法是在数据库中存储一段数据,以此为锁对象,存在则表示锁已被其他服务获取,不存在则表示可获取。当然此方案完全没考虑过死锁、可重入性等问题,而且如果是用关系型数据库来实现,则无法支撑高并发的场景。因此通常我们会采用 Redis、ZooKeeper 等方案来实现,并对锁代码进行一定设计,增加超时、重试等等功能。
<!-- more -->
### Redis 分布式锁
可以直接采用:`set [k] [v] px [milliseconds] nx`来原子的创建一个锁对象,其中 `px` 为超时时间,`nx` 为在 key 不存在时才创建。因此,对于尝试锁的逻辑,只有当上述命令返回`OK`时,才代表获得锁。同时,为了防止各种原因导致的死锁,超时时间过后,锁对象自动释放。
若考虑锁的可重入性,则需要对锁对象的值进行设计,确认不同线程(实例)获取锁时写入的值唯一,因此涉及可重入判断时,先`get [k]`获取值,若与本地唯一值一致,则可重入,重入后重置超时时间。
### Spring Integration Redis
Spring Integration 集成了许多中间件、第三方组件与 Spring 的适配,其中也包括 Redis。由于 Redis 锁简单、可靠的特点而被大规模使用,Spring Integration 索性直接提供了 Redis 锁的实现来简化开发,对应的类名:`RedisLockRegisty`。
`RedisLockRegisty`作为一个锁注册器,主要提供了`obtain(lock key)`和`destroy()`两种方法分别实现注册锁对象以及销毁。在`RedisLockRegisty`的内部实现了`RedisLock`内部类,它继承自 Java `Lock`,因此拥有锁通用的几个方法:
- `lock()`
- `tryLock()`
- `unlock()`
实际上,该实现采用了两层锁的结构,一层本地锁,一层 Redis 锁。这样做的好处是对于单实例内部的并发调用,可以直接走本地锁而不必与 Redis 通信,减少了操作时间,同时也降低了 Redis 的压力。
在`RedisLockRegisty`中,获取锁的操作,采用直接调用 hardcode 在类内的一段 lua 代码:
```lua
local lockClientId = redis.call('GET', KEYS[1])
if lockClientId == ARGV[1] then
redis.call('PEXPIRE', KEYS[1], ARGV[2])
return true
elseif not lockClientId then
redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])
return true
end
return false
```
其中`KEYS[1]`为 key 值,`ARGV[1]`为 clientId,是在创建类时生成的 UUID,设置为锁的值用以判断可重入 `ARGV[2]`为超时时间。
可见上述 lua 代码与上一节提到的获取锁的流程一致。
### Webflux 结合 RedisLockRegistry
如何在采用 Project Reactor 异步框架为核心的 Spring Webflux 中应用`RedisLockRegistry`来实现原子操作?
Webflux 的编程思想是所有的操作都应在一个 stream 内完成,`RedisLock.lock()`作为一个阻塞操作,会阻塞当前流。那么如何在 Webflux 中使用 Redis 锁?
在 Project Reactor 文档中提到[如何包装一个同步阻塞的调用?](https://projectreactor.io/docs/core/release/reference/#faq.wrap-blocking)简单来讲,为了确保阻塞调用不阻塞整个流,我们需要将之运行在一个独立的线程内,采用`subscribeOn`来实现。
以下为相应实现代码:
```java
@Component
public class TransactionHelper {
private RedisLockRegistry redisLockRegistry;
@Autowired
public TransactionHelper(RedisLockRegistry redisLockRegistry) {
this.redisLockRegistry = redisLockRegistry;
}
/**
* Do supplier in a transaction protected by a distributed lock, lock key is given by param key.
*/
public <T> Mono<T> doInTransaction(String transactionKey, Supplier<Mono<T>> supplier) {
Lock lock = redisLockRegistry.obtain(transactionKey);
return Mono.just(0)
.doFirst(lock::lock)
.doFinally(dummy -> lock.unlock())
.flatMap(dummy -> supplier.get())
.subscribeOn(Schedulers.elastic());
}
}
```
上述代码通过对 supplier 操作的前后进行加锁,来实现将整个 supplier 的操作放置在同一事务内。
其中:
- supplier 为返回 `Mono<?>` 的的无参数调用(当然也可采用 Function,返回`Flux<?>`等形式更灵活的满足需要)
- `doFirst(Runnable)` 会确保 runnable 操作在执行 supplier 之前执行,此处的 runnable 为加锁,当无法获取锁时阻塞等待
- `doFinally(SignalType)`确保无论流发出任何结束信号(success,fail,cancel)都会在最后调用其设定的逻辑。
- `subscribeOn(Schedulers.elastic())`将上述流的所有操作放入由 Schedulers 创建的新线程中执行,因此不会阻塞主线程。
> 先进行 `doFirst` 和 `doFinally` 的原因是 supplier 中的操作有可能会造成线程切换,导致 `doFinally` 可能与 `doFirst`不在同一线程中执行,这有可能出现 Thread-A 创建的锁最终由 Thread-B 来释放的情况,使得锁报错并无法正确得到释放。
### 最后
上文介绍了用 Redis 构建分布式锁,并在 Webflux 框架下实现的方案。
Redis 分布式锁固然优秀,然而却并不是无懈可击的。试想假如有某个操作在 Redis 集群的某节点上创建了锁,然而在集群同步完成前该节点挂掉,那么锁就失效了。
基于此,Redis 的作者给出了“RedLock”方案,大致来讲是通过构造多个 Redis 集群,并多重上锁的方案,来降低故障的概率。Dr. Martin Kleppmann并不认为 Redlock 能解决故障,并[写了篇文章来论证](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html),详情不在本文展开,请参考相关资料。
|
Markdown
|
UTF-8
| 845 | 2.59375 | 3 |
[] |
no_license
|
+++
name = "Solitwork"
weight = 10
ID = 3
title = "Hands-on mentoring"
subtitle = "Technical leadership"
date = "2014-07-07"
img = "../clients/solitwork.png"
preview = "../clients/solitwork.png"
client = "Solitwork"
clientLink = "//www.solitwork.com/"
category = "Technical Leadership"
+++
Solitwork are a BI Consultancy in Denmark. They help organisations fast-track their data warehouse and reporting solutions to get value of their data sooner.
A lot of their clients are reaching out to Solitwork to help them start adding data science capabilities into their BI environment.
As a result, Solitwork were facing a skills gap.
Locke Data helped Solitwork address this by doing a blend of training and remote mentoring through the delivery of a project.
Now Solitwork can help their customers tackle this new area much more effectively.
|
JavaScript
|
UTF-8
| 680 | 2.609375 | 3 |
[] |
no_license
|
(function () {
var write = function writeCss(view, className) {
ASSERT(view instanceof jQuery, "expected jQuery object");
/* Remove the old class if there is one. */
var old = view.data("hd-klass");
if (old) {
view.removeClass(old);
}
/* Add the new class and remember it. */
view.addClass(className);
view.data("hd-klass", className);
};
hd.binders["klass"] = function bindKlass(view, classes) {
/* Allow short-hand for a single class. */
if (!Array.isArray(classes)) {
classes = [classes];
}
classes.forEach(function (className) {
hd.bindWrite(className, view, { write: write });
});
};
}());
|
C++
|
UTF-8
| 643 | 2.703125 | 3 |
[] |
no_license
|
/*************************************************************************
> File Name: ID.cpp
> Author: Xu
> Created Time: 2019年05月31日 星期五 19时26分35秒
************************************************************************/
#include"ID.h"
int ID::getscore()
{
return score;
}
string ID::getname()
{
return name;
}
void ID::setname(string n )
{
name=n;
}
bool ID::operator == (ID& x)
{
return (x.getname()==getname())&&(x.getscore()==getscore());
};
bool ID::operator < ( ID& x)
{
return x.getscore()>getscore();
};
ID ID::operator + ( ID& x)
{
return ID((x.getname()+getname()),x.getscore()+getscore());
};
|
PHP
|
UTF-8
| 6,490 | 2.640625 | 3 |
[] |
no_license
|
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "encuesta";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($_POST['tiempo'] == ""){
$sql = "INSERT INTO data (nombre, genero, hobby)
VALUES ('{$_POST['nombre']}', '{$_POST['genero']}', '{$_POST['hobby']}')";
} else {
$sql = "INSERT INTO data (nombre, genero, hobby, tiempo)
VALUES ('{$_POST['nombre']}', '{$_POST['genero']}', '{$_POST['hobby']}', '{$_POST['tiempo']}')";
}
if ($conn->query($sql) === TRUE) {
// nombre
$sql = "SELECT nombre, COUNT(nombre) AS total from data group by nombre ORDER BY total DESC LIMIT 5;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$nombres[] = $row["nombre"];
$valorNombre[] = $row["total"];
}
}
setcookie("nombres", json_encode($nombres), time() + 86400, "/");
setcookie("valorNombre", json_encode($valorNombre), time() + 86400, "/");
// genero
$sql = "SELECT genero, COUNT(*) as total FROM data GROUP BY genero;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$generos[] = $row["genero"];
$valorGenero[] = $row["total"];
}
}
setcookie("generos", json_encode($generos), time() + 86400, "/");
setcookie("valorGenero", json_encode($valorGenero), time() + 86400, "/");
// hobby
$sql = "SELECT hobby, COUNT(*) as total FROM data GROUP BY hobby;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$hobbys[] = $row["hobby"];
$valorHobby[] = $row["total"];
}
}
setcookie("hobbys", json_encode($hobbys), time() + 86400, "/");
setcookie("valorHobby", json_encode($valorHobby), time() + 86400, "/");
// tiempo
$sql = "SELECT tiempo, COUNT(*) as total FROM data WHERE tiempo IS NOT NULL GROUP BY tiempo ORDER BY total asc;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tiempo[] = $row["tiempo"];
$valorTiempo[] = $row["total"];
}
}
setcookie("tiempo", json_encode($tiempo), time() + 86400, "/");
setcookie("valorTiempo", json_encode($valorTiempo), time() + 86400, "/");
// resumen
// total encuestados
$sql = "SELECT COUNT(*) AS total from data;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$totalEncuestados = $row["total"];
}
}
setcookie("totalEncuestados", json_encode($totalEncuestados), time() + 86400, "/");
// nombre mas utilizado
$sql = "SELECT nombre, COUNT(*) as total FROM data GROUP BY nombre ORDER BY total DESC LIMIT 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$nombreMasUtilizado = $row["total"];
}
}
setcookie("nombreMasUtilizado", json_encode($nombreMasUtilizado), time() + 86400, "/");
// total sin hobby
$sql = "SELECT COUNT(*) AS total from data WHERE hobby = 'ninguno';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$totalSinHobby = $row["total"];
}
}
setcookie("totalSinHobby", json_encode($totalSinHobby), time() + 86400, "/");
// total con hobby
$sql = "SELECT COUNT(*) AS total from data WHERE hobby != 'ninguno';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$totalConHobby = $row["total"];
}
}
setcookie("totalConHobby", json_encode($totalConHobby), time() + 86400, "/");
// hobby mas elegido
$sql = "SELECT hobby, COUNT(*) as total FROM data GROUP BY hobby ORDER BY total DESC LIMIT 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$hobbyMasElegido = $row["hobby"];
}
}
setcookie("hobbyMasElegido", json_encode($hobbyMasElegido), time() + 86400, "/");
// hobby menos elegido
$sql = "SELECT hobby, COUNT(*) as total FROM data GROUP BY hobby ORDER BY total ASC LIMIT 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$hobbyMenosElegido = $row["hobby"];
}
}
setcookie("hobbyMenosElegido", json_encode($hobbyMenosElegido), time() + 86400, "/");
// mujeres encuestadas
$sql = "SELECT genero, COUNT(*) as total FROM data where genero = 'mujer';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$mujerEncuestadas = $row["total"];
}
}
setcookie("mujerEncuestadas", json_encode($mujerEncuestadas), time() + 86400, "/");
// hombres encuestados
$sql = "SELECT genero, COUNT(*) as total FROM data where genero = 'hombre';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$hombreEncuestados = $row["total"];
}
}
setcookie("hombreEncuestados", json_encode($hombreEncuestados), time() + 86400, "/");
// tiempo menos dedicado
$sql = "SELECT tiempo, COUNT(*) as total FROM data WHERE tiempo IS NOT NULL GROUP BY tiempo ORDER BY total ASC LIMIT 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tiempoMenosDedicado = $row["tiempo"];
}
}
setcookie("tiempoMenosDedicado", json_encode($tiempoMenosDedicado), time() + 86400, "/");
// tiempo mas dedicado
$sql = "SELECT tiempo, COUNT(*) as total FROM data WHERE tiempo IS NOT NULL GROUP BY tiempo ORDER BY total DESC LIMIT 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tiempoMasDedicado = $row["tiempo"];
}
}
setcookie("tiempoMasDedicado", json_encode($tiempoMasDedicado), time() + 86400, "/");
// todo
$sql = "SELECT * FROM data";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$todo[] = array($row["nombre"], $row["genero"], $row["hobby"], $row["tiempo"]);
}
}
setcookie("todo", json_encode($todo), time() + 86400, "/");
header('Location: http://127.0.0.1:8080/test/view/view2.php');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
|
Java
|
UTF-8
| 1,872 | 3.96875 | 4 |
[] |
no_license
|
package offer66;
/**
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
**/
public class A6 {
public static int minNumberInRotateArray(int [] array) {
if(array.length <=0){
return 0;
}
int i=0;
int j=array.length-1;
int mid = 0;
while(i<=j){
if(j-i == 1){
mid = j;
break;
}
mid = (j+i)/2;
if(array[i] == array[mid] && array[i] == array[j]){ //[1,0,1,1,1]
return MinInOrder(array,i,j);
}else if(array[i] <= array[mid]){
i = mid;
}else if(array[mid] <= array[j]){
j = mid;
}
}
return array[mid];
}
public static int MinInOrder(int[] arr,int i,int j){
int min = arr[i];
for(int k=i+1 ; k<=j ; k++){
if(arr[k] < min){
min = arr[k];
}
}
return min;
}
public static int solution(int [] array) {
int low = 0 ; int high = array.length - 1;
while(low < high){
int mid = low + (high - low) / 2;
if(array[mid] > array[high]){
low = mid + 1;
}else if(array[mid] == array[high]){
high = high - 1;
}else{
high = mid;
}
}
return array[low];
}
public static void main(String[] args) {
int[] array = {3, 4, 5, 1, 2};
int result = solution(array);
System.out.println(result);
}
}
|
SQL
|
UTF-8
| 2,936 | 3.15625 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.4.12
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 24 Mei 2019 pada 09.06
-- Versi Server: 5.6.25
-- PHP Version: 5.6.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `kasir`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `data_pembeli`
--
CREATE TABLE IF NOT EXISTS `data_pembeli` (
`id_customer` varchar(20) NOT NULL,
`nama` varchar(255) NOT NULL,
`kontak` varchar(255) NOT NULL,
`tanggal` varchar(255) NOT NULL,
`total` varchar(255) NOT NULL,
`bayar` int(255) NOT NULL,
`kembalian` int(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `data_pembeli`
--
INSERT INTO `data_pembeli` (`id_customer`, `nama`, `kontak`, `tanggal`, `total`, `bayar`, `kembalian`) VALUES
('001', 'pembeli1', '0888888', '12/12/2018', '300000', 350000, 50000),
('002', 'pembeli2', '021554', '12/1/2019', '400000', 500000, -100000),
('003', 'siapaaja2', '0515454', '12/12/2018', '350000', 400000, 50000),
('004', 'cust3', '0514545', '12/12/2018', '300000', 400000, 100000);
-- --------------------------------------------------------
--
-- Struktur dari tabel `data_penjualan`
--
CREATE TABLE IF NOT EXISTS `data_penjualan` (
`id_barang` int(11) NOT NULL,
`id_customer` varchar(20) NOT NULL,
`nama_barang` varchar(255) NOT NULL,
`harga` int(255) NOT NULL,
`qty` int(255) NOT NULL,
`jumlah` int(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `data_penjualan`
--
INSERT INTO `data_penjualan` (`id_barang`, `id_customer`, `nama_barang`, `harga`, `qty`, `jumlah`) VALUES
(1, '001', 'handuk', 20000, 2, 40000),
(3, '001', 'sarung', 20000, 2, 40000),
(4, '001', 'bantal', 10000, 3, 30000),
(7, '002', 'sepatu', 100000, 1, 100000),
(8, '002', 'tas', 150000, 2, 300000),
(9, '003', 'sepatu', 50000, 3, 150000),
(10, '003', 'tas', 100000, 2, 200000),
(11, '004', 'kursi', 50000, 3, 150000),
(12, '004', 'meja', 50000, 3, 150000);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `data_pembeli`
--
ALTER TABLE `data_pembeli`
ADD PRIMARY KEY (`id_customer`);
--
-- Indexes for table `data_penjualan`
--
ALTER TABLE `data_penjualan`
ADD PRIMARY KEY (`id_barang`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `data_penjualan`
--
ALTER TABLE `data_penjualan`
MODIFY `id_barang` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=13;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
C++
|
GB18030
| 17,659 | 2.640625 | 3 |
[] |
no_license
|
// Utils.cpp: implementation of the Utils class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Utils.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#include <direct.h>
#define is_space(c) \
(((c) == ' ') || ((c) == '\r') || ((c) == '\n') || ((c) == '\t'))
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
void FormatDate(SYSTEMTIME& time, char* sz)
{
sprintf(sz, "%d-%02d-%02d", time.wYear, time.wMonth, time.wDay);
}
void FormatTime(SYSTEMTIME& time, char* sz)
{
sprintf(sz, "%02d:%02d:%02d", time.wHour, time.wMinute, time.wSecond);
}
char* getExePath(char* path)
{
char file [MAX_PATH];
GetModuleFileName(NULL, file, sizeof(file));
splitFName(file, path, NULL);
return path;
}
char* trim_whites(char *s)
{
char *from = s;
while(*from)
{
if(!is_space(*from))
break;
from++;
}
char* to = from+strlen(from) - 1;
while(to >= from)
{
if(!is_space(*to))
break;
to--;
}
*(to+1) = 0;
return from;
}
char* c_strncpy(char* dest, const char* src, int size)
{
strncpy(dest, src, size-1);
dest[size-1] = 0;
return dest;
}
void ErrMessage(DWORD error)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
// Process any inserts in lpMsgBuf.
// ...
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
// Free the buffer.
LocalFree( lpMsgBuf );
}
void splitFName(const char* fname, char* dir, char* basename)
{
char* p = strrchr(fname, '\\');
if(!p)
p = strrchr(fname,'/');
if(p == NULL)
{
if(dir)
*dir = 0;
if(basename)
strcpy(basename, fname);
}
else
{
p++;
if(dir)
{
memcpy(dir, fname, p - fname);
dir[p - fname] = 0;
}
if(basename)
strcpy(basename, p);
}
}
/*bool split2(const char* s, char c, char*d1, char* d2); //host in cim reader
void splitBaseName(const char* baseName, char* name, char* postfix)
{
if(!split2(baseName,'.', name, postfix))
{
strcpy(name, baseName);
*postfix = 0;
}
}
*/
char* basename(char* fullName)
{
char* p = strrchr(fullName, '/');
if(!p)
p = strrchr(fullName, '\\');
if(!p)
p = fullName;
else
p = p+1;
return p;
}
BOOL tryAccessFile(const char* fnameLocate, const char* time, char* fAccessed, int size)
{
char fname[MAX_PATH];
char path[MAX_PATH];
char name[MAX_PATH];
const char *strs[] = {path, "log\\", time, name};
if(!findFile(fnameLocate, fname))
return FALSE;
::splitFName(fname, path, name);
char *p = fAccessed;
for(int i = 0; i < sizeof(strs)/sizeof(strs[0]); i++)
{
int cp = strlen(strs[i]);
if(cp >= size)
{
// log_error("ļ̫%s\n", fname);
return FALSE;
}
memcpy(p, strs[i], cp);
p += cp;
size -= cp;
}
*p = 0;
strcat(path, "log\\");
if(!findFile(path, NULL))
_mkdir(path);
if(MoveFile(fname, fAccessed))
return TRUE;
return FALSE;
}
BOOL findFile(const char* fname, char* finded)
{
WIN32_FIND_DATA data;
memset(&data, 0, sizeof(data));
HANDLE handle = FindFirstFile(fname, &data);
if(handle != INVALID_HANDLE_VALUE)
{
if(finded)
{
splitFName(fname, finded, NULL);
strcat(finded, data.cFileName);
}
FindClose(handle);
return TRUE;
}
return FALSE;
}
void GetDevName(DWORD id, BYTE devtype, char* devname)
{
if(devname==NULL||id<=0)
return;
devname[0]=0;
if(strlen(DevTableName[devtype])<2)
return;
BYTE* ptempdata=NULL;
int datanum=0;
CUIntArray posarray;
CString szsql;
szsql.Format("NU=%d", id);
while(1)
{
if(!SearchData("visualpw", (char*)DevTableName[devtype], szsql, "", (void**)&ptempdata, datanum, posarray))
{
if(devtype==EQUIP_TYPE_BITRS)
{
devtype=EQUIP_TYPE_TRITRS;
if(!SearchData("visualpw", (char*)DevTableName[devtype], szsql, "", (void**)&ptempdata, datanum, posarray))
return;
}
else
return;
}
if(ptempdata==NULL)
return;
switch(devtype)
{
case EQUIP_TYPE_GEN: //
{
visualpw_Gen* pgen = (visualpw_Gen*)ptempdata;
strcat(devname, pgen->Name);
break;
}
case EQUIP_TYPE_BUS: //ĸ
{
visualpw_Bus* pbus = (visualpw_Bus*)ptempdata;
strcat(devname, pbus->Name);
break;
}
case EQUIP_TYPE_LINE: //·
{
visualpw_Line* pline = (visualpw_Line*)ptempdata;
strcat(devname, pline->Name);
break;
}
case EQUIP_TYPE_BITRS: //˫
{
visualpw_Tfm1* ptfm = (visualpw_Tfm1*)ptempdata;
strcat(devname, ptfm->Name);
break;
}
case EQUIP_TYPE_TRITRS://
{
visualpw_Tfm2* ptfm = (visualpw_Tfm2*)ptempdata;
strcat(devname, ptfm->Name);
break;
}
case EQUIP_TYPE_LOAD: //
{
visualpw_Load* pload = (visualpw_Load*)ptempdata;
strcat(devname, pload->Name);
break;
}
case EQUIP_TYPE_SHUNT: //豸
{
visualpw_Shunt* pshunt = (visualpw_Shunt*)ptempdata;
strcat(devname, pshunt->Name);
break;
}
case EQUIP_TYPE_SWITCH://
{
visualpw_Switch* pbreak = (visualpw_Switch*)ptempdata;
strcat(devname, pbreak->Name);
break;
}
case EQUIP_TYPE_DCLINE://ֱ·
case EQUIP_TYPE_REACT://翹
break;
case EQUIP_TYPE_SUB: //վ
{
visualpw_Station* pstation = (visualpw_Station*)ptempdata;
strcat(devname, pstation->Name);
break;
}
case EQUIP_TYPE_AREA: //
{
visualpw_Zone* pzone = (visualpw_Zone*)ptempdata;
strcat(devname, pzone->Name);
break;
}
default:
break;
}
break;
}
if(ptempdata!=NULL)
delete []ptempdata;
ptempdata=NULL;
}
void GetIDByName(char* devname, BYTE devtype, DWORD& id) //վID
{
if(devname==NULL)
return;
id=0;
if(strlen(DevTableName[devtype])<2)
return;
BYTE* ptempdata=NULL;
int datanum=0;
CUIntArray posarray;
CString szsql;
szsql.Format("Name=%s", devname);
szsql.TrimLeft();
szsql.TrimRight();
while(1)
{
if(!SearchData("visualpw", (char*)DevTableName[devtype], szsql, "", (void**)&ptempdata, datanum, posarray))
{
if(devtype==EQUIP_TYPE_BITRS)
{
devtype=EQUIP_TYPE_TRITRS;
if(!SearchData("visualpw", (char*)DevTableName[devtype], szsql, "", (void**)&ptempdata, datanum, posarray))
return;
}
else
return;
}
if(ptempdata==NULL)
return;
switch(devtype)
{
case EQUIP_TYPE_GEN: //
{
visualpw_Gen* pgen = (visualpw_Gen*)ptempdata;
id=pgen->NU;
break;
}
case EQUIP_TYPE_BUS: //ĸ
{
visualpw_Bus* pbus = (visualpw_Bus*)ptempdata;
id=pbus->NU;
break;
}
case EQUIP_TYPE_LINE: //·
{
visualpw_Line* pline = (visualpw_Line*)ptempdata;
id=pline->NU;
break;
}
case EQUIP_TYPE_BITRS: //˫
{
visualpw_Tfm1* ptfm = (visualpw_Tfm1*)ptempdata;
id=ptfm->NU;
break;
}
case EQUIP_TYPE_TRITRS://
{
visualpw_Tfm2* ptfm = (visualpw_Tfm2*)ptempdata;
id=ptfm->NU;
break;
}
case EQUIP_TYPE_LOAD: //
{
visualpw_Load* pload = (visualpw_Load*)ptempdata;
id=pload->NU;
break;
}
case EQUIP_TYPE_SHUNT: //豸
{
visualpw_Shunt* pshunt = (visualpw_Shunt*)ptempdata;
id=pshunt->NU;
break;
}
case EQUIP_TYPE_SWITCH://
{
visualpw_Switch* pbreak = (visualpw_Switch*)ptempdata;
id=pbreak->NU;
break;
}
case EQUIP_TYPE_DCLINE://ֱ·
case EQUIP_TYPE_REACT://翹
break;
case EQUIP_TYPE_SUB: //վ
{
visualpw_Station* pstation = (visualpw_Station*)ptempdata;
id=pstation->NU;
break;
}
case EQUIP_TYPE_AREA: //
{
visualpw_Zone* pzone = (visualpw_Zone*)ptempdata;
id=pzone->NU;
break;
}
default:
break;
}
break;
}
if(ptempdata!=NULL)
delete []ptempdata;
ptempdata=NULL;
}
bool LoadSystemLimit(CPtrArray& m_syslimit)
{
ClearSysLimit(m_syslimit);
CTime curtm = CTime::GetCurrentTime();
CTimeSpan spantime = curtm-CTime(curtm.GetYear(), curtm.GetMonth(), curtm.GetDay(),0,0,0);
LONG Curseconds = spantime.GetTotalSeconds();
void* m_char = NULL;
int recnum = 0;
CUIntArray posarray;
char szdb[32]={"ScadaAVC"};
if(SearchData(szdb, "AVCRunParam", "", "srttm", (void**)&m_char, recnum, posarray))
{
_AVCLimit* pnew[6];
pnew[0]= new _AVCLimit();
pnew[1]= new _AVCLimit();
pnew[2]= new _AVCLimit();
pnew[3]= new _AVCLimit();
pnew[4]= new _AVCLimit();
pnew[5]= new _AVCLimit();
ScadaAVC_AVCRunParam* prun = (ScadaAVC_AVCRunParam*)m_char;
for(int i=0; i<recnum; i++)
{
ScadaAVC_AVCRunParam* ptmp = prun+i;
if(ptmp==NULL)
continue;
for(int n=0; n<6; n++)
{
pnew[n]->m_limit[i].nu=0;
pnew[n]->m_limit[i].startt=ptmp->srttm;
pnew[n]->m_limit[i].endt=ptmp->endtm;
pnew[n]->m_limit[i].cosdn=ptmp->SCosDn;
pnew[n]->m_limit[i].cosup=ptmp->SCosUp;
pnew[n]->m_limit[i].gcosdn=ptmp->CosDn;
pnew[n]->m_limit[i].gcosup=ptmp->CosUp;
pnew[n]->m_limit[i].capnum=ptmp->CPNum;
pnew[n]->m_limit[i].xfmnum=ptmp->XfrNum;
}
pnew[0]->m_limit[i].bvol=6.0;
pnew[0]->m_limit[i].voldn=ptmp->V6Dn;
pnew[0]->m_limit[i].volup=ptmp->V6Up;
pnew[1]->m_limit[i].bvol=10.0;
pnew[1]->m_limit[i].voldn=ptmp->V10Dn;
pnew[1]->m_limit[i].volup=ptmp->V10Up;
pnew[2]->m_limit[i].bvol=35.0;
pnew[2]->m_limit[i].voldn=ptmp->V35Dn;
pnew[2]->m_limit[i].volup=ptmp->V35Up;
pnew[3]->m_limit[i].bvol=110.0;
pnew[3]->m_limit[i].voldn=ptmp->V110Dn;
pnew[3]->m_limit[i].volup=ptmp->V110Up;
pnew[4]->m_limit[i].bvol=220.0;
pnew[4]->m_limit[i].voldn=ptmp->V220Dn;
pnew[4]->m_limit[i].volup=ptmp->V220Up;
pnew[5]->m_limit[i].bvol=330.0;
pnew[5]->m_limit[i].voldn=ptmp->V330Dn;
pnew[5]->m_limit[i].volup=ptmp->V330Up;
}
for(int n=0; n<6; n++)
{
m_syslimit.Add(pnew[n]);
}
if(m_char!=NULL)
delete []m_char;
m_char=NULL;
}
else
return false;
if(SearchData(szdb, "AVCTimePart", "", "", (void**)&m_char, recnum, posarray))
{
ScadaAVC_AVCTimePart* ptpart = (ScadaAVC_AVCTimePart*)m_char;
for(int i=0; i<recnum; i++)
{
ScadaAVC_AVCTimePart* ptmp = ptpart+i;
if(ptmp==NULL)
continue;
_AVCLimit* pnew = new _AVCLimit();
pnew->m_limit[0].nu=ptmp->ID;
pnew->m_limit[0].bvol=0.0;
pnew->m_limit[0].startt=CTime(2000,1,1,0,0,0);
pnew->m_limit[0].endt=ptmp->Tm1;
pnew->m_limit[0].voldn=ptmp->VDn1;
pnew->m_limit[0].volup=ptmp->VUp1;
pnew->m_limit[0].cosdn=ptmp->CosDn1;
pnew->m_limit[0].cosup=ptmp->CosUp1;
pnew->m_limit[0].capnum=ptmp->CP_Num1;
pnew->m_limit[0].xfmnum=ptmp->XF_Num1;
pnew->m_limit[1].nu=ptmp->ID;
pnew->m_limit[1].bvol=0.0;
pnew->m_limit[1].startt=ptmp->Tm1;
pnew->m_limit[1].endt=ptmp->Tm2;
pnew->m_limit[1].voldn=ptmp->VDn2;
pnew->m_limit[1].volup=ptmp->VUp2;
pnew->m_limit[1].cosdn=ptmp->CosDn2;
pnew->m_limit[1].cosup=ptmp->CosUp2;
pnew->m_limit[1].capnum=ptmp->CP_Num2;
pnew->m_limit[1].xfmnum=ptmp->XF_Num2;
pnew->m_limit[2].nu=ptmp->ID;
pnew->m_limit[2].bvol=0.0;
pnew->m_limit[2].startt=ptmp->Tm2;
pnew->m_limit[2].endt=ptmp->Tm3;
pnew->m_limit[2].voldn=ptmp->VDn3;
pnew->m_limit[2].volup=ptmp->VUp3;
pnew->m_limit[2].cosdn=ptmp->CosDn3;
pnew->m_limit[2].cosup=ptmp->CosUp3;
pnew->m_limit[2].capnum=ptmp->CP_Num3;
pnew->m_limit[2].xfmnum=ptmp->XF_Num3;
pnew->m_limit[3].nu=ptmp->ID;
pnew->m_limit[3].bvol=0.0;
pnew->m_limit[3].startt=ptmp->Tm3;
pnew->m_limit[3].endt=ptmp->Tm4;
pnew->m_limit[3].voldn=ptmp->VDn4;
pnew->m_limit[3].volup=ptmp->VUp4;
pnew->m_limit[3].cosdn=ptmp->CosDn4;
pnew->m_limit[3].cosup=ptmp->CosUp4;
pnew->m_limit[3].capnum=ptmp->CP_Num4;
pnew->m_limit[3].xfmnum=ptmp->XF_Num4;
pnew->m_limit[4].nu=ptmp->ID;
pnew->m_limit[4].bvol=0.0;
pnew->m_limit[4].startt=ptmp->Tm4;
pnew->m_limit[4].endt=ptmp->Tm5;
pnew->m_limit[4].voldn=ptmp->VDn5;
pnew->m_limit[4].volup=ptmp->VUp5;
pnew->m_limit[4].cosdn=ptmp->CosDn5;
pnew->m_limit[4].cosup=ptmp->CosUp5;
pnew->m_limit[4].capnum=ptmp->CP_Num5;
pnew->m_limit[4].xfmnum=ptmp->XF_Num5;
pnew->m_limit[5].nu=ptmp->ID;
pnew->m_limit[5].bvol=0.0;
pnew->m_limit[5].startt=ptmp->Tm5;
pnew->m_limit[5].endt=CTime(2000,1,1,23,59,59);
pnew->m_limit[5].voldn=ptmp->VDn6;
pnew->m_limit[5].volup=ptmp->VUp6;
pnew->m_limit[5].cosdn=ptmp->CosDn6;
pnew->m_limit[5].cosup=ptmp->CosUp6;
pnew->m_limit[5].capnum=ptmp->CP_Num6;
pnew->m_limit[5].xfmnum=ptmp->XF_Num6;
m_syslimit.Add(pnew);
}
if(m_char!=NULL)
delete []m_char;
m_char=NULL;
}
else
return false;
return true;
}
bool GetVolLimit(CPtrArray& m_syslimit, DWORD pltyp, float* flimit, float vl, CTime curtime, bool isgate)
{
memset(flimit, 0, sizeof(float)*4);
AVCLimitParam* plimit = NULL;
CTime curtm=CTime(2000,1,1, curtime.GetHour(), curtime.GetMinute(), curtime.GetSecond());
CString sztext;
int count = m_syslimit.GetSize();
for(int i=0; i<count; i++)
{
_AVCLimit* ptmp = (_AVCLimit*)m_syslimit.GetAt(i);
if(ptmp==NULL)
continue;
bool isfind=false;
for(int n=0; n<7; n++)
{
AVCLimitParam* psublimit = &ptmp->m_limit[n];
if(psublimit->nu!=pltyp)
break;
sztext.Format("%s,%s-%s", curtm.Format("%Y-%m-%d %H:%M:%S"), psublimit->startt.Format("%Y-%m-%d %H:%M:%S"), psublimit->endt.Format("%Y-%m-%d %H:%M:%S"));
if(curtm<psublimit->startt||curtm>psublimit->endt)
continue;
if(pltyp==0&&vl>0.5)
{
if(pltyp==0&&fabs(vl-psublimit->bvol)/psublimit->bvol>0.12)
continue;
}
plimit=psublimit;
isfind=true;
break;
}
if(isfind==false)
continue;
else
break;
/*if(devtype==EQUIP_TYPE_BUS)
{
if(fabs(vl-ptmp->bvol)/ptmp->bvol>0.12)
continue;
}*/
break;
}
if(plimit!=NULL)
{
flimit[0]=plimit->volup; //ѹ
flimit[1]=plimit->voldn; //ѹ
if(isgate==true)
{
flimit[2]=plimit->gcosup; //
flimit[3]=plimit->gcosdn; //
}
else
{
flimit[2]=plimit->cosup; //
flimit[3]=plimit->cosdn; //
}
return true;
}
return false ;
/* if(flimit==NULL)
return false;
memset(flimit, 0, sizeof(float)*4);
if(pltyp<0)
return false;
float Volup=0.0; //ѹ
float Voldn=0.0; //ѹ
float Cosup=0.0; //
float Cosdn=0.0; //
bool Isfind=false;
CTime curtm = CTime::GetCurrentTime();
CTimeSpan spantime = curtm-CTime(curtm.GetYear(), curtm.GetMonth(), curtm.GetDay(),0,0,0);
LONG Curseconds = spantime.GetTotalSeconds();
CString szsql;
if(pltyp==0) //ϵͳ
{
int paramnum = 0;
refavc_Avc_RunParam* pParam=NULL;
CUIntArray parampos;
if(!SearchData("refavc", "Avc_RunParam", "", "", (void**)&pParam, paramnum, parampos))
return false;
CString secfile;
for(int j=0; j<paramnum; j++)
{
refavc_Avc_RunParam* ptmp = pParam+j;
if(ptmp==NULL)
continue;
LONG starttm, endtm;
starttm = (ptmp->starttime-CTime(ptmp->starttime.GetYear(), ptmp->starttime.GetMonth(), ptmp->starttime.GetDay(), 0 ,0,0)).GetTotalSeconds();
endtm = (ptmp->endtime-CTime(ptmp->endtime.GetYear(), ptmp->endtime.GetMonth(), ptmp->endtime.GetDay(), 0 ,0,0)).GetTotalSeconds();
if(Curseconds>starttm&&Curseconds<=endtm)
{
Volup = ptmp->Volup;
Voldn = ptmp->Voldn;
if(isgate==false)
{
Cosup = ptmp->FacCosup;
Cosdn = ptmp->FacCosdn;
}
else
{
Cosup = ptmp->GateCosup;
Cosdn = ptmp->GateCosdn;
}
Isfind=true;
break;
}
}
if(pParam!=NULL)
delete []pParam;
pParam=NULL;
}
else
{
int paramnum = 0;
refavc_SetLim_table* pSet=NULL;
CUIntArray parampos;
szsql.Format("shLimitNo=%ld", pltyp);
if(!SearchData("refavc", "SetLim_table", szsql, "shOrderNo", (void**)&pSet, paramnum, parampos))
return false;
CString secfile;
for(int j=0; j<paramnum; j++)
{
refavc_SetLim_table* ptmp = pSet+j;
if(ptmp==NULL)
continue;
LONG starttm, endtm;
starttm = (ptmp->tStartTime-CTime(ptmp->tStartTime.GetYear(), ptmp->tStartTime.GetMonth(), ptmp->tStartTime.GetDay(), 0 ,0,0)).GetTotalSeconds();
endtm = (ptmp->tEndTime-CTime(ptmp->tEndTime.GetYear(), ptmp->tEndTime.GetMonth(), ptmp->tEndTime.GetDay(), 0 ,0,0)).GetTotalSeconds();
if(Curseconds>starttm&&Curseconds<=endtm)
{
Cosup = ptmp->fVarUp;
Cosdn = ptmp->fVarDown;
Isfind=true;
break;
}
}
if(pSet!=NULL)
delete []pSet;
pSet=NULL;
}
flimit[0]=Volup; //ѹ
flimit[1]=Voldn; //ѹ
flimit[2]=Cosup; //
flimit[3]=Cosdn; //
return Isfind;*/
}
char MeasTypeName[][20]={"й","","ѹ","","","¶",""};
char MeasSubName[][20]={"","ĩ","ѹ","ѹ","ѹ"};
void GetDevMeasureName(SEMEAS_RTNET_EMS_Model* pmeas, char* measinfo)
{
if(pmeas==NULL||measinfo==NULL)
return;
measinfo[0]=0;
DWORD devid = pmeas->devid;
if(devid<=0)
return;
char devname[64]={0};
for(int i=EQUIP_TYPE_GEN; i<EQUIP_TYPE_DUMMY; i++)
{
GetDevName(devid, i, devname);
if(strlen(devname)<=0)
continue;
else
break;
}
if(strlen(devname)<0)
return;
sprintf(measinfo,"%s", devname);
//sprintf(measinfo,"%s:%s%s", devname, MeasSubName[pmeas->meassub], MeasTypeName[pmeas->devmtyp]);
}
|
C#
|
UTF-8
| 1,204 | 3.421875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Shape.ShapeComponents;
namespace Shape
{
abstract class AbstractQuadrilateral : IShape
{
protected Random rnd = new Random();
protected Line height;
protected Line width;
internal Dote A;
internal Dote B;
internal Dote C;
internal Dote D;
protected double Area { get; set; }
protected double Perimetr { get; set; }
public virtual void Display()
{
GetArea();
GetPerimetr();
GetCoordinates();
}
public virtual void GetCoordinates()
{
Console.WriteLine("The shape has 4 vertices with the following coordinates:\nA:{0:#.##}\nB:{1:#.##}\nC:{2:#.##}\nD:{3:#.##}", A.Point.ToString(), B.Point.ToString(), C.Point.ToString(), D.Point.ToString());
}
public virtual void GetArea()
{
Console.WriteLine("Area:{0}", this.Area);
}
public virtual void GetPerimetr()
{
Console.WriteLine("Perimetr:{0}", this.Perimetr);
}
}
}
|
Java
|
UTF-8
| 1,784 | 2.5625 | 3 |
[] |
no_license
|
/*
* Copyright (C) 2008 Universidade Federal de Campina Grande
*
* This file is part of OurGrid.
*
* OurGrid is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.fogbowcloud.app.jdfcompiler.lexical;
import org.fogbowcloud.app.jdfcompiler.TokenDelimiter;
import org.fogbowcloud.app.jdfcompiler.token.Token;
public interface LexicalAnalyzer {
/**
* This is the main function of the lexical analyzer. It will read the next
* string from source and return the token it represents ( the string, the
* code it has and the line it was found ).
*
* @return The next valid token object and null if the source finished
*/
public Token getToken() throws LexicalException;
/**
* It will read the next string from source and return the token it
* represents. This method uses the given set of delimiters to know where
* the token stops.
*
* @param delimiters the set of delimiters that determines the end of token.
* @return A token where the token's symbol is the string read.
* @throws LexicalException if a I/O problem ocurres at the reader
*/
public Token getToken( TokenDelimiter delimiters ) throws LexicalException;
}
|
Ruby
|
UTF-8
| 157 | 3.140625 | 3 |
[] |
no_license
|
def combine_anagrams(words)
hash = Hash.new([])
words.each { |str| hash[str.downcase.split(//).sort.join] += [str] }
hash.values
hash.values.to_s
end
|
JavaScript
|
UTF-8
| 1,407 | 3.765625 | 4 |
[] |
no_license
|
var prize = [];
var get = [];
function gachaSystem() {
for (var count = 1; count <= 100; count++) {
if (count % 10 == 0) {
var prize0;
prize0[count] = "A";
} else if (count % 10 == 1 || count == 1) {
var prize1;
prize1[count] = "B";
} else if (count % 10 == 2) {
var prize2;
prize2[count] = "C";
} else if (count % 10 == 3) {
var prize3;
prize3[count] = "D";
} else if (count % 10 == 4) {
var prize4;
prize4[count] = "E";
} else if (count % 10 == 5) {
var prize5;
prize5[count] = "F";
} else if (count % 10 == 6) {
var prize6;
prize6[count] = "G";
} else if (count % 10 == 7) {
var prize7;
prize7[count] = "H";
} else if (count % 10 == 8) {
var prize8;
prize8[count] = "I";
} else {
var prize9;
prize9[count] = "J";
}
prize = [
prize0,
prize1,
prize2,
prize3,
prize4,
prize5,
prize6,
prize7,
prize8,
prize9
];
}
console.log(prize);
}
function draw() {
var x = Math.floor(Math.random()) * 10;
var y = Math.floor(Math.random()) * 10;
if (document.getElementById("money").value == 0) {
alert(お金が足りません);
} else {
document.getElementById("money").value =
document.getElementById("money").value - 100;
get.push(prize[x][y]);
}
}
|
C++
|
UTF-8
| 3,571 | 2.890625 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <string>
#include <cassert>
#include <climits>
using namespace std;
#define MAX_SONGS 55
#define MAX_SUM 55000
int dp[MAX_SONGS];
int dp2[MAX_SONGS][2][MAX_SUM];
/* 0 is no touch; 1 is chosen */
int choice[MAX_SONGS];
void fill_dp(int val) {
for(int i = 0; i < MAX_SONGS; i++) {
dp[i] = val;
}
}
void fill_dp2(int val) {
for(int i = 0; i < MAX_SONGS; i++) {
for(int k = 0; k < 2; k++) {
for(int j = 0; j < MAX_SUM; j++) {
dp2[i][k][j] = val;
}
}
}
}
void fill_choice(int val) {
for(int i = 0; i < MAX_SONGS; i++) {
choice[i] = 0;
}
}
class ChangingSounds {
public :
int maxFinal(vector <int> changeIntervals, int beginLevel, int maxLevel) {
fill_dp(-1);
vector<int> increased;
vector<int> decreased;
int sum = beginLevel;
for(int i = 0; i < changeIntervals.size(); i++) {
sum += changeIntervals[i];
increased.push_back(changeIntervals[i]);
}
if(sum < maxLevel) { return sum; }
int ret_val = (get_combo(increased, decreased, maxLevel - sum));
if(ret_val == INT_MAX) {
return -1;
} else {
int val = maxLevel + ret_val;
if(val < 0) { return -1; } else { return val; }
}
}
private :
int get_combo(vector<int> &vals, vector<int> &vals2, int sum) {
fill_dp2(-1);
//fill_choice(0);
int result = rec(vals, 0, sum);
return result;
if(result == INT_MAX) {
return result;
}
/* Traverse the rec tree to get the choice */
vector<bool> choice = get_choice(vals, result);
for(int i = 0; i < choice.size(); i++) {
if(choice[i]) {
vals2.push_back(vals[i]);
}
}
vector<int>::iterator it = vals.begin();
int iter = 0;
while(it != vals.end()) {
if(choice[iter]) {
it = vals.erase(it);
} else {
it++;
}
iter++;
}
return result;
}
vector<bool> get_choice(vector<int> &vals, int result) {
vector<bool> choice;
for(int i = 0; i < vals.size(); i++) {
choice.push_back(false);
}
int selected_sum = result;
for(int i = 0; i < vals.size(); i++) {
int sum1 = selected_sum - vals[i];
int sum2 = selected_sum;
if(sum1 == result) {
choice[i] = true;
break;
}
bool select_s1 = false;
bool select_s2 = false;
if(sum1 >= 0) {
if(dp2[i][1][sum1] == result) {
select_s1 = true;
}
}
if(dp2[i][1][sum2] == result) {
select_s2 = true;
}
assert(select_s2 == true || select_s1 == true);
if(select_s1) {
choice[i] = true;
selected_sum = sum1;
} else {
selected_sum = sum2;
}
}
return choice;
}
int rec(vector<int> &vals, int idx, int sum) {
if(idx >= vals.size()) {
return sum;
}
if(sum == 0) {
return 0;
}
int val = -1;
int v1, v2;
if(sum - vals[idx] < 0) {
v1 = sum;
} else {
if(dp2[idx + 1][1][sum - vals[idx]] == -1) {
dp2[idx + 1][1][sum - vals[idx]] = rec(vals, idx + 1, sum - vals[idx]);
}
v1 = dp2[idx + 1][1][sum - vals[idx]];
}
if(dp2[idx + 1][1][sum] == -1) {
dp2[idx + 1][1][sum] = rec(vals, idx + 1, sum);
}
v2 = dp2[idx + 1][1][sum];
if(v1 == 0 || v2 == 0) {
val = (v1 == 0) ? v1 : v2;
return val;
}
if(v1 > 0 && v2 > 0) {
val = INT_MAX;
return val;
}
if(v1 < 0 && v2 < 0) {
val = max(v1, v2);
return val;
} else {
val = min(v1, v2);
return val;
}
return val;
}
};
|
Java
|
UTF-8
| 20,734 | 1.929688 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.interestrate;
import static org.testng.AssertJUnit.assertEquals;
import static com.opengamma.financial.interestrate.SimpleInstrumentFactory.*;
import com.opengamma.financial.convention.businessday.BusinessDayConventionFactory;
import com.opengamma.financial.convention.calendar.MondayToFridayCalendar;
import com.opengamma.financial.convention.daycount.DayCountFactory;
import com.opengamma.financial.convention.frequency.SimpleFrequency;
import com.opengamma.financial.instrument.index.IborIndex;
import com.opengamma.financial.interestrate.annuity.definition.AnnuityCouponFixed;
import com.opengamma.financial.interestrate.annuity.definition.AnnuityCouponIbor;
import com.opengamma.financial.interestrate.annuity.definition.GenericAnnuity;
import com.opengamma.financial.interestrate.bond.definition.Bond;
import com.opengamma.financial.interestrate.cash.definition.Cash;
import com.opengamma.financial.interestrate.fra.ForwardRateAgreement;
import com.opengamma.financial.interestrate.future.definition.InterestRateFuture;
import com.opengamma.financial.interestrate.payments.CouponCMS;
import com.opengamma.financial.interestrate.payments.CouponFixed;
import com.opengamma.financial.interestrate.payments.CouponIbor;
import com.opengamma.financial.interestrate.payments.Payment;
import com.opengamma.financial.interestrate.payments.PaymentFixed;
import com.opengamma.financial.interestrate.swap.definition.CrossCurrencySwap;
import com.opengamma.financial.interestrate.swap.definition.FixedCouponSwap;
import com.opengamma.financial.interestrate.swap.definition.FixedFloatSwap;
import com.opengamma.financial.interestrate.swap.definition.ForexForward;
import com.opengamma.financial.interestrate.swap.definition.OISSwap;
import com.opengamma.financial.interestrate.swap.definition.Swap;
import com.opengamma.financial.interestrate.swap.definition.TenorSwap;
import com.opengamma.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.math.curve.ConstantDoublesCurve;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.CurrencyAmount;
import java.util.ArrayList;
import java.util.List;
import javax.time.calendar.Period;
import org.testng.annotations.Test;
/**
*
*/
public class PresentValueCalculatorTest {
private static final PresentValueCalculator PVC = PresentValueCalculator.getInstance();
private static final String FIVE_PC_CURVE_NAME = "5%";
private static final String FOUR_PC_CURVE_NAME = "4%";
private static final String ZERO_PC_CURVE_NAME = "0%";
private static final YieldCurveBundle CURVES;
private static final Currency CUR = Currency.USD;
static {
YieldAndDiscountCurve curve = new YieldCurve(ConstantDoublesCurve.from(0.05));
CURVES = new YieldCurveBundle();
CURVES.setCurve(FIVE_PC_CURVE_NAME, curve);
curve = new YieldCurve(ConstantDoublesCurve.from(0.04));
CURVES.setCurve(FOUR_PC_CURVE_NAME, curve);
curve = new YieldCurve(ConstantDoublesCurve.from(0.0));
CURVES.setCurve(ZERO_PC_CURVE_NAME, curve);
}
@Test
public void testCash() {
final double t = 7 / 365.0;
final YieldAndDiscountCurve curve = CURVES.getCurve(FIVE_PC_CURVE_NAME);
double r = 1 / t * (1 / curve.getDiscountFactor(t) - 1);
Cash cash = new Cash(CUR, t, 1, r, FIVE_PC_CURVE_NAME);
double pv = PVC.visit(cash, CURVES);
assertEquals(0.0, pv, 1e-12);
final double tradeTime = 2.0 / 365.0;
final double yearFrac = 5.0 / 360.0;
r = 1 / yearFrac * (curve.getDiscountFactor(tradeTime) / curve.getDiscountFactor(t) - 1);
cash = new Cash(CUR, t, 1, r, tradeTime, yearFrac, FIVE_PC_CURVE_NAME);
pv = PVC.visit(cash, CURVES);
assertEquals(0.0, pv, 1e-12);
}
@Test
public void testFRA() {
final double paymentTime = 0.5;
final double fixingPeriodEnd = 7. / 12.;
String fundingCurveName = ZERO_PC_CURVE_NAME;
final String forwardCurveName = FIVE_PC_CURVE_NAME;
double paymentYearFraction = fixingPeriodEnd - paymentTime;
final double notional = 1;
final IborIndex index = new IborIndex(CUR, Period.ofMonths(1), 2, new MondayToFridayCalendar("A"), DayCountFactory.INSTANCE.getDayCount("Actual/365"),
BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Following"), true);
double fixingTime = paymentTime;
final double fixingPeriodStart = paymentTime;
double fixingYearFraction = paymentYearFraction;
final YieldAndDiscountCurve forwardCurve = CURVES.getCurve(FIVE_PC_CURVE_NAME);
final double rate = (forwardCurve.getDiscountFactor(paymentTime) / forwardCurve.getDiscountFactor(fixingPeriodEnd) - 1.0) * 12.0;
ForwardRateAgreement fra = new ForwardRateAgreement(CUR, paymentTime, fundingCurveName, paymentYearFraction, notional, index, fixingTime, fixingPeriodStart, fixingPeriodEnd, fixingYearFraction,
rate, forwardCurveName);
double pv = PVC.visit(fra, CURVES);
assertEquals(0.0, pv, 1e-12);
fixingTime = paymentTime - 2. / 365.;
fixingYearFraction = 31. / 365;
paymentYearFraction = 30. / 360;
fundingCurveName = FIVE_PC_CURVE_NAME;
final double forwardRate = (forwardCurve.getDiscountFactor(fixingPeriodStart) / forwardCurve.getDiscountFactor(fixingPeriodEnd) - 1) / fixingYearFraction;
final double fv = (forwardRate - rate) * paymentYearFraction / (1 + forwardRate * paymentYearFraction);
final double pv2 = fv * forwardCurve.getDiscountFactor(paymentTime);
fra = new ForwardRateAgreement(CUR, paymentTime, fundingCurveName, paymentYearFraction, notional, index, fixingTime, fixingPeriodStart, fixingPeriodEnd, fixingYearFraction, rate, forwardCurveName);
pv = PVC.visit(fra, CURVES);
assertEquals(pv, pv2, 1e-12);
}
@Test
public void testFutures() {
final IborIndex iborIndex = new IborIndex(CUR, Period.ofMonths(3), 2, new MondayToFridayCalendar("A"), DayCountFactory.INSTANCE.getDayCount("Actual/365"),
BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Following"), true);
final double lastTradingTime = 1.473;
final double fixingPeriodStartTime = 1.467;
final double fixingPeriodEndTime = 1.75;
final double fixingPeriodAccrualFactor = 0.267;
final double paymentAccrualFactor = 0.25;
final double referencePrice = 0.0; // TODO CASE - Future refactor - referencePrice = 0.0
final YieldAndDiscountCurve curve = CURVES.getCurve(FIVE_PC_CURVE_NAME);
final double rate = (curve.getDiscountFactor(fixingPeriodStartTime) / curve.getDiscountFactor(fixingPeriodEndTime) - 1.0) / fixingPeriodAccrualFactor;
final double price = 1 - rate;
final double notional = 1;
InterestRateFuture ir = new InterestRateFuture(lastTradingTime, iborIndex, fixingPeriodStartTime, fixingPeriodEndTime,
fixingPeriodAccrualFactor, referencePrice, notional, paymentAccrualFactor, "A", FIVE_PC_CURVE_NAME, FIVE_PC_CURVE_NAME);
double pv = PVC.visit(ir, CURVES);
assertEquals(price * notional * paymentAccrualFactor, pv, 1e-12);
final double deltaPrice = 0.01;
ir = new InterestRateFuture(lastTradingTime, iborIndex, fixingPeriodStartTime, fixingPeriodEndTime, fixingPeriodAccrualFactor, deltaPrice,
notional, paymentAccrualFactor, "A", FIVE_PC_CURVE_NAME, FIVE_PC_CURVE_NAME);
pv = PVC.visit(ir, CURVES);
assertEquals((price - deltaPrice) * notional * paymentAccrualFactor, pv, 1e-12);
}
@Test
public void testFixedCouponAnnuity() {
AnnuityCouponFixed annuityReceiver = new AnnuityCouponFixed(CUR, new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 1.0, ZERO_PC_CURVE_NAME, false);
double pv = PVC.visit(annuityReceiver, CURVES);
assertEquals(10.0, pv, 1e-12);
final int n = 15;
final double alpha = 0.49;
final double yearFrac = 0.51;
final double[] paymentTimes = new double[n];
final double[] coupons = new double[n];
final double[] yearFracs = new double[n];
final YieldAndDiscountCurve curve = CURVES.getCurve(FIVE_PC_CURVE_NAME);
final double rate = curve.getInterestRate(0.0);
for (int i = 0; i < n; i++) {
paymentTimes[i] = (i + 1) * alpha;
coupons[i] = Math.exp((i + 1) * rate * alpha);
yearFracs[i] = yearFrac;
}
annuityReceiver = new AnnuityCouponFixed(CUR, paymentTimes, Math.PI, rate, yearFracs, ZERO_PC_CURVE_NAME, false);
pv = PVC.visit(annuityReceiver, CURVES);
assertEquals(n * yearFrac * rate * Math.PI, pv, 1e-12);
final AnnuityCouponFixed annuityPayer = new AnnuityCouponFixed(CUR, paymentTimes, Math.PI, rate, yearFracs, ZERO_PC_CURVE_NAME, true);
assertEquals(pv, -PVC.visit(annuityPayer, CURVES), 1e-12);
}
@Test
public void testForwardLiborAnnuity() {
final int n = 15;
final double alpha = 0.245;
final double yearFrac = 0.25;
final double spread = 0.01;
final double[] paymentTimes = new double[n];
final double[] indexFixing = new double[n];
final double[] indexMaturity = new double[n];
final double[] paymentYearFracs = new double[n];
final double[] forwardYearFracs = new double[n];
final double[] spreads = new double[n];
for (int i = 0; i < n; i++) {
indexFixing[i] = i * alpha + 0.1;
paymentTimes[i] = (i + 1) * alpha;
indexMaturity[i] = paymentTimes[i] + 0.1;
paymentYearFracs[i] = yearFrac;
forwardYearFracs[i] = alpha;
spreads[i] = spread;
}
AnnuityCouponIbor annuity = new AnnuityCouponIbor(CUR, paymentTimes, FIVE_PC_CURVE_NAME, ZERO_PC_CURVE_NAME, true);
double pv = PVC.visit(annuity, CURVES);
assertEquals(0.0, pv, 1e-12);
annuity = new AnnuityCouponIbor(CUR, paymentTimes, ZERO_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, false);
double forward = 1 / alpha * (1 / CURVES.getCurve(FIVE_PC_CURVE_NAME).getDiscountFactor(alpha) - 1);
pv = PVC.visit(annuity, CURVES);
assertEquals(alpha * forward * n, pv, 1e-12);
forward = 1 / alpha * (1 / CURVES.getCurve(FIVE_PC_CURVE_NAME).getDiscountFactor(alpha) - 1);
annuity = new AnnuityCouponIbor(CUR, paymentTimes, indexFixing, indexFixing, indexMaturity, paymentYearFracs, forwardYearFracs, spreads, Math.E, ZERO_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, false);
pv = PVC.visit(annuity, CURVES);
assertEquals(yearFrac * (spread + forward) * n * Math.E, pv, 1e-12);
final AnnuityCouponIbor annuityPayer = new AnnuityCouponIbor(CUR, paymentTimes, indexFixing, indexFixing, indexMaturity, paymentYearFracs, forwardYearFracs, spreads, Math.E, ZERO_PC_CURVE_NAME,
FIVE_PC_CURVE_NAME, true);
assertEquals(pv, -PVC.visit(annuityPayer, CURVES), 1e-12);
}
@Test
public void testBond() {
final int n = 20;
final double tau = 0.5;
final double yearFrac = 180 / 365.0;
final YieldAndDiscountCurve curve = CURVES.getCurve(FIVE_PC_CURVE_NAME);
final double coupon = (1.0 / curve.getDiscountFactor(tau) - 1.0) / yearFrac;
final double[] coupons = new double[n];
final double[] yearFracs = new double[n];
final double[] paymentTimes = new double[n];
for (int i = 0; i < n; i++) {
paymentTimes[i] = tau * (i + 1);
coupons[i] = coupon;
yearFracs[i] = yearFrac;
}
Bond bond = new Bond(CUR, paymentTimes, 0.0, ZERO_PC_CURVE_NAME);
double pv = PVC.visit(bond, CURVES);
assertEquals(1.0, pv, 1e-12);
bond = new Bond(CUR, paymentTimes, coupons, yearFracs, 0.3, FIVE_PC_CURVE_NAME);
pv = PVC.visit(bond, CURVES);
assertEquals(1.0, pv, 1e-12);
}
@Test
public void testFixedFloatSwap() {
final int n = 20;
final double[] fixedPaymentTimes = new double[n];
final double[] floatPaymentTimes = new double[2 * n];
double sum = 0;
final YieldAndDiscountCurve curve = CURVES.getCurve(FIVE_PC_CURVE_NAME);
for (int i = 0; i < n * 2; i++) {
if (i % 2 == 0) {
fixedPaymentTimes[i / 2] = (i + 2) * 0.25;
sum += curve.getDiscountFactor(fixedPaymentTimes[i / 2]);
}
floatPaymentTimes[i] = (i + 1) * 0.25;
}
final double swapRate = (1 - curve.getDiscountFactor(10.0)) / 0.5 / sum;
final Swap<?, ?> swap = new FixedFloatSwap(CUR, fixedPaymentTimes, floatPaymentTimes, swapRate, FIVE_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, false);
final double pv = PVC.visit(swap, CURVES);
assertEquals(0.0, pv, 1e-12);
final double swapRateNonATM = 0.05;
final Swap<?, ?> swapPayer = new FixedFloatSwap(CUR, fixedPaymentTimes, floatPaymentTimes, swapRateNonATM, FIVE_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, true);
final Swap<?, ?> swapReceiver = new FixedFloatSwap(CUR, fixedPaymentTimes, floatPaymentTimes, swapRateNonATM, FIVE_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, false);
final double pvPayer = PVC.visit(swapPayer, CURVES);
final double pvReceiver = PVC.visit(swapReceiver, CURVES);
assertEquals(0.0, pvPayer + pvReceiver, 1e-12);
}
@Test
public void testOISSwap() {
double notional = 1e8;
double maturity = 10.0;
double rate = Math.exp(0.05) - 1;
OISSwap swap = makeOISSwap(maturity, FIVE_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, rate, notional);
double pv = PVC.visit(swap, CURVES);
assertEquals(0.0, pv, 1e-7); //NB the notional is 100M
swap = makeOISSwap(maturity, FOUR_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, rate, notional);
pv = PVC.visit(swap, CURVES);
assertEquals(0.0, pv, 1e-7);
}
@Test
public void testCrossCurrencySwap() {
double fxRate = 76.755;
CurrencyAmount usd = CurrencyAmount.of(CUR, 1e6);
CurrencyAmount jpy = CurrencyAmount.of(Currency.JPY, fxRate * 1e6);
SimpleFrequency dFq = SimpleFrequency.QUARTERLY;
SimpleFrequency fFq = SimpleFrequency.SEMI_ANNUAL;
CrossCurrencySwap ccs = makeCrossCurrencySwap(usd, jpy, 15, dFq, fFq, FIVE_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, FOUR_PC_CURVE_NAME, FOUR_PC_CURVE_NAME, 0.0);
double pv = PVC.visit(ccs, CURVES);
assertEquals(0.0, pv, 1e-9); //NB the notional is 1M
double tau = 0.5;
double spread = (Math.exp(0.04 * tau) - Math.exp(0.05 * tau)) / tau; //this is negative
ccs = makeCrossCurrencySwap(usd, jpy, 10, dFq, fFq, FOUR_PC_CURVE_NAME, FOUR_PC_CURVE_NAME, FOUR_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, spread);
pv = PVC.visit(ccs, CURVES);
assertEquals(0.0, pv, 1e-9); //NB the notional is 1M
}
@Test
public void testForexForward() {
double t = 3.0;
double spotFX = 1.5394;
double fwdFX = spotFX*Math.exp(0.01*t);
CurrencyAmount dom = CurrencyAmount.of(Currency.GBP, 3.5e9);
CurrencyAmount frn = CurrencyAmount.of(Currency.USD, -fwdFX* 3.5e9);
ForexForward fxFwd = makeForexForward(dom,frn,3.0,1/spotFX,FOUR_PC_CURVE_NAME,FIVE_PC_CURVE_NAME);
double pv = PVC.visit(fxFwd, CURVES);
assertEquals(0.0, pv, 1e-9);
}
@Test
public void testTenorSwap() {
final int n = 20;
final double tau = 0.25;
final double[] paymentTimes = new double[n];
final double[] spreads = new double[n];
final double[] yearFracs = new double[n];
final double[] indexFixing = new double[n];
final double[] indexMaturity = new double[n];
final YieldAndDiscountCurve curve = CURVES.getCurve(FIVE_PC_CURVE_NAME);
final double forward = (1.0 / curve.getDiscountFactor(tau) - 1.0) / tau;
for (int i = 0; i < n; i++) {
indexFixing[i] = i * tau;
paymentTimes[i] = (i + 1) * tau;
indexMaturity[i] = paymentTimes[i];
spreads[i] = forward;
yearFracs[i] = tau;
}
final GenericAnnuity<CouponIbor> payLeg = new AnnuityCouponIbor(CUR, paymentTimes, indexFixing, indexMaturity, yearFracs, 1.0, FIVE_PC_CURVE_NAME, FIVE_PC_CURVE_NAME, true);
final GenericAnnuity<CouponIbor> receiveLeg = new AnnuityCouponIbor(CUR, paymentTimes, indexFixing, indexFixing, indexMaturity, yearFracs, yearFracs, spreads, 1.0, FIVE_PC_CURVE_NAME,
ZERO_PC_CURVE_NAME, false);
final Swap<?, ?> swap = new TenorSwap<CouponIbor>(payLeg, receiveLeg);
final double pv = PVC.visit(swap, CURVES);
assertEquals(0.0, pv, 1e-12);
}
@Test
public void testGenericAnnuity() {
final double time = 3.4;
final double amount = 34.3;
final double coupon = 0.05;
final double yearFrac = 0.5;
final double resetTime = 2.9;
final double notional = 56;
final List<Payment> list = new ArrayList<Payment>();
double expected = 0.0;
Payment temp = new PaymentFixed(CUR, time, amount, FIVE_PC_CURVE_NAME);
expected += amount * CURVES.getCurve(FIVE_PC_CURVE_NAME).getDiscountFactor(time);
list.add(temp);
temp = new CouponFixed(CUR, time, FIVE_PC_CURVE_NAME, yearFrac, notional, coupon);
expected += notional * yearFrac * coupon * CURVES.getCurve(FIVE_PC_CURVE_NAME).getDiscountFactor(time);
list.add(temp);
temp = new CouponIbor(CUR, time, ZERO_PC_CURVE_NAME, yearFrac, notional, resetTime, resetTime, time, yearFrac, 0.0, FIVE_PC_CURVE_NAME);
expected += notional * (CURVES.getCurve(FIVE_PC_CURVE_NAME).getDiscountFactor(resetTime) / CURVES.getCurve(FIVE_PC_CURVE_NAME).getDiscountFactor(time) - 1);
list.add(temp);
final GenericAnnuity<Payment> annuity = new GenericAnnuity<Payment>(list, Payment.class, true);
final double pv = PVC.visit(annuity, CURVES);
assertEquals(expected, pv, 1e-12);
}
@Test
public void testFixedPayment() {
final double time = 1.23;
final double amount = 4345.3;
final PaymentFixed payment = new PaymentFixed(CUR, time, amount, FIVE_PC_CURVE_NAME);
final double expected = amount * CURVES.getCurve(FIVE_PC_CURVE_NAME).getDiscountFactor(time);
final double pv = PVC.visit(payment, CURVES);
assertEquals(expected, pv, 1e-8);
}
@Test
public void testFixedCouponPayment() {
final double time = 1.23;
final double yearFrac = 0.56;
final double coupon = 0.07;
final double notional = 1000;
final CouponFixed payment = new CouponFixed(CUR, time, ZERO_PC_CURVE_NAME, yearFrac, notional, coupon);
final double expected = notional * yearFrac * coupon;
final double pv = PVC.visit(payment, CURVES);
assertEquals(expected, pv, 1e-8);
}
@Test
public void ForwardLiborPayment() {
final double time = 2.45;
final double resetTime = 2.0;
final double maturity = 2.5;
final double paymentYF = 0.48;
final double forwardYF = 0.5;
final double spread = 0.04;
final double notional = 4.53;
CouponIbor payment = new CouponIbor(CUR, time, FIVE_PC_CURVE_NAME, paymentYF, notional, resetTime, resetTime, maturity, forwardYF, spread, ZERO_PC_CURVE_NAME);
double expected = notional * paymentYF * spread * CURVES.getCurve(FIVE_PC_CURVE_NAME).getDiscountFactor(time);
double pv = PVC.visit(payment, CURVES);
assertEquals(expected, pv, 1e-8);
payment = new CouponIbor(CUR, time, ZERO_PC_CURVE_NAME, paymentYF, 1.0, resetTime, resetTime, maturity, forwardYF, spread, FIVE_PC_CURVE_NAME);
final double forward = (Math.exp(0.05 * (maturity - resetTime)) - 1) / forwardYF;
expected = paymentYF * (forward + spread);
pv = PVC.visit(payment, CURVES);
assertEquals(expected, pv, 1e-8);
}
@Test
/**
* Tests CouponCMS pricing by simple discounting (no convexity adjustment).
*/
public void testCouponCMS() {
final String discountCurve = FOUR_PC_CURVE_NAME;
final String forwardCurve = FIVE_PC_CURVE_NAME;
// Swap: 5Y x 10Y semi/quarterly
final int n = 20;
final double settleTime = 5.0;
final double[] fixedPaymentTimes = new double[n];
final double[] floatPaymentTimes = new double[2 * n];
for (int i = 0; i < n * 2; i++) {
if (i % 2 == 0) {
fixedPaymentTimes[i / 2] = (i + 2) * 0.25 + settleTime;
}
floatPaymentTimes[i] = (i + 1) * 0.25 + settleTime;
}
final FixedCouponSwap<? extends Payment> swap = new FixedFloatSwap(CUR, fixedPaymentTimes, floatPaymentTimes, 1.0, discountCurve, forwardCurve, true);
// CMS coupon
final double notional = 10000000.0; //10m
final double paymentYearFraction = 0.51;
final double cmsFixing = settleTime - 2.0 / 365.0;
final double paymentTime = settleTime + 0.51;
final CouponCMS payment = new CouponCMS(CUR, paymentTime, paymentYearFraction, notional, cmsFixing, swap, settleTime);
// Pricing
final ParRateCalculator parRateCalc = ParRateCalculator.getInstance();
final double rate = parRateCalc.visit(swap, CURVES);
final double df = CURVES.getCurve(discountCurve).getDiscountFactor(paymentTime);
final double expected = notional * paymentYearFraction * rate * df;
final double pv = PVC.visit(payment, CURVES);
assertEquals(expected, pv, 1e-8);
}
}
|
Markdown
|
UTF-8
| 569 | 2.671875 | 3 |
[
"CC0-1.0"
] |
permissive
|
# マークダウン
1改行で`<br/>`。2改行で`<p>`。
## リスト
* あ
* い
* う
* え
* お
* か
## 順序リスト
1. あ
1. い
1. う
1. え
1. お
1. か
`A`,`a`,`i`では使えなかった。
## テーブル
A|B
-|-
a|b
c|d
e|f
## リンク
* https://www.google.co.jp
* [https://www.google.co.jp]
* [Google](https://www.google.co.jp)
* [Google](https://www.google.co.jp "検索エンジン")
* [Google]
[Google]: https://www.google.co.jp "検索エンジン"
|
Java
|
UTF-8
| 3,724 | 2.671875 | 3 |
[] |
no_license
|
package Biblioteca.contoller;
import Biblioteca.model.Library;
import Biblioteca.model.valueObject.Author;
import Biblioteca.model.Book;
import Biblioteca.model.valueObject.Title;
import Biblioteca.model.valueObject.Year;
import Biblioteca.view.InputDriver;
import Biblioteca.view.OutputDriver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static Biblioteca.common.Constants.NUMBER_OF_COLUMNS_IN_BOOK_DETAILS;
import static org.mockito.Mockito.*;
class LibraryManagementSystemTest {
private LibraryManagementSystem libraryManagementSystem;
private OutputDriver outputDriver;
private InputDriver inputDriver;
private Book book1, book2;
@BeforeEach
void init() {
outputDriver = mock(OutputDriver.class);
inputDriver = mock(InputDriver.class);
when(inputDriver.getIntInput()).thenReturn(1).thenReturn(0);
book1 = new Book(new Title("Book1"), new Author("Mrinal"), new Year(1996));
book2 = new Book(new Title("Book2"), new Author("Arpan"), new Year(1997));
final List<Book> books = new ArrayList<>();
books.add(book1);
books.add(book2);
final Library library = new Library(books);
libraryManagementSystem = new LibraryManagementSystem(library, outputDriver, inputDriver);
}
@DisplayName("LibraryManagementSystem should welcome customer")
@Test
void testWelcome() {
verifyZeroInteractions(outputDriver);
libraryManagementSystem.start();
verify(outputDriver).println("Welcome Customer to Biblioteca");
}
@DisplayName("Should println all the books")
@Test
void testDisplayingBookList() {
verifyZeroInteractions(outputDriver);
libraryManagementSystem.start();
verify(outputDriver).printInColumns(Arrays.asList(
"Book1", "Mrinal", "1996", "Book2", "Arpan", "1997"), NUMBER_OF_COLUMNS_IN_BOOK_DETAILS);
}
@DisplayName("Should not println books not in the system")
@Test
void testDisplayingBookListNotDisplayThoseNotIn() {
libraryManagementSystem.start();
verify(outputDriver, times(0))
.printInColumns(Arrays.asList("bookNotInLibrary"), NUMBER_OF_COLUMNS_IN_BOOK_DETAILS);
}
@DisplayName("Should show 'Select a valid option!' when an option more than number of menus is given")
@Test
void testInvalidOptionForGreater() {
verifyZeroInteractions(outputDriver);
when(inputDriver.getIntInput()).thenReturn(Menu.values().length).thenReturn(0);
libraryManagementSystem.start();
verify(outputDriver).println("Select a valid option!");
}
@DisplayName("Should show 'Select a valid option!' when selecting option less than 0")
@Test
void testInvalidOptionForLess() {
verifyZeroInteractions(outputDriver);
when(inputDriver.getIntInput()).thenReturn(-1).thenReturn(0);
libraryManagementSystem.start();
verify(outputDriver).println("Select a valid option!");
}
@DisplayName("Should remove book that's checked out")
@Test
void testCheckOutBook1() {
verifyZeroInteractions(outputDriver);
when(inputDriver.getInput()).thenReturn("Book1");
when(inputDriver.getIntInput()).thenReturn(2).thenReturn(1).thenReturn(0);
libraryManagementSystem.start();
verify(outputDriver).printInColumns(Arrays.asList("Book2", "Arpan", "1997"), NUMBER_OF_COLUMNS_IN_BOOK_DETAILS);
}
@AfterEach
void cleanUp() {
System.setIn(System.in);
}
}
|
C++
|
UTF-8
| 2,997 | 2.53125 | 3 |
[] |
no_license
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QListWidgetItem>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QDebug>
#include <QString>
#include <QFile>
#include <QFileDialog>
#include <QVector>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
/**
* @brief Constructeur de la classe MainWindow
* @param QWidget* parent
*/
explicit MainWindow(QWidget *parent = 0);
/**
* @brief Destructeur de la classe MainWindow
*/
~MainWindow();
private slots:
/**
* @brief Fonction appelé lorsqu'on choisit une base de données
* @param QString nomBase : nom de la base de données choisis
*/
void on_comboBoxBdd_activated(const QString &nomBase);
/**
* @brief Fonction appelé lorsqu'on clique sur un item de la liste des tables
* @param QListWidgetItem* item : l'item de la liste choisis
*/
void on_listWidgetTables_itemClicked(QListWidgetItem *item);
/**
* @brief Fonction appelé à chaque fois que le texte change dans le textEdit
*/
void on_textEditRequete_textChanged();
/**
* @brief Fonction appelé à chaque fois qu'on appui sur le bouton d'infos, le "?"
*/
void on_pushButtonInfos_clicked();
/**
* @brief Fonction appelé lorsque l'on clique sur un item de la liste d'historique
* @param QListWidgetItem* item : L'item de la liste chosis
*/
void on_listWidgetHistorique_itemClicked(QListWidgetItem *item);
/**
* @brief Fonction appelé à chaque fois qu'on appui sur le bouton pour sauvegarder l'historique
*/
void on_pushButtonSauvegarde_clicked();
/**
* @brief Fonction appelé à chaque fois qu'on appui sur le bouton pour historiser l'historique
*/
void on_pushButtonHistorise_clicked();
/**
* @brief Fonction appelé à chaque fois qu'on appui sur le bouton pour charger un fichier texte contenant des requêtes historique
*/
void on_pushButtonLoad_clicked();
/**
* @brief Fonction appelé à chaque fois qu'on appui sur le bouton pour exporter le résultat de la requête au format csv
*/
void on_pushButtonExporter_clicked();
/**
* @brief Fonction appelé lorsque l'on appui sur le menu "fichier" puis "quitter"
*/
void on_actionQuit_activated();
/**
* @brief Fonction appelé lorsque l'on appui sur le menu "fichier" et "charger fichier"
*/
void on_actionLoad_file_activated();
/**
* @brief Fonction appelé lorsque l'on appui sur le menu "?" et "about"
*/
void on_actionAbout_activated();
private:
Ui::MainWindow *ui;
/**
* @brief L'erreur sql récupéré, tant que le résultat est faux, en QString
*/
QString erreurSql;
/**
* @brief Vecteur contenant les requêtes de l'historique
*/
QVector<QString> vecteurHistorique;
};
#endif // MAINWINDOW_H
|
SQL
|
UTF-8
| 587 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
# --- !Ups
ALTER TABLE label_point
DROP COLUMN canvas_height,
DROP COLUMN canvas_width,
DROP COLUMN alpha_x,
DROP COLUMN alpha_y;
ALTER TABLE gsv_link DROP COLUMN road_argb;
# --- !Downs
ALTER TABLE gsv_link ADD COLUMN road_argb CHARACTER VARYING(2044) COLLATE pg_catalog."POSIX" NOT NULL DEFAULT '';
ALTER TABLE label_point
ADD COLUMN canvas_height INTEGER NOT NULL DEFAULT 480,
ADD COLUMN canvas_width INTEGER NOT NULL DEFAULT 720,
ADD COLUMN alpha_x DOUBLE PRECISION NOT NULL DEFAULT 4.6,
ADD COLUMN alpha_y DOUBLE PRECISION NOT NULL DEFAULT -4.65;
|
C++
|
UTF-8
| 987 | 2.96875 | 3 |
[] |
no_license
|
#pragma once
#include <GLFW\glfw3.h>
class Mouse
{
public:
enum Mouse_Button
{
LEFT,
RIGHT,
CENTER
};
static void Init();
static void Update();
static bool IsButtonPressed(Mouse_Button button);
static double GetPosX() { return posX; }
static double GetPosY() { return posY; }
static double GetPrevPosX() { return prevPosX; }
static double GetPrevPosY() { return prevPosY; }
static double GetPosDeltaX() { return posDeltaX; }
static double GetPosDeltaY() { return posDeltaY; }
static double GetScrollX() { return scrollX; }
static double GetScrollY() { return scrollY; }
private:
static double scrollX, scrollY;
static double posX, posY;
static double prevPosX, prevPosY;
static double posDeltaX, posDeltaY;
static int GLFWButtonCodes[3];
static void scroll_callback(GLFWwindow *w, double x, double y) { scrollX = x; scrollY = y; }
static void cursor_pos_callback(GLFWwindow* window, double xpos, double ypos)
{
posX = xpos;
posY = ypos;
}
};
|
Java
|
UTF-8
| 1,427 | 2.296875 | 2 |
[] |
no_license
|
package com.dexels.r2dbc;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.reactivestreams.servlet.ResponseSubscriber;
import io.r2dbc.postgresql.PostgresqlConnectionConfiguration;
import io.r2dbc.postgresql.PostgresqlConnectionFactory;
public class SQLServletR2DBC extends HttpServlet {
private static final long serialVersionUID = 4008686226298740688L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ResponseSubscriber subscriber = new ResponseSubscriber(req.startAsync());
PostgresqlConnectionConfiguration configuration = PostgresqlConnectionConfiguration.builder()
.database("dvdrental")
.host("postgres")
.password("mysecretpassword")
.username("postgres")
.build();
PostgresqlConnectionFactory connectionFactory = new PostgresqlConnectionFactory(configuration);
connectionFactory.create()
.flatMapMany(connection->connection.createStatement("select title from film")
.execute())
.flatMap(e->e.map((row,rowmeta)->row.get("title",String.class)+"\n"))
.map(String::getBytes)
.map(ByteBuffer::wrap)
.subscribe(subscriber);
}
}
|
JavaScript
|
UTF-8
| 1,387 | 4.625 | 5 |
[] |
no_license
|
// In JS the WAY a function is called determines what
// 'this' keyword represents (depends on a context)
function first() {
return this;
};
console.log('Equal to Global space: ' + (first() === global));
////////////////////////////////////////////////////////////////////////////////
function second() {
'use strict'; // changes the context
return this;
};
console.log(`Equal to Global space: ${second() === global} (${second()})`);
///////////////////////////////////////////////////////////////////////////////
let myObject = {
value: 'My Object'
};
global.value = '- Global Object -';
function third() {
return this.value; // what is the value of 'this'
};
function forth(name) {
return this.value + ': ' + name; // what is the value of 'this'
};
// what is 'this'? - depends on the call
console.log(third()); // 'this' is bound to global object
console.log(third.call(myObject)); // 'this' is bound to myObject:
// call vs apply
console.log(forth.call(myObject, 'Victor'));
console.log(forth.apply(myObject, ['Victor']));
// Context is an object
let customer1 = {
firstName: 'victor',
lastName: 'govorov',
print: fifth
};
let customer2 = {
firstName: 'luda',
lastName: 'ferents',
print: fifth
};
function fifth() {
console.log(this.firstName + ' ' + this.lastName);
};
customer1.print();
customer2.print();
|
Python
|
UTF-8
| 228 | 3.265625 | 3 |
[] |
no_license
|
import operator
x = {
1: 'd) one',
2: 'e) two',
3: 'a) three',
4: 'c) four',
5: 'b) five'
}
sorted_x = sorted(
x.items(),
key=operator.itemgetter(1),
# reverse=True
)
print sorted_x
|
Python
|
UTF-8
| 686 | 3.515625 | 4 |
[] |
no_license
|
class Ninja:
def __init__(self, first_name, last_name, treats, pet_food, pet):
self.first_name = first_name
self.last_name = last_name
self.treats = treats
self.pet_food = pet_food
self.pet = pet
def walk(self):
self.pet.play()
print(self.first_name, "has taken", self.pet.name, "for a walk")
return self
def feed(self):
self.pet.eat()
print(self.first_name, "has fed", self.pet.name, "with", self.pet_food)
return self
def bath(self):
print(self.first_name, "gave", self.pet.name, "a much needed bath")
self.pet.noise()
return self
|
C#
|
UTF-8
| 1,140 | 2.71875 | 3 |
[
"MS-PL"
] |
permissive
|
using System;
using System.Diagnostics;
namespace SPMeta2.Containers.Utils
{
public class TraceUtils
{
#region static
public static void WithScope(Action<TraceUtils> action)
{
action(new TraceUtils());
}
#endregion
#region properties
protected int IndentIndex { get; set; }
#endregion
#region methods
protected string GetCurrentIndent()
{
var result = string.Empty;
for (var i = 0; i < IndentIndex; i++)
result += " ";
return result;
}
public TraceUtils WriteLine(string traceMessage)
{
Trace.WriteLine(string.Format("{0}{1}", GetCurrentIndent(), traceMessage));
return this;
}
public TraceUtils WithTraceIndent(Action<TraceUtils> action)
{
try
{
IndentIndex++;
action(this);
}
finally
{
IndentIndex--;
}
return this;
}
#endregion
}
}
|
Java
|
UTF-8
| 911 | 1.992188 | 2 |
[] |
no_license
|
package com.czxy.changgou3.mapper;
import com.czxy.changgou3.pojo.SkuPhoto;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
/**
* @author zhandehuang@itcast.cn
* @version 1.0
* @date 2020/4/21 0021
**/
@org.apache.ibatis.annotations.Mapper
public interface SkuPhotoMapper extends Mapper<SkuPhoto> {
/**
* 查询指定Skuid的所有图片
* @param skuId
* @return
*/
@Select("select * from tb_sku_photo where sku_id =#{skuId}")
@Results({
@Result(property = "id",column = "id"),
@Result(property = "skuId",column = "sku_id"),
@Result(property = "url",column = "url"),
})
public List<SkuPhoto>findSkuPhotoBySkuId(@Param("skuId") Integer skuId);
}
|
Java
|
UTF-8
| 182 | 2.015625 | 2 |
[] |
no_license
|
package ca.uvic.seng330.assn3;
import java.util.UUID;
public interface Device {
public Status getStatus();
public void setStatus(Status s);
public UUID getIdentifier();
}
|
Ruby
|
UTF-8
| 1,603 | 2.546875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module Trample
class Session
include Logging
include Timer
attr_reader :config, :response_times, :cookies, :last_response
def initialize(config)
@config = config
@response_times = []
@cookies = {}
end
def trample
@config.login.each {|page| hit page} unless @config.login.empty?
@config.iterations.times do
@config.pages.each do |p|
hit p
end
end
end
protected
def hit(page)
response_times << request(page)
# this is ugly, but it's the only way that I could get the test to pass
# because rr keeps a reference to the arguments, not a copy. ah well.
@cookies = cookies.merge(last_response.cookies)
logger.info "#{page.request_method.to_s.upcase} #{page.url} #{response_times.last}s #{last_response.code}"
end
def request(page)
time do
@last_response = send(page.request_method, page)
end
end
def get(page)
RestClient.get(page.url, :cookies => cookies, :accept => :html)
end
def post(page)
params = page.parameters
if authenticity_token = parse_authenticity_token(@last_response)
params.merge!(:authenticity_token => authenticity_token)
end
RestClient.post(page.url, params, :cookies => cookies, :accept => :html)
end
def parse_authenticity_token(html)
return nil if html.nil?
input = Hpricot(html).at("input[@name='authenticity_token']")
input.nil? ? nil : input['value']
end
end
end
|
Markdown
|
UTF-8
| 5,101 | 3.296875 | 3 |
[] |
no_license
|
# TP2
#### :alarm_clock: [Date de remise le dimanche 10 octobre à 23h59](https://www.timeanddate.com/countdown/generic?iso=20211010T2359&p0=165&msg=Remise&font=cursive&csz=1#)
## Objectif
Ce TP poursuit votre apprentissage de l'algorithmie avec le langage de programmation Python.
Plus particulièrement l'utilisation de structure de contrôles et de structure de données.
Celui-ci est composé de 4 exercices, pour lesquels vous devez compléter le code avec l'indicateur `TODO`.
Les exercices sont tous indépendants, l'exercice 4 est composé de 3 parties.
## Consignes à respecter
Tout d'abord, assurez-vous d'avoir lu le fichier [instructions.md](instructions.md) et d'avoir téléchargé les exercices1-4.py que vous devrez compléter.
Pour ce TP, vous ne pouvez pas importer d'autres librairies que celles qui sont déjà importées dans les fichiers.
## Exercice 1 (3 points):
Dans cet exercice, vous devez écrire un programme qui combine deux dictionnaires dans un 3e dictionnaire en gardant la valeur maximale des clés communes.
**Exemple :**
```python
dic_1 = {'a': 5, 'b': 2, 'c':9}
dic_2 = {'a': 1, 'b': 8, 'd':17}
dic_3 = {'a': 5, 'b': 8, 'd': 17, 'c': 9}
```
## Exercice 2 (3 points):
Lors de la manipulation de liste il est commun de vouloir trier les valeurs qui la compose.
Pour ce faire nous allons implémenter un algorithme de tri appelé tri à bulle. Il s'agit d'un algorithme peu efficace, mais facile à implémenter.
**Le pseudo-code de l'algorithme est le suivant :**
```
tri_à_bulles(Tableau T)
pour i allant de (taille de T)-1 à 1
pour j allant de 0 à i-1
si T[j+1] < T[j]
on inverse les valeurs
```
**Une animation qui représente le fonctionnement de l'algorithme :**
<img align="center" src="img/Sorting_bubblesort_anim.gif"/>
Nous ferons un tri par ordre croissant ce qui donnera :
```python
val = [5,8,1,9,6,2,4,3,7,5]
sorted_val = [1,2,3,4,5,5,6,7,8,9]
```
**ATTENTION** Un *pseudo-code* est une façon de décrire un algorithme qui ne prend pas en compte les spécificités du language.
Mais dans le cas présent les tableaux sont quand même considérés comme commençant à 0.
## Exercice 3 (4 points):
Nous voulons réaliser un programme estimant la valeur du nombre π. Pour cela, nous utilisons la formule suivante :
<img align="center" src="img/formule_pi.png"/>
Cette formule permet une estimation précise de π pour un nombre d’itérations n suffisamment grand.
Vous devez compléter la fonction `compute_pi(p)` où p est la précision que l'on veut.
Dès que l'écart entre 2 valeurs successives est inférieur à la précision on s'arrête.
Le programme met normalement moins d'une seconde à s'exécuter.
## Exercice 4 :
Le but de cet exercice est de programmer un petit jeu de labyrinthe dans lequel on guide le joueur jusqu'à la sortie. Le joueur peut se déplacer dans toutes les directions mais il ne peut pas sortir du labyrinthe ou passer à travers les murs, ce n'est pas un fantôme.
Toutes les fonctions vous sont fournies, il vous faut seulement compléter les diverses parties identifiées par un `TODO`.
Le labyrinthe que l'on va représenter est le suivant :
<img align="center" src="img/grille.png"/>
Cependant comme nous allons afficher le labyrinthe dans le terminal, notre affichage est simplifié et ressemblera à cela :
<img align="center" src="img/terminal.png"/>
- O : le joueur
- X : la sortie
- W : un mur
- _ : une case libre
**ATTENTION** Pour la correction une autre définition du labyrinthe sera utilisée, donc votre code devra pouvoir s'adapter.
### Partie 1 : Génaration du labyrinthe (3 points)
Il vous faut compléter la fonction `init_maze` pour ce faire nous avons :
- la dimension du labyrinthe
- la position du joueur
- la position de la sortie
- une liste de position de mur
Il faut également compléter le début du `main` pour définir la position du joueur comme étant le coin en haut à gauche et la sortie comme étant en bas à droite.
Voir l'image ci-dessus.
### Partie 2 : Vérification d'un mouvement (3 points)
Dans cette partie on va compléter la fonction `validate_move`, pour cette fonction nous avons *maze* qui correspond au labyrinthe générer à la question d'avant et *new_player_pos*.
qui correspond à une nouvelle position que le joueur serait sur le point de prendre.
L'objectif ici est de compléter la fonction pour que l'on renvoie *True* si *new_player_pos* est valide, c'est à dire dans le labyrinthe et pas sur un mur.
Sinon on renverra *False*.
### Partie 3 : Faire un mouvement (4 points)
Dans cette dernière partie nous allons compléter la fonction `move`, Dans un premier temps à l'aide d'un dictionnaire
il faut convertir l'entré *input* en sa direction correspondante. On s'attend à avoir :
- w -> up
- a -> left
- s -> down
- d -> right
Il faut ensuite vérifier si l'entrée est valide, puis en fonction de la direction générer une nouvelle position potentielle pour le joueur.
Enfin si le mouvement est valide on change la position du joueur dans le labyrinthe.
|
C#
|
UTF-8
| 2,172 | 2.6875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MappingDB;
namespace DL
{
public class DatVenta
{
public int Insertar(VENTA P)
{
try
{
ContextoDB ct = new ContextoDB();
ct.VENTA.Add(P);
ct.SaveChanges();
return P.CVenta;
}
catch (Exception ex)
{
throw ex;
}
}
public void Actualizar(VENTA P)
{
try
{
ContextoDB ct = new ContextoDB();
VENTA VENTA = ct.VENTA.Where(x => x.CVenta == P.CVenta).SingleOrDefault();
if (VENTA != null)
{
ct.Entry(VENTA).CurrentValues.SetValues(P);
ct.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Eliminar(int CVenta)
{
try
{
ContextoDB ct = new ContextoDB();
VENTA VENTA = ct.VENTA.Where(x => x.CVenta == CVenta).SingleOrDefault();
if (VENTA != null)
{
ct.VENTA.Remove(VENTA);
ct.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
public List<VENTA> Leer()
{
try
{
ContextoDB ct = new ContextoDB();
return ct.VENTA.ToList();
}
catch (Exception ex)
{
throw ex;
}
}
public VENTA GetById(int CVenta)
{
try
{
ContextoDB ct = new ContextoDB();
VENTA VENTA = ct.VENTA.Where(x => x.CVenta == CVenta).SingleOrDefault();
return VENTA;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
Markdown
|
UTF-8
| 1,551 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
# Actions
## Action life cycle
Actions runs by State, when Adam FSM entering to this state. Every action have a runtime context. Actions can be interruped or not executed, if Adam FSM will change their state during other state execution. When State is leaving, all actions in this state call "release" callback to clear their state or do some additional stuff.
## Finished event
Almost every actions (exlude the infinity one) pass finished event when actions is done. If action is not deferred, finished event will be triggered instantly after the action call.
## Deferred actions
Deferred action - action is not instant and have custom logic to finish. For example - delayed actions. This action will execute and finish after delay. Actions can be deferred and no have finish conditions - they will not trigger finish event to complete the State (for example action with every frame logic).
### Delayed Events
A lof of actions can be delayed, this mean action will be executed after some seconds of delay. You can use variables instead of constants in action logic.
### Every Frame
Some actions can be triggered every frame. This type of actions have no finish conditions and lasts forever(until states will be changed in other way). If in State you have several every frame actions, they will keep their execution order.
### Periodic events
The logic is similar to Every Frame actions, but they have time between their execution. For example - trigger action every second. This actions also deferred and have no condition to finish.
|
Java
|
UTF-8
| 3,252 | 2.4375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.littleshoot.proxy;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class that keeps track of the cached HTTP chunks for a single HTTP response.
*/
public class DefaultCachedHttpChunks implements CachedHttpChunks {
public boolean isComplete() {
// TODO Auto-generated method stub
return false;
}
public boolean writeAllChunks(Channel channel) {
// TODO Auto-generated method stub
return false;
}
public void cache(HttpChunk chunk, ChannelBuffer encoded) {
// TODO Auto-generated method stub
}
/*
private final Logger log = LoggerFactory.getLogger(getClass());
private final CacheManager cacheManager;
private volatile int chunkCount = 0;
private final String uri;
private volatile boolean complete = false;
private final ChannelFutureListener writeListener;
public DefaultCachedHttpChunks(final CacheManager cacheManager,
final HttpRequest httpRequest,
final ChannelFutureListener writeListener) {
this.cacheManager = cacheManager;
this.writeListener = writeListener;
this.uri = ProxyUtils.cacheUri(httpRequest);
}
public void cache(final HttpChunk chunk, final ChannelBuffer encoded) {
final Cache cache =
this.cacheManager.getCache(ProxyConstants.CHUNK_CACHE);
final String chunkUri = this.uri + chunkCount;
log.info("Caching chunk {}", chunkUri);
final Element elem = new Element(chunkUri, encoded);
cache.put(elem);
if (chunk.isLast()) {
this.complete = true;
}
chunkCount++;
}
public boolean isComplete() {
return complete;
}
public boolean writeAllChunks(final Channel channel) {
if (!complete) {
throw new IllegalStateException(
"Trying to write incomplete cached chunks!!");
}
final Cache cache =
this.cacheManager.getCache(ProxyConstants.CHUNK_CACHE);
ChannelFuture cf = null;
for (int i = 0; i < chunkCount; i++) {
final String chunkUri = this.uri + i;
final Element elem = cache.get(chunkUri);
if (elem == null) {
// This indicates a serious problem. The cache has expelled
// a chunk in the middle of us trying to write the responses.
log.error("Could not find chunk!!! {}", chunkUri);
throw new IllegalStateException("Missing chunk for: "+chunkUri);
}
final ChannelBuffer encoded = (ChannelBuffer) elem.getObjectValue();
cf = channel.write(encoded);
}
if (cf == null) {
log.error("Channel future is null?");
throw new IllegalStateException("No future? Chunks: "+chunkCount);
}
cf.addListener(this.writeListener);
return true;
}
*/
}
|
Rust
|
UTF-8
| 2,089 | 3.28125 | 3 |
[
"MIT"
] |
permissive
|
use std::fs::{File,read_dir};
use std::io::{BufReader,BufRead};
use std::path::Path;
/// Return true if a file should regenerated
pub fn source_changed<P: AsRef<Path>>(source: P, dest: P) -> bool {
let file_mod = source.as_ref().metadata().unwrap().modified().unwrap();
if let Ok(metadata) = dest.as_ref().metadata() {
return metadata.modified().unwrap() > file_mod;
}
true
}
/// Scan directory for files with the following extension, using the provided `new`
/// method to create collected object infos.
pub fn scan_dir<F,T>(path: &str, extension: &str, new: F) -> Result<Vec<T>, String>
where F: Fn(&str) -> Option<T>
{
read_dir(path)
.map_err(|e| format!("{}", e))
.map(|dir|
dir.filter_map(|entry|
match entry {
Ok(entry) => match entry.path().to_str() {
Some(path) if !path.starts_with('.') && path.ends_with(extension) => new(path),
_ => None
},
_ => None
}
)
.collect()
)
}
/// Parse comments of a file for comment with the provided prefix (including comments
/// escape).
///
/// Return a tuple of `("operand", "value")`, such as comments would take
/// the following form:
///
/// ```
/// //: type my_binding_type
/// ```
///
pub fn parse(source: &str, prefix: &str) -> Option<Vec<(String,String)>> {
File::open(source).ok().map(|file|
BufReader::new(file).lines()
.filter_map(move |l| {
let l = &l.unwrap();
let l = l.trim_start();
match l.starts_with(prefix) {
true => Some(l.replace(prefix,"").trim().to_string()),
false => None
}
})
.map(move |l| {
let mut l = l.trim().splitn(2,' ');
let (a,b) = (l.next().unwrap(), l.next().unwrap());
(String::from(a.trim()), String::from(b.trim()))
})
.collect()
)
}
|
Markdown
|
UTF-8
| 4,843 | 3.515625 | 4 |
[] |
no_license
|
### 代理模式
***
> 代理模式就是由代理对象去帮核心对象完成一些前期和后期工作。
>
> 代理对象先调用自己的方法完成前期铺垫,然后调用核心对象的方法完成核心功能,然后再调用自己的方法完成后期扫尾
>
> 朝阳经纪公司可以看作一个代理对象,歌手周杰伦可以看作核心对象。经纪公司调用自己的方法去签合同,布置场地,接送歌手完成前期铺垫。然后调用周杰伦的方法唱歌完成核心功能,再调用自己的方法打扫场地完成后期扫尾
>
> 代理类和核心类最好是实现同一个接口,这样后期用起来比较方便。例如Thread类也实现了Runnable接口,也有run方法
#### 静态代理模式
> 静态代理模式表示代理类是我们自己写的。动态代理模式表示代理类是系统自动生成的
``` java
/**
* 定义一个接口
* 代理类和核心类都要实现这个接口
*/
public interface VocalRecital {
void selectArea();
void sing();
void cleanArea();
}
```
``` java
/**
* 定义核心类,实现前期和后期功能的代码这里不用编写
*/
public class Singer implements VocalRecital {
@Override
public void selectArea() {
}
@Override
public void sing() {
System.out.println("歌手唱了一首歌");
}
@Override
public void cleanArea() {
}
}
```
``` java
/**
* 定义一个代理类,和核心类实现同一个接口
* 前期和后期工作由代理类完成
* 核心工作由代理类调用核心对象的方法来实现
*/
public class Agent implements VocalRecital {
Singer singer;
public Agent(Singer s) {
this.singer = s;
}
@Override
public void selectArea() {
System.out.println("经纪公司选择好了场地");
}
@Override
public void sing() {
singer.sing(); //调用歌手的唱歌方法来完成核心功能
}
@Override
public void cleanArea() {
System.out.println("经纪公司打扫好了场地");
}
}
```
#### 动态代理模式
> 动态代理表示代理类是动态生成的
>
> 动态代理的实现方法有JDK自带的动态代理、javaassist字节码操作库实现、CGLIB、ASM
>
> 和静态代理相比,动态代理中接口中所有的方法调用处理器一个集中的方法中处理,这样我们可以更加灵活和统一的处理众多的方法
>
> 在动态代理中,我们要用到接口、接口的实现类、处理器类和Proxy类
``` java
/**
* 定义一个接口,核心类和后期生成的代理类都要转换为这个接口型
*/
public interface Singer {
void sing();
void sayBye();
}
```
``` java
/**
* 定义一个核心类,实现接口
*/
public class MrZhou implements Singer {
@Override
public void sing() {
System.out.println("I am zhoujielun");
}
@Override
public void sayBye() {
System.out.println("byebye");
}
}
```
``` java
/**
* 定义一个处理器
* 核心对象传输进来
*/
public class SingerHandler implements InvocationHandler {
Singer singer;//核心对象
public SingerHandler(Singer singer) {
this.singer = singer;
}
/**
* 这个method形参是反射包下的method型
* 我们最后会调用Proxy.newProxyInstance()获得一个代理对象,将代理对象强转为核心对象实现的那个接口
* 通过代理对象调用核心对象的方法时,就是通过method的invoke方法
* 我们可以在invoke方法的前后,加上一些语句,完成我们在静态代理中完成的功能
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("选择场地");
method.invoke(singer,args);//调用singer的某个方法,参数是args
System.out.println("收尾");
return null;
}
}
```
``` java
public class Test2 {
public static void main(String[] args) {
Singer mrZhou = new MrZhou(); //创建核心对象
SingerHandler handler = new SingerHandler(mrZhou); //创建处理器对象
/**
* 创建一个代理对象,参数为类加载器、Class实例数组和处理器对象
* 这个Class实例数组里面,是代理类需要实现的接口
* 返回值类型用接口类型将其转换
*/
Singer prox = (Singer)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),
new Class[]{Singer.class},handler);
/**
* 因为代理类也实现了和核心类一样的接口
* 所以核心类的方法,代理类都有
* 只不过代理类中方法的实现是通过调用handler中的invoker方法
*/
prox.sing();
}
}
```
|
C
|
UTF-8
| 1,377 | 3.296875 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
struct Stack
{
int data;
struct Stack *next;
};
struct Stack *InitStack()
{
struct Stack *pHead;
pHead=(struct Stack*)malloc(sizeof(struct Stack));
pHead->next=NULL;
}
void Push(struct Stack *stack,int n,int e)
{
struct Stack *pTai=stack;
while(stack->next!=NULL)
{
n--;
if(n==0)
return;
stack=stack->next;
}
struct Stack *pHead;
pHead=(struct Stack *)malloc(sizeof(struct Stack));
pHead->data=e;
pHead->next=pTai->next;
pTai->next=pHead;
}
int Pop(struct Stack *stack)
{
int n;
if(stack->next==NULL)
return 0;
n=stack->next->data;
stack->next=stack->next->next;
return n;
}
void ListDisplay_L(struct Stack *list)
{
list=list->next;
while(list!=NULL)
{
printf("%d ",list->data);
list=list->next;
}
printf("\n");
}
int main()
{
int m,n,sum,i,e;
char a[100];
struct Stack *stack;
stack=InitStack();
scanf("%d",&m);
scanf("%d%d",&n,&sum);
for(i=0;i<m;i++)
{
scanf("%s",a);
if(a[0]=='a')
{
scanf("%d",&e);
Push(stack,n,e);
}
else if(a[0]=='c')
{
sum=sum-Pop(stack);
if(sum<=0)
printf("chungeV5\n");
else
printf("%d\n",sum);
}
}
return 0;
}
|
PHP
|
UTF-8
| 563 | 2.6875 | 3 |
[] |
no_license
|
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "UTS";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die ("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE regis (
NAMA VARCHAR(200) NOT NULL,
PHONE INT(15),
EMAIL VARCHAR(50) NOT NULL,
ADDRESS TEXT NOT NULL,
CODE INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY)";
if (mysqli_query($conn, $sql)){
echo "Created successfuly";
} else {
echo "Error creating" . mysqli_error($conn);
}
mysqli_close($conn);
?>
|
C
|
UTF-8
| 2,888 | 3.28125 | 3 |
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "shell.h"
#include <string.h>
//buffer is the input string of characters
//args is the output array of arguments. It has already been created with argsSize slots.
//nargs as the number filled in that is passed back
void parseArgs(char* buffer, char** args, int argsSize, int *nargs) {
char *bufArgs[argsSize];
char **cp;
char *wbuf;
int i;
int j;
wbuf = buffer;
bufArgs[0] = buffer;
args[0] = buffer;
for (cp = bufArgs; (*cp = strsep(&wbuf, " \n\t")) != NULL;) {
if ((*cp != '\0') && (++cp >= &bufArgs[argsSize])) {
break;
}
}
for (j = i = 0; bufArgs[i] != NULL; i++) {
if (strlen(bufArgs[i]) > 0 ) {
args[j++] = bufArgs[i];
}
}
//Add the NULL as the end argument because we need that for later
*nargs = j;
args[j] = NULL;
}
int scanForIIR(char** args, int nargs) {
int i = 0;
while (i < nargs) {
if (strcmp(args[i], "<") == 0) {
return i;
}
i++;
}
return -1;
}
int scanForIOR(char** args, int nargs) {
int i = 0;
while (i < nargs) {
if (strcmp(args[i], ">") == 0) {
return i;
}
i++;
}
return -1;
}
void deleteAtIndex(char** args, int index) {
int i = index;
while(args[i + 1] != NULL) {
args[i] = args[i + 1];
i++;
}
args[i] = NULL;
//Printing args
int argIndex = 0;
while (args[argIndex] != NULL) {
printf("%s ", args[argIndex]);
argIndex++;
}
printf("\n");
}
int main() {
int exit = 0;
while(exit == 0) {
printf("%s>", getcwd(0,0));
char buffer[40];
fgets(buffer, 40, stdin);
char* args[10];
int nargs;
parseArgs(buffer, args, 10, &nargs);
//Printing args
int argIndex = 0;
while (args[argIndex] != NULL) {
printf("%s ", args[argIndex]);
argIndex++;
}
printf("\n");
char toBeInput[20];
char toBeOutput[20];
if (strcmp(args[0], "exit") == 0) {
exit = 1;
} else if (strcmp(args[0], "cd") == 0) {
int dir = chdir(args[1]);
if (dir != 0) {
printf("Directory not found\n");
}
} else {
int pid = fork();
if (pid == -1) {
printf("You don't do that!");
} else if (pid == 0) { //child
int inputRedir = scanForIIR(args, nargs);
printf("inputRedir = %d\n", inputRedir);
if (inputRedir != -1) {
strcpy(toBeInput, args[inputRedir + 1]);
deleteAtIndex(args, inputRedir + 1);
deleteAtIndex(args, inputRedir);
freopen(toBeInput, "r", stdin);
}
int outputRedir = scanForIOR(args, nargs);
printf("outpurRedir = %d\n", outputRedir);
if (outputRedir != -1) {
strcpy(toBeOutput, args[outputRedir + 1]);
deleteAtIndex(args, outputRedir + 1);
deleteAtIndex(args, outputRedir);
freopen(toBeOutput, "w", stdout);
}
execvp(args[0], args);
} else { //parent
int reapingInfo;
waitpid(pid, &reapingInfo, 0);
}
}
}
}
|
Python
|
UTF-8
| 2,208 | 3.375 | 3 |
[] |
no_license
|
#*****PYTHON POLL*****
#import os module
import os
#import csv module
import csv
csvdata = os.path.join('..', 'Resources', 'election_data.csv')
Voter_ID = []
County = []
Candidate = []
with open(csvdata) as csvfile:
#csv reader read file based on column separated values
csvreader = csv.reader(csvfile, delimiter=",")
header = next(csvreader)
for row in csvreader:
#extract Voter ID
Voter_ID.append(row[0])
#extract County
County.append(row[1])
#extract Candidate
Candidate.append(row[2])
#number of voters
Num_of_Voters = len(Voter_ID)
#print summary to screen
print(f"""Election Results
---------------------------------
Total Votes: {Num_of_Voters},
---------------------------------
""")
def unique(CandidateList):
unique_Candidates = []
for x in CandidateList:
# check if exists in unique_list or not
if x not in unique_Candidates:
unique_Candidates.append(x)
for x in unique_Candidates:
count = Candidate.count(x)
percent = round(100*count / Num_of_Voters,3)
print(x,": ", percent,"% ", "(",count,")")
unique(Candidate)
#print part 2 of summary to screen
print(f"""
---------------------------------
"Winner:" {max(Candidate)}
---------------------------------
""")
# #write summary to text file
Summary_File = open("Summarized_main.txt", "w")
#print summary to screen
Summary_File.write(f"""Election Results
---------------------------------
Total Votes: {Num_of_Voters},
---------------------------------
""")
def unique(CandidateList):
unique_Candidates = []
for x in CandidateList:
# check if exists in unique_list or not
if x not in unique_Candidates:
unique_Candidates.append(x)
for x in unique_Candidates:
count = Candidate.count(x)
percent = round(count*100/Num_of_Voters,3)
Summary_File.write(f"""{x},": ", {percent},"% ", "(",{count},")" """)
unique(Candidate)
#print part 2 of summary to screen
Summary_File.write(f"""
---------------------------------
Winner: {max(Candidate)}
---------------------------------
""")
Summary_File.close()
|
SQL
|
UTF-8
| 537 | 3.296875 | 3 |
[] |
no_license
|
/*
Convert Unnormalized Data to Normalized Table
Example data;
TableA: StudentID, StudentName, Mark1, Mark2, Mark3
TableB is normalized with the following columns:
TableB: StudentID, StudentName, SubjectID, Marks
Use the following SQL in SQL Server:
*/
Insert into TableB (StudentID, StudentName, SubjectID, Marks)
Select StudentID, StudentName, 'S1', Mark1
From TableA
Union All
Select StudentID, StudentName, 'S2', Mark2
From TableA
Union All
Select StudentID, StudentName, 'S3', Mark3
From TableA
Order by 1,2,3,4
|
Go
|
UTF-8
| 679 | 3.390625 | 3 |
[] |
no_license
|
package cmd
import (
"log"
"sync"
"time"
)
func New() *Command {
return &Command{
wg: &sync.WaitGroup{},
quit: make(chan struct{}),
}
}
type Command struct {
wg *sync.WaitGroup
quit chan struct{}
}
func (c *Command) Open() error {
c.wg.Add(1)
go c.monitor()
return nil
}
func (c *Command) Close() error {
close(c.quit)
c.wg.Wait()
// add artificial shutdown time for example
time.Sleep(5 * time.Second)
return nil
}
func (c *Command) monitor() {
defer c.wg.Done()
ticker := time.NewTicker(time.Second)
for {
select {
case <-c.quit:
log.Println("shutting down monitor")
return
case <-ticker.C:
log.Println("monitor check")
}
}
}
|
Shell
|
UTF-8
| 3,517 | 4.34375 | 4 |
[] |
no_license
|
#!/bin/sh
# Script to sanitize the input files of password dumps, and to send it to a logstash instance running on localhost:3515
#
# Run: ./sanitizePasswordDump.sh $inputfile $DumpName
#
# Inputfile is expected to contain per line: username:password
# Exports to logstash in the form of: DumpName EmailAddress Passowrd EmailDomain
#
# Author: Outflank B.V. / Marc Smeets / @mramsmeets
#
#
if [ $# -eq 0 ] ; then
echo '[X] Error - need name of file to work on as 1st parameter, and optinally name of dump as 2nd parameter.'
exit 1
fi
if [ ! -f $1 ] ; then
echo "[X] ERROR - $1 not found."
exit 1
fi
if [ ! hash uconv 2>/dev/null ] ; then
echo '[X] ERROR - uconv required (apt install icu-devtools)'
exit 1
fi
echo "[*] Working on file $1"
if [ $# -eq 1 ] ; then
echo '[!] Warning - missing name of dump as 2nd parameter, setting it to NoDumpName.'
DUMPNAME=NoDumpName
else
DUMPNAME=$2
fi
FILENAME=`basename $1`
STARTNRLINES=`wc -l $1|awk '{print $1}'`
echo "[*] Source file has $STARTNRLINES lines."
echo "[*] Will perform the following actions: "
echo "[+] Remove spaces"
echo "[+] Convert to all ASCII"
echo "[+] Remove non printable characters"
echo "[+] Remove lines without proper email address format"
echo "[+] Remove lines without a colon (errors)"
echo "[+] Remove lines with empty username"
echo "[+] Remove lines with empty passwords"
echo "[+] Remove really long lines (60+ char)"
echo "[+] Remove Russian email addresses (.ru)"
# remove spaces and convert to ASCII
cat $1|tr -d " "|uconv -i -c -s -t ASCII | \
# remove non printable chars
tr -dC '[:print:]\t\n' | \
# only valid email addresses
grep -E "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" | \
# remove without colon
grep -E \: | \
# remove empty usernames
grep -v -E ^\: | \
# remove empty passwords - find emailaddress folowd by :$
grep -v -E "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b\:$" | \
# remove long lines
grep -v '.\{60\}' > /tmp/sanitized$FILENAME
# remove Russion addresses
# grep -v -i ".ru" > /tmp/sanitized$FILENAME
ENDNRLINES=`wc -l /tmp/sanitized$FILENAME|awk '{print $1}'`
echo "[*] Halfway: sanitized file has $ENDNRLINES lines."
echo "[+] Rearranging in desired format"
# prefered input is name@emaildomain.com:password - we need these in format: Dumpname name@emaildomain.com password emaildomain.
# we use awk -v to insert the var of the Dumpname, and we use the split function to get only the domainname of the email address.
# However, the split function returns a number for the amount of items in the array. So we end up with:
# Dumpname name@emaildomain.com password 2 emaildomain.
# The if statement in the awk oneliner makes sure that in case of input file errors where the password field starts with a ":", we pick skip over that ":"
# We use the 2 to grep for all lines that have a username and password.
# We also grep for lines ending with a 1, for the highly unlikely cases where there was a 2 inserted due to input file errors
awk -v d="$DUMPNAME" -F":" '{if ($2=="")print d,$1,":"$3, split($1,a,"@") " " a[2]; else print d,$1,$2, split($1,a,"@") " " a[2]}' /tmp/sanitized$FILENAME |grep " 2 " |grep -v -E ' 1 $'| awk '{print $1,$2,$3,$5}' > /tmp/sanitized2$FILENAME
ENDNRLINES=`wc -l /tmp/sanitized2$FILENAME|awk '{print $1}'`
echo "[*] Sanitized file has $ENDNRLINES lines."
echo "[+] Sending to Logstash"
cat /tmp/sanitized2$FILENAME | nc -v 127.0.0.1 3515
echo "[*] Cleaning up /tmp dir"
rm /tmp/sanitized*$FILENAME
echo "[*] Done with file $1"
echo ""
|
C++
|
UTF-8
| 195 | 2.640625 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main()
{
cout<<"Intituto Tecnologico Superior de los Rios"<<endl;
cout<<"Mi nombre es: Eder Juarez Montuy" <<endl;
cout<<"I am programmer" <<endl;
}
|
Markdown
|
UTF-8
| 877 | 2.796875 | 3 |
[] |
no_license
|
Events
======
Java Listener framework
More detailed description will be ready soon
import static ru.vmsoftware.events.Events.*;
emit(this, KeyboardEvent.KEY_DOWN, keyCode);
Registrars
Emitters
Emitter is a holder of real emitter instance and allow to simplify event emitting,
especially when emitting from inner classes.
Was:
public void doWork() {
emit(this, MyEvent.EVENT_1);
// ... do some work ...
emit(this, MyEvent.EVENT_5, data);
}
Become:
void init() {
// ... somewhere in initialization code ...
emitter = Events.emitter(this);
}
public void doWork() {
// process implementation
emitter.emit(MyEvent.EVENT_1);
// ... do some work ...
emitter.emit(MyEvent.EVENT_5, data);
}
Thread safety:
Currently, Events isn't thread safe but there is a plans to make it.
|
Python
|
UTF-8
| 253 | 2.78125 | 3 |
[] |
no_license
|
def ru (numero,fila):
"""
>>> ru(5,[1,2,3,4,5])
'135-24'
"""
alunos = ""
stas = ""
for elem in fila:
if elem%2!=0:
alunos = alunos + str(elem)
else:
stas = stas + str(elem)
return alunos + "-" + stas
import pydojo
pydojo.testmod()
|
JavaScript
|
UTF-8
| 261 | 3.453125 | 3 |
[] |
no_license
|
/**
* @author goggio
*/
//exercise02
function fibonacci (n) {
fibonacci[0] = 0;
fibonacci[1] = 1;
if (!(n in fibonacci)) {
fibonacci[n] = fibonacci(n - 1) + fibonacci(n - 2);
}
return fibonacci[n];
}
//esempio con n=4
console.log(fibonacci(4));
|
Markdown
|
UTF-8
| 13,283 | 2.609375 | 3 |
[] |
no_license
|
# INDIGO DataCloud Tutorial: testing Ophidia for an astronomical image calibration task
Dear User,
in order to test Ophidia for the reduction of astronomical images you are kindly requested to follow
the procedure listed below. Before you start you should have already registered a new OphidiaLab
account and have received your credentials via email. If not, please register [here](https://ophidialab.cmcc.it/register/registration.html).
This tutorial presents the output of a use-case which is the result of a collaboration between
INAF (Trieste) and CMCC (Lecce) in the context of the INDIGO DataCloud European project for
the development and improvement of open-source cloud-based software.
## Introduction to the Tutorial
**Ophidia** is a framework for data intensive analysis that exploits advanced parallel computing
techniques and smart data distribution methods. In particular, the point of strength that makes
it extremely efficient in parallel data processing is the adoption of an array-based storage model
and a hierarchical data organization for the distribution of scientific datasets over multiple nodes.
The framework was developed in the context of climate change and it has been mostly used in
that field up to now. With this use-case we aim at potentially extending its use to the field of
astronomy. Ophidia has been developed within the CMCC Foundation. More information about
the project can be found here: <http://ophidia.cmcc.it/>.
**OpidiaLab** is a science gateway that offers to the end-user the possibility to exploit the full
Ophidia potential directly from the browser. It includes a JupyterHub installation for the creation
and sharing of documents containing live code through the Jupyter Notebooks. Python bindings
are available for Ophidia (PyOphidia). OphidiaLab gives also the possibility to use the Ophidia
Terminal which is basically an Ophidia client with a functionality similar to that of the bash shell.
Both these features will be explored during the tutorial.
The image calibration test is based on a set of calibration images (bias and flats) and science
images that are already loaded into OphidiaLab. If you want to reduce your own set of images
please sent an email to londero@oats.inaf.it.
Thanks to an extension, developed in the context of this use-case, Ophidia can now read the
FITS format. The latest release of the software includes this feature. If you are interested to install
it locally on your machine, please download the code and follow the procedure described [here](http://ophidia.cmcc.it/the-official-release-of-ophidia-v1-1-0-is-available/).
Once loaded into Ophidia, two metadata keys are selected to identify the FITS files: the filter
type (FLT ID) and the observation type (OBS TYPE). For the set of images specifically used for
this tutorial, three different filters are found: B JOHN 10, V JOHN 11 and R JOHN 12. The
observation type specifies if an image is of bias, flat or science type. In case you want to reduce
your own set of images you must know the values of these two metadata keys in advance because
they need to be set in the Python script.
The tutorial begins here.
## Log in to OphidiaLab
In this section we are going to log in into OphidiaLab gateway.
1. By using the credentials received by email, log in to OphidiaLab following the [link](https://ophidialab.cmcc.it/jupyter/hub/login).
2. Get acquainted with the environment: you can find a short guide explaining OphidiaLab
capabilities in your home folder under quickstart → Quick Start.ipynb
3. the folder INDIGO-FITS/fits-raw contains all the FITS files that are going to be used
for this calibration example
## The Ophidia Terminal
In this section you will become familiar with Ophidia Terminal, and you will learn how to
create, manage and delete datacubes.
1. Open an Ophidia Terminal by clicking on the New button on the top-right part of your home page and select _Terminal_.
2. Use the `pdd` command to check your current directory.
3. Use the `lsd` command to list directories and files.
4. Create an empty container called FITS2:
oph_createcontainer container=FITS2;dim=NAXIS2|NAXIS1;dim_type=int|int;
5. Load a FITS file (from the already available repository) in the container by giving the command:
oph importfits src path=[path=/data/INDIGO-FITS/fits-raw;
file=LRS.2016-06-06T20-30-03.925.fits];measure=mymeasure;
exp dim=NAXIS1;imp dim=NAXIS2;container=FITS2
6. Use the `ll` command to check that the cube has been loaded.
7. In order to check that all the metadata of the FITS file have been loaded, replace the stars with the PID number identifying your cube in the following command (see picture):
oph_metadata mode=read;cube=https://ophidialab.cmcc.it/ophidia/***/***;

8. To select the metadata value corresponding to the `FLT_ID` key replace the stars with the PID number identifying your cube as before:
oph_metadata mode=read;cube=https://ophidialab.cmcc.it/ophidia/***/***;
metadata_key=FLT_ID;metadata_type=text;metadata_value=test_text;
9. Delete the cube by issuing this command, where again the stars need to be replaced:
oph_delete cube=https://ophidialab.cmcc.it/ophidia/***/***;
10. If you experience problems try to remove the FITS2 container by using:
oph_deletecontainer container=FITS2;
and restart from scratch.
This section has shown that it is possible to execute Ophidia operators to manipulate the FITS files
directly from the Ophidia terminal. From the same terminal it is also possible to submit workflows
specified in a JSON file. If you want to learn more about the commands available for the Ophidia
Terminal you can check [this page](http://ophidia.cmcc.it/documentation/users/terminal/term_advanced.html).
## The Astronomical Image Calibration Process
The calibration process of astronomical images is crucial to have science ready data from images acquired with a telescope.
The figure below shows a raw image of the NGC5364 spiral galaxy as taken at the telescope without any calibration process.

The image is very noisy and the faintest spiral arms are mixed up with the background.
To improve the image quality for scientific purposes we need to use calibration frames and to
subtract them from the raw image.
We will use three kinds of calibration frames: flat field, dark and bias.
**Flat field frames**
Flat field frames are used to address unwanted problems in the optical path, including dust, vignetting and internal reflections.
Flat field frames are usually taken from the twilight sky.
The exposure time has to be chosen in such a way that the intensity level reached about 50% of the maximum.
Flat field frames should be taken for all filters used for the raw images, about 15-20 flat frames for each filter.
With these flat field frames we can generate a master flat field frame.
**Dark frames**
The purpose of a dark frame is to remove the non-image related thermal and electronic noise
that the CCD generated when capturing raw images. It also removes imperfections of the chip,
such as hot pixels. Since we are capturing the build up of thermal and electronic noise,
it is important to match the dark frame to the same conditions as the raw image,
this should include the same duration of exposure, chip temperature, gain, brightness and contrast.
Dark frames can be taken by closing the telescope, about 15-20 images with the same exposure length as the raw images.
With these dark frames we can generate a master dark frame.
**Bias frames**
When using a CCD chip, not all the pixels start out at a value of zero.
The purpose of a bias frame is to apply it to a dark and raw images to bring all the pixels on the CCD
to an equal starting value. Bias frames can be taken by closing the telescope and capturing
at the lowest possible time setting.
Bias frames should be taken at the same temperature and settings as the raw images, about 15-20 bias frames.
With these bias frames we can generate a master bias frame.
The figure below shows a summary of the procedure that we will follow to perform calibration of astronomical images.

## Run the Calibration Script from a Jupyter Notebook
Now we are going to explore the Jupyter environment to perform astronomical image calibration with Ophidia.
We have prepared a Jupyter Notebook that will guide towards this goal, using PyOphidia applied to standard astronomical
image calibration routines.
1. Log in to [OphidiaLab](https://ophidialab.cmcc.it/jupyter/hub/login)
2. Click on the Upload button on the top-right part of your home page and search for the file `fits_reduction_script.ipynb`,
which is contained inside this git repository.
3. Click on the blue Upload button that it appears in your home;
after that you should see the file `fits_reduction_script.ipynb` in your home directory.
4. Open it by clicking on it. The notebook is divided in Sections.
5. In Section I, fill in the credentials used for accessing OphidiaLab; this way you will connect
to the server instance. Notice that from PyOphidia the modules client and cube are
imported: the first is used for submitting any type of request (from simple tasks to
workflows) while the second makes the direct interaction with the cubes (in our case
the metadata and data of the FITS files) possible. Click on the cell and run it by using
the run cell button at the top of the page identified by the symbol:

6. In Section II, the FITS files are imported onto Ophidia by specifying the path and the
dimensions of the files (NAXIS1 and NAXIS2 for optical images). Click on the cell and
run it. The following two cells set the values of the metadata for the filters used and
for the observation type (flat, science or bias). Run both the cells. If you are analyzing
your own set of images, set the values for the filters here.
7. In Section III, the median of all the bias files is calculated; run the cell.
8. Sections IV-VI, the median for the flat files is set-up without doing the calculation. Each
cell performs the operation for one particular filter. Run the cells.
9. Sections VII-IX, the median for the science images is set-up without doing the calculation.
Each of the three cells performs the operation for a different filter. Run all the cells.
10. Sections X-XI, calculate the median for the flat and science images respectively. Run
all the cells.
11. In Section XII, the bias image obtained in Section III is subtracted from the three science
images resulting from Sections VII-IX. Run the cell.
12. In Section XIII, the bias image obtained in Section III is subtracted from the three flat
images resulting from Sections IV-VI. Run the cell.
13. In Section XIV, the three science images obtained in Section XII are divided by the flat
images obtained in Section XIII. Run the cell.
14. Finally the result of the calibration procedure is written to a FITS file by using the
oph_exportfits Ophidia operator. Replace the stars with your username. Run the cell.
15. Now you can download the file and visualize it by using for example [fv](https://heasarc.gsfc.nasa.gov/ftools/fv/fv_download.html).
The figure below shows a calibrated image of the NGC5364, where deatails are now clearly visible.

In case you get stuck and want to run all the cells again, first remove all the cubes by
using the Ophidia Terminal. Do the following: first issue ll to check the status of the
loaded cubes; then remove all the cubes by the command oph_delete cube=[***:***].
The stars have to be replaced by the last number characterizing a cube PID.
This section has shown the structure of the calibration script and the flexibility of the Jupiter
Notebooks. The script can be easily adapted to other calibration tasks according to the needs of
the user, therefore feel free to explore and edit it.
## Considerations on the performance
There are 100 cores all together on the CMCC cluster and the script you have tested uses
2 cores for each task. In order to improve the performance you can increase the number of
cores and measure the time elapsed by using a structure of this type:
import time
start = time.time()
end = time.time()
print(end - start)
Remember that there is a number of users logged into the system so the performance can
vary depending on the load on the system.
## Conclusions and Final Remarks
This tutorial has shown how to use Ophidia for an astronomical image calibration task. In
order to make Ophidia competitive with other already available software and to extend its
use also to other astronomical analysis tasks, further development of the code is needed. To
this end it is important to us if you could express your degree of satisfaction with this tutorial
and we would also like to know your opinion on a possible future extension of the Ophidia
capabilities to the astronomical field. Would it be valuable for your research? The survey
you are asked to fill in can be found following this [link](https://form.jotformeu.com/72554203448354).
Thank you for your cooperation.
|
Python
|
UTF-8
| 2,261 | 3.375 | 3 |
[] |
no_license
|
'''
This module includes some commonly used algorithms.
Created on Oct 17, 2013
@author: zhil2
'''
import math
def subsetSumToX(dictCost,targetSum):
'''
Return a subset in dictCost that sum to targetSum.
Example:
>>> subsetSumToX({'x':3,'y':1,'z':5,'w':8},13)
['w', 'z']
>>> subsetSumToX({'x':3,'y':1,'z':5,'w':8},10)
[]
>>> subsetSumToX({'x':3,'y':1,'z':5,'w':8},1)
['y']
'''
for v in dictCost.itervalues():
assert(v>0)
targetSumKey=id(dictCost)
dictCost[targetSumKey]=-targetSum
subset=_subset_summing_to_zero(dictCost)
if not subset:#subset is []
return []
else:
assert(targetSumKey in subset)
subset.remove(targetSumKey)
return subset
def _subset_summing_to_zero(activities):
'''
Subset sum to zero problem.
Example:
>>> _subset_summing_to_zero({'x':-3,'y':-2,'z':5,'w':8})
['x', 'y', 'z']
>>> _subset_summing_to_zero({'x':-3,'y':-2,'z':6,'w':8})
[]
'''
subsets = {0: []}
for (activity, cost) in activities.iteritems():
old_subsets = subsets
subsets = {}
for (prev_sum, subset) in old_subsets.iteritems():
subsets[prev_sum] = subset
new_sum = prev_sum + cost
new_subset = subset + [activity]
if 0 == new_sum:
new_subset.sort()
return new_subset
else:
subsets[new_sum] = new_subset
return []
def excludeRange(r,i):
'''
Return the list of range equal to range r excluding range i
'''
rL,rR=r
iL,iR=i
assert(rL<=rR)
assert(iL<=iR)
e=[(rL,iL-1),(iR+1,rR)]
#remove negative intervals
e=[(low,high) for low,high in e if low<=high]
return e
def getNeighbor(trial):
'''
Return a number that is in the neighbor of 0.
Examples:
>>> print getNeighbor(0)
0
>>> print getNeighbor(1)
1
>>> print getNeighbor(2)
-1
>>> print getNeighbor(3)
2
>>> print getNeighbor(4)
-2
>>> print getNeighbor(5)
3
>>> print getNeighbor(6)
-3
'''
return int(math.ceil(trial/2.0)*((trial%2)*2-1))
if __name__ == '__main__':
import doctest
print doctest.testmod()
|
Go
|
UTF-8
| 2,403 | 3.4375 | 3 |
[] |
no_license
|
package server
import (
"net"
"strings"
)
type User struct {
Name string
Addr string
C chan string
conn net.Conn
server *Server
}
// 创建一个User的API
func NewUser(conn net.Conn, server *Server) *User {
userAddr := conn.RemoteAddr().String()
user := &User{
Name: userAddr,
Addr: userAddr,
C: make(chan string),
conn: conn,
server: server,
}
// 启动监听当前user channel消息的goroutine
go user.ListenMessage()
return user
}
//监听当前user channel的方法,一旦有消息,就直接发送给对端客户端
func (u *User) ListenMessage() {
for {
msg := <-u.C
_, _ = u.conn.Write([]byte(msg + "\n"))
}
}
func (u *User) Online() {
// 用户上线
u.server.mapLock.Lock()
u.server.OnlineMap[u.Name] = u
u.server.mapLock.Unlock()
// 广播
u.server.BroadCast(u, "已上线.")
}
func (u *User) Offline() {
// 用户下线
u.server.mapLock.Lock()
delete(u.server.OnlineMap, u.Name)
u.server.mapLock.Unlock()
// 广播
u.server.BroadCast(u, "下线啦.")
}
func (u *User) DoMessage(msg string) {
if msg == "who" {
// 查询当前在线用户
u.server.mapLock.Lock()
for _, user := range u.server.OnlineMap {
onlineMsg := "[" + user.Addr + "]" + user.Name + "在线...\n"
u.SendMsg(onlineMsg)
}
u.server.mapLock.Unlock()
} else if len(msg) > 7 && msg[:7] == "rename|" {
// 修改名称: rename|张三
newName := strings.Split(msg, "|")[1]
_, ok := u.server.OnlineMap[newName]
if ok {
u.SendMsg("当前用户名被使用\n")
} else {
u.server.mapLock.Lock()
delete(u.server.OnlineMap, u.Name)
u.server.OnlineMap[newName] = u
u.server.mapLock.Unlock()
u.Name = newName
u.SendMsg("您已更新用户名:" + u.Name + "\n")
}
} else if len(msg) > 4 && msg[:3] == "to|" {
// 私聊: to|张三|xxx
s := strings.Split(msg, "|")
remoteName := s[1]
if remoteName == "" {
u.SendMsg("消息格式不正确,请使用\"to|张三|xxx\"格式.\n")
return
}
remoteUser, ok := u.server.OnlineMap[remoteName]
if ok {
u.SendMsg("该用户名不存在\n")
return
} else {
content := s[2]
if content == "" {
u.SendMsg("无消息内容,请重发.\n")
return
}
remoteUser.SendMsg(u.Name + "对您说:" + content)
}
} else {
u.server.BroadCast(u, msg)
}
}
func (u *User) SendMsg(msg string) {
_, _ = u.conn.Write([]byte(msg))
}
|
C#
|
UTF-8
| 538 | 2.875 | 3 |
[] |
no_license
|
using System;
using Xunit;
using InsertQuery;
namespace InsertQueryTest
{
public class QueryTest
{
[Fact]
public void Simple()
{
var expect = "INSERT Foo SET (A, B) VALUES (@A, @B)";
var actual = Query.Construct(new Foo());
Assert.Equal(expect, actual);
}
public class Foo
{
public int A { get; } = 1;
public string B { get; } = "B";
private string C { get; } = "C";
}
}
}
|
C++
|
UTF-8
| 808 | 2.84375 | 3 |
[] |
no_license
|
#ifndef _BASE64_H_
#define _BASE64_H_
#include <string>
/**
* @brief Helpers namespace aggregates functions that are not part of core functionalities but are involved in some
* code procedure.
*
*/
namespace Helpers {
/**
* @brief Base64 encoder and decoder.
*
*/
class Base64 {
public:
/**
* @brief Encode string to base64 string.
*
* @param std::string data data to be encoded.
* @return std::string encoded data.
*/
static std::string Encode(const std::string &data);
/**
* @brief Decode base64 string.
*
* @param data Encoded data.
* @return std::string Decoded data.
*/
static std::string Decode(const std::string &data);
};
}
#endif
|
Python
|
UTF-8
| 2,811 | 2.828125 | 3 |
[] |
no_license
|
import gzip
import math
import pickle
from pathlib import Path
import numpy as numpy
import requests
import torch
from matplotlib import pyplot
from tqdm import tqdm
# mnist is a dataset of black-white img of digits
data_path = Path('data')
path = data_path / 'mnist'
path.mkdir(parents=True, exist_ok=True)
url = "http://deeplearning.net/data/mnist/"
filename = "mnist.pkl.gz"
file_path = path / filename
if not file_path.exists():
content = requests.get(url + filename).content
file_path.open('wb').write(content)
with gzip.open(file_path.as_posix(), 'rb') as f:
data = pickle.load(f, encoding='latin-1')
((x_train, y_train), (x_valid, y_valid), _) = data
# img = pyplot.imshow(x_train[0].reshape(28, 28), cmap='gray')
# pyplot.show()
data = (x_train, y_train, x_valid, y_valid)
x_train, y_train, x_valid, y_valid = map(torch.tensor, data)
n_samples, dim_sample = x_train.shape
# print(x_train, y_train)
# print(x_train.shape)
# print(y_train.min(), y_train.max())
# pytorch model
weights_dim = 10
# initalize with the Xavier initialization: rand / sqrt(n)
weights = torch.randn(dim_sample, weights_dim) / math.sqrt(n_samples)
weights.requires_grad_() # other form to require_grad
bias = torch.zeros(weights_dim, requires_grad=True)
def log_softmax(x):
return x - x.exp().sum(-1).log().unsqueeze(-1)
def model(x):
return log_softmax(x @ weights + bias)
batch_size = 3
x = x_train[:batch_size]
preds = log_softmax(x @ weights + bias)
# in the reality the log part is in log_softmax
def negative_log_likehood(input, target):
# Only select the elements correspondig to the correct ones
return -input[range(target.shape[0]), target].mean()
loss_func = negative_log_likehood
y = y_train[:batch_size]
loss = loss_func(preds, y)
print(f'The loss function is : {loss} ')
def accuracy(outputs, y):
preds = torch.argmax(outputs, dim=1)
return (preds == y).float().mean()
print(accuracy(preds, y))
learning_rate = 0.1
epochs = 4
for epoch in tqdm(range(epochs)):
for i in range((n_samples - 1) // batch_size + 1):
start_i = i * batch_size
end_i = start_i + batch_size
xb = x_train[start_i:end_i]
yb = y_train[start_i:end_i]
pred = model(xb)
loss = loss_func(pred, yb)
loss.backward()
# at every operation the gradient is recorded,
# in this case must be avoid with no_grad
with torch.no_grad():
weights -= weights.grad * learning_rate
bias -= bias.grad * learning_rate
# the gradient accumulate by default, need reset
weights.grad.zero_()
bias.grad.zero_()
outputs = model(x_valid)
loss = loss_func(outputs, y_valid)
acc = accuracy(outputs, y_valid)
print(f'The loss is : {loss}, accuracy : {acc}')
|
Java
|
UTF-8
| 375 | 3.28125 | 3 |
[] |
no_license
|
package com.d4.InnerClasses;
class Test
{
public void calc()
{
class Add
{
int sum(int n1,int n2)
{
return n1+n2;
}
}
Add o=new Add();
System.out.println(o.sum(1, 2));
System.out.println(o.sum(11, 22));
}
}
class MLICDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test t=new Test();
t.calc();
}
}
|
C++
|
UTF-8
| 5,632 | 2.921875 | 3 |
[] |
no_license
|
// ---------------------------------------------------------------------------
// This shows a simple application that uses an lp3::input::Controller to
// move a face around the screen. It also shows all device keys that being
// pressed.
// ---------------------------------------------------------------------------
#include <boost/format.hpp>
#include <lp3/gfx.hpp>
#include <lp3/input.hpp>
#include <lp3/main.hpp>
namespace core = lp3::core;
namespace gfx = lp3::gfx;
namespace input = lp3::input;
namespace sdl = lp3::sdl;
void set_default_controls(lp3::input::Controls & controls) {
// Tell the input system that, if it's available, we'd love to use a
// gamepad.
input::PreferredButtonMapping game_pad_mapping;
game_pad_mapping.device = input::PreferredDevice::GAME_PAD;
// Set the mapping. The names of the keys for each device are in the order
// of the virtual control buttons we wish to assign.
game_pad_mapping.set_mapping(
"Left Analog Up", "Left Analog Down", "Left Analog Left",
"Left Analog Right", "A", "B", "X");
// Tell the input system that our second choice is for keyboard controls.
input::PreferredButtonMapping kb_mapping;
kb_mapping.device = input::PreferredDevice::KEYBOARD;
// Ditto.
kb_mapping.set_mapping(
"Up", "Down", "Left", "Right", "X", "C", "Z");
std::vector<input::PreferredButtonMapping> preferred_mappings = {
game_pad_mapping, kb_mapping
};
controls.set_defaults(0, preferred_mappings);
}
int _main(core::PlatformLoop & loop) {
core::LogSystem log;
sdl::SDL2 sdl2(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK| SDL_INIT_GAMECONTROLLER);
input::Controls controls;
set_default_controls(controls);
core::MediaManager media;
const glm::vec2 screen_size(1280, 720);
const glm::vec2 tile_size(16, 16);
const glm::vec2 map_size = screen_size / tile_size;
gfx::Window window("Lp3::Input Example", screen_size);
glEnable(GL_DEPTH_TEST);
gfx::Texture texture_text{IMG_Load_RW(media.load("Engine/text.bmp"), 0)};
gfx::ElementWriter<gfx::TexVert> elements(
lp3::narrow<std::size_t>((map_size.x * map_size.y + 1) * 4));
gfx::programs::SimpleTextured program;
gfx::TileMap tm{ map_size };
auto pokey_quad = elements.add_quad();
auto quads = tm.create_quads(elements);
tm.write({20, 1}, "~ INSTRUCTIONS ~", true);
int tm_y = 2;
auto write_text = [&](const char * msg, int button_index) {
// Find out what the virtual button is set to now.
auto button_config = controls.get_button_configuration(0, button_index);
auto text = str(boost::format(
"%s: %s %s") % msg % button_config.first % button_config.second);
tm.write({ 1, tm_y }, text.c_str(), true);
++ tm_y;
};
write_text("Up", 0);
write_text("Down", 1);
write_text("Left", 2);
write_text("Right", 3);
write_text("Face", 4);
write_text("Snail", 5);
write_text("Cat", 6);
glm::vec2 pokey_position = screen_size / glm::vec2(2.0, 2.0);
auto drawer = [&](const glm::mat4 & previous) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto _2d = gfx::create_2d_screen(previous, screen_size);
program.use();
program.set_mvp(_2d);
program.set_texture(texture_text.gl_id());
program.draw(elements);
};
const glm::vec2 faces[] = {
{1, 6}, // smiley face
{12, 6}, // snail
{13, 6} // cat
};
const glm::vec2 texture_resolution(256.0f, 128.0f);
glm::vec2 current_avatar = faces[0];
return loop.run([&]() {
bool quit = false;
SDL_Event e;
if (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT:
quit = true;
break;
case SDL_WINDOWEVENT:
window.handle_events(e.window);
break;
}
}
// Must be called each frame
controls.update();
// Print out currently pressed keys
tm.write({ 1, 19 }, "Currently pressed keys:", true);
int row = 20;
tm.fill({0, 20}, {map_size.x, map_size.y - 20}); // clear text
for (const auto & key : controls.get_current_pressed_keys()) {
auto text = str(boost::format("%s %s") % key.first % key.second);
tm.write({ 1, row }, text.c_str(), true);
row += 1;
}
input::Control & controller = controls.get_control(0);
// Move avatar
pokey_position.y +=
(controller.analog_state(0) * -1.0f) + controller.analog_state(1);
pokey_position.x +=
(controller.analog_state(2) * -1.0f) + controller.analog_state(3);
// Change faces
if (controller.state(4)) {
current_avatar = faces[0];
} else if (controller.state(5)) {
current_avatar = faces[1];
} else if (controller.state(6)) {
current_avatar = faces[2];
}
glm::vec2 half_pokey(8, 8);
gfx::upright_quad(
pokey_quad,
pokey_position - half_pokey,
pokey_position + half_pokey,
0.0f,
(glm::vec2(16, 16) * current_avatar) / texture_resolution,
(glm::vec2(16, 16) * (current_avatar + glm::vec2(1, 1)))
/ texture_resolution);
tm.set_quads({ 32.0f, 0.0f }, 0.0f, tile_size, quads, tile_size,
texture_text.size());
window.render(drawer);
return !quit;
});
return 0;
}
LP3_MAIN(_main)
// ~end-doc
|
Python
|
UTF-8
| 785 | 2.8125 | 3 |
[] |
no_license
|
import unittest
import os
import sys
lib_path = os.path.abspath('../src')
sys.path.append(lib_path)
from mapredoopy import mappy
def square(x):
return x*x
class TestSumOfSquares(unittest.TestCase):
def test_wordcount_p1(self):
seq = range(518)
m = reduce(lambda x,y: x+y, mappy(square, seq, 1))
r = reduce(lambda x,y: x+y, map(square, seq))
assert m == r
def test_wordcount_p4(self):
seq = range(4232)
m = reduce(lambda x,y: x+y, mappy(square, seq, 4))
r = reduce(lambda x,y: x+y, map(square, seq))
assert m == r
def test_wordcount_p32(self):
seq = range(7932)
m = reduce(lambda x,y: x+y, mappy(square, seq, 32))
r = reduce(lambda x,y: x+y, map(square, seq))
assert m == r
if __name__ == '__main__':
unittest.main()
|
C++
|
UTF-8
| 1,318 | 3.265625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
bool store[1000][1000];
int main (void)
{
unsigned int n, m, r1, c1, r, c, testcase;
cin >> testcase;
while (testcase--)
{
memset(store, false, sizeof(store));
cin >> n >> m;
cin >> r1 >> c1;
cin >> r >> c;
r1--; c1--;
r--; c--;
store[r1][c1]= true;
// Run the loop
while ((r1 < n) && (c1 < m) && !((r1 == r) && (c1 == c)))
{
cout << "Checking: " << r1 << " " << c1;
if (((c1 + 1) < m) && !store[r1][c1+1]) {c1++; store[r1][c1] = true;}
else if (c1 && ((c1 - 1) < m) && (!store[r1][c1-1])) {c1--; store[r1][c1] = true;}
else if (r1 && ((r1 - 1) < n) && (!store[r1-1][c1])) {r1--; store[r1][c1] = true;}
else if (((r1 + 1) < n) && (!store[r1+1][c1])) {r1++; store[r1][c1] = true;}
cout << " :Checked: " << r1 << " " << c1 << endl;
}
store[r][c] = true;
// we have reached our destination
if (((c+1) < m) && !store[r][c+1]) cout << "Right";
else if (c && !store[r][c-1]) cout << "Left";
else if (r && !store[r-1][c]) cout << "Front";
else if (((r+1) < n) && !store[r+1][c]) cout << "Back";
else cout << "Over";
cout << endl;
}
}
|
Markdown
|
UTF-8
| 3,605 | 2.78125 | 3 |
[] |
no_license
|
#### **Title**
Add `incubate_before` and `temperature` to spectrophotometry instructions
#### **Authorship**
Peter Lee <peter@transcriptic.com>
Ross Trundy <ross@transcriptic.com>
#### **Motivation**
Addition of `incubate_before` and `temperature` parameters to spectrophotometry instructions allow for the possibility of recording spectrophotometric observations over a period of time by adding incubation for a `duration` with the option of `shaking` prior to reading a plate and setting `temperature` during the entire instruction recording. Amongst many additional functionalities, these parameters will enable the study of growth and enzyme kinetics, aid in resolving bubbles prior to reading, allow for readings at physiological temperatures, and permit storage for light-sensitive assays prior to reading.
#### **Proposal**
The spectrophotometry instruction groups `fluorescence`, `absorbance` and `luminescence` should accept the additional optional parameters of `incubate_before` and `temperature`.
```
/* dictionary of parameters governing conditions prior to reading */
`incubate_before` - object
/* duration of incubation prior to reading */
`duration` - time
/* shake parameters during `time` prior to read, optional */
`shaking` - object
`amplitude` - distance
`orbital` - bool // true for orbital, false for linear
/* temperature to heat plate environment during incubation and reading */
`temperature` - temperature
```
Vendor specific limitations may apply to the availability of these optional parameters.
```
[
{
"op": "absorbance",
"object": container,
"wells": [
well
],
"wavelength": length,
"num_flashes": integer,
"dataref": string,
/* optional */
"temperature": temperature,
/* optional */
"incubate_before": {
/* required if `incubate_before` specified */
"duration": time,
/* optional */
"shaking": {
/* required if `shaking` specified */
"amplitude": length,
/* required if `shaking` specified */
"orbital": bool
}
}
},
{
"op": "fluorescence",
"object": container,
"wells": [
well
],
"excitation": length,
"emission": length,
"num_flashes": integer,
"dataref": string,
/* optional */
"temperature": temperature,
/* optional */
"incubate_before": {
/* required if `incubate_before` specified */
"duration": time,
/* optional */
"shaking": {
/* required if `shaking` specified */
"amplitude": length,
/* required if `shaking` specified */
"orbital": bool
}
}
},
{
"op": "luminescence",
"object": container,
"wells": [
well
],
"dataref": string,
/* optional */
"temperature": temperature,
/* optional */
"incubate_before": {
/* required if `incubate_before` specified */
"duration": time,
/* optional */
"shaking": {
/* required if `shaking` specified */
"amplitude": length,
/* required if `shaking` specified */
"orbital": bool
}
}
}
]
```
#### **Execution**
All parameters of the instruction should be completed on a single device such that the time from `incubate_before` to reading the plate is minimized. Not all vendors/devices will be able to support the additional optional parameters.
#### **Compatibility**
This ASC specifies new fields for existing instructions. Spectrophotometry instructions without these optional parameters will read plates without shaking, heating, or delay - duplicating the previous behavior.
|
TypeScript
|
UTF-8
| 2,174 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
import { extendMethod, extension } from './utils'
export default extension('canvas.to-data-url-promise', (fabric) => {
/**
* Extend object.
*/
fabric.util.object.extend(fabric.Object.prototype, {
loadingPromise: null,
})
/**
* Extend image.
*/
fabric.util.object.extend(fabric.Image.prototype, {
initialize: extendMethod(fabric.Image, 'initialize', function () {
this.loadingPromise = new Promise((resolve) => {
const element = this.getElement() as HTMLImageElement
if (element && !element.complete) {
element.addEventListener('load', resolve)
} else {
resolve()
}
})
}),
})
/**
* Extend StaticCanvas.
*/
fabric.util.object.extend(fabric.StaticCanvas.prototype, {
/**
* Get the list of loading objects.
*/
getLoadingPromises(this: fabric.StaticCanvas) {
const promises: Promise<any>[] = []
this._objects.forEach(function _(object) {
if (object.loadingPromise) {
promises.push(object.loadingPromise)
}
if (object instanceof fabric.Group) {
object._objects.forEach(_)
}
})
if (this.backgroundImage instanceof fabric.Image && this.backgroundImage?.loadingPromise) {
promises.push(this.backgroundImage.loadingPromise)
}
if (this.overlayImage instanceof fabric.Image && this.overlayImage.loadingPromise) {
promises.push(this.overlayImage.loadingPromise)
}
return promises
},
/**
* Load all objects before return data url.
*/
toDataURL: ((toDataURL: fabric.StaticCanvas['toDataURL']) => {
return async function (this: fabric.StaticCanvas, options?: fabric.IDataURLOptions) {
await Promise.all(this.getLoadingPromises())
return toDataURL.call(this, options)
}
})(fabric.StaticCanvas.prototype.toDataURL),
})
})
declare module 'fabric' {
namespace fabric {
interface Object {
loadingPromise: null | Promise<any>
}
interface StaticCanvas {
toDataURL(options?: IDataURLOptions): Promise<string>
getLoadingPromises(): Promise<any>[]
}
}
}
|
Java
|
UTF-8
| 4,656 | 2.71875 | 3 |
[] |
no_license
|
package agent.aiwolf.kajiClient.reinforcementLearning;
import java.util.Map.Entry;
import org.aiwolf.common.data.Agent;
import org.aiwolf.common.data.Role;
import agent.aiwolf.kajiClient.lib.EnemyCase;
import agent.aiwolf.kajiClient.lib.Pattern;
/**
* Patternを抽象化したもの.Agentが違っていても,状態として同じならば同じものとして捉える
* @author kajiwarakengo
*
*/
public class Scene {
private static final int
WOLF_NUM = 2,
IS_SEER_HASH = 1,
IS_SEER_ALIVE_HASH = 2,
IS_MEDIUM_HASH = 4,
IS_MEDIUM_ALIVE_HASH = 8,
SEER_NUM_HASH = 16,
MEDIUM_NUM_HASH = SEER_NUM_HASH * (WOLF_NUM + 3),
BLACK_ENEMY_NUM_HASH = MEDIUM_NUM_HASH * (WOLF_NUM + 3),
WHITE_ENEMY_NUM_HASH = BLACK_ENEMY_NUM_HASH * (WOLF_NUM + 1),
GRAY_ENEMY_NUM_HASH = WHITE_ENEMY_NUM_HASH * 2,
WHITE_AGENT_NUM_HASH = GRAY_ENEMY_NUM_HASH * (WOLF_NUM + 2);
private boolean isSeer,
isSeerAlive,
isMedium,
isMediumAlive;
private int seerNum,
mediumNum,
blackEnemyNum,
whiteEnemyNum,
grayEnemyNum,
whiteAgentNum;
public Scene(Pattern p){
isSeer = (p.getSeerAgent() == null)? false: true;
isMedium = (p.getMediumAgent() == null)? false: true;
isSeerAlive = (p.getAliveAgents().contains(p.getSeerAgent()))? true: false;
isMediumAlive = (p.getAliveAgents().contains(p.getMediumAgent()))? true: false;
for(Entry<Agent, Role> set: p.getComingoutMap().entrySet()){
switch (set.getValue()) {
case SEER:
seerNum++;
break;
case MEDIUM:
mediumNum++;
break;
}
}
for(Entry<Agent, EnemyCase> set: p.getEnemyMap().entrySet()){
switch (set.getValue()) {
case black:
blackEnemyNum++;
break;
case gray:
grayEnemyNum++;
break;
case white:
whiteEnemyNum++;
break;
}
}
whiteAgentNum = p.getWhiteAgentSet().size();
}
public Scene getScene(Pattern p){
return new Scene(p);
}
public Scene(int hash){
whiteAgentNum = hash / WHITE_AGENT_NUM_HASH;
hash = hash % WHITE_AGENT_NUM_HASH;
grayEnemyNum = hash / GRAY_ENEMY_NUM_HASH;
hash = hash % GRAY_ENEMY_NUM_HASH;
whiteEnemyNum = hash / WHITE_ENEMY_NUM_HASH;
hash = hash % WHITE_ENEMY_NUM_HASH;
blackEnemyNum = hash / BLACK_ENEMY_NUM_HASH;
hash = hash % BLACK_ENEMY_NUM_HASH;
mediumNum = hash / MEDIUM_NUM_HASH;
hash = hash % MEDIUM_NUM_HASH;
seerNum = hash / SEER_NUM_HASH;
hash = hash % SEER_NUM_HASH;
isMediumAlive = (hash/IS_MEDIUM_ALIVE_HASH == 1)? true: false;
hash = hash % IS_MEDIUM_ALIVE_HASH;
isMedium = (hash/IS_MEDIUM_HASH == 1)? true: false;
hash = hash % IS_MEDIUM_HASH;
isSeerAlive = (hash/IS_SEER_ALIVE_HASH == 1)? true: false;
hash = hash % IS_SEER_ALIVE_HASH;
isSeer = (hash/IS_SEER_HASH == 1)? true: false;
}
public int getHashNum(){
/**
* private boolean isSeer,
isMedium;
private int blackEnemyNum,
whiteEnemyNum,
grayEnemyNum,
whiteAgnetNum;
*/
/*
* isSeer 2
* isMedium 2
* seerNum 5
* mediumNum 5
* blackNum 3
* whiteNum 2
* gray 4
* whiteAgent たくさん
*/
int hash = 0;
hash += (isSeer)? IS_SEER_HASH: 0;
hash += (isSeerAlive)? IS_SEER_ALIVE_HASH: 0;
hash += (isMedium)? IS_MEDIUM_HASH: 0;
hash += (isMediumAlive)? IS_MEDIUM_HASH: 0;
hash += seerNum * SEER_NUM_HASH;
hash += mediumNum * MEDIUM_NUM_HASH;
hash += blackEnemyNum * BLACK_ENEMY_NUM_HASH;
hash += whiteEnemyNum * WHITE_ENEMY_NUM_HASH;
hash += grayEnemyNum * GRAY_ENEMY_NUM_HASH;
hash += whiteAgentNum * WHITE_AGENT_NUM_HASH;
return hash;
}
public boolean isSeer() {
return isSeer;
}
public void setSeer(boolean isSeer) {
this.isSeer = isSeer;
}
public boolean isMedium() {
return isMedium;
}
public void setMedium(boolean isMedium) {
this.isMedium = isMedium;
}
public int getSeerNum() {
return seerNum;
}
public void setSeerNum(int seerNum) {
this.seerNum = seerNum;
}
public int getMediumNum() {
return mediumNum;
}
public void setMediumNum(int mediumNum) {
this.mediumNum = mediumNum;
}
public int getBlackEnemyNum() {
return blackEnemyNum;
}
public void setBlackEnemyNum(int blackEnemyNum) {
this.blackEnemyNum = blackEnemyNum;
}
public int getWhiteEnemyNum() {
return whiteEnemyNum;
}
public void setWhiteEnemyNum(int whiteEnemyNum) {
this.whiteEnemyNum = whiteEnemyNum;
}
public int getGrayEnemyNum() {
return grayEnemyNum;
}
public void setGrayEnemyNum(int grayEnemyNum) {
this.grayEnemyNum = grayEnemyNum;
}
public int getWhiteAgentNum() {
return whiteAgentNum;
}
public void setWhiteAgentNum(int whiteAgentNum) {
this.whiteAgentNum = whiteAgentNum;
}
}
|
Java
|
UTF-8
| 1,758 | 4.21875 | 4 |
[] |
no_license
|
/**
* This program shifts all characters within a string incrementally depending on the user's input.
* Authors: Sarah Peng
* Created: May 18th, 2019
*/
//Imports scanner.
import java.util.Scanner;
//Encrypts the user's message by shifting all the characters by a certain amount based on the input.
public class ComplexCaesarCipher
{
//Asks the user for information for the encryption, printing out the original and the incrementally shifted messages.
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
String plainText, shift;
int shiftNum, counter = 0;
boolean validEntry;
//Asks the user to input the message they want to encrypt.
System.out.print("Enter your message: ");
plainText = kb.nextLine();
//Prevents the user from inputing any other characters except for numbers between -25 to 25.
do
{
System.out.print("Choose the shifting value: ");
shift = kb.nextLine();
try
{
shiftNum = Integer.parseInt(shift);
//Prevents the user from entering an integer less than 25 or more than 25.
if (shiftNum < -25 || shiftNum > 25)
{
System.out.println("INVALID ENTRY. MUST BE AN INTEGER BETWEEN -25 TO 25");
validEntry = false;
}
else
validEntry = true;
}
catch (NumberFormatException e)
{
System.out.println("INVALID ENTRY. MUST BE AN INTEGER BETWEEN -25 TO 25");
validEntry = false;
}
}
while (validEntry == false);
//Prints the original and shifted messages.
shiftNum = Integer.parseInt(shift);
System.out.println("Plaintext: " + plainText);
System.out.print("Ciphertext: ");
for (int i = shiftNum; counter < plainText.length(); i++)
{
System.out.print(CaesarCipher.newChar(plainText, i, counter));
counter++;
}
}
}
|
TypeScript
|
UTF-8
| 302 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
module BP3D.Items {
/** Meta data for items. */
export interface Metadata {
/** Name of the item. */
itemName?: string;
/** Type of the item. */
itemType?: number;
/** Url of the model. */
modelUrl?: string;
/** Resizeable or not */
resizable?: boolean;
}
}
|
PHP
|
UTF-8
| 2,120 | 2.953125 | 3 |
[] |
no_license
|
<?php
///////////////////////////////////////////////
// Semesterproject - ECIN //
// Fachbereich Medien FH-Kiel - 4. Semester //
// Beschreibung : Footer //
// Ersteller : Sven Krumbeck //
// Stand : 22.05.19 //
// Version : 1.0 //
///////////////////////////////////////////////
//Controll Anzeigen für Debuggen
// echo "Variablen Check <br>";
// echo "<b>Session</b><br>";
// echo print_r($_SESSION);
// echo "<br>";
// echo "<b>Post</b><br>";
// echo print_r($_POST);
// echo "<br>";
// echo "<b>Coockies</b><br>";
// echo print_r($_COOKIE);
// echo "<hr>";
//Score anzeigen
//User ID an Variable Übergeben wenn gesetzt
if (isset($_COOKIE['UserID'])) {
$userID = $_COOKIE['UserID'];
$DatenbankAbfrageScore = "SELECT * FROM score WHERE userID LIKE '$userID'";
$ScoreArray = mysqli_query ($db_link, $DatenbankAbfrageScore);
// Wenn mehr als 0 Tupel vorhanden sind -------------------------------
if (mysqli_num_rows ($ScoreArray) > 0)
{
// aktuelles Tupel ausgeben --------------------------------------------------
while ($zeile = mysqli_fetch_array($ScoreArray))
{
echo "<h3>Statistik</h3>\n";
echo "<hr>";
echo "Punktestand: <b>".$zeile['score']." Punkte</b><br>";
echo "<span class=\"green\">Richtige Fragen: ".$zeile['questionsRight']."</span><br>";
echo "<span class=\"red\">Falsche Fragen: ".$zeile['questionsWrong']."</span><br>";
}
}
else {
if (isset($_COOKIE['UserID'])) {
// Dem neuen User einen Score Eintrag erstellen
$DatenbankRegistierungScore = "INSERT INTO score (userID, questionsRight, questionsWrong, score) VALUES ('$userID',0,0,0)";
$UserArray = mysqli_query ($db_link, $DatenbankRegistierungScore);
}
}
//Buttons ausgeben
echo "<br>";
statsbutton();
echo"<hr>";
echo "<h3>Hilfe<h2>";
helpbutton();
echo"<hr>";
}
?>
|
C++
|
UTF-8
| 1,635 | 3.046875 | 3 |
[] |
no_license
|
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string justification(vector<string> s, int w){
int num = 0;
for(int i = 0; i < s.size(); ++i) num += s[i].size();
int remain = w - num;
int even;
if(s.size() > 1){
even = remain / (s.size()-1);
remain = remain - even * (s.size() - 1);
}
else even = w - s[0].size(), remain = 0;
string res = s[0];
for(int i = 0; i < even + (bool)remain; ++i){
res.push_back(' ');
}
remain -= (bool)remain;
for(int i =1; i < s.size(); ++i){
res += s[i];
for(int i = 0; i < even + (bool)remain; ++i){
res.push_back(' ');
}
if(remain) remain--;
}
while(res.size() != w) res.pop_back();
return res;
}
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> res;
if(words.size() == 0) return res;
int n = words.size();
vector<string> str;
int num = -1;
for(int i = 0; i <n; ++i){
if(num + words[i].size() + 1 <= maxWidth){
str.push_back(words[i]);
num += 1+words[i].size();
}
else{
res.push_back(justification(str, maxWidth));
str.clear();
num = -1;
--i;
}
}
string l;
for(int i = 0; i < str.size(); ++i) {
l+= str[i] + ' ';
}
l.pop_back();
while(l.size() < maxWidth) l.push_back(' ');
res.push_back(l);
return res;
}
};
|
C
|
UTF-8
| 676 | 3.375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<math.h>
int ispalindrome(long int num)
{
long long int x=num, num1=0;
int r;
while(x!=0)
{
r=x%10;
num1=num1*10+r;
x=x/10;
}
if(num1==num)
return 1;
else return 0;
}
int findbinary(long long int newnum )
{
int arr1[1000],i=0,j,flag=1,x;
while(newnum>0)
{
j=newnum%2;
arr1[i++]=j;
newnum=newnum/2;
}
for(x=i-1;x>=0;x--)
{
if(arr1[x]!=0)
break;
}
for(j=0;j<=x;j++,x--)
{
if(arr1[j]!=arr1[x])
{
return 0;
}
}
return 1;
}
void main()
{
long long int i,result=0;
for(i=0;i<=1000000;i++)
{
if(ispalindrome(i))
{
if(findbinary(i))
result=result+i;
}
}
printf("\nresult of sum is%ld ",result);
}
|
Markdown
|
UTF-8
| 886 | 2.75 | 3 |
[] |
no_license
|
### Schedule
If there are the backup jobs scheduled to run, they are listed here.
Select **+**, then select the type and time to add a backup schedule.
Select >**Edit** or **Delete** to edit or delete a backup schedule.
- **Delta Run** is an incremental backup that includes only changes. **Full Run** backs up everything. The first time you run the job, it will be a full backup, even if you select **Delta Run**.
- Select the time in UTC and frequency that you want the backup to run. If you select **Last Day of Month**, you cannot select any other days. If you also want to run a backup on a day that is not the last day of the month, create a second backup.
- When you add a new schedule, the system warns if there are conflicts with other schedules. Failure to correct those could result in skipped backups or other issues.
|
Markdown
|
UTF-8
| 593 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
# Tor IP Checker
Checks if given IP is coming from Tor (exit) node.
## Installation
The best way to install Tor IP Checker is using [Composer](http://getcomposer.org/):
```sh
$ composer require licvido/tor-ip-checker
```
## Usage
```php
// prepare required list
$exitNodeList = new ExitNodeList;
$fullNodeList = new FullNodeList;
$checker = new TorIpChecker($exitNodeList);
if ($checker->isInList($_SERVER['REMOTE_ADDR'])) {
// TOR
} else {
// standard way
}
```
## License
This library is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.
|
C++
|
UTF-8
| 4,928 | 3.65625 | 4 |
[] |
no_license
|
#include "pch.h"
#include <iostream>
using namespace std;
void printBoard(char board[9]) {
std::cout << " " << board[0] << " | " << board[1] << " | " << board[2] << " \n";
std::cout << " --|---|--\n";
std::cout << " " << board[3] << " | " << board[4] << " | " << board[5] << " \n";
std::cout << " --|---|--\n";
std::cout << " " << board[6] << " | " << board[7] << " | " << board[8] << " \n";
}
int turnX();
int turnO();
int analyzeBoard(char board[9]);
int main() {
char gameState = 0; // 0 = run game, 1 = X wins 2 = O wins 3 = draw
char boardPlaces[9] = { '0','1','2','3','4','5','6','7','8' };
int turnCount = 0; //when turnCount hits 9 game decides its a draw
int location;
int turn = 0;
while (gameState == 0) {
printBoard(boardPlaces);
while (turn == 0) {
location = turnX();
if (location < 0 || location > 8) { // if location is not within the grid, retry
std::cout << "Enter a valid position\n";
}
else if (boardPlaces[location] != 'X' && boardPlaces[location] != 'O') {
boardPlaces[location] = 'X';
turn = 1; // sets turn to O
turnCount ++;
}
else {
std::cout << "Location already chosen, please retry\n";
}
}
printBoard(boardPlaces);
gameState = analyzeBoard(boardPlaces);
if(turnCount == 9) {
gameState = 3;
break;
}
if(gameState == 1) {
break;
}
while (turn == 1) {
location = turnO();
if (location < 0 || location > 8) { // if location is not within the grid, retry
std::cout << "Enter a valid position\n";
}
else if (boardPlaces[location] != 'X' && boardPlaces[location] != 'O') {
boardPlaces[location] = 'O';
turn = 0; // sets turn to X
turnCount ++;
}
else {
std::cout << "Location already chosen, please retry\n";
}
}
gameState = analyzeBoard(boardPlaces);
}
if(gameState == 1) {
std::cout << "Player X has won\n";
}
if(gameState == 2) {
std::cout << "Player O has won\n";
}
if(gameState == 3) {
std::cout << "Game is a draw\n";
}
return 0;
}
int turnX() {
int locationX = 0;
bool input = false;
while(!input) {
std::cout << "Player X, choose a location\n";
std::cin >> locationX;
if(!cin) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Try again:\n";
}
else {
input = true;
}
}
return locationX;
}
int turnO() {
int locationO = 0;
bool input = false;
while(!input) {
std::cout << "Player O, choose a location\n";
std::cin >> locationO;
if(!cin){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Try again:\n";
}
else {
input = true;
}
}
return locationO;
}
int analyzeBoard(char board[9]) {
int gameState = 0;
if(board[0] == board[1] && board[1] == board[2] && board[0] != 0) {
if(board[0] == 'X') {
gameState = 1;
}
else {
gameState = 2;
}
}
if(board[3] == board[4] && board[4] == board[5] && board[3] != 0) {
if(board[3] == 'X') {
gameState = 1;
}
else {
gameState = 2;
}
}
if(board[6] == board[7] && board[7] == board[8] && board[6] != 0) {
if(board[6] == 'X') {
gameState = 1;
}
else {
gameState = 2;
}
}
if(board[0] == board[3] && board[3] == board[6] && board[0] != 0) {
if(board[0] == 'X') {
gameState = 1;
}
else {
gameState = 2;
}
}
if(board[1] == board[4] && board[4] == board[7] && board[1] != 0) {
if(board[1] == 'X') {
gameState = 1;
}
else {
gameState = 2;
}
}
if(board[2] == board[5] && board[5] == board[8] && board[2] != 0) {
if(board[2] == 'X') {
gameState = 1;
}
else {
gameState = 2;
}
}
if(board[0] == board[4] && board[4] == board[8] && board[0] != 0) {
if(board[0] == 'X') {
gameState = 1;
}
else {
gameState = 2;
}
}
if(board[2] == board[4] && board[4] == board[6] && board[2] != 0) {
if(board[2] == 'X') {
gameState = 1;
}
else {
gameState = 2;
}
}
return gameState;
}
|
Markdown
|
UTF-8
| 695 | 2.671875 | 3 |
[] |
no_license
|
## C5 <img src="../images/empty-star.png" width="23px"/>
**Applying Design Principles**<br/>
Acts as the technical design authority for multiple teams <b>within a domain</b>, ensuring the appropriateness, quality and suitability of complex designs.
**Reusability**<br/>
Ensures that their team designs solutions containing components suitable for reuse.
**Aligning with business objectives**<br/>
Translates the CTO domain's objectives into technical solutions across multiple teams
**Technical Innovations**<br/>
Actively considers new disruptive technologies, understanding the impact on the teams and business operation across CTO domains with the support of more experienced colleagues.
|
C++
|
UTF-8
| 4,484 | 2.546875 | 3 |
[] |
no_license
|
#include "../include/Brick.h"
#include "SDL2/SDL.h"
#include "../include/InitUtils.hpp"
#include "../include/CustomEventUtils.hpp"
#include "../include/GlobalConstants.h"
#include <SDL2/SDL_mixer.h>
Brick::Brick() {
this->value = 20;
this->sound = NULL;
this->destroyed = false;
this->textureWithPosition = NULL;
this->deadDirection = 1;
}
void Brick::setValue(int value) {
this->value = value;
}
int Brick::getValue() {
return this->value;
}
TextureWithPosition* Brick::getTextureWithPosition() {
return this->textureWithPosition;
}
void Brick::setTextureWithPosition(TextureWithPosition *textureWithPosition) {
this->textureWithPosition = textureWithPosition;
}
Brick::~Brick() {
std::cout << "DEBUG: Brick destruction." << std::endl;
this->setTextureWithPosition(NULL);
this->setDestroyed(true);
}
bool Brick::isDestroyed() {
return this->destroyed;
}
void Brick::setDestroyed(bool destroyed) {
this->destroyed = destroyed;
}
void Brick::render() {
if (!isDestroyed()) {
SDL_RenderCopy(InitUtils::getInstance()->getRenderer(), getTextureWithPosition()->getTexture(), NULL, &(getTextureWithPosition()->getPosition()));
} else {
playDestroy();
}
}
void Brick::playDestroy() {
int y = getTextureWithPosition()->getY();
int h = getTextureWithPosition()->getPosition().h;
SDL_RendererFlip sdlRendererFlip = SDL_FLIP_NONE;
if (y < GlobalConstants::BALL_ZONE_Y + GlobalConstants::BALL_ZONE_HEIGHT - h) {
if (h == 0 || h == getTextureWithPosition()->getOriginRect().h) {
deadDirection = -deadDirection;
}
y = y + 2;
h = h + deadDirection;
if (h == 0){
sdlRendererFlip= SDL_FLIP_VERTICAL;
} else {
sdlRendererFlip = SDL_FLIP_NONE;
}
getTextureWithPosition()->setY(y);
getTextureWithPosition()->setH(h);
SDL_RenderCopyEx(InitUtils::getInstance()->getRenderer(),
getTextureWithPosition()->getTexture(),
NULL,
&(getTextureWithPosition()->getPosition()),
0,
nullptr,
sdlRendererFlip);
} else {
CustomEventUtils::getInstance()->postEventBrickRemoved(this);
}
}
Mix_Chunk* Brick::getSound() {
return this->sound;
}
void Brick::setSound(Mix_Chunk *sound) {
this->sound = sound;
}
bool Brick::isTouchedByBall(Ball *ball) {
bool result = false;
if (!isDestroyed()) {
int x = ball->getTextureWithPosition()->getAbsCenterX();
int y = ball->getTextureWithPosition()->getAbsCenterY();
int halfBallSize = ball->getTextureWithPosition()->getPosition().w / 2;
result = x >= this->getTextureWithPosition()->getX() - halfBallSize && x <= this->getTextureWithPosition()->getX2() + halfBallSize
&& y >= this->getTextureWithPosition()->getY() - halfBallSize && y <= this->getTextureWithPosition()->getY2() + halfBallSize;
}
return result;
}
void Brick::bounces(Ball *ball) {
Mix_PlayChannel(-1, InitUtils::getInstance()->getMapSounds()[GlobalConstants::BRICK_SOUND_KEY], 0);
int halfBallSize = this->getTextureWithPosition()->getPosition().w / 2;
int x = ball->getTextureWithPosition()->getAbsCenterX();
int y = ball->getTextureWithPosition()->getAbsCenterY();
if (x >= getTextureWithPosition()->getX() - halfBallSize && x < getTextureWithPosition()->getX2() + halfBallSize) {
if ((y >= getTextureWithPosition()->getY() - halfBallSize && y <= getTextureWithPosition()->getY())
|| (y >= getTextureWithPosition()->getY2() && y <= getTextureWithPosition()->getY2() + halfBallSize)) {
ball->setDirY(-ball->getDirY());
}
}
if (y >= getTextureWithPosition()->getY() - halfBallSize && y <= getTextureWithPosition()->getY2() + halfBallSize) {
if ((x >= getTextureWithPosition()->getX() - halfBallSize && x <= getTextureWithPosition()->getX())
|| (x >= getTextureWithPosition()->getX2() && x <= getTextureWithPosition()->getX2() + halfBallSize)) {
ball->setDirX(-ball->getDirX());
}
}
}
void Brick::init() {
SDL_Rect tmpRect;
TextureWithPosition *textureWithPosition = new TextureWithPosition(InitUtils::getInstance()->getMapTextures()[GlobalConstants::TEXTURE_KEY], tmpRect);
setTextureWithPosition(textureWithPosition);
}
void Brick::performEvent(SDL_Event &event) {
if (event.user.code == CustomEventUtils::Code::BALL_MOVED) {
Ball *ball = (Ball*) event.user.data1;
if (this->isTouchedByBall(ball)) {
this->bounces(ball);
this->setDestroyed(true);
CustomEventUtils::getInstance()->postEventBrickTouched(this);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.