language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Markdown | UTF-8 | 1,992 | 3.25 | 3 | [] | no_license | # 新的一年,祝你简单勇敢
春节一个人过,头两天的确感觉比较孤单,但是一打游戏就忘了孤单,利用低成本的娱乐设施,缓解对抗世俗的痛苦,可以说是非常高效的了。这么做的后果就是,产生了负罪感,因为每次放假还都带回去一堆书的。但是负罪感没有像以前那么重了,因为我现在能够接纳自己了,真是一个很大的进步。我厌恶喧嚣,厌恶仪式,曾经也试图妥协,可是无奈自己骗不了自己。
我已经三十一岁了,可以说才刚刚看到了人格独立之后的自己。我不再花心思去讨好别人,所以别人对我的看法不如以前了,可是我觉得自己走对了路。三个月的时间,学了python,学了神经网络,学了GUI编程,最重要的是,学会了坚持自己。当然,人格的独立也不是那么简单就能够做到。比如,我还会生闲气,对他人的赞美还有希冀之情,还是不由自主地去按照“合理”的假设去衡量别人。这些无端升起的杂念,实际上并不真实,除了限制自己毫无用处。
观照世间,可以说没有什么太复杂的道理。不论在马克思还是尼采那里,凡人(mortal)要对抗自身的凡人性(mortality),除了投身技术与艺术的创造,没有他法。这种创造,有时被称之为工作,就是罗丹所说的“工作就是人生的价值,人生的欢乐”中的那种工作。
据我观察,世界上大大小小的成功者,无一不保持着良好的工作状态。不论是学术界、产业界的创造者,从事运动、文艺的艺术家,还是单纯在生意场上打拼的交换者们(沟通与服务也是一种艺术),他们在热情地对待工作,从来没有丢了手艺。拳不离手,曲不离口,不是生活所迫,是自得其乐,并且敢于真的去做。这种品格实际上是最宝贵的品格,新的一年,祝你简单勇敢。
|
Java | UTF-8 | 716 | 2.09375 | 2 | [] | no_license | package com.rianta9.dao.impl;
import java.util.List;
import com.rianta9.dao.ICommentDAO;
import com.rianta9.model.CommentModel;
public class CommentDAO implements ICommentDAO{
@Override
public List<CommentModel> getAll() {
// TODO Auto-generated method stub
return null;
}
@Override
public long insert(CommentModel comment) {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean update(CommentModel comment) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean delete(Long id) {
// TODO Auto-generated method stub
return false;
}
@Override
public CommentModel find(Long id) {
// TODO Auto-generated method stub
return null;
}
}
|
Shell | UTF-8 | 277 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #! /bin/bash
set -e
pushd $( dirname $0 )
dotnet publish ../ --configuration Release
docker-compose rm -f
docker-compose -p ci up --build --force-recreate -d
docker container ls
exitCode=$(docker wait test)
docker logs -f test
docker-compose stop -t 1
popd
exit $exitCode
|
C++ | UTF-8 | 461 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int FindtheDuplicateNumber(vector<int>&nums){
int fast=0,slow=0;
do{
fast=nums[nums[fast]];
slow=nums[slow];
}while(fast!=slow);
slow=0;
while(slow!=fast){
slow=nums[slow];
fast=nums[fast];
}
return slow;
}
int main(int argc, char const *argv[]) {
vector<int> nums={1,3,4,2,2};
cout<<FindtheDuplicateNumber(nums)<<endl;
return 0;
}
|
C | UTF-8 | 5,292 | 3.296875 | 3 | [] | no_license | //#include "uarray2.h"
#include "array.h"
#include "mem.h"
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#define T UArray2b_T
typedef struct T *T;
struct T{
int height; //rows
int width; //cols
int blocksize;
int size;
Array_T uarrayb;
};
extern T UArray2b_new (int width, int height, int size, int blocksize){
T uarrayb;
NEW(uarrayb);
uarrayb->width = width; //columns
uarrayb->height = height; //rows
uarrayb->size = size;
uarrayb->blocksize = blocksize;
// take ceiling of width/blocksize and height/blocksize to accomodate extra pixels
// that don't perfectly fit in block
uarrayb->uarrayb = Array_new(((height / blocksize) + 1) * ((width / blocksize) + 1), sizeof(Array_T*));
//populate each element with a 1D array of size blocksize * blocksize
for(int i = 0; i < Array_length(uarrayb->uarrayb); i++){
Array_T cells = Array_new(blocksize * blocksize, size);
Array_T *block = Array_get(uarrayb->uarrayb, i);
*block = cells;
}
//set blocks to point to Array
return uarrayb;
}
/* new blocked 2d array: blocksize = square root of # of cells in block */
extern T UArray2b_new_16K_block(int width, int height, int size){
int blocksize = sqrt(16 * 1024 / size); //16K max blocksize
return UArray2b_new (width, height, size, blocksize);
}
/* new blocked 2d array: blocksize as large as possible provided
block occupies at most 16KB (if possible) */
extern void UArray2b_free (T *array2b){
for(int i = 0; i < Array_length((*array2b)->uarrayb); i++){
Array_T *block = Array_get((*array2b)->uarrayb, i);
Array_free(&((*block)));
}
Array_free(&(*array2b)->uarrayb);
FREE(*array2b);
}
extern int UArray2b_width (T array2b){
return array2b->width;
}
extern int UArray2b_height(T array2b){
return array2b->height;
}
extern int UArray2b_size (T array2b){
return array2b->size;
}
extern int UArray2b_blocksize(T array2b){
return array2b->blocksize;
}
extern void *UArray2b_at(T array2b, int i, int j){
int y = i / array2b->blocksize; //finds col of block
int x = j / array2b->blocksize; //finds row of block
int c = i % array2b->blocksize; //finds col of cell in block
int r = j % array2b->blocksize; //finds row of cell in block
//int total = array2b->width * array2b->height;
//check if valid pixel coordinates
//assert(i > -1 && i < array2b->width && j > -1 && j < array2b->height);
int blockIndex = (x * ((array2b->height / array2b->blocksize) + 1)) + y;
int cell = (r * ((array2b->width / array2b->blocksize) + 1)) + c;
//assert(cell > -1 && cell < total);
Array_T *block = Array_get(array2b->uarrayb, blockIndex); //get block, then find cell coordinates
return Array_get(*block, cell);
//I'm just going to assume that there is bound checking in this because I can't use assert() without
//it yelling
}
/* return a pointer to the cell in column i, row j;
index out of range is a checked run-time error
*/
void UArray2b_map(T array2b,
void apply(int i, int j, T array2b, void *elem, void *cl), void *cl){
int i, j, n, m;
//Get the block array dimensions
int blockArrayWidth = array2b->width / array2b->blocksize;
int blockArrayHeight = array2b->height / array2b->blocksize;
//Iterate through each block
for (j = 0; j < blockArrayHeight; j++){
for (i = 0; i < blockArrayWidth; i++){
//get block 1D array
int blockIndex = (j * ((array2b->height / array2b->blocksize) + 1)) + i;
if(blockIndex > -1 && blockIndex < Array_length(array2b->uarrayb)){
Array_T *block = Array_get(array2b->uarrayb, blockIndex);
//we need to calculate the index for the first cell in the
//block as a point of reference
int topLeftCellinBlockRowIndex = j * array2b->blocksize;
int topLeftCellinBlockColIndex = i * array2b->blocksize;
//Iterate through all cells in a block
for (n = 0;n < array2b->blocksize; n++){
for (m = 0; m < array2b->blocksize; m++){
//calculate the individual cell's index values
int actualX = n * topLeftCellinBlockRowIndex;
int actualY = n * topLeftCellinBlockColIndex;
//Check to ensure we have not left the actual 2d array bounds
if ((actualX < array2b->width) && (actualY < array2b->height)){
int cell = actualX * array2b->blocksize + actualY;
//your apply fucntion parameters may be slightly differnt
apply(actualY, actualX,array2b, Array_get(*block, cell),cl);
}
//Else we are outside the bounds of the array so we do nothing
}
}
}
}
}
}
extern void UArray2b_map(T array2b,
void apply(int i, int j, T array2b, void *elem, void *cl), void *cl);
/* visits every cell in one block before moving to another block */
/* it is a checked run-time error to pass a NULL T
to any function in this interface */
#undef T
|
TypeScript | UTF-8 | 396 | 2.921875 | 3 | [] | no_license | export const getYear = (date: string): string => {
let year = '';
if (date !== '') {
let newDate = new Date(date);
year = newDate.getFullYear().toString();
}
return year;
};
export const convertTime = (time: number): string => {
let hours = Math.floor(time / 60);
let minutes = time % 60;
let convertedTime = `${hours} hours ${minutes} minutes`;
return convertedTime;
};
|
JavaScript | UTF-8 | 1,279 | 2.828125 | 3 | [] | no_license | // this handles some scripts to update data on the server
var hackerApp = {
server: app.server,
queryResults: {},
msgFilter: function() { return true; }
};
hackerApp.geMessages = function() {
const qurl = app.server + '?order=-createdAt';
$.ajax({url: qurl, type: 'GET', success: (data)=>queryResults = data.results, error: (err)=>console.log(err)});
};
hackerApp.updateMsg = function(msgObj) {
$.ajax({
url: app.server + '/' + msgObj.objectId,
type: 'PUT',
data: JSON.stringify(msgObj),
contentType: 'application/json',
success: (data)=>console.log(data),
error: (err)=>console.log(err)});
};
hackerApp.addNoteToAll = function(msgs, note) {
_.each(msgs, (msg)=>{
if (this.msgFilter(msg)) {
msg.text = msg.text + note;
this.updateMsg(msg);
}
});
};
hackerApp.setFilterFunc = function(cb) {
this.msgFilter = cb;
};
// runs the provided function on provided messages and sends them to the server
hackerApp.updateAll = function(msgs, cb) {
_.each(msgs, (msg)=>{
if (this.msgFilter(msg)) {
msg = cb(msg);
this.updateMsg(msg);
}
});
};
// runs the provided function on one message and sends it to the server
hackerApp.update = function(msg, cb) {
msg = cb(msg);
this.updateMsg(msg);
};
|
PHP | UTF-8 | 1,405 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Business\Utils\Sms\Zwj;
use App\Business\Utils\Unique;
use App\Business\Utils\Util;
use Illuminate\Support\Facades\Log;
/**
* 假装某个发送短信的渠道
*/
class Zhu
{
public $tempId = '1'; // 默认的短信模板
/**
* 发送短信
*
* @param $tel
* @param $params
* @param string $tempId
* @return mixed
*/
public function send($tel, $params, $tempId = '')
{
$params = $this->getParams($params, $tempId);
$res['tel'] = $tel;
$res['tempId'] = $tempId;
$res = array_merge($res, $params);
Log::info('[Zhu MSM 模拟短信发送...]', $res);
return $params['code'];
}
/**
* 根据短信模板生成对应的参数列表
*
* @param $params
* @param $tempId
*/
public function getParams($params, $tempId){
if (! $tempId) {
$tempId = $this->tempId;
}
$res = [];
$code = Util::msmCode(4);
switch ($tempId) {
case '1' :
$res[] = $code;
$res[] = $params['prefix'];
break;
default:
throw new \LogicException(Unique::ERR_SMSTMP_NOTEXIST, Unique::ERR_SMSTMP_NOTEXIST);
break;
}
return [
'code' => $code,
'params' => $res
];
}
} |
Python | UTF-8 | 1,463 | 3.828125 | 4 | [] | no_license | def count_compression(string):
string += '~'
previous_letter = string[0]
compression_list = []
consecutive_letters = 0
for char in string:
if previous_letter == char:
consecutive_letters += 1
else:
compression_list.append((previous_letter, consecutive_letters))
consecutive_letters = 1
previous_letter = char
return compression_list
print('Testing count_compression')
print(count_compression('aaabbcaaaa'))
assert count_compression('aaabbcaaaa') == [('a',3), ('b',2), ('c',1), ('a',4)]
print('passed')
print(count_compression('22344444'))
assert count_compression('22344444') == [('2',2), ('3',1), ('4',5)]
print('passed')
def count_decompression(compressed_string):
uncompressed_string = ''
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for compressions in compressed_string:
values = []
for char in compressions:
if isinstance(char, str) == True:
values.append(char)
if isinstance(char, int) == True:
values.append(char)
while values[1] >= 1:
uncompressed_string += values[0]
values[1] -= 1
return uncompressed_string
print('Testing count_decompression')
print(count_decompression([('a',3),('b',2),('c',1),('a',4)]))
assert count_decompression([('a',3),('b',2),('c',1),('a',4)]) == 'aaabbcaaaa'
print('passed')
print(count_decompression([('2',2), ('3',1), ('4',5)]))
assert count_decompression([('2',2), ('3',1), ('4',5)]) == '22344444'
print('passed')
|
JavaScript | UTF-8 | 890 | 3.265625 | 3 | [] | no_license | // alert('hi')
// structure de base IF
if (true) {
// code
}
var nb1 = 10;
if (nb1 < 50){
console.log("nb1 est inférieur à 50");
}
//---------------------
if (true) {
// code si vrai
} else {
// code si faux
}
if (nb1 > 50) {
console.log("nb1 est bien supérieur à 50");
} else {
console.log("nb1 n'est pas supérieur à 50");
}
// exo
// vérifier l'age de l'internaute
// majeur ==> "bienvenue"
// sinon je [1]lui signale et [2] le renvoie vers un autre site
//
// 1 déclarer la l'age de majorité
var majoriteFR=18;
// 2 demande de l'age
var age =parseInt(prompt("Indiquez votre age"));
// 3 condition si majeur
if (age>=majoriteFR) {
alert ("bienvenue, vous êtes majeur");
} else {
alert("Allez voir un super site...");
doument.location.href="http://www.darty.com";
}
//
|
C++ | UTF-8 | 697 | 3.125 | 3 | [] | no_license | #include "StdAfx.h"
#include "Kernel.h"
#include <math.h>
void Kernel::calcKernel(int half_x, int half_y)
{
double euclideanDistance;
for( int x = -half_x; x<half_x; x++ )
for( int y = -half_y; y<half_y; y++ )
{
euclideanDistance = getKernelAt(x, y, half_x, half_y);
m_pKlArr[x+half_x][y+half_y] = euclideanDistance;
m_pKlGradArr[x+half_x][y+half_y] = euclideanDistance; //g(x) = - k'(x), k = 1-x
}
}
double Kernel::getKernelAt(int x, int y, int half_x, int half_y)
{
double euclideanDistance = sqrt( (float)x/half_x *(float)x/half_x + (float)y/half_y*(float)y/half_y );
if(euclideanDistance > 1 )
return 0.0;
else
return (1.0 - euclideanDistance * euclideanDistance);
} |
C | UTF-8 | 195 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
int main(int argc, char const *argv[])
{
int k;
float m;
printf("enter value in kmph:\n");
scanf("%d", &k);
m=0.278 * k;
printf("value in m/s is:%f\n", m );
return 0;
} |
Python | UTF-8 | 1,497 | 2.515625 | 3 | [] | no_license | import pandas as pd
import spacy
from tqdm import tqdm
train_p = 'data/snli_1.0/snli_1.0_train.txt'
dev_p = 'data/snli_1.0/snli_1.0_dev.txt'
test_p= 'data/snli_1.0/snli_1.0_test.txt'
train_df = pd.read_csv(train_p, sep='\t', keep_default_na=False)
dev_df = pd.read_csv(dev_p, sep='\t', keep_default_na=False)
test_df = pd.read_csv(test_p, sep='\t', keep_default_na=False)
def convert(df):
return list(zip(df['sentence1'], df['sentence2'], df['gold_label']))
train_list = convert(train_df)
dev_list = convert(dev_df)
test_list = convert(test_df)
def clean(data):
return [(sent1, sent2, label) for (sent1, sent2, label) in data if label != '-']
train_data = clean(train_list)
dev_data = clean(dev_list)
test_data = clean(test_list)
token = spacy.load('en_core_web_sm')
def tokenize(string):
return ' '.join([token.text for token in token.tokenizer(string)])
def tokenize_data(data):
return [(tokenize(sent1), tokenize(sent2), label) for (sent1, sent2, label) in tqdm(data)]
train_data = tokenize_data(train_data)
dev_data = tokenize_data(dev_data)
test_data = tokenize_data(test_data)
train_df = pd.DataFrame.from_records(train_data)
dev_df = pd.DataFrame.from_records(dev_data)
test_df = pd.DataFrame.from_records(test_data)
headers = ['sentence1', 'sentence2', 'label']
train_df.to_csv(f'{train_p[:-4]}.csv', index=False, header=headers)
dev_df.to_csv(f'{dev_p:-4]}.csv', index=False, header=headers)
test_df.to_csv(f'{test_p[:-4]}.csv', index=False, header=headers)
|
PHP | UTF-8 | 1,995 | 2.921875 | 3 | [] | no_license | <?php
class venda{
private $cod_venda;
private $forma_pagamento;
private $qtd_parcela;
private $obs;
private $data;
private $cliente;
private $produto;
private $funcionario;
public function __construct() {
$n_args = (int) func_num_args();
$args = @func_get_arg();
if($n_args ==0){
$this->cod_venda = " ";
$this->forma_pagamento = " ";
$this->qtd_parcela = " ";
$this->obs = " ";
$this->data = " ";
$this->cliente = " ";
$this->produto = " ";
$this->funcionario = " ";
}
if($n_args == 13){
$this->cod_venda = $args[0];
$this->forma_pagamento = $args[1];
$this->qtd_parcela = $args[2];
$this->obs = $args[3];
$this->data = $args[4];
$this->cliente = $args[5];
$this->produto = $args[6];
}
}
function setCod_venda($cod_venda){
$this->cod_venda = $cod_venda;
}
function getCod_venda(){
return $this->cod_venda;
}
function setForma_pagamento($forma_pagamento){
$this->forma_pagamento = $forma_pagamento;
}
function getForma_pagamento(){
return $this->forma_pagamento;
}
function setQtd_parcela($qtd_parcela){
$this->qtd_parcela = $qtd_parcela;
}
function getQtd_parcela(){
return $this->qtd_parcela;
}
function setObs($obs){
$this->obs = $obs;
}
function getObs(){
return $this->obs;
}
function setCliente($cliente){
$this->cliente = $cliente;
}
function getCliente(){
return $this->cliente;
}
function setProduto($produto){
$this->produto = $produto;
}
function getProduto(){
return $this->produto;
}
function setData($data){
$this->data = $data;
}
function getData(){
return $this->data;
}
function setFuncionario($funcionario){
$this->funcionario = $funcionario;
}
function getFuncionario(){
return $this->funcionario;
}
} |
C | UTF-8 | 524 | 4.21875 | 4 | [] | no_license | //Seção 08 - Exercício 03
/*Faça um programa que carregue um vetor com dez números inteiros.
Mostre o vetor na ordem inversa a que foi digitado.*/
#include <stdio.h>
int main(){
//variável
int vetor[10];
//entradas
for(int i = 0; i <10; i++){ //vetor[10] = 0,1,2...9
printf("Informe um valor inteiro para o vetor: ");
scanf("%d", &vetor[i]);
}
for(int i = 9; i >= 0; i--){
printf("%d\n", vetor[i]);
//se o primeiro elemento é 0 e o ultimo é 9, iniciamos com 9 até o 0 para invertermos.
}
}
|
Java | UTF-8 | 3,960 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package com.github.wtiger001.brigade.general;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class BrigadeGeneralConfiguration {
public static final String MESOS_MASTER = "MESOS_MASTER";
public static final String KAFKA_ADDRESS= "KAFKA_ADDRESS";
public static final String BRIGADE_EXECUTOR = "BRIGADE_EXECUTOR";
public static final String MARATHON_ADDRESS = "MARATHON_ADDRESS";
public static final String GROUP_ID = "GROUP_ID";
public static final String SCHEDULER_IMAGE = "SCHEDULER_IMAGE";
public static final String PROCESSOR_DIR = "PROCESSOR_DIR";
public String mesosMaster;
public String kafkaAddress;
public String frameworkName = "BrigadeProc";
public String executorCommand = "java -jar /home/john/exe/executor.jar";
public String marathonAddress;
public String groupId = "Brigade";
public String schedulerImage = "brigadepreprocessor";
public String processorDir = "/etc/brigade/processors";
public BrigadeGeneralConfiguration() {
Map<String, String> env = System.getenv();
if (env.containsKey(MESOS_MASTER)) {
mesosMaster = env.get(MESOS_MASTER);
}
if (env.containsKey(KAFKA_ADDRESS)) {
kafkaAddress = env.get(KAFKA_ADDRESS);
}
if (env.containsKey(BRIGADE_EXECUTOR)) {
executorCommand = env.get(BRIGADE_EXECUTOR);
}
if (env.containsKey(MARATHON_ADDRESS)) {
marathonAddress = env.get(MARATHON_ADDRESS);
}
if (env.containsKey(SCHEDULER_IMAGE)) {
schedulerImage = env.get(SCHEDULER_IMAGE);
}
if (env.containsKey(GROUP_ID)) {
groupId = env.get(GROUP_ID);
}
if (env.containsKey(PROCESSOR_DIR)) {
processorDir = env.get(PROCESSOR_DIR);
}
}
public void fromFile(String propertiesFile) throws IOException{
Properties props = new Properties();
props.load(new FileInputStream(propertiesFile));
if (props.containsKey(MESOS_MASTER)) {
mesosMaster = props.getProperty(MESOS_MASTER);
}
if (props.containsKey(KAFKA_ADDRESS)) {
kafkaAddress = props.getProperty(KAFKA_ADDRESS);
}
if (props.containsKey(BRIGADE_EXECUTOR)) {
executorCommand = props.getProperty(BRIGADE_EXECUTOR);
}
if (props.containsKey(MARATHON_ADDRESS)) {
marathonAddress = props.getProperty(MARATHON_ADDRESS);
}
if (props.containsKey(SCHEDULER_IMAGE)) {
schedulerImage = props.getProperty(SCHEDULER_IMAGE);
}
if (props.containsKey(GROUP_ID)) {
groupId = props.getProperty(GROUP_ID);
}
if (props.containsKey(PROCESSOR_DIR)) {
processorDir = props.getProperty(PROCESSOR_DIR);
}
}
@Override
public String toString() {
return "BrigadeGeneralConfiguration [mesosMaster=" + mesosMaster + ", kafkaAddress=" + kafkaAddress
+ ", frameworkName=" + frameworkName + ", executorCommand=" + executorCommand + ", marathonAddress="
+ marathonAddress + ", groupId=" + groupId + ", schedulerImage=" + schedulerImage + ", processorDir="
+ processorDir + "]";
}
public void validate() {
List<String> errors = new ArrayList<>();
if (mesosMaster == null || mesosMaster.isEmpty()) {
errors.add("MESOS_MASTER cannot be empty");
}
if (kafkaAddress == null || kafkaAddress.isEmpty()) {
errors.add("KAFKA_ADDRESS cannot be empty");
}
if (executorCommand == null || executorCommand.isEmpty()) {
errors.add("BRIGADE_EXECUTOR cannot be empty");
}
if (marathonAddress == null || marathonAddress.isEmpty()) {
errors.add("MARATHON_ADDRESS cannot be empty");
}
if (groupId == null || groupId.isEmpty()) {
errors.add("GROUP_ID cannot be empty");
}
if (schedulerImage == null || schedulerImage.isEmpty()) {
errors.add("SCHEDULER_IMAGE cannot be empty");
}
if (kafkaAddress == null || processorDir.isEmpty()) {
errors.add("PROCESSOR_DIR cannot be empty");
}
if (errors.isEmpty() == false) {
String errorStr = String.join(", ", errors);
throw new IllegalStateException(errorStr);
}
}
}
|
Markdown | UTF-8 | 1,955 | 2.625 | 3 | [] | no_license | #### 本文诞生的起因
1. 在使用 egg 之后,首先大家都知道它是基于 koa 封装的一个企业级应用 web 框架,那么到底它是如何封装、如何启动、如何集群部署、如何停止多线程服务的呢
2. 在蚂蚁金服的面试中也多次问到我是否看过 egg-core 的源码(我当时没看),这也侧面让我明白到其在内部的地位,因为我们都知道 egg 是在阿里内部经过大量实践后才经过处理后开源出来的,所以在这之后我花了一些时间去消化 egg-core 的源码,然后知道了 egg 跑起来是如何做环境区分的、如何根据环境变量去做配置、插件、全局中间件(在插件中判断)注入应用的,插件是如何作为一个单独应用被注入等
3. 随后我发现在自己粗略分析的过程中其实也是通过多个入口去看的(因为我的学习习惯就是追本溯源),通过不同的入口区分不同的情况,比如本地开发跑的是 egg-bin 脚本,线上测试与生产跑的是 egg-scripts 脚本,前置步骤其实是较为繁琐的,看完后过2天我已经将核心忘的差不多了
#### 针对上述问题的解决方案
遂有了这篇文章的诞生,旨在记录这个运行的大概过程,当然我也不保证自己写的会全是正确的,所以如果有错误希望大家指出,我会查看并仔细修改,共勉~
#### so,本文将从几个角度分析 egg 是如何运行起来的
1. [x] 开发环境入口 egg-bin
2. [x] 线上测试以及生产环境入口 egg-scripts
* egg-scripts start
* egg-scripts stop
* 源码分析入口为 /egg-scirpts/summary.md(egg-scripts 解析大纲)
3. [x] egg-scripts 对于集群部署 cluster 模块的运用
* egg-cluster(太特么多了,正在进行中...)
4. [ ] egg-core
* 如何进行环境区分
* 配置注入(插件与 config 配置的注入)
* 继承 KoaApplication 启动应用
|
Java | UTF-8 | 821 | 2.96875 | 3 | [] | no_license | package io.zipcoder.polymorphism;
import io.zipcoder.pets.Cat;
import io.zipcoder.pets.Pet;
import org.junit.Assert;
import org.junit.Test;
public class CatTest {
@Test
public void catInstanceOfTest(){
Cat cat= new Cat("Ay");
Assert.assertTrue(cat instanceof Pet);
}
@Test
public void catGetNameTest(){
Cat cat= new Cat("Ay");
String actual = cat.getName();
Assert.assertEquals("Ay",actual);
}
@Test
public void catSetNameTest(){
Cat cat= new Cat("Ay");
cat.setName("Bee");
String actual = cat.getName();
Assert.assertEquals("Bee",actual);
}
@Test
public void catSpeakTest(){
Cat cat= new Cat("Ay");
String actual = cat.speak();
Assert.assertEquals("Meow!",actual);
}
}
|
Java | UTF-8 | 753 | 1.867188 | 2 | [] | no_license | package cn.eeepay.framework.daoSuperbank;
import org.apache.ibatis.annotations.Insert;
import cn.eeepay.framework.model.CreditloanEnterData;
public interface CreditloanEnterDataDao {
/**新增数据分析记录*/
@Insert("insert into creditloan_enter_data" +
"(analysis_code,login_source,business_source,credit_bank,loan_source,open_type,day_pv_num,week_pv_num,month_pv_num,day_uv_num,week_uv_num,month_uv_num,org_id,analysis_date) " +
" values " +
" (#{analysisCode},#{loginSource},#{businessSource},#{creditBank},#{loanSource},#{openType},#{dayPvNum},#{weekPvNum},#{monthPvNum},#{dayUvNum},#{weekUvNum},#{monthUvNum},#{orgId},DATE_SUB(curdate(),INTERVAL 1 DAY))")
int saveCreditloanEnterData(CreditloanEnterData record);
}
|
PHP | UTF-8 | 530 | 3.015625 | 3 | [] | no_license | <?php
$name = 'Женя';
$age = 29;
date_default_timezone_set('Europe/Moscow');
$date = date('d-m-y H:i');
$string = 'Меня зовут $name.'
. '<br>'
. 'Через год мне будет '
. ($age + 1)
. ' лет, а еще через год '
. ($age + 2)
. ' год.'
. '<br>'
. 'На моих часах сейчас: '
. $date
. '.';
echo $string . '<br>' . '<br>';
$string2 = str_replace(' ', '_', $string);
$string3 = substr($string2, 115, 100);
echo $string3 . '<br>' . '<br>';
|
Markdown | UTF-8 | 3,097 | 2.71875 | 3 | [] | no_license | +++
categories = ["personal"]
tags = ["misc"]
date = "2016-06-02T18:43:22-07:00"
title = "Big Pitch - Mild Depression"
+++
I make a bid to change the job I have into the job I want, with luke-warm result.
<!--more-->
<hr/><br/>
It seems, for whatever reason, the people I work with don't want me to leave.
Lucky for them my greatest success so far in my job search has been getting some
feedback on a few of my rejected my applications.
Knowing that I want to move to a software development role; some people in my
office have been making noises at higher levels. As a result I got a chance
today to pitch a member of the executive leadership team. One of the projects I
have in mind would solve workload and staffing problems we've been having, and
also capture valuable data that we are currently throwing away.
On Tuesday I prepared some graphics and application mockups, and worked on my
delivery. The meeting got pushed from Wednesday due to a last minute schedule
change, but I spent basically all day today selling my plan. As a result of
my efforts and seemingly convincing arguments I've received a resounding *meh*.
Now I knew going in that the person I was trying to sell this to didn't actually
have the power to make anything happen. He is very sharp though, and he has the
ear of the CEO and other executives that *can* make decisions. If I got him on my
side I might have a chance of making a new position for myself.
In the end he agreed that if I could do what I said, and if I could adapt it to
the variety of business models that exist in our company, he thought it would be
worthwhile. He did not seem very optimistic about my chances of getting
green-lit with a budget though, especially not any time soon.
It turns out though that the CFO is actually currently tasked with resolving the
very problems my system would address. He is on vacation right now, which gives
me a little time to build a prototype and refine my pitch.
The question is whether it is really worth my time. I'll be working unpaid
building something nobody asked for to try and sell it to someone who doesn't
want it, or me for that matter.
So yeah, I was feeling pretty low today when I left the office. The last three
months of hard work trying to get a job have been a complete failure, and my big
chance to fix the job I have ended in apathetic mediocrity.
Today was also my self imposed drop-dead date - the day where I either get some
kind of concession in my current job, or quit outright and re-focus on my job
search. I expected the outcome of todays meeting to push me one way or the
other but instead I'm just more disillusioned and indecisive.
### Edit - Resolution
Well I've made a decision. With no active projects, and no indication that I will
get paid for what I've been working on, there are no reasons left for me to stay
any longer. Even acknowledging those realities it was a hard choice. In the end
I flipped a coin - best two out of three - to decide if I should stay and build
my prototype, twice. I was flipping heads to stay, but the coins came up tails
every flip... |
Python | UTF-8 | 372 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | from TrainingController.TrainingController import TrainingController
class MaxIterations(TrainingController):
def __init__(self, max_iterations):
self.max_iterations = max_iterations
def after_training_iteration(self, trainable):
'''Stop training if epochs is greater than max_iterations'''
return trainable.epoch >= self.max_iterations
|
Swift | UTF-8 | 4,274 | 2.546875 | 3 | [] | no_license | //
// RecipeDetailViewModel.swift
// recipeApp
//
// Created by Maggie Williams on 11/6/19.
// Copyright © 2019 CMU. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class RecipeDetailViewModel {
let client = GetRecipeDetailClient()
var recipeDetail: RecipeDetail?
var recipeID: Int
var recipeIngredients = [ExtendedIngredient]()
var recipeInstructions = [RecipeInstruction]()
var recipeInstructionSteps = [Step]()
init(id: Int) {
self.recipeID = id
}
func createRecipe(_ entity: String) -> NSManagedObject? {
// Helpers
var result: NSManagedObject?
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// Create Entity Description
let entityDescription = NSEntityDescription.entity(forEntityName: entity, in: context)
if let entityDescription = entityDescription {
// Create Managed Object
result = NSManagedObject(entity: entityDescription, insertInto: context)
}
return result
}
func fetchRecipe(_ entity: String) -> [NSManagedObject]? {
// Create Fetch Request
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
do {
// Execute Fetch Request
let records = try context.fetch(fetchRequest) as? [NSManagedObject]
return records
} catch {
print("Unable to fetch managed objects for entity \(entity).")
return nil
}
}
func resetData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.reset()
UserDefaults.standard.set(false, forKey: "TermsAccepted")
}
func numberOfIngredientsTableRows() -> Int? {
return self.recipeIngredients.count
}
func ingredientTitleForRowAtIndexPath(_ indexPath: IndexPath) -> String? {
return self.recipeIngredients[indexPath.row].name
}
func ingredientAmountForRowAtIndexPath(_ indexPath: IndexPath) -> String? {
let amt = rationalApproximationOf(x0: self.recipeIngredients[indexPath.row].amount!)
let unit = self.recipeIngredients[indexPath.row].unit!
return String(format: "%@ %@", amt, unit)
}
func numberOfInstructionTableRows() -> Int? {
return self.recipeInstructionSteps.count
}
func instructionForRowAtIndexPath(_ indexPath: IndexPath) -> String? {
if(self.numberOfInstructionTableRows() == 0){
return "No instructions to display"
}
return self.recipeInstructionSteps[indexPath.row].step
}
func instructionNumberForRowAtIndexPath(_ indexPath: IndexPath) -> String? {
if(self.numberOfInstructionTableRows() == 0){
return "N/A"
}
return String(self.recipeInstructionSteps[indexPath.row].number)
}
func refresh(completion: @escaping () -> Void) {
client.fetchRecipeDetail(inputID: self.recipeID) { [unowned self] recipeDetail in
self.recipeDetail = recipeDetail!
self.recipeIngredients = (self.recipeDetail?.extendedIngredients)!
completion()
}
client.fetchRecipeInstructions(inputID: self.recipeID) { [unowned self] recipeInstructions in
self.recipeInstructions = recipeInstructions!
self.recipeInstructionSteps = self.recipeInstructions[0].steps
completion()
}
}
func refreshDetailByID(recipeID: Int, completion: @escaping () -> Void) {
client.fetchRecipeDetail(inputID: recipeID) { [unowned self] recipeDetail in
self.recipeDetail = recipeDetail!
}
}
}
typealias Rational = (num : Int, den : Int)
func rationalApproximationOf(x0 : Double, withPrecision eps : Double = 1.0E-6) -> String {
var x = x0
var a = floor(x)
var (h1, k1, h, k) = (1, 0, Int(a), 1)
while x - a > eps * Double(k) * Double(k) {
x = 1.0/(x - a)
a = floor(x)
(h1, k1, h, k) = (h, k, h1 + Int(a) * h, k1 + Int(a) * k)
}
if (k == 1) {
return String(format: "%d", h)
} else {
return String(format: "%d/%d", h, k)
}
}
|
JavaScript | UTF-8 | 1,665 | 3.875 | 4 | [] | no_license | // (c) Enroute 2018
//
// Prepared by AMG
//
// FOR LOOP
for (let i = 0; i <= 10; i++) {
if (i === 5) {
console.log("We are just in the middle");
continue;
}
console.log(i);
}
startTime = new Date().getTime();
//console.log(startTime);
// FOR LOOP - Break & Continue
for (let i = 0; i < 100; i++) {
timeElapsed = new Date().getTime() - this.startTime;
if (i === 5) {
console.log("We are just in the middle");
continue;
}
if (timeElapsed > 3) {
console.log(
`Time Elapsed ${timeElapsed} is too long. End cicle at iteration ${i}`
);
break;
} else {
console.log(`time elapsed ${timeElapsed} i=${i}`);
}
}
// WHILE LOOP
let tickets = 10;
while (tickets > 0) {
console.log(`Ride the Rollacoster, we have ${tickets} ticket left!`);
tickets--;
}
console.log("Tickets are gone!");
// DO .. WHILE
let scoop = 1;
do {
console.log(`Add scoop #${scoop}`);
scoop++;
} while (scoop <= 5);
{
console.log(`This is a ${scoop - 1}-scoops icecream!`);
}
// Arrays loops
const fruits = ["apple", "banana", "orange", "grape", "watermelon"];
fruits.forEach(function(fruit, index) {
console.log(`fruit #${index} = ${fruit}`);
});
// MAP
const users = [
{ id: 101, name: "Richard Mathew" },
{ id: 201, name: "Albert Siqueiros" },
{ id: 212, name: "Spencer Robins" },
{ id: 215, name: "Marcell Menendez" },
{ id: 532, name: "Sophie Maturana" }
];
const idArray = users.map(function(user, i) {
return user.id;
});
console.log(idArray);
// For ... in loop
var obj = { a: 1, b: 2, c: 3 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
for (let user in users) {
console.log(user + " " + users[user].name);
}
|
Java | UTF-8 | 2,388 | 3.0625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pecl1;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import javax.swing.JTextField;
/**
*
* @author Fran
*/
public class Mesa {
private ArrayList<String> mesa;
private Semaphore mesaLlena; //Huecos que quedan libres
private Semaphore mesaVacia= new Semaphore(0); //Num elementos en el array
private Semaphore exclusionMutua = new Semaphore(1);
private JTextField me;
private String estado;
public Mesa (int max, JTextField me){ //20
mesa = new ArrayList<String>();
mesaLlena = new Semaphore (max);
this.me=me;
}
public void dejarPedido(String pedido){
try {
mesaLlena.acquire();
exclusionMutua.acquire();
mesa.add(pedido);
imprimirMesa();
} catch (InterruptedException ie){}
finally {
exclusionMutua.release();
mesaVacia.release();
}
}
public String cogerPedido (){
try {
mesaVacia.acquire();
exclusionMutua.acquire();
String pedido = mesa.get(0);
mesa.remove(0);
imprimirMesa();
return pedido;
} catch (InterruptedException ie){}
finally {
exclusionMutua.release();
mesaLlena.release();
}
return "";
}
public void imprimirMesa() {
String escribir="";
//System.out.println("ESTADO MESA");
for (int i = 0; i<mesa.size();i++){
if (i == 0){
escribir = mesa.get(i);
}
else{
escribir = escribir + ", " + mesa.get(i);
}
}
//System.out.println(pintar);
me.setText(escribir);
}
public String getString(int i){
return this.mesa.get((int) i);
}
public ArrayList<String> getMesa() {
return mesa;
}
public void setMesa(ArrayList<String> mesa) {
this.mesa = mesa;
}
}
|
C++ | UTF-8 | 4,447 | 2.703125 | 3 | [
"MIT"
] | permissive | /*
* DbgTraceContext.cpp
*
* Created on: 14.04.2015
* Author: aschoepfer
*/
#include "DbgTraceContext.h"
#include "DbgTracePort.h"
#include "DbgTraceOut.h"
#include <string.h>
DbgTrace_Context* DbgTrace_Context::s_context = 0;
DbgTrace_Context::DbgTrace_Context(DbgCli_Topic* cliParentNode)
: m_contextDbgTopic(cliParentNode)
, m_firstPort(0)
, m_firstOut(0)
{
s_context = this;
}
DbgTrace_Port* DbgTrace_Context::getTracePort(const char* tag)
{
if(0 == m_firstPort)
{
// no ports, return
return 0;
}
else
{
// search port
DbgTrace_Port* tmpPort = m_firstPort;
while((0 != tmpPort))
{
if(0 == strncmp(tmpPort->getTag(), tag, DbgTrace_Port::s_cMaxPortTagLength))
{
// Port with this tag could be found
return tmpPort;
}
tmpPort = tmpPort->getNextPort();
}
return tmpPort;
}
}
void DbgTrace_Context::addTracePort(DbgTrace_Port* port)
{
// check if port with this tag already exists in the list.
DbgTrace_Port* tmpPort = m_firstPort;
DbgTrace_Port* previousPort = m_firstPort;
const char* portTag;
if(0 != port)
{
portTag = port->getTag();
while((0 != tmpPort))
{
if(0 == strncmp(tmpPort->getTag(), portTag, DbgTrace_Port::s_cMaxPortTagLength))
{
// fail, port with this tag already exists.
return;
}
previousPort = tmpPort;
tmpPort = tmpPort->getNextPort();
}
// no port with this tag, add port to list.
if(0 != previousPort)
{
previousPort->setNextPort(port);
}
else
{ // special adding of the very first out.
m_firstPort = port;
}
// Create DbgCliTopic and DbgCliCommands for this port
if(0 != m_contextDbgTopic)
{
port->createCliNodes(m_contextDbgTopic);
}
}
}
void DbgTrace_Context::deleteTracePort(const char* tag)
{
// check if port with this tag already exists in the list.
DbgTrace_Port* tmpPort = m_firstPort;
DbgTrace_Port* previousPort = m_firstPort;
while((0 != tmpPort))
{
if(0 == strncmp(tmpPort->getTag(), tag, DbgTrace_Port::s_cMaxPortTagLength))
{
// found the searched TracePort, change nextPort-ptrs
DbgTrace_Port* nextPort = tmpPort->getNextPort();
if(0 != nextPort)
{
previousPort->setNextPort(nextPort);
}
else
{
// found TracePort was the last one.
previousPort->setNextPort(0);
}
return;
}
previousPort = tmpPort;
tmpPort = tmpPort->getNextPort();
}
}
DbgTrace_Out* DbgTrace_Context::getTraceOut(const char* name)
{
if(0 == m_firstOut)
{
// no out's, return
return 0;
}
else
{
// search out
DbgTrace_Out* tmpOut = m_firstOut;
while((0 != tmpOut))
{
if(0 == strncmp(tmpOut->getName(), name, DbgTrace_Out::s_cMaxOutNameLength))
{
// Out with this name could be found
return tmpOut;
}
tmpOut = tmpOut->getNextOut();
}
return tmpOut;
}
}
void DbgTrace_Context::addTraceOut(DbgTrace_Out* out)
{
// check if out with this name already exists in the list.
DbgTrace_Out* tmpOut = m_firstOut;
DbgTrace_Out* previousOut = m_firstOut;
const char* outName;
if(0 != out)
{
outName = out->getName();
while((0 != tmpOut))
{
if(0 == strncmp(tmpOut->getName(), outName, DbgTrace_Out::s_cMaxOutNameLength))
{
// fail, out with this name already exists.
return;
}
previousOut = tmpOut;
tmpOut = tmpOut->getNextOut();
}
// no out with this name, add out to list.
if(0 != previousOut)
{
previousOut->setNextOut(out);
}
else
{ // special adding of the very first out.
m_firstOut = out;
}
}
}
void DbgTrace_Context::deleteTraceOut(const char* name)
{
// check if out with this name already exists in the list.
DbgTrace_Out* tmpOut = m_firstOut;
DbgTrace_Out* previousOut = m_firstOut;
while((0 != tmpOut))
{
if(0 == strncmp(tmpOut->getName(), name, DbgTrace_Out::s_cMaxOutNameLength))
{
// found the searched TraceOut, change nextOut-ptrs
DbgTrace_Out* nextOut = tmpOut->getNextOut();
if(0 != nextOut)
{
previousOut->setNextOut(nextOut);
}
else
{
// found TraceOut was the last one.
previousOut->setNextOut(0);
}
return;
}
previousOut = tmpOut;
tmpOut = tmpOut->getNextOut();
}
}
|
Rust | UTF-8 | 4,546 | 3.328125 | 3 | [] | no_license | use crate::random::{random, random_min_max};
use crate::vector::dot;
use std::f32::consts::PI;
use std::ops;
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Vec3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl Vec3 {
pub fn new(x: f32, y: f32, z: f32) -> Self {
Vec3 { x, y, z }
}
pub fn random_unit_vector() -> Self {
let a = random_min_max(0.0, 2.0 * PI);
let z = random_min_max(-1.0, 1.0);
let r = (1.0 - z * z).sqrt();
Vec3::new(r * a.cos(), r * a.sin(), z)
}
pub fn random_in_unit_sphere() -> Self {
loop {
let p = Self::random();
if p.length_squared() >= 1.0 {
continue;
}
return p;
}
}
pub fn random_in_hemisphere(&self) -> Self {
let in_unit_sphere = Self::random_in_unit_sphere();
if dot(&in_unit_sphere, self) > 0.0 {
in_unit_sphere
} else {
-in_unit_sphere
}
}
pub fn random() -> Self {
Vec3::new(random(), random(), random())
}
pub fn random_min_max(min: f32, max: f32) -> Self {
Vec3::new(
random_min_max(min, max),
random_min_max(min, max),
random_min_max(min, max),
)
}
pub fn random_in_unit_disk() -> Self {
loop {
let p = Vec3::new(random_min_max(-1.0, 1.0), random_min_max(-1.0, 1.0), 0.0);
if p.length_squared() >= 1.0 {
continue;
}
return p;
}
}
pub fn x(&self) -> f32 {
self.x
}
pub fn y(&self) -> f32 {
self.y
}
pub fn z(&self) -> f32 {
self.z
}
pub fn length(&self) -> f32 {
self.length_squared().sqrt()
}
pub fn length_squared(&self) -> f32 {
self.x * self.x + self.y * self.y + self.z * self.z
}
}
impl ops::Div<f32> for Vec3 {
type Output = Self;
fn div(mut self, rhs: f32) -> Self::Output {
let k = 1.0 / rhs;
self.x *= k;
self.y *= k;
self.z *= k;
self
}
}
impl ops::Mul<f32> for Vec3 {
type Output = Self;
fn mul(mut self, rhs: f32) -> Self::Output {
self.x *= rhs;
self.y *= rhs;
self.z *= rhs;
self
}
}
impl ops::Mul<Vec3> for Vec3 {
type Output = Self;
fn mul(mut self, rhs: Vec3) -> Self::Output {
self.x *= rhs.x;
self.y *= rhs.y;
self.z *= rhs.z;
self
}
}
impl ops::Add for Vec3 {
type Output = Self;
fn add(mut self, rhs: Self) -> Self::Output {
self.x += rhs.x;
self.y += rhs.y;
self.z += rhs.z;
self
}
}
impl ops::Sub for Vec3 {
type Output = Self;
fn sub(mut self, rhs: Self) -> Self::Output {
self.x -= rhs.x;
self.y -= rhs.y;
self.z -= rhs.z;
self
}
}
impl ops::Neg for Vec3 {
type Output = Self;
fn neg(mut self) -> Self::Output {
self.x *= -1.0;
self.y *= -1.0;
self.z *= -1.0;
self
}
}
#[cfg(test)]
mod test_vec3 {
use super::*;
#[test]
fn test_dividing_vec3_with_factor() {
let vec3 = Vec3::new(2.0, 4.0, 8.0);
let expected = Vec3::new(1.0, 2.0, 4.0);
let result = vec3 / 2.0;
assert_eq!(result, expected);
}
#[test]
fn test_multiplying_vec3_with_factor() {
let vec3 = Vec3::new(2.0, 4.0, 8.0);
let expected = Vec3::new(4.0, 8.0, 16.0);
let result = vec3 * 2.0;
assert_eq!(result, expected);
}
#[test]
fn test_adding_to_vec3s_together() {
let a = Vec3::new(1.0, 2.0, 3.0);
let b = Vec3::new(4.0, 5.0, 6.0);
let expected = Vec3::new(5.0, 7.0, 9.0);
let result = a + b;
assert_eq!(result, expected);
}
#[test]
fn test_negating_a_vector() {
let a = Vec3::new(4.0, 5.0, 6.0);
let expected = Vec3::new(-4.0, -5.0, -6.0);
let result = -a;
assert_eq!(result, expected);
}
#[test]
fn test_subtracting_vec3_from_vec3() {
let a = Vec3::new(4.0, 5.0, 6.0);
let b = Vec3::new(1.0, 2.0, 3.0);
let expected = Vec3::new(3.0, 3.0, 3.0);
let result = a - b;
assert_eq!(result, expected);
}
#[test]
fn test_params() {
let vec3 = Vec3::new(2.0, 4.0, 8.0);
assert!(vec3.x().eq(&2.0f32));
assert!(vec3.y().eq(&4.0f32));
assert!(vec3.z().eq(&8.0f32));
}
}
|
Java | UTF-8 | 311 | 1.640625 | 2 | [
"BSD-3-Clause"
] | permissive | package org.firstinspires.ftc.teamcode.control;
public class Stages {
interface basicStage {
String name();
boolean finishState();
void startFunction();
void mainFunction();
void endFunction();
StageStartVars AUTO_START_VARS = new StageStartVars();
}
}
|
Java | UTF-8 | 308 | 1.851563 | 2 | [] | no_license | package com.topvision.ems.epon.fault.helper;
/**
* 上联口 转换 辅助类
*
* @author w1992wishes
* @created @2018年1月18日-下午4:40:10
*
*/
public interface PortConvertHelper {
Integer convertPort(Long entityId, Integer port);
Integer convertSlot(Long entityId, Integer slot);
}
|
C++ | UTF-8 | 3,177 | 3.703125 | 4 | [] | no_license | // 103. Binary Tree Zigzag Level Order Traversal
// Given the root of a binary tree, return the zigzag level order traversal of
// its nodes' values. (i.e., from left to right, then right to left for the next level
// and alternate between).
// Explanation:
// used two stacks<pair<TreeNode*, int>>, pair stores the node and current level.
// used two stack pointers, when changing levels, need to swap the pointers.
// one pointer points to current level, other points to lower level.
// loop will end when both stack is empty
// when level is changed, direction "dir" is inversed.
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <string>
#include <unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
if (root==nullptr) {
return result;
}
pair<TreeNode*, int> currNodeAndLevel;
TreeNode* currNode;
int level;
stack<pair<TreeNode*,int>> st1;
stack<pair<TreeNode*,int>> st2;
bool dir = true;
stack<pair<TreeNode*,int>> *currSt, *lowSt, *temp;
currSt = &st1;
lowSt = &st2;
currSt->push(make_pair(root, 0));
while(!st1.empty() || !st2.empty()) {
if (currSt->empty()) {
// stack that currSt is empty. which means we visited all curr level nodes;
// need to move to next level;
temp = currSt;
currSt = lowSt;
lowSt = temp;
}
currNodeAndLevel = currSt->top();
currNode = currNodeAndLevel.first;
level = currNodeAndLevel.second;
if (result.size() <= level) {
result.push_back({currNode->val});
dir = !dir;
//cout << endl;
} else {
result[level].push_back(currNode->val);
}
//cout << currNode->val << ", ";
// based on the dir, either start from left or right node;
if (dir) {
if (currNode->right) {
lowSt->push(make_pair(currNode->right, level+1));
}
if (currNode->left) {
lowSt->push(make_pair(currNode->left, level+1));
}
} else {
if (currNode->left) {
lowSt->push(make_pair(currNode->left, level+1));
}
if (currNode->right) {
lowSt->push(make_pair(currNode->right, level+1));
}
}
currSt->pop();
}
return result;
}
}; |
Java | UTF-8 | 1,738 | 3.078125 | 3 | [] | no_license | import java.util.ArrayList;
public class AdministradorDeAlquileres {
private ArrayList<Alquiler> alquilers;
public AdministradorDeAlquileres(){
alquilers = new ArrayList<>();
}
public void agregarAlquiler(Alquiler alquiler){
alquilers.add(alquiler);
}
public Alquiler getMayorAlquiler(){
Alquiler aDevolver = alquilers.get(0);
for (Alquiler alquiler: alquilers) {
if(aDevolver.calcularPresupuesto() < alquiler.calcularPresupuesto()){
aDevolver = alquiler;
}
}
return aDevolver;
}
public Alquiler getMenorAlquiler(){
Alquiler aDevolver = alquilers.get(0);
for (Alquiler alquiler: alquilers) {
if(aDevolver.calcularPresupuesto() > alquiler.calcularPresupuesto()){
aDevolver = alquiler;
}
}
return aDevolver;
}
public int calcularPromedioParaMes(int mes){
int alquileres = 0;
int contadorDeAlquileres = 0;
for (Alquiler alquiler : alquilers){
if(alquiler.getMes() == mes){
alquileres+= alquiler.calcularPresupuesto();
contadorDeAlquileres +=1;
}
}
if(contadorDeAlquileres == 0){
return 0;
}
return (alquileres / contadorDeAlquileres);
}
public int calcularPromedioParaAnio(){
int alquileres = 0;
int contadorDeAlquileres = 0;
for (Alquiler alquiler : alquilers){
alquileres+= alquiler.calcularPresupuesto();
contadorDeAlquileres +=1;
}
return (alquileres / contadorDeAlquileres);
}
}
|
Python | UTF-8 | 309 | 2.796875 | 3 | [] | no_license | #!/usr/bin/evn python
# excoding: utf-8
import Image
import ImageFont
import ImageDraw
text = u"7"
im = Image.open('./image.jpg')
dr = ImageDraw.Draw(im)
font = ImageFont.truetype("msyh.ttf", 34)
dr.text(im.size[0]*0.85, im.size[1]*0.05, text, font=font, fill="#ff0000")
im.show()
im.save('result.jpg')
|
Python | UTF-8 | 2,171 | 2.59375 | 3 | [
"MIT"
] | permissive | from test.dungeons.TestDungeon import TestDungeon
class TestThievesTown(TestDungeon):
def testThievesTown(self):
self.starting_regions = ['Thieves Town (Entrance)']
self.run_tests([
["Thieves' Town - Attic", False, []],
["Thieves' Town - Attic", False, [], ['Big Key (Thieves Town)']],
["Thieves' Town - Attic", False, [], ['Small Key (Thieves Town)']],
["Thieves' Town - Attic", True, ['Big Key (Thieves Town)', 'Small Key (Thieves Town)']],
["Thieves' Town - Big Key Chest", True, []],
["Thieves' Town - Map Chest", True, []],
["Thieves' Town - Compass Chest", True, []],
["Thieves' Town - Ambush Chest", True, []],
["Thieves' Town - Big Chest", False, []],
["Thieves' Town - Big Chest", False, [], ['Big Key (Thieves Town)']],
["Thieves' Town - Big Chest", False, [], ['Small Key (Thieves Town)']],
["Thieves' Town - Big Chest", False, [], ['Hammer']],
["Thieves' Town - Big Chest", True, ['Hammer', 'Small Key (Thieves Town)', 'Big Key (Thieves Town)']],
["Thieves' Town - Blind's Cell", False, []],
["Thieves' Town - Blind's Cell", False, [], ['Big Key (Thieves Town)']],
["Thieves' Town - Blind's Cell", True, ['Big Key (Thieves Town)']],
["Thieves' Town - Boss", False, []],
["Thieves' Town - Boss", False, [], ['Big Key (Thieves Town)']],
["Thieves' Town - Boss", False, [], ['Small Key (Thieves Town)']],
["Thieves' Town - Boss", False, [], ['Hammer', 'Progressive Sword', 'Cane of Somaria', 'Cane of Byrna']],
["Thieves' Town - Boss", True, ['Small Key (Thieves Town)', 'Big Key (Thieves Town)', 'Hammer']],
["Thieves' Town - Boss", True, ['Small Key (Thieves Town)', 'Big Key (Thieves Town)', 'Progressive Sword']],
["Thieves' Town - Boss", True, ['Small Key (Thieves Town)', 'Big Key (Thieves Town)', 'Cane of Somaria']],
["Thieves' Town - Boss", True, ['Small Key (Thieves Town)', 'Big Key (Thieves Town)', 'Cane of Byrna']],
]) |
Java | UTF-8 | 454 | 2.125 | 2 | [] | no_license | package project.web;
import project.model.Book;
import project.service.Service;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.util.List;
@ManagedBean
@SessionScoped
public class Controller {
@EJB
private Service service;
public String getText() {
return service.getText();
}
public List<Book> getAllBooks() {
return service.findAllBooks();
}
}
|
C++ | UTF-8 | 1,202 | 3.40625 | 3 | [] | no_license | //counthdt.cpp
//Bradley Morton
//9/30/18
//Contains definitions of functions for Assignment 4
#include "counthdt.h" //For prototypes
#include <vector>
using std::vector;
#include <iostream>
int countHDT(int dim_x, int dim_y, int forbid1_x, int forbid1_y, int forbid2_x, int forbid2_y)
{
vector<vector<int>> board(dim_x, std::vector<int>(dim_y,0));
board[forbid1_x][forbid1_y]=1;
board[forbid2_x][forbid2_y]=1;
int total=countHDT_recurse(board, dim_x, dim_y, dim_y*dim_x-2);
return total;
}
int countHDT_recurse(vector<vector<int>> board, int dim_x, int dim_y, int squaresLeft)
{
if(squaresLeft==0)
{
return 1;
}
int total=0;
for(int i=0; i<dim_x; ++i)
{
for(int j=0; j<dim_y; ++j)
{
if(board[i][j]==1)
continue;
if(i+1<dim_x)
{
if(board[i+1][j]==0)
{
board[i][j]=1;
board[i+1][j]=1;
total+= countHDT_recurse(board, dim_x, dim_y, squaresLeft-2);
board[i][j]=0;
board[i+1][j]=0;
}
}
if(j+1<dim_y)
if(board[i][j+1]==0)
{
board[i][j]=1;
board[i][j+1]=1;
total+= countHDT_recurse(board, dim_x, dim_y, squaresLeft-2);
board[i][j]=0;
board[i][j+1]=0;
}
return total;
}
}
return 0;
}
|
Java | UTF-8 | 748 | 1.976563 | 2 | [] | no_license | package com.action;
import com.service.UserRelationshipService;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("friend")
public class FriendController {
@Autowired
private UserRelationshipService userRelationshipService;
@RequestMapping("search")
public ResponseBean findMutualConcern(Integer uid){
try {
return userRelationshipService.findMutualConcern(uid);
} catch (Exception e) {
e.printStackTrace();
return new ResponseBean(400, e.getMessage(),null);
}
}
}
|
C++ | UTF-8 | 1,533 | 2.71875 | 3 | [] | no_license | #include "Bomb.h"
Bomb::Bomb(float x, float y, float SpeedX, float SpeedY):
GameObject("images/bomb/bomb0.png", x, y, SpeedX, SpeedY)
{
parent = NULL;
relativeX = 0;
relativeY = 0;
time = 0.f;
Alive = true;
animation[0] = al_load_bitmap("images/bomb/bomb0.png");
animation[1] = al_load_bitmap("images/bomb/bomb1.png");
explodeSample = al_load_sample("sounds/rocket.wav");
xplode = al_load_bitmap("images/roboBoom.png");
}
Bomb::~Bomb(void)
{
}
void Bomb::Update(float delta, float gravity){
if(parent != NULL && !parent->isAliv())
parent = NULL;
if(parent == NULL){
SpeedY += gravity*delta;
SetX(x + SpeedX*delta);
SetY(y + SpeedY*delta);
SpeedX *= 0.999;
}else{
x = parent->GetX() + relativeX;
y = parent->GetY() + relativeY;
}
time += delta*3;
}
void Bomb::DrawBomb(){
if(parent == NULL)
al_draw_rotated_bitmap(animation[(int)time % 2], picW/2, picH/2, x, y, time*6, NULL);
else
al_draw_bitmap(animation[(int)time % 2], x, y, NULL);
}
void Bomb::Glue(GameObject* g){
parent = g;
relativeX = x - parent->GetX();
relativeY = y - parent->GetY();
}
GameObject* Bomb::getParent(){
return parent;
}
Effect* Bomb::Detonate(int p){
Alive = false;
Effect *e;
e = new Effect(xplode ,GetOriginX() - 85, GetOriginY() - 85, 0, - 10, 0.2);
e->setParentPlayerNumber(p);
al_play_sample(explodeSample, 1, 0.0,1.0,ALLEGRO_PLAYMODE_ONCE,NULL);
return e;
}
bool Bomb::isSticked(){
if(parent == NULL)
return false;
return true;
}
bool Bomb::isAlive(){
return Alive;
} |
Markdown | UTF-8 | 5,228 | 3.140625 | 3 | [] | no_license | # Web_html (웹사이트 완성)
우리는 Link 까지 배움으로 각각의 페이지를 역어 하나의 책으로 만들수 있는 방법을 배웠다 대신 이 Web 에선 이 책을 Website 라고 일컫는다.
그럼 우리는 이제 우리가 Webpage 를 만들고 역어 역어서 하나의 Website 로 만들어 볼 것이다.
```
파일명 : main.html
<!doctype html>
<html>
<head>
<title> Web html </title>
<mata charset="utf-8">
</head>
<body>
<h1><a href="main.html"> Web</a></h1>
<ol>
<li> <a href="1.html">HTML</a> </li>
<li> <a href="2.html">CSS</a> </li>
<li> <a href="3.html">JavaScript</a> </li>
</ol>
</body>
</html>
```
```
파일명 : 1.html
<!doctype html>
<html>
<head>
<h1><a href="main.html"> Web</a></h1>
<ol>
<li> <a href="1.html">HTML</a> </li>
<li> <a href="2.html">CSS</a> </li>
<li> <a href="3.html">JavaScript</a> </li>
</ol>
</head>
<body>
<h2>HTML </h2>
<h3>HTML 이란 무엇인가?</h3> <a href="https://ko.wikipedia.org/wiki/HTML" target="_blank" title="https://ko.wikipedia.org/wiki/HTML"><h4><strong> H</strong>yperT</strong>ext <strong>M</strong>arkup <strong>L</strong>anguage</a>
<p>
HTML또는 하이퍼텍스트 마크업 언어(HyperText Markup Language) 는 웹 페이지를 위한 지배적인 마크업 언어다. HTML은 제목, 단락, 목록 등과 같은 본문을 위한 구조적 의미를 나타내는 것뿐만 아니라 링크, 인용과 그 밖의 항목으로 구조적 문서를 만들 수 있는 방법을 제공한다.</h4>
</p>
<br><br>
<img src="1.jpg" width="70%">
</body>
</html>
```
```
파일명 : 2.html
<!doctype html>
<html>
<head>
<h1><a href="main.html"> Web</a></h1>
<ol>
<li> <a href="1.html">HTML</a> </li>
<li> <a href="2.html">CSS</a> </li>
<li> <a href="3.html">JavaScript</a> </li>
</ol>
</head>
<body>
<h2>CSS </h2>
<h3>CSS 란 무엇인가?</h3>
<a href="https://ko.wikipedia.org/wiki/%EC%A2%85%EC%86%8D%ED%98%95_%EC%8B%9C%ED%8A%B8" target="_blank" title="https://ko.wikipedia.org/wiki/%EC%A2%85%EC%86%8D%ED%98%95_%EC%8B%9C%ED%8A%B8"><h4><strong>C</strong>ascading <strong>S</strong>tyle <strong>S</strong>heets</a>
<p>
종속형 시트 또는 캐스케이딩 스타일 시트(Cascading Style Sheets, CSS)는 마크업 언어가 실제 표시되는 방법을 기술하는 언어로, HTML과 XHTML에 주로 쓰이며, XML에서도 사용할 수 있다. W3C의 표준이며, 레이아웃과 스타일을 정의할 때의 자유도가 높다.
마크업 언어(ex. HTML)가 웹사이트의 몸체를 담당한다면 CSS는 옷과 액세서리 같은 꾸미는 역할을 담당한다고 할 수 있다. 즉, HTML 구조는 그대로 두고 CSS 파일만 변경해도 전혀 다른 웹사이트처럼 꾸밀 수 있다.
현재 개발 중인 CSS3의 경우 그림자 효과, 그라데이션, 변형 등 그래픽 편집 프로그램으로 제작한 이미지를 대체할 수 있는 기능이 추가되었다. 또한 다양한 애니메이션 기능이 추가되어 어도비 플래시를 어느 정도 대체하고 있다.
</h4></p>
<br><br>
<img src="2.jpg" width="70%">
</body>
</html>
```
```
파일명 : 3.html
<!doctype html>
<html>
<head>
<h1><a href="main.html"> Web</a></h1>
<ol>
<li> <a href="1.html">HTML</a> </li>
<li> <a href="2.html">CSS</a> </li>
<li> <a href="3.html">JavaScript</a> </li>
</ol>
</head>
<body>
<h2>JavaScript </h2>
<h3>JavaScript 란 무엇인가?</h3>
<a href="https://ko.wikipedia.org/wiki/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8" title="https://ko.wikipedia.org/wiki/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8" target="_blank"><h4><strong>J</strong>ava<strong>S</strong>cript</a>
<p>
자바스크립트(영어: JavaScript)는 객체 기반의 스크립트 프로그래밍 언어이다. 이 언어는 웹 브라우저 내에서 주로 사용하며, 다른 응용 프로그램의 내장 객체에도 접근할 수 있는 기능을 가지고 있다. 또한 Node.js와 같은 런타임 환경과 같이 서버 사이드 네트워크 프로그래밍에도 사용되고 있다. 자바스크립트는 본래 넷스케이프 커뮤니케이션즈 코퍼레이션의 브렌던 아이크(Brendan Eich)가 처음에는 모카(Mocha)라는 이름으로, 나중에는 라이브스크립트(LiveScript)라는 이름으로 개발하였으며, 최종적으로 자바스크립트가 되었다.</h4>
</p>
<img src="3.jpg" width="70%"
</body>
</html>
```
우리는 위처럼 각각의 main, 1, 2, 3 이라는 html 로 작성된 WebPage 를 link 로 역어서 하나의 Website 처럼 만들수 있다.
## 키워드
Website : Webpage 를 link 로 역어서 구성한 하나의 완성된 사이트로 마치 Page 로 역인 하나의 책과 같다.
Webpage : 하나의 Page 로 이것들을 link 들로 역고 역어서 하나의 Website 가 완성된다.
link : page 와 page , site 와 site 를 연결 시켜주는 방법 이 떄 Tag a 와 href 로 경로 지정을 해준다.
## 참고
[생활코딩](https://opentutorials.org/course/3084/18431)
|
C++ | UTF-8 | 1,912 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | #include "stdafx.h"
// General
#include "ObjectGUID.h"
// Additional
#include <sstream>
#include <iomanip>
CWoWObjectGuid const CWoWObjectGuid::Empty = CWoWObjectGuid();
char const* CWoWObjectGuid::GetTypeName(EWoWObjectHighGuid high)
{
switch (high)
{
case EWoWObjectHighGuid::Item: return "Item";
case EWoWObjectHighGuid::Player: return "Player";
case EWoWObjectHighGuid::GameObject: return "Gameobject";
case EWoWObjectHighGuid::Transport: return "Transport";
case EWoWObjectHighGuid::Unit: return "Creature";
case EWoWObjectHighGuid::Pet: return "Pet";
case EWoWObjectHighGuid::Vehicle: return "Vehicle";
case EWoWObjectHighGuid::DynamicObject: return "DynObject";
case EWoWObjectHighGuid::Corpse: return "Corpse";
case EWoWObjectHighGuid::Mo_Transport: return "MoTransport";
case EWoWObjectHighGuid::Instance: return "InstanceID";
case EWoWObjectHighGuid::Group: return "Group";
default:
return "<unknown>";
}
}
std::string CWoWObjectGuid::ToString() const
{
std::ostringstream str;
str << "GUID Full: 0x" << std::hex << std::setw(16) << std::setfill('0') << _guid << std::dec;
str << " Type: " << GetTypeName();
if (HasEntry())
str << (IsPet() ? " Pet number: " : " Entry: ") << GetEntry() << " ";
str << " Low: " << GetCounter();
return str.str();
}
CWoWObjectGuid CWoWObjectGuid::Global(EWoWObjectHighGuid type, CounterType_t counter)
{
return CWoWObjectGuid(type, counter);
}
CWoWObjectGuid CWoWObjectGuid::MapSpecific(EWoWObjectHighGuid type, uint32 entry, CounterType_t counter)
{
return CWoWObjectGuid(type, entry, counter);
}
CByteBuffer& operator<<(CByteBuffer& buf, const CWoWObjectGuid& guid)
{
buf << uint64(guid.GetRawValue());
return buf;
}
CByteBuffer& operator>>(CByteBuffer& buf, CWoWObjectGuid& guid)
{
uint64 value;
buf.readBytes(&value, sizeof(uint64));
guid.Set(value);
return buf;
} |
JavaScript | UTF-8 | 1,741 | 3.203125 | 3 | [] | no_license | import apiManager from "./apiManager.js"
import contactListPrinter from "./contactList.js"
// get contacts from json server
apiManager.getAllContacts().then(parsedContacts => {
// loop through contacts from json server
parsedContacts.forEach(contact => {
contactListPrinter.printSingleEntry(contact)
})
});
// collect form field values
// use doc.querySel to select your input fields
// use .value property on input field elements to get the text that was typed
document.querySelector("#contact-submit-btn").addEventListener("click", function() {
const nameInput = document.querySelector("#contact-name-input").value;
const phoneInput = document.querySelector("#contact-phone-input").value;
const emailInput = document.querySelector("#contact-email-input").value;
const newContactEntry = {
name: nameInput,
phone: phoneInput,
email: emailInput
};
// use POST method to create resources
// use FETCH to create contact entry in the API. the code below saves the contact info to the API
apiManager.postOneContact(newContactEntry)
.then(apiManager.getAllContacts)
.then(parsedEntries => {
document.querySelector("#contact-output-container").innerHTML = ""
// loop through the contacts from json server
parsedEntries.forEach(contact => {
contactListPrinter.printSingleEntry(contact)
});
});
});
// --------CLICK EVENT FOR DELETE BUTTONS------
// add event listener to the body element because the delete button does not exist upon page load.
document.querySelector("body").addEventListener("click", () => {
// if the user clicks on the delete button, do some stuff
if(event.target.id.includes(""))
}) |
Java | UTF-8 | 396 | 1.921875 | 2 | [] | no_license | package com.gz.manager.domain;
/**
* 描述:<br>
* 版权:Copyright (c) 2011-2018<br>
* 公司:北京活力天汇<br>
* 作者:龚钊<br>
* 版本:1.0<br>
* 创建日期:2019年02月19日<br>
*/
public class UserName {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
JavaScript | UTF-8 | 2,426 | 2.6875 | 3 | [] | no_license | const sql = require("./connection");
// constructor
const Teacher = function (teacher) {
this.teacherID = teacher.teacherID;
this.fullName = teacher.fullName;
this.gender = teacher.gender;
this.birthday = teacher.birthday;
this.cccd = teacher.cccd;
this.position = teacher.position;
this.addressName = teacher.addressName;
this.phone = teacher.phone;
this.email = teacher.email;
this.reportsTo = teacher.reportsTo
};
Teacher.getAll = result => {
sql.query("select t.teacherID, t.fullName, t.position,"
+ " date_format(t.birthday, \"%d/%m/%Y\") as birthday , "
+ "c.className from teacher t left join class c on c.teacherID = t.teacherID;",
(err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("teacher list: ", res);
result(null, res);
});
};
Teacher.create = (newTeacher, result) => {
sql.query("INSERT INTO teacher SET ?", newTeacher, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created teacher: ", {id: res.insertId, ...newTeacher});
result(null, {id: res.insertId, ...newTeacher});
});
};
Teacher.delete = (teacherID, result) => {
sql.query("delete from teacher where teacherID = ?", teacherID, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows === 0) {
// not found Account with the id
result({kind: "not_found"}, null);
return;
}
console.log("deleted teacher with teacher id: ", teacherID);
result(null, res);
});
};
Teacher.updateById = (teacher, result) => {
sql.query("UPDATE teacher SET " +
"fullName = ?, gender = ?, birthday = ?, cccd = ?" +
",addressName = ?, phone = ?, email = ? WHERE teacherID = ?",
[teacher.fullName, teacher.gender, teacher.birthday, teacher.cccd,
teacher.addressName, teacher.phone, teacher.email, teacher.teacherID],
(err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows === 0) {
// not found Teacher with the id
result({kind: "not_found"}, null);
return;
}
console.log("updated teacher: ", {...teacher});
result(null, {...teacher});
}
);
};
module.exports = Teacher; |
TypeScript | UTF-8 | 2,750 | 2.875 | 3 | [] | no_license | import User, { UserInstance } from '../models/User';
import { Op } from 'sequelize';
import bcrypt from 'bcryptjs';
export class UserService {
async create(name: string, email: string, password: string): Promise<UserInstance | null> {
let user = null;
if (await this.existingEmail(email)) {
return null;
}
try {
let hash = bcrypt.hashSync(password, bcrypt.genSaltSync(10));
user = await User.create({ name, email, password: hash });
} catch (err) {
console.log('Ocorreu um erro ao criar o usuário:', err);
}
return user;
}
async update(id: number, name: string, email: string, password: string): Promise<boolean> {
if (await this.existingEmail(email, id)) {
return false;
}
try {
let hash = bcrypt.hashSync(password, bcrypt.genSaltSync(10));
await User.update({ name, email, password: hash }, { where: { id } });
} catch (err) {
console.log('Erro ao atualizar o usuário:', err);
return false;
}
return true;
}
async delete(id: number): Promise<boolean> {
try {
await User.destroy({ where: { id } });
} catch (err) {
console.log('Ocorreu um erro ao excluir o usuário:', err);
return false;
}
return true;
}
async findById(id: number): Promise<UserInstance | null> {
let user = null;
try {
user = await User.findByPk(id);
} catch (err) {
console.log('Ocorreu um erro ao buscar o usuário:', err);
}
return user;
}
async findByEmail(email: string): Promise<UserInstance | null> {
let user = null;
try {
user = await User.findOne({ where: { email } });
} catch(err) {
console.log('Ocurreu um erro ao buscar o usuário:', err);
}
return user;
}
async getAll(): Promise<UserInstance[]> {
let emails = await User.findAll();
return emails;
}
async existingEmail(email: string, ignore_id: number = 0): Promise<boolean> {
let where: any = { email };
if (ignore_id > 0) {
where.id = {
[Op.ne]: ignore_id
};
}
let emails = await User.findAll({ where });
return (emails.length > 0);
}
async login(email: string, password: string): Promise<UserInstance | null> {
let user = await this.findByEmail(email);
if(user) {
if(bcrypt.compareSync(password, user.password)) {
return user;
}
}
return null;
}
} |
Python | UTF-8 | 1,012 | 3.03125 | 3 | [] | no_license | '''
Define funções responsáveis pelo controle interno da aplicação (ações, por exemplo)
'''
import datetime as dt
import monitoradas
import constantes as cte
def update_action(app, action=None):
'''
Atualiza o texto que indica a ação sendo realizada pela aplicação ('Edição', 'Remoção', etc.).
Esse texto aparece no canto inferior direito e é removido após 1 segundo se não forem
realizadas outras ações.
'''
current_time = dt.datetime.today()
if action is None:
if current_time - monitoradas.last_call >= dt.timedelta(seconds=1):
monitoradas.cur_action.set('')
return
monitoradas.last_call = current_time
monitoradas.cur_action.set(cte.ACTIONS.get(action, action))
# Após 1 segundo, rechamaremos essa função sem especificar uma action no argumento
# o que fará o texto sumir caso nenhuma outra ação tenha ocorrido durante esse 1 segundo.
app.root.after(1000, lambda *_: update_action(app))
|
TypeScript | UTF-8 | 1,382 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | import { buildParams, getCommonOptions, Omit } from 'miniprogram-network-utils';
import { UploaderResponse, UploadOption, wx } from './uploader';
/**
* 微信请求参数 (不包含回调函数)
*/
export type UploadParams = Omit<wx.UploadFileOption, 'success' | 'fail' | 'complete'>;
/**
* 构建请求参数
* baseUrl和dataUrl不同时为空
* @param data - 完整参数
*/
export function transformUploadSendDefault(data: UploadOption): UploadParams {
return getCommonOptions<Partial<UploadParams>>(
{
url: buildParams(data.url || '', data.params, data.baseURL),
formData: data.data,
header: data.headers
},
data,
['filePath', 'name']) as UploadParams;
}
/**
* 根据错误码处理数据(会尝试JSON.parse)
* statusCode 2xx 操作成功仅返回data数据
* 否则抛出错误(rejected)
* @param res - 返回结果
* @param options - 全部配置
* @returns 反序列化对象
*/
export function transformUploadResponseOkData<T = any>(res: UploaderResponse, options: UploadOption): T {
if (res.statusCode >= 200 && res.statusCode < 300) {
if (typeof res.data === 'string') {
try {
return JSON.parse(res.data) as T;
} catch {
// empty
}
}
return res.data as any as T;
}
throw res;
}
|
Java | UTF-8 | 615 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | package com.itvillage.chapter05.chapter0501;
import com.itvillage.utils.LogType;
import com.itvillage.utils.Logger;
import com.itvillage.utils.TimeUtil;
import io.reactivex.Observable;
import java.util.concurrent.TimeUnit;
public class ObservableTimerExample {
public static void main(String[] args) {
Logger.log(LogType.PRINT, "# Start!");
Observable<String> observable =
Observable.timer(2000, TimeUnit.MILLISECONDS)
.map(count -> "Do work!");
observable.subscribe(data -> Logger.log(LogType.ON_NEXT , data));
TimeUtil.sleep(3000);
}
}
|
TypeScript | UTF-8 | 297 | 2.625 | 3 | [] | no_license | import { isBefore, startOfDay } from 'date-fns';
import { MilestoneType } from 'src/app/domain/milestone';
export abstract class AbstractMilestone {
abstract type: MilestoneType;
abstract isValid(): boolean;
isExpired(date: Date) {
return isBefore(startOfDay(new Date()), date);
}
}
|
Markdown | UTF-8 | 3,104 | 3.3125 | 3 | [] | no_license | ---
layout: post
title: leetcode 第 341 场算法比赛
description: 树形DP,屡试不爽?
keywords: 算法,leetcode,算法比赛
tags: [算法,leetcode,算法比赛]
categories: [算法]
updateData: 2023-04-16 18:13:00
published: true
---
## 零、背景
这次比赛比较简单,拼手速的时候到了。
## 一、一最多的行
题意:给一个矩阵,问矩阵的哪一行之和最大,有多个时输出第一个。
思路:循环计算,比大小即可。
小技巧:`accumulate`函数可以快速计算一行的和。
## 二、找出可整除性得分最大的整数
题意:给一批分母和分子,问分母和分子组合里面,能被分母整除最多的分子的值,如果有多个,输出最小的分子。
思路:数据范围不大,两层循环判断、比较。
## 三、构造有效字符串的最少插入数
题意:给一个只包含`abc` 三个字符的字符串,问至少多少个字符,才能使得字符串保持为`(abc)+`的格式。
思路:贪心。
上一个字母是固定的,当前字母是固定的,中间插入的最少字母也是固定的。
组合分 9 中情况。
1) 3 种前后字母相同,`aa`,`bb`,`cc`,需要插入两个字符。
2) 前后字母正序相邻,`ab`,`bc`,`ca`,不需要插入字符。
3) 其他情况,`ac`,`ba`,`cb`,需要插入一个字符。
按照这个规则循环计算答案即可。
小技巧:可以把 9 中规则做成 map 映射表,循环相加即可。
## 四、最小化旅行的价格总和
题意:给一个树代表城市之间到道路,给若干路径代表城市之间的旅行计划,每个城市有过路费。
问现在可以对一批不相邻的节点集合的过路费打5折,问怎么选择这个集合,才能使得旅行的总过路费最小。
思路:典型的树形DP,之前分享无数次了。
不过这道题需要先进行数据建模,即将原始问题转化为树形DP问题。
不打折的情况下,旅行的过路费是固定的,即所有旅行的过路费的和。
问题稍微转化一下,答案就变成了所有城市收取的过路费之和。
即旅行次数问题,转化为城市收费次数问题。
第一步可以通过求所有的 LCA,预处理所有旅行,计算出每个城市被经过的次数。
第二步即可使用树形DP来做这道题了。
对于每个节点子树,可以计算当前打折与不打折两种情况的最小费用。
对于一个父节点,选择了,子节点就不能选择;没选择,则子节点任意选择,最终取最小费用。
## 五、最后
思考题1:第二题原题分子和分母的数据范围是 1000,修改为 10万该如何做呢?
思考题2:第三题是求一个字符串的串联,如果修改为可选的 n 个字符串的串联,怎么做呢?
《完》
-EOF-
本文公众号:天空的代码世界
个人微信号:tiankonguse
公众号ID:tiankonguse-code
|
Python | UTF-8 | 2,136 | 2.859375 | 3 | [] | no_license | #-*-coding:utf-8-*-
from numpy import *
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import time
def sigmod (num) :
return 1.0 / (1 + exp (-num));
def gradientDescent (train_x , train_y , operation) :
startTime = time.time ()
cntSample , cntFeature = shape (train_x)
alpha = operation['alpha']
maxIteration = operation['maxIteration']
weight = ones ((cntFeature , 1))
if operation['optimizeType'] == 'gradDescent' :
#normal gradient descent algorithm
for cntIteration in range (maxIteration) :
get_y = sigmod (train_x * weight)
error = (get_y - train_y)
weight = weight - alpha * train_x.T * error
elif operation['optimizeType'] == 'randomGradDescent' :
#random gradient descent algorithm
for i in range (cntSample) :
get_y = sigmod (train_x[i , :] * weight)
error = (get_y - train_y[i , 0])
weight = weight - alpha * train_x[i , :].T * error
elif operation['optimizeType'] == 'smoothRandomGradDescent' :
#smooth random gradident descent algorithm
for cntIteration in range (maxIteration) :
dataIndex = range (cntSample)
for i in range (cntSample) :
alpha = 4.0 / (1 + cntIteration + i) + 0.01
randInt = int (random.uniform (0 , len (dataIndex)))
index = dataIndex[randInt]
gety_y = sigmod (train_x[index , :] * weight)
error = (gety_y - train_y[index , 0])
weight = weight - alpha * train_x[index , :].T * error
del (dataIndex[randInt])
print 'Congratulations, training complete! Took %fs!' % (time.time() - startTime)
print 'the final error for train set is %f!' % (sum (square ((sigmod (train_x * weight) - train_y))) / 2.0)
return weight
def showLogistic (train_x , train_y) :
cntSample , cntFeature = shape (train_x)
weight = gradientDescent (train_x , train_y , {'alpha' : 0.01 , 'maxIteration' : 500 , 'optimizeType' : 'gradDescent'})
return weight
def testLogistic (test_x , test_y , weight) :
cntSample , cntFeature = shape (test_x)
cntMatch = 0
for i in range (cntSample) :
if (sigmod (test_x[i , :] * weight)[0 , 0] > 0.5) == bool (test_y[i , 0] - 1.0) :
cntMatch += 1
return cntMatch * 1.0 / cntSample |
PHP | UTF-8 | 13,227 | 2.65625 | 3 | [] | no_license | <?php
/**
* Yii view VoiUtil
*
* @author luunguyen
* @since Oct 2, 2012 - 10:30:44 AM
*/
class VoiUtil
{
static function currentUrl($full = TRUE)
{
return $full ? "http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"] : $_SERVER["REQUEST_URI"];
}
static function word_limiter($str, $limit = 100, $end_char = '…')
{
if (trim($str) == '')
{
return $str;
}
preg_match('/^\s*+(?:\S++\s*+){1,' . (int) $limit . '}/', $str, $matches);
if (strlen($str) == strlen($matches[0]))
{
$end_char = '';
}
return strip_tags(rtrim($matches[0]) . $end_char);
}
static function timeToString($time = 0)
{
if (!$time)
{
return "";
}
$time = time() - $time;
$y = intval($time / (3600 * 24 * 365));
if ($y > 0)
{
return "$y năm trước";
}
$d = intval($time / (3600 * 24));
if ($d > 0)
{
return "$d ngày trước";
}
$h = intval($time / 3600);
if ($h > 0)
{
return "$h giờ trước";
}
$m = intval($time / 60);
if ($m > 0)
{
return "$m phút trước";
}
return "$time giây trước";
}
static function formatTime($time)
{
return date('d-m-Y H:i:s', $time);
}
public static function vn_url_filename($chuTiengViet)
{
$trans = array(
'à' => 'a', 'á' => 'a', 'ả' => 'a', 'ã' => 'a', 'ạ' => 'a',
'ă' => 'a', 'ằ' => 'a', 'ắ' => 'a', 'ẳ' => 'a', 'ẵ' => 'a', 'ặ' => 'a',
'â' => 'a', 'ầ' => 'a', 'ấ' => 'a', 'ẩ' => 'a', 'ẫ' => 'a', 'ậ' => 'a',
'À' => 'a', 'Á' => 'a', 'Ả' => 'a', 'Ã' => 'a', 'Ạ' => 'a',
'Ă' => 'a', 'Ằ' => 'a', 'Ắ' => 'a', 'Ẳ' => 'a', 'Ẵ' => 'a', 'Ặ' => 'a',
'Â' => 'a', 'Ầ' => 'a', 'Ấ' => 'a', 'Ẩ' => 'a', 'Ẫ' => 'a', 'Ậ' => 'a',
'đ' => 'd', 'Đ' => 'd',
'è' => 'e', 'é' => 'e', 'ẻ' => 'e', 'ẽ' => 'e', 'ẹ' => 'e',
'ê' => 'e', 'ề' => 'e', 'ế' => 'e', 'ể' => 'e', 'ễ' => 'e', 'ệ' => 'e',
'È' => 'e', 'É' => 'e', 'Ẻ' => 'e', 'Ẽ' => 'e', 'Ẹ' => 'e',
'Ê' => 'e', 'Ề' => 'e', 'Ế' => 'e', 'Ể' => 'e', 'Ễ' => 'e', 'Ệ' => 'e',
'ì' => 'i', 'í' => 'i', 'ỉ' => 'i', 'ĩ' => 'i', 'ị' => 'i',
'Ì' => 'i', 'Í' => 'i', 'Ỉ' => 'i', 'Ĩ' => 'i', 'Ị' => 'i',
'ò' => 'o', 'ó' => 'o', 'ỏ' => 'o', 'õ' => 'o', 'ọ' => 'o',
'ô' => 'o', 'ồ' => 'o', 'ố' => 'o', 'ổ' => 'o', 'ỗ' => 'o', 'ộ' => 'o',
'ơ' => 'o', 'ờ' => 'o', 'ớ' => 'o', 'ở' => 'o', 'ỡ' => 'o', 'ợ' => 'o',
'Ò' => 'o', 'Ó' => 'o', 'Ỏ' => 'o', 'Õ' => 'o', 'Ọ' => 'o',
'Ô' => 'o', 'Ồ' => 'o', 'Ố' => 'o', 'Ổ' => 'o', 'Ỗ' => 'o', 'Ộ' => 'o',
'Ơ' => 'o', 'Ờ' => 'o', 'Ớ' => 'o', 'Ở' => 'o', 'Ỡ' => 'o', 'Ợ' => 'o',
'ù' => 'u', 'ú' => 'u', 'ủ' => 'u', 'ũ' => 'u', 'ụ' => 'u',
'ư' => 'u', 'ừ' => 'u', 'ứ' => 'u', 'ử' => 'u', 'ữ' => 'u', 'ự' => 'u',
'Ù' => 'u', 'Ú' => 'u', 'Ủ' => 'u', 'Ũ' => 'u', 'Ụ' => 'u',
'Ư' => 'u', 'Ừ' => 'u', 'Ứ' => 'u', 'Ử' => 'u', 'Ữ' => 'u', 'Ự' => 'u',
'ỳ' => 'y', 'ý' => 'y', 'ỷ' => 'y', 'ỹ' => 'y', 'ỵ' => 'y',
'Y' => 'y', 'Ỳ' => 'y', 'Ý' => 'y', 'Ỷ' => 'y', 'Ỹ' => 'y', 'Ỵ' => 'y',
' - ' => '-', ' ' => '-'
);
$str = strtolower(strtr($chuTiengViet, $trans));
$str = ltrim($str, '-');
$str = rtrim($str, '-');
return $str;
}
public static function vn_url_title($chuTiengViet)
{
$trans = array(
'à' => 'a', 'á' => 'a', 'ả' => 'a', 'ã' => 'a', 'ạ' => 'a',
'ă' => 'a', 'ằ' => 'a', 'ắ' => 'a', 'ẳ' => 'a', 'ẵ' => 'a', 'ặ' => 'a',
'â' => 'a', 'ầ' => 'a', 'ấ' => 'a', 'ẩ' => 'a', 'ẫ' => 'a', 'ậ' => 'a',
'À' => 'a', 'Á' => 'a', 'Ả' => 'a', 'Ã' => 'a', 'Ạ' => 'a',
'Ă' => 'a', 'Ằ' => 'a', 'Ắ' => 'a', 'Ẳ' => 'a', 'Ẵ' => 'a', 'Ặ' => 'a',
'Â' => 'a', 'Ầ' => 'a', 'Ấ' => 'a', 'Ẩ' => 'a', 'Ẫ' => 'a', 'Ậ' => 'a',
'đ' => 'd', 'Đ' => 'd',
'è' => 'e', 'é' => 'e', 'ẻ' => 'e', 'ẽ' => 'e', 'ẹ' => 'e',
'ê' => 'e', 'ề' => 'e', 'ế' => 'e', 'ể' => 'e', 'ễ' => 'e', 'ệ' => 'e',
'È' => 'e', 'É' => 'e', 'Ẻ' => 'e', 'Ẽ' => 'e', 'Ẹ' => 'e',
'Ê' => 'e', 'Ề' => 'e', 'Ế' => 'e', 'Ể' => 'e', 'Ễ' => 'e', 'Ệ' => 'e',
'ì' => 'i', 'í' => 'i', 'ỉ' => 'i', 'ĩ' => 'i', 'ị' => 'i',
'Ì' => 'i', 'Í' => 'i', 'Ỉ' => 'i', 'Ĩ' => 'i', 'Ị' => 'i',
'ò' => 'o', 'ó' => 'o', 'ỏ' => 'o', 'õ' => 'o', 'ọ' => 'o',
'ô' => 'o', 'ồ' => 'o', 'ố' => 'o', 'ổ' => 'o', 'ỗ' => 'o', 'ộ' => 'o',
'ơ' => 'o', 'ờ' => 'o', 'ớ' => 'o', 'ở' => 'o', 'ỡ' => 'o', 'ợ' => 'o',
'Ò' => 'o', 'Ó' => 'o', 'Ỏ' => 'o', 'Õ' => 'o', 'Ọ' => 'o',
'Ô' => 'o', 'Ồ' => 'o', 'Ố' => 'o', 'Ổ' => 'o', 'Ỗ' => 'o', 'Ộ' => 'o',
'Ơ' => 'o', 'Ờ' => 'o', 'Ớ' => 'o', 'Ở' => 'o', 'Ỡ' => 'o', 'Ợ' => 'o',
'ù' => 'u', 'ú' => 'u', 'ủ' => 'u', 'ũ' => 'u', 'ụ' => 'u',
'ư' => 'u', 'ừ' => 'u', 'ứ' => 'u', 'ử' => 'u', 'ữ' => 'u', 'ự' => 'u',
'Ù' => 'u', 'Ú' => 'u', 'Ủ' => 'u', 'Ũ' => 'u', 'Ụ' => 'u',
'Ư' => 'u', 'Ừ' => 'u', 'Ứ' => 'u', 'Ử' => 'u', 'Ữ' => 'u', 'Ự' => 'u',
'ỳ' => 'y', 'ý' => 'y', 'ỷ' => 'y', 'ỹ' => 'y', 'ỵ' => 'y',
'Y' => 'y', 'Ỳ' => 'y', 'Ý' => 'y', 'Ỷ' => 'y', 'Ỹ' => 'y', 'Ỵ' => 'y',
' - ' => '-', ' ' => '-'
);
$str = strtolower(strtr($chuTiengViet, $trans));
$str = preg_replace('/[^a-zA-Z0-9\s\-]/', '', $str);
$str = ltrim($str, '-');
$str = rtrim($str, '-');
return $str;
}
public static function getEmbedYoutubeUrl($url)
{
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $matches);
$youtube_id = isset($matches[0]) ? $matches[0] : '#';
return 'http://www.youtube.com/embed/' . $youtube_id;
}
public static function moneyFormat($money)
{
return self::numberFormat($money) . " đ";
}
public static function numberFormat($number)
{
return number_format($number, 0, ",", ".");
}
public static function weekList($year, $month)
{
$array = array();
$temp = strtotime("$year/$month/01");
$temp_month = $month;
//neu dau tuan van nho hon tuan ke tiep
while ($temp_month == $month)
{
if (date('w', $temp) == 1)
{
$monday = $temp;
}
else
{
$monday = strtotime('last monday', $temp);
}
$sunday = strtotime('this sunday', $temp);
$array[$monday] = date('d/m - ', $monday) . date('d/m', $sunday);
$temp += 7 * 24 * 60 * 60;
$temp_month = date('m', $temp);
}
return $array;
}
public static function weekList2($start_date, $end_date)
{
$array = array();
$temp = $start_date;
//neu dau tuan van nho hon tuan ke tiep
while ($temp <= $end_date)
{
$int_week = (int) date('W', $temp);
$monday = strtotime('last monday', $temp);
$sunday = strtotime('this sunday', $temp);
$array[] = array(
'start' => $monday,
'end' => $sunday,
'week' => $int_week
);
$temp = strtotime('next monday', $temp);
}
return $array;
}
public static function yearList()
{
$year = (int) date('Y', time());
$start_year = $year - 5;
$end_year = $year + 5;
$rtn = array();
for ($i = $start_year; $i <= $end_year; $i++)
{
$rtn[$i] = $i;
}
return $rtn;
}
public static function monthList()
{
$rtn = array();
for ($i = 1; $i <= 12; $i++)
{
$rtn[$i] = "Tháng $i";
}
return $rtn;
}
public static function dateToTime($date)
{
$dateArray = explode('/', $date);
return strtotime($dateArray[2] . "/" . $dateArray[1] . "/" . $dateArray[0]);
}
static function resizePhoto($img, $width = FALSE, $height = FALSE)
{
$original_dir = 'files';
$output_dir = 'cache';
$original_path = Yii::app()->baseUrl . "/$original_dir/";
$base_image_path = trim(str_replace($original_path, "", $img), './');
$original_file = "$original_dir/$base_image_path";
if (!file_exists($original_file) OR $img == NULL)
{
$base_image_path = 'no-image.png';
$original_file = "$original_dir/$base_image_path";
}
$output_file = "$output_dir/{$width}x{$height}/$base_image_path";
// Neu chua ton tai forder thi tao
if (!is_dir(dirname($output_file)))
{
@mkdir(dirname($output_file), 0777, true);
}
// Neu Khong ton tai anh thi crop anh
if (!file_exists($output_file))
{
self::doResize($original_file, $output_file, $width, $height);
}
return Yii::app()->baseUrl . "/" . $output_file;
}
static function doResize($original_file, $output_file, $width = FALSE, $height = FALSE)
{
$thumb = Yii::app()->phpThumb->create($original_file);
if ($width == FALSE && $height)
{
$thumb->resizeByHeight($height);
}
elseif ($width && $height == FALSE)
{
$thumb->resizeByHeight($height);
}
elseif ($width && $height)
{
$thumb->adaptiveResize($width, $height);
}
else
{
return $original_file;
}
$thumb->save($output_file);
return $output_file;
}
static function makeRequest($url, $method, $fields = array())
{
$fieldsString = http_build_query($fields);
$ch = curl_init();
if ($method == 'POST')
{
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);
}
else
{
$url .= '?' . $fieldsString;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false); // we want headers
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$return['response'] = $result;
$return['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$log = date('d/m/Y H:i:s') . " \n\t $method : $url | " . json_encode($fields);
$log .= "\n\t Respone " . $return['status'] . " : $result";
self::log('call', $log);
return $return;
}
// static function makeJsonRequest($url, $method = "POST", $data = array())
// {
// $data_string = json_encode($data);
//
// $ch = curl_init($url);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_HTTPHEADER, array(
// 'Content-Type: application/json',
// 'Content-Length: ' . strlen($data_string))
// );
//
// $result = curl_exec($ch);
// $return['response'] = $result;
// $return['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//
// curl_close($ch);
//
// $log = date('d/m/Y H:i:s') . " \n\t $method : $url | " . $data_string;
// $log .= "\n\t Respone " . $return['status'] . " : $result";
// self::log('call', $log);
// return $return;
// }
static public function log($name, $content)
{
$year = date('Y');
$month = date('m');
$day = date('d');
$hour = date('H');
$dir = dirname(__file__) . "/../../log/$year/$month/$day/$hour";
@mkdir($dir, 0777, TRUE);
@chmod($dir, 0777);
// @chown($dir, "apache");
$filename = "$dir/$name";
$data = $content . "\n";
@file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
}
static function formatPhone($phone, $code = "84")
{
if (strpos($phone, $code) === false)
{
return $code . ltrim($phone, "0");
}
else
{
return $phone;
}
}
}
|
TypeScript | UTF-8 | 886 | 2.796875 | 3 | [] | no_license | import styled from "styled-components";
import { Button as SemanticButton } from "semantic-ui-react";
import { ITheme } from "constants/theme";
enum Emphasis {
primary = "primary",
secondary = "secondary",
warning = "warning",
}
const EMPHASIS = {
primary: "primary",
secondary: "secondary",
warning: "warning",
};
const COLORS = {
[Emphasis.primary]: "primary",
[Emphasis.secondary]: "secondary",
[Emphasis.warning]: "error",
};
const getColor = (emphasis: Emphasis = Emphasis.primary) => COLORS[emphasis];
interface IProps extends SemanticButton {
emphasis?: Emphasis;
theme: ITheme;
}
export const Button = styled(SemanticButton).attrs(({ emphasis }: IProps) =>
emphasis !== EMPHASIS.secondary
? {
primary: true,
}
: {}
)`
background: ${({ theme: { colors }, emphasis }: IProps) =>
colors[getColor(emphasis)]} !important;
`;
|
Markdown | UTF-8 | 939 | 3.109375 | 3 | [] | no_license | ### Schedule
**9:00 am**: Coffee up, squad.
**9:30 am**: Present Project Luther!
**12:00 pm**: Must we eat lunch?
**1:00 pm**: Even more Luther.
**2:00 pm**: Start your blogs, finish project, prepare for trivia!
Second project done, third project starting on Monday!
Take this time to wrap up Luther. You won't have time to look back much as we move forward!
Before Monday, you should have:
* A Luther GitHub repository (with a nice descriptive name, not "luther") with your code and a README with any relevant links, such as links to your presentation deck online and/or your write-up (see next).
* A write-up of your project work as a blog post. This can have more technical depth and completeness than your presentation. You could also write up short posts about particular aspects of your project. For example, you could write a post about data collection, a post with visualizations, and a post about your regression work. |
Java | UTF-8 | 1,973 | 2.4375 | 2 | [] | no_license | package steps;
import pages.YandexMarketElectronicsTVPage;
import ru.yandex.qatools.allure.annotations.Step;
public class StepsYandexMarketElectronicsTVPage {
@Step("открыть все фильтры")
public void clickAllFilters() {
new YandexMarketElectronicsTVPage().clickAllFilters();
}
@Step("поле 'цена от' заполняется значением {0}")
public void minPriceFromTV(String value) {
new YandexMarketElectronicsTVPage().minPriceFromTV(value);
}
@Step("выбрать производителя {0}")
public void сheckboxTVPage (String Item3){
new YandexMarketElectronicsTVPage().сheckboxTVPage(Item3);
}
@Step("применить фильтры")
public void applyFilters() {
new YandexMarketElectronicsTVPage().applyFilters();
}
@Step("выбрать отображение 12 элементов на странице")
public void twelveElement() {
new YandexMarketElectronicsTVPage().twelveElement(); }
@Step("проверить, что количество показанных элементов = \"{0}\"")
public void checkElementsOnPage(int item) {
new YandexMarketElectronicsTVPage().checkElementsOnPage(item); }
@Step("запомнить первый эелемент в списке")
public void getTextOfFirstBlockElement() {
new YandexMarketElectronicsTVPage().getTextOfFirstBlockElement(); }
@Step("в поисковую строку ввести запомненное значение")
public void inputFirstItemText() {
new YandexMarketElectronicsTVPage().inputFirstItemText(); }
@Step("найти и проверить, что наименование товара соответствует запомненному значению.")
public void checkTitleOfElement() {
new YandexMarketElectronicsTVPage().checkTitleOfElement(); }
}
|
PHP | UTF-8 | 2,243 | 3.390625 | 3 | [] | no_license | <?php
class Page{
private $total; //保存所有的数据表记录的总条数
private $page; //保存当前是第几页
private $num; //保存每页显示记录的条数
private $pageNum; //保存一共分的页数
private $offset ; //保存从数据库中取得的记录的开始偏移数
function __construct($total,$page=1,$num=5){
$this->total = $total;
$this->page = $page;
$this->num = $num;
$this->pageNum = $this->getPageNum();
$this->offset = $this->getOffset();
}
private function getPageNum(){
return ceil($this->total/$this->num); //返回记录的总页数
}
private function getNextPage(){
if($this->page==$this->pageNum){ //判断是不是最后一页
return false ;
}
return $this->page + 1;
}
private function getPrevPage(){
if($this->page==1){
return false;
}
return $this->page - 1;
}
private function getOffset(){
return ($this->page-1)*$this->num;
}
private function getStartNum(){ //调用这个方法,返回当前页开始的记录偏移数
if($this->total==0)
return 0; //若是表中没有记录,返回0
else
return $this->offset + 1; //若是表中有记录,返回记录开始偏移数
}
private function getEndNum(){
return min($this->offset+$this->num,$this->total);
}
public function getPageInfo(){
$pageInfo = array(
"row_total" => $this->total,
"row_num" => $this->num,
"page_num" => $this->getPageNum(),
"current_page" => $this->page,
"row_offset" => $this->getOffset(),
"next_page" => $this->getNextPage(),
"prev_page" => $this->getPrevPage(),
"page_start" => $this->getStartNum(),
"page_end" => $this->getEndNum()
);
return $pageInfo;
}
}
?>
|
C# | UTF-8 | 612 | 3.78125 | 4 | [] | no_license | using System;
namespace P06CalculateTriangleArea
{
class Program
{
static void Main(string[] args)
{
double triangleBase = double.Parse(Console.ReadLine());
double triangleHeight = double.Parse(Console.ReadLine());
double area = GetTriangleArea(triangleBase, triangleHeight);
Console.WriteLine(area);
//main ends here
}
static double GetTriangleArea(double triangleBase, double triangleHeight)
{
return triangleBase * triangleHeight / 2.0;
}
//class ends here
}
}
|
C++ | UTF-8 | 2,709 | 2.96875 | 3 | [] | no_license | #include "SmokeManager.h"
#include <time.h>
#include <Windows.h>
#include <GL/glut.h>
// Code gotten and adapted from http://snipplr.com/view/54306/opengl-particle-system-smoke-stream/
struct Particle
{
float posX;
float posY;
float posZ;
float alpha;
};
const int MAX_PARTICLES = 50;
const int MIN_PARTICLES = 50;
const float limits = .8;
Particle particles[MAX_PARTICLES];
SmokeManager::SmokeManager()
{
X = 0;
Y = 0;
Z = 0;
currentParticle = 1;
for (int i = 0; i < MAX_PARTICLES; ++i)
{
particles[i].alpha = 1.0f;
}
}
SmokeManager::~SmokeManager()
{
}
void SmokeManager::draw(float alphaDec)
{
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glAlphaFunc(GL_GREATER,0.2);
glEnable(GL_ALPHA_TEST);
float R, G, B;
glPushMatrix();
for (int i = 0; i < MAX_PARTICLES; i++)
{
R = 0.6;
G = 0.6;
B = 0.6;
glColor4f(R, G, B, particles[i].alpha);
glPushMatrix();
glTranslatef(0, -0.25, -0.7);
glRotatef(-45, 1, 0, 0);
glTranslatef(X * 6, Y * 2 - 1, Z * 6);
glScalef(1 + Y, 1 + Y, 1 + Y);
glRotatef(45, 1, 0, 0);
glutSolidSphere(0.04, 10, 10);
glPopMatrix();
particles[i].alpha -= alphaDec;
X = particles[i].posX;
Y = particles[i].posY;
Z = particles[i].posZ;
}
glPopMatrix();
}
void SmokeManager::moveParticles(int amount_of_particles)
{
float myX, myY;
glColor3d(2, .5, 0);
for (int i = 0; i < amount_of_particles; i++) {
myX = rand() % 3 + 1;
if(myX==1 && particles[i].posX<=limits ){
int mytemp = rand() % 100 + 1;
int temp = rand() % 5 + 1;
particles[i].posX+=temp*.001;
particles[i].posZ+=temp*.001;
particles[i].posY+=mytemp*.0004;
}
if(myX==2){particles[i].posX+=.00;particles[i].posY+=.01;}
if(myX==3 && particles[i].posX>=-limits){
int temp = rand() % 5 + 1;
int mytemp = rand() % 100 + 1;
particles[i].posX-=temp*.001;
particles[i].posZ+=temp*.001;
particles[i].posY+=mytemp*.0004;
}
///////////////////////////////////////////
if(particles[i].alpha <= 0){
particles[i].posX=0;
particles[i].posY=0;
particles[i].posZ=0;
particles[i].alpha = 1;
}
}
}
void SmokeManager::idle()
{
moveParticles(currentParticle);
if (currentParticle != MAX_PARTICLES) {
currentParticle++;
}
} |
Java | UTF-8 | 436 | 1.851563 | 2 | [] | no_license | package com.techkid.anh82.randomquote.network.services;
import com.techkid.anh82.randomquote.network.RegisterRequest;
import com.techkid.anh82.randomquote.network.RegisterResponse;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
/**
* Created by AnhLT on 5/27/2017.
*/
public interface LoginService {
@POST("login")
Call<RegisterResponse> register(@Body RegisterRequest registerRequest);
}
|
Python | UTF-8 | 1,823 | 4.28125 | 4 | [] | no_license | # Write two functions, the first, validity_check which takes a potential
# cover and the adjacency matrix of a graph as its inputs and returns True
# if the potential cover is a cover of the graph and False otherwise.
# The second, vertex_cover_naive, takes the adjacency matrix of a graph
# as its input, checks all potential covers, and returns the size of a
# minimum vertex cover. You should assume there are no loops in the graph.
from itertools import *
def validity_check(cover, graph):
for i in range(len(cover)):
for j in range(i+1, len(cover)):
if graph[i][j]==1 and cover[i] != 1 and cover[j] !=1:
return False
return True
def vertex_cover_naive(input_graph):
n = len(input_graph)
minimum_vertex_cover = n
# loops through all strings of 0s and 1s of length n
for assignment in product([0,1], repeat=n):
# Your code should go here.
# Based on the assignment (a list of 0s and 1s)
# - Check the assignment is valid
# - Calculate the size of assignment
# - Update the minimum_vertex_cover variable if appropriate
if validity_check(assignment, input_graph):
minimum_vertex_cover = assignment.count(1) if assignment.count(1) < minimum_vertex_cover else minimum_vertex_cover
# End of your code
return minimum_vertex_cover
def test():
graph = [
[0, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 1, 1],
[1, 0, 1, 0, 1],
[1, 1, 1, 1, 0]
]
assert vertex_cover_naive(graph)==3
# If you've not seen testing like this before, all you need to do is
# to call test(). If the tests pass, you'll get no output. If they don't
# you'll get an assertion error. Don't forget to remove the call to the
# test before submitting your code.
test()
|
Markdown | UTF-8 | 1,371 | 2.90625 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | ---
layout: post
title: " 함수 스코프(Function Scope)와 실행 컨텍스트(Excution Context)"
categories: JavaScript
author: goodGid
---
* content
{:toc}

* 둘의 **가장 큰 차이**는 각각 **발생하는 시점**에 있다.


<br>
* 코드를 통해 두 개념을 알아보자.
* 다음 코드의 결과값을 예측해보자.

.
.
.
.
.
.
.
.
.

<br>
* 자세하게 알아보자.

* 우선 함수 전역 컨테스트에서 호이스팅이 이뤄진다.
* 호이스팅 작업(1,2번)이 끝난 후 할당 작업(3번)이 진행된다.
* 그리고 outer()함수를 호출하게 된다.(4번)
* outer 컨텍스트에서 또 호이스팅 작업(5번)이 이뤄진다.
* 그리고 inner()함수를 호출하게 된다.(7번)
* inner 컨텍스트에서 또 호이스팅 작업(8번)이 이뤄진다.
* 그리고 마지막 줄에서는 global scope에서 a를 탐색해 1을 출력한다.
|
C# | UTF-8 | 944 | 3.578125 | 4 | [] | no_license | namespace WildFarm
{
using System;
public class Mice : Mammal
{
public Mice(string name, double weight, string livingRegion)
: base(name, weight, livingRegion)
{
}
public override void AskForFood()
{
Console.WriteLine("Squeak");
}
public override void EatFood(Food foodType, int foodQuantity)
{
if (foodType.GetType().Name != "Vegetable" && foodType.GetType().Name != "Fruit")
{
Console.WriteLine($"{this.GetType().Name} does not eat {foodType.GetType().Name}!");
}
else
{
base.FoodEaten += foodQuantity;
base.Weight += 0.1 * foodQuantity;
}
}
public override string ToString()
{
return $"Mouse [{this.Name}, {this.Weight}, {this.LivingRegion}, {this.FoodEaten}]";
}
}
}
|
JavaScript | UTF-8 | 846 | 2.53125 | 3 | [
"MIT"
] | permissive | var picpik = picpik || {};
(function () {
'use strict';
/**
* The basic Pic Model represents an image that can be
* favorited or deleted as needed.
*/
picpik.Pic = Backbone.Model.extend({
/*
* Default attribtues for the pic. Ensures it has the deleted
* and favorited attributes.
*/
defaults: function() {
return {
title: "Untitled Photo",
deleted: false,
favorited: false,
picId: picpik.picSet.nextPicId(),
};
},
toggleFavorited: function() {
this.save({favorited: !this.get("favorited")});
},
toggleDeleted: function() {
this.save({deleted: !this.get("deleted")});
},
});
})(); |
JavaScript | UTF-8 | 9,023 | 2.625 | 3 | [] | no_license | const readline = require("readline");
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const { randInt } = require("./rng.js");
const __rootdir = path.resolve(__dirname, "../..");
const config = require(__rootdir + "/config");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let override;
const prompt = () =>
rl.question("Override existing problem data? [y/N] ", answer => {
if (/^(y|yes)$/i.test(answer)) {
override = true;
genProblemData();
} else if (/^(n|no)$/i.test(answer)) {
override = false;
genProblemData();
} else {
prompt();
}
});
const genProblemData = () => {
config.problemDirs.forEach(problemDir => {
loadData(__rootdir + problemDir);
});
process.exit();
};
const loadData = problemsDir => {
const problemsConfig = require(problemsDir + "/config.json");
const excluded = problemsConfig.excluded || [];
fs.readdirSync(problemsDir)
.filter(file => fs.lstatSync(`${problemsDir}/${file}`).isDirectory())
.filter(file => !excluded.includes(file))
.filter(problem => {
const formatExists = fs.existsSync(
`${problemsDir}/${problem}/format.txt`
);
if (!formatExists) {
console.log(`Skipping [${problem}]: No format.txt`);
}
return formatExists;
})
.forEach(problem => generateData(`${problemsDir}/${problem}`));
};
const prepare = problemDir => {
if (override) {
const dataDir = problemDir + "/data/generated";
console.log(`Removing all data in ${dataDir}`);
fs.readdirSync(dataDir).forEach(file => {
fs.unlinkSync(`${dataDir}/${file}`);
});
}
const javaFiles = fs
.readdirSync(problemDir + "/solution")
.filter(file => file.endsWith(".java"));
if (javaFiles.length === 0) {
console.log(`No .java files in ${problemDir}/solution, aborting`);
return false;
} else if (javaFiles.length > 1) {
console.log(`Multiple .java files in ${problemDir}/solution, aborting`);
return false;
}
execSync(`javac "${problemDir}/solution/${javaFiles[0]}"`);
return `java -cp "${problemDir}/solution" ${javaFiles[0].split(".")[0]}`;
};
const generateData = problemDir => {
if (!fs.existsSync(problemDir + "/data")) {
fs.mkdirSync(problemDir + "/data");
}
if (!fs.existsSync(problemDir + "/data/generated")) {
fs.mkdirSync(problemDir + "/data/generated");
}
const solveScript = prepare(problemDir);
if (!solveScript) return;
const problemName = path.basename(problemDir);
const lines = fs
.readFileSync(`${problemDir}/format.txt`)
.toString("utf-8")
.split("\n")
.map(line => line.split("#")[0]);
var i = 0;
const config = {};
while (!lines[i].startsWith("---")) {
const parts = lines[i].split(":");
// If in format "name: value"
if (parts.length === 2) {
const name = parts[0].trim().toLowerCase();
const value = parts[1].trim();
config[name] = value;
}
i++;
}
let cases = config.count || 1;
// Hard limit at 100 cases
cases = Math.min(cases, 100);
if (isNaN(cases)) cases = 1;
console.log(`Generating ${cases} testcases for [${problemName}]`);
const startingIndex = i;
for (let caseNum = 0; caseNum < cases; caseNum++) {
i = startingIndex;
const vars = {};
const getValue = str => {
if (Object.keys(vars).includes(str)) return vars[str];
if (str.startsWith("{") && str.endsWith("}")) {
const parts = str.substring(1, str.length - 1).split(":");
const min = getValue(parts[0]);
const max = getValue(parts[1]);
return randInt(min, max);
} else if (str.startsWith("[") && str.endsWith("]")) {
str = str.substring(1, str.length - 1);
const type = str.split(":")[0];
const args = str.split(":")[1].split(",");
switch (type) {
case "STR": {
const length = getValue(args[0]);
let ret = "";
for (let i = 0; i < length; i++) {
ret += String.fromCharCode(
"a".charCodeAt(0) + randInt(0, 26 - 1)
);
}
return ret;
}
case "TREE": {
const tree = [];
const nodes = getValue(args[0]);
if (nodes <= 1) {
console.error(`Invalid tree length ${nodes}. Must be >= 2`);
throw "";
}
for (let i = 1; i < nodes; i++) {
tree.push(`${i} ${randInt(0, i - 1)}`);
}
return tree;
}
case "ARR": {
const array = [];
const length = getValue(args[0]);
const min = getValue(args[1]);
const max = getValue(args[2]);
for (let i = 0; i < length; i++) {
array.push(randInt(min, max));
}
return array.join(" ");
}
case "PROP":
const obj = getValue(args[0]);
const index = getValue(args[1]);
if (obj instanceof Array && typeof index === "number") {
return obj[index];
} else {
if (!(obj instanceof Array)) {
console.error(`Invalid object when indexing: ${obj}`);
}
if (!(typeof index === "number")) {
console.error(`Invalid index when indexing: ${index}`);
}
throw "";
}
default:
console.error(`Invalid object type: ${type}`);
throw "";
}
} else {
if (str.includes("+")) {
const parts = str.split(/\+/);
return parts.map(getValue).reduce((a, b) => a + b);
} else if (str.includes("-")) {
if (str.startsWith("-")) str = "0" + str;
const parts = str.split(/-/);
return (
getValue(parts[0]) -
parts
.slice(1)
.map(getValue)
.reduce((a, b) => a + b)
);
} else {
return Number.parseFloat(str);
}
}
};
const END_BLOCK = {};
const genOutput = () => {
i++;
if (i >= lines.length) return "";
const currLine = lines[i];
const parts = currLine.split(/\s+/);
const cmd = parts[0].toLowerCase();
switch (cmd) {
case "var":
const name = parts[1];
const value = parts[2];
vars[name] = getValue(value);
return "";
// Print out
case ">":
return (
parts
.slice(1)
.filter(str => str !== "")
.map(getValue)
.map(data => (data instanceof Array ? data.join("\n") : data))
.join(" ") + "\n"
);
case "end":
return END_BLOCK;
case "times":
let ret = "";
const reps = getValue(parts[1]);
const oriIndex = i;
for (var j = 0; j < reps; j++) {
i = oriIndex;
let res = "";
let part = "";
do {
res += part;
const tmp = genOutput();
part = tmp;
} while (part !== END_BLOCK);
ret += res;
}
return ret;
case "if":
let condition = parts.slice(1).join("");
let negate = false;
if (condition.startsWith("!")) {
condition = condition.substring(1);
negate = true;
}
let truthiness;
if (condition.includes(">")) {
const parts = condition.split(">");
truthiness = getValue(parts[0]) > getValue(parts[1]);
} else if (condition.includes("==")) {
const parts = condition.split("==");
truthiness = getValue(parts[0]) == getValue(parts[1]);
} else if (condition.includes("<")) {
const parts = condition.split("<");
truthiness = getValue(parts[0]) < getValue(parts[1]);
} else {
console.log("Invalid condition: " + condition);
process.exit();
}
if (negate) truthiness = !truthiness;
let res = "";
let part = "";
do {
res += part;
part = genOutput();
} while (part !== END_BLOCK);
return truthiness ? res : "";
default:
return "";
}
};
let inputStr = "";
while (i != lines.length) {
inputStr += genOutput();
}
const dataBase = `${problemDir}/data/generated/${caseNum}`;
const inputFile = dataBase + ".in";
const outputFile = dataBase + ".out";
if (override || !(fs.existsSync(inputFile) && fs.existsSync(outputFile))) {
fs.writeFileSync(inputFile, inputStr);
fs.writeFileSync(outputFile, "");
execSync(`${solveScript} < "${inputFile}" > "${outputFile}"`);
}
}
};
prompt();
|
C# | UTF-8 | 1,665 | 2.890625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using Proiect1.API;
namespace Proiect1.Service
{
public class FileService
{
private FileRepository fileRepository = new FileRepository();
public void SaveFile(File file)
{
if (GetAllFiles().Exists(f => f.FilePath == file.FilePath))
{
throw new Exception("File already in gallery.");
}
fileRepository.SaveFile(file);
}
public List<File> GetAllFiles()
{
return fileRepository.GetAllFiles();
}
public List<Metadata> GetAllMedata()
{
return fileRepository.GetAllMetadata();
}
public List<Property> GetAllProperties()
{
return fileRepository.GetAllProperties();
}
public List<File> FileFilter(string condition)
{
/*Functie/Serviciu ce va fi folosita pentru filtrarea fisierelor dupa criteriile
oferite de utilizator in aplicatie. Return-ul este pus doar pentru a satisface conditia
functiei de a returna un List<File>*/
return new List<File>();
}
public void AddProperty(Property property)
{
/* Functie/Serviciu folosit pentru a adauga proprietati introduse de utilizator
in aplicatie pentru un fisier (persoane din fisiere, locuri din fisiere etc. */
}
public void DeleteFile(File file)
{
/* Functie/Serviciu folosit pentru stergerea unui fisier (marcarea flagului isDeleted din
tabela Metadata ca fiind True */
}
}
}
|
Go | UTF-8 | 2,890 | 2.5625 | 3 | [
"MIT"
] | permissive | package auth
import (
"context"
"strconv"
"github.com/google/go-github/v32/github"
"github.com/wearedevx/keystone/api/pkg/models"
"golang.org/x/oauth2"
)
var (
githubClientId string
githubClientSecret string
)
type PublicKey struct {
Typ string
KeyID string
PublicKey string
}
type gitHubAuthService struct {
apiUrl string
ctx context.Context
conf *oauth2.Config
loginRequest models.LoginRequest
client *github.Client
token *oauth2.Token
}
// Name method returns the name of the service
func (g gitHubAuthService) Name() string { return "GitHub" }
// GitHubAuth function returns an instance of GitHubAuth service
func GitHubAuth(ctx context.Context, apiUrl string) AuthService {
return &gitHubAuthService{
apiUrl: apiUrl,
ctx: ctx,
}
}
// Start method initiate the oauth process by creating a login request
// on the Keystone server and requesting a login url to GitHub
func (g *gitHubAuthService) Start() (string, error) {
lr, err := getLoginRequest(g.apiUrl)
if err != nil {
return "", err
}
g.loginRequest = lr
g.conf = &oauth2.Config{
ClientID: githubClientId,
ClientSecret: githubClientSecret,
Scopes: []string{"user", "user:email"},
RedirectURL: authRedirectURL,
Endpoint: oauth2.Endpoint{
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
},
}
state, err := makeOAuthState(lr.TemporaryCode)
if err != nil {
return "", err
}
return g.conf.AuthCodeURL(state, oauth2.AccessTypeOffline), err
}
// WaitForExternalLogin method polls the API until the user has completed the
// login process and authorized the Keystone application
func (g *gitHubAuthService) WaitForExternalLogin() error {
c := make(chan pollResult)
var result pollResult
go pollLoginRequest(g.apiUrl, g.loginRequest.TemporaryCode, c)
result = <-c
if result.err != nil {
return result.err
}
token, err := g.conf.Exchange(g.ctx, result.authCode)
if err != nil {
return err
}
ts := oauth2.StaticTokenSource(token)
tc := oauth2.NewClient(g.ctx, ts)
g.token = token
g.client = github.NewClient(tc)
return nil
}
// Finish method finish the login process
func (g gitHubAuthService) Finish(
pk []byte,
device string,
deviceUID string,
) (models.User, string, error) {
return completeLogin(
g.apiUrl,
models.GitHubAccountType,
g.token,
pk,
device,
deviceUID,
)
}
// CheckAccount method returns true if the account is github one
func (g gitHubAuthService) CheckAccount(
account map[string]string,
) (bool, error) {
gUser, _, err := g.client.Users.Get(g.ctx, "")
if err != nil {
return false, err
}
if account["account_type"] != string(models.GitHubAccountType) {
return false, nil
}
if account["ext_id"] == strconv.Itoa(int(*gUser.ID)) {
return true, nil
}
return false, nil
}
|
Java | UTF-8 | 1,100 | 2.5 | 2 | [] | no_license | package com.pathfinder.app;
import java.util.ArrayList;
class NavPoint extends MapEntity
{
int type;
int floorNum;
int buildingNum;
ArrayList<NavPoint> visiblePoints;
public NavPoint(double xCoord, double yCoord, int thisId)
{
super(xCoord, yCoord, thisId);
}
public NavPoint(double xCoord, double yCoord, int thisId, int thisType, int thisFloorNum, int thisBuildingNum, ArrayList<NavPoint> thisVisiblePoints)
{
super(xCoord, yCoord, thisId);
this.type = thisType;
this.floorNum = thisFloorNum;
this.buildingNum = thisBuildingNum;
visiblePoints = new ArrayList<NavPoint>(thisVisiblePoints);
}
public NavPoint(double xCoord, double yCoord, int thisId, String thisName, int thisType, int thisFloorNum, int thisBuildingNum, ArrayList<NavPoint> thisVisiblePoints)
{
super(xCoord, yCoord, thisId, thisName);
this.type = thisType;
this.floorNum = thisFloorNum;
this.buildingNum = thisBuildingNum;
visiblePoints = new ArrayList<NavPoint>(thisVisiblePoints);
}
}
|
C | ISO-8859-1 | 1,365 | 4.0625 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*/
@type: Function - int main()
@title: Preenchimento de Vetor III
@author: Rafael Lima Coelho
@since: 23-10-2019
@version: RLC.1.0.URI
@description: Leia um valor X. Coloque este valor na primeira posio de um vetor N[100].
Em cada posio subsequente de N (1 at 99), coloque a metade do valor armazenado na posio anterior,
conforme o exemplo abaixo. Imprima o vetor N.
A entrada contem um valor de dupla preciso com 4 casas decimais.
@param: [i], inteiro, Contador e indice do vetor.
@param: [n], inteiro, Numero de posies.
@param: [aux], inteiro, Auxiliar para adicionar ao verto os valores de 0 at n.
@param: [vet], inteiro, Vetor com o tamanho 1000.
@return: caractere, Para cada posio do vetor N, escreva "N[i] = Y", onde i a posio do vetor e Y o valor armazenado naquela posio.
Cada valor do vetor deve ser apresentado com 4 casas decimais.
/*/
/*Inicio da Funo*/
int main() {
/*Declarao das variveis*/
int i;
double vet[100], n;
scanf("%lf",&n);
vet[0] = n;
//Atribuindo valores ao vetor
for(i = 1; i < 100; i++)
{
vet[i] = vet[i-1]/2;
}
//imprimindo valores
for(i = 0; i < 100; i++)
{
printf("N[%d] = %.4lf\n",i,vet[i]);
}
/*Retorno da funo para o fim do programa*/
return 0;
}
|
Python | UTF-8 | 1,365 | 3.375 | 3 | [] | no_license | # this is test of development branch
def print_fig(fig):
for i in range(len(fig)):
if fig[i] == '':
print('_',end='')
else:
print(fig[i],end='')
if i == 2 or i == 5 or i == 8:
print('')
else:
print('|',end='')
def check_fig(fig):
winest = [[0,1,2], [3,4,5], [6,7,8], [0,4,8], [2,4,6], [0,3,6], [1,4,7], [2,5,8]]
for i in winest:
if fig[i[0]] == fig[i[1]] and fig[i[1]] == fig[i[2]] and '_' not in fig[i[0]] and fig[i[0]] != '':
if fig[i[0]] == 'X':
print('Player №1 WIN!')
else:
print('Player №2 WIN!')
return True
#print(fig)
fig = list('' for x in range(0, 9))
win = False
while not win:
i=1
while i < 3:
try:
answer = int(input(f'Player №{i} your move? '))
except:
print('Please enter Integer 0..8!')
continue
if answer not in range(0, 9):
print('Please enter Integer 0..8!')
continue
if fig[answer] != '':
print(f'In this cell already have move={fig[answer]}')
continue
if i==1:
fig[answer] = 'X'
else:
fig[answer] = 'O'
print_fig(fig)
win = check_fig(fig)
if win:
break
i+=1
|
Shell | UTF-8 | 702 | 3.296875 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/bash
set -u
START_DIR=$(pwd)
OUTPUT_DIR=${START_DIR}/OUTPUT
if [ "X$TAG_VERSION" != "X" ]; then
VER=$TAG_VERSION
else
VER=$(cat etc/version)
fi
set -e
LINUX_BASE_NAME="stardog-graviton_$VER""_linux_amd64.zip"
LINUX_ZIP=$OUTPUT_DIR/$VER/$LINUX_BASE_NAME
DARWIN_BASE_NAME="stardog-graviton_$VER""_darwin_amd64.zip"
DARWIN_ZIP=$OUTPUT_DIR/$VER/$DARWIN_BASE_NAME
echo "aws --debug --region us-east-1 s3 cp $LINUX_ZIP s3://$S3_BUCKET/$LINUX_BASE_NAME"
cat /etc/issue
aws --version
s3cmd put $LINUX_ZIP s3://$S3_BUCKET/$LINUX_BASE_NAME
aws --region us-east-1 s3 cp $LINUX_ZIP s3://$S3_BUCKET/$LINUX_BASE_NAME
aws --region us-east-1 s3 cp $DARWIN_ZIP s3://$S3_BUCKET/$DARWIN_BASE_NAME
|
JavaScript | UTF-8 | 489 | 3.125 | 3 | [] | no_license | var symbolSize = 16;
var streams = [];
var toggle = true;
function setup() {
createCanvas(window.innerWidth, window.innerHeight);
textSize(symbolSize);
for(var i = 0; i < width; i+=symbolSize) {
var stream = new Stream(i);
stream.generateSymbols();
streams.push(stream);
}
}
function draw() {
if(toggle) {
background(0, 120);
for (var i = 0; i < streams.length; i++) {
streams[i].render();
}
}
}
function mousePressed() {
toggle = !toggle;
}
|
Python | UTF-8 | 11,311 | 2.703125 | 3 | [] | no_license | import json
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import numpy as np
import plotly.graph_objs as go
import pandas as pd
import math
from flask import Flask
from dash.dependencies import Input, Output
server = Flask(__name__)
import random
"""
Dash web page for C19 visualisation
Data from "Our world in data" and destatis
"""
data= pd.read_csv("https://covid.ourworldindata.org/data/owid-covid-data.csv")
#data= pd.read_csv("owid-covid-data.csv")
deathdata = pd.read_csv("sterbefallzahlen.csv", delimiter =";") # manually download csv or register for API access @destatis
# stats about total amount of deaths
coronaweeklydeaths2020 = deathdata['2020 (davon COVID-19)']
deaths2020withoutcorona = deathdata['2020']-coronaweeklydeaths2020
def GetCountryData(countryname,table=data):
return data[data.values==countryname] #chose data from dataframe on specific country
def days_average(data_in,days,dfvalue):
"""
calculation of test positive per last number of days (moving average)
"""
dayavg=[]
daydate=[]
number_of_values = int(math.trunc(data_in.shape[0]/days))
relevant_data= data_in[dfvalue]
relevant_data= np.array(relevant_data)
for l in range(0,data_in.shape[0]):
if l <= days:
print("days<7")
pass
else:
avg = (np.sum(relevant_data[l-days:l])/days)
dayavg.append(avg)
daydate.append(np.array(data_in['date'])[l])
return daydate, dayavg
#random color generation
number_of_colors = 52
color = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])
for i in range(number_of_colors)]
#specifying styling colors
colors = {
'background': '#111111',
'text': '#000099',
'plot_color': '#D3D3D3',
'paper_color':'#3333ff',
'fontcolor':'#FFFFFF'
}
#initializing graph data for first setup
cdata= GetCountryData("Germany")
xdaydates,ydayavg = days_average(cdata,7,'new_cases')
prate = np.array(cdata['positive_rate'])*100 # to percent
pratedates = cdata['date'][~np.isnan(prate)] #removing empty columns from dataset and getting non-empty dates
prate = prate[~np.isnan(prate)]
def build_all_graphs(cdata,countryname,xdaydates,ydayavg,pratedates,prate):
"""
Function to build first Graph, returning subgraphs and layout for use in dash Figure
"""
newcases = go.Scatter(
name="New Cases",
x = cdata['date'],
y = cdata['new_cases'],
mode = 'markers',
marker=dict(
color='LightSkyBlue',
size=2,
opacity=0.5,
line=dict(
color='LightSkyBlue',
width=2)),
marker_color='LightSkyBlue',
yaxis='y1'
)
casestotaldeaths=go.Scatter(
name="Total Deaths",
x = cdata['date'],
y = cdata['total_deaths'],
mode = 'lines',
marker_color='#ff4d4d',
#text=ger['new_cases'],
yaxis='y1',
fill='tozeroy',
fillcolor='rgba(255, 77, 77,0.3)'
)
sevendays = go.Scatter(
name="Seven Day Average",
x = xdaydates,
y = ydayavg,
mode = 'lines+markers',
#marker_color="#995c00",
marker=dict(
color='#995c00',
size=1,
opacity=0.5),
yaxis='y1',
fill='tozeroy',
fillcolor='rgba(255, 153, 0,0.8)'
)
percentpositive = go.Scatter(
name="Positive Rate in Percent",
x = pratedates,
#y = ger['positive_rate'],
y= prate,
mode = 'lines+markers',
line = dict(color='#ccffcc', width=2, dash='dot'),
marker_color='#ccffcc',
#text=ger['new_cases'],
yaxis='y2'
)
layout = go.Layout(
title={
'text': 'COVID-19 in {}'.format(countryname),
'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top'},
activeshape={"fillcolor": "#ff0000"},
plot_bgcolor='#1a1a1a',
paper_bgcolor=colors['background'],
font= {'color' : colors['fontcolor']},
xaxis = {'title': 'Date',"gridcolor":colors['background'],"gridwidth": 0.5},
yaxis = {'title': 'Number of Test Positives', "gridcolor":colors['background'],"gridwidth": 0.5},
yaxis2 = {'title': 'Test Positive in Percent', "gridcolor":"#4d4d4d","gridwidth": 0.5,'overlaying':'y','side':'right', "zerolinecolor": colors['background'] },
#yaxis2=dict(title='Test Positive in Percent',overlaying='y',side='right', gridcolor= "#cccccc", gridwidth= 0.5),
height = 700)
return newcases, casestotaldeaths,sevendays, percentpositive, layout # all subplots + layout
def getGermanIGraph(cdata,years201519avg):
#Line Chart average Influenza Deaths
gig = go.Scatter(
name="2015-2019 Influenza Deaths",
x = cdata['date'],
y = years201519avg,
mode = 'lines',
line = dict(color='firebrick', width=2, dash='dot'),
marker_color='#ccffcc',
#text=ger['new_cases'],
yaxis='y1')
return gig
## first initialization with germany on page load
newcases, casestotaldeaths,sevengraph,percentpositive,layout =build_all_graphs(cdata,"Germany",xdaydates,ydayavg,pratedates,prate)
fig = go.Figure(data = [newcases, casestotaldeaths,sevengraph,percentpositive], layout = layout)
# configuring dropdown menue
dropmenue= dcc.Dropdown(id='my_dropdown',
options=[
{'label': 'Sweden', 'value': 'Sweden'},
{'label': 'Germany', 'value': 'Germany'},
{'label': 'France', 'value': 'France'},
{'label': 'Belgium', 'value': 'Belgium'},
{'label': 'Poland', 'value': 'Poland'},
{'label': 'Austria', 'value': 'Austria'},
{'label': 'Spain', 'value': 'Spain'},
{'label': 'Chile', 'value': 'Chile'},
],
optionHeight=35, #height/space between dropdown options
value='Germany', #dropdown value selected automatically when page loads
disabled=False, #disable dropdown value selection
multi=False, #allow multiple dropdown values to be selected
searchable=False, #allow user-searching of dropdown values
search_value='', #remembers the value searched in dropdown
placeholder='Please select...', #gray, default text shown when no option is selected
clearable=True, #allow user to removes the selected value
style={'fontSize': 16,'text-align': 'center','backgroundColor':'#1a1a1a'},
)
# css stylesheets:
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css','/static/reset.css']
# setting up Dash App
app = dash.Dash(name='app1',server=server,assets_external_path=external_stylesheets)
# Graph for death of all causes in germany
deathgraph= dcc.Graph(
id='deathstats-chart',
figure = {
'data':[
go.Scatter(
name="2020 without Corona",
x = deathdata['Kalenderwoche'],
y = deaths2020withoutcorona,
#y = deathdata['2020 (davon COVID-19)'],
mode = 'lines',
line = dict(color='#e6e600', width=3, dash='dot'),
marker_color='#ccffcc'
),
go.Scatter(
name="2020",
x = deathdata['Kalenderwoche'],
y = deathdata['2020'],
mode = 'lines',
line = dict(color='firebrick', width=3),
marker_color='#ccffcc',
fill='tonexty'
),
go.Scatter(
name="2019",
x = deathdata['Kalenderwoche'],
y = deathdata['2019'],
mode = 'lines',
line = dict(color='#3399ff', width=1, dash='dot'),
marker_color='#ccffcc',
),
go.Scatter(
name="2018",
x = deathdata['Kalenderwoche'],
y = deathdata['2018'],
mode = 'lines',
line = dict(color='#006600', width=1, dash='dot'),
marker_color='#ccffcc',
),
go.Scatter(
name="2017",
x = deathdata['Kalenderwoche'],
y = deathdata['2017'],
mode = 'lines',
line = dict(color='#cc3399', width=1, dash='dot'),
marker_color='#ccffcc',
)
],
'layout' : go.Layout(
title= 'Deaths per Calender Week Germany',
plot_bgcolor='#1a1a1a',
paper_bgcolor=colors['background'],
font= {'color' : colors['fontcolor']},
xaxis = {'title': 'Week Number'},
#yaxis = {'title': 'Total Deaths of all Causes', 'range': "[0,30000]"},
yaxis= dict(range=[16000, 28000],title='Total deaths of all causes'),
height = 700
)}) # /deathgraph
# setting Page Layout:
app.layout = html.Div([dropmenue,
dcc.Graph(id="graph", figure=fig),
html.H6('Disclaimer: Usage of PCR / Antigen Tests differs between countries',style={'color': '#FFFFFF', 'fontSize': 14,'backgroundColor': '#1a1a1a','text-align': 'center'}),
deathgraph
],style={'backgroundColor': '#1a1a1a', 'height':'2000px'})
"""
Callback functions
Changing graph values on dropdown callback
"""
@app.callback(
Output("graph", "figure"),
[Input("my_dropdown", "value")])
def build_graph(value):
# init again with chosen country
cdata= GetCountryData(value)
xdaydates,ydayavg = days_average(cdata,7,'new_cases')
prate = np.array(cdata['positive_rate'])*100
pratedates = cdata['date'][~np.isnan(prate)]
prate = prate[~np.isnan(prate)]
# buildung graphs with countrydata
newcases, casestotaldeaths, sevengraph,percentpositive, layout = build_all_graphs(cdata,value,xdaydates,ydayavg,pratedates,prate)
# Average Influenza deathstats only available in germany:
if value=='Germany':
years201519avg=[23000]*cdata.shape[0]
gig = getGermanIGraph(cdata,years201519avg)
fig = go.Figure(data = [newcases, casestotaldeaths, sevengraph,percentpositive,gig], layout = layout)
else:
fig = go.Figure(data = [newcases, casestotaldeaths, sevengraph,percentpositive], layout = layout)
return fig
if __name__ == '__main__':
app.run_server(host="127.0.0.1",port=80,debug=True)
|
C# | UTF-8 | 4,074 | 2.703125 | 3 | [
"MIT"
] | permissive | // Copyright (c) Dmytro Kyshchenko. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
namespace xFunc.Maths.Expressions.Matrices;
/// <summary>
/// Represents a matrix expression.
/// </summary>
public class Matrix : IExpression
{
private const int MinParametersCount = 1;
/// <summary>
/// Initializes a new instance of the <see cref="Matrix"/> class.
/// </summary>
/// <param name="vectors">The vectors.</param>
/// <exception cref="ArgumentNullException"><paramref name="vectors"/> is null.</exception>
public Matrix(Vector[] vectors)
: this(vectors.ToImmutableArray())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Matrix"/> class.
/// </summary>
/// <param name="vectors">The vectors.</param>
/// <exception cref="ArgumentNullException"><paramref name="vectors"/> is null.</exception>
public Matrix(ImmutableArray<Vector> vectors)
{
if (vectors == null)
throw new ArgumentNullException(nameof(vectors));
if (vectors.Length < MinParametersCount)
throw new ArgumentException(Resource.LessParams, nameof(vectors));
var size = vectors[0].ParametersCount;
foreach (var vector in vectors)
if (vector.ParametersCount != size)
throw new InvalidMatrixException();
Vectors = vectors;
}
/// <summary>
/// Gets or sets the <see cref="Vector"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="Vector"/>.
/// </value>
/// <param name="index">The index.</param>
/// <returns>The element of matrix.</returns>
public Vector this[int index] => Vectors[index];
/// <inheritdoc />
public override bool Equals(object? obj)
{
if (ReferenceEquals(this, obj))
return true;
if (obj is null || GetType() != obj.GetType())
return false;
var matrix = (Matrix)obj;
if (Vectors.Length != matrix.Vectors.Length)
return false;
return Vectors.SequenceEqual(matrix.Vectors);
}
/// <inheritdoc />
public string ToString(IFormatter formatter) => Analyze(formatter);
/// <inheritdoc />
public override string ToString() => ToString(CommonFormatter.Instance);
/// <inheritdoc />
public object Execute() => Execute(null);
/// <inheritdoc />
public object Execute(ExpressionParameters? parameters)
{
var vectors = new VectorValue[Vectors.Length];
for (var i = 0; i < Vectors.Length; i++)
{
var result = Vectors[i].Execute(parameters);
if (result is not VectorValue vectorValue)
throw new ResultIsNotSupportedException(this, result);
vectors[i] = vectorValue;
}
return Unsafe.As<VectorValue[], MatrixValue>(ref vectors);
}
/// <inheritdoc />
public TResult Analyze<TResult>(IAnalyzer<TResult> analyzer)
{
if (analyzer is null)
throw new ArgumentNullException(nameof(analyzer));
return analyzer.Analyze(this);
}
/// <inheritdoc />
public TResult Analyze<TResult, TContext>(
IAnalyzer<TResult, TContext> analyzer,
TContext context)
{
if (analyzer is null)
throw new ArgumentNullException(nameof(analyzer));
return analyzer.Analyze(this, context);
}
/// <summary>
/// Clones this instance of the <see cref="IExpression" />.
/// </summary>
/// <param name="vectors">The list of arguments.</param>
/// <returns>
/// Returns the new instance of <see cref="IExpression" /> that is a clone of this instance.
/// </returns>
public IExpression Clone(ImmutableArray<Vector>? vectors = null)
=> new Matrix(vectors ?? Vectors);
/// <summary>
/// Gets the vectors.
/// </summary>
public ImmutableArray<Vector> Vectors { get; }
} |
C | UTF-8 | 329 | 3.703125 | 4 | [] | no_license | #include <stdio.h>
int main(int argc, char** argv) {
printf("Arithemetic mean:\n");
float sum;
float ar;
for (int i = 1; i <= 5; i++) {
printf("Enter number -> ");
float a;
scanf("%f", &a);
sum = sum + a;
ar = sum / i;
printf("number entered %.0i: %.2f arithmetic mean %.2f\n", i, a, ar);
}
return 0;
} |
JavaScript | UTF-8 | 2,623 | 3.328125 | 3 | [] | no_license | //object that has all the getElementById of the main page (of users)
var divs = { stats: document.getElementById("stats"), users: document.getElementById("users-managment"), game: document.getElementById("game"), user: document.getElementById("user") }
//store what section the website is showing
var showing = "stats"
/**
* show a section of the webiste (display show) and refresh the "showing" variable
* @param {string} what the name of the section to show
*/
function show(what) {
hideAll()
divs[what].style.display = "block";
showing = what
}
/**
* set to display none all the section
*/
function hideAll() {
for (var doc in divs) {
divs[doc].style.display = "none";
}
}
/**
* remove from the local storage the user's data
* and redirect the user to the login page
*/
function logout() {
localStorage.removeItem("user");
window.location.replace('/users/login');
}
/**
* this function will fetch the profile picture of the user (will use the user saved in the local storage to get the information)
* and will render the image in the icon on the top right and the dedicate user section
*/
async function getPfp() {
console.log('/users/pfp/' + user.username);
var res = await fetch('/users/pfp/' + user.username, {
method: "GET"
});
var respJson = await res.json();
console.log(respJson);
document.getElementById("pfp").src = respJson[0]
document.getElementById("pfp2").src = respJson[0]
}
/**
* this function is assinged to a onclick event and will save as the last page saw the stats page
* and will run the initCalendar function
*/
async function stats() {
locationSaver('stats');
await initCalendar()
}
/**
* this function will either return the last page saw or save in local storage the last page
* @param {string} position if not undefined the function will save the string in the local storage, will be used when the user logs in
* @returns if position is undefined the function will return the last element in the local storage (and show that page to the user using the show function)
*/
function locationSaver(position) {
if (position == undefined) {
if (localStorage.getItem("location") == undefined) {
localStorage.setItem("location", "stats");
show("stats");
return "stats";
} else {
showing = localStorage.getItem("location");
show(showing);
return showing;
}
} else {
localStorage["location"] = position;
showing = position;
show(position);
return position;
}
}
|
Markdown | UTF-8 | 18,100 | 2.765625 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: MABS & System Center DPM support matrix
description: This article summarizes Azure Backup support when you use Microsoft Azure Backup Server (MABS) or System Center DPM to back up on-premises and Azure VM resources.
ms.date: 04/20/2023
ms.topic: conceptual
author: AbhishekMallick-MS
ms.author: v-abhmallick
---
# Support matrix for backup with Microsoft Azure Backup Server or System Center DPM
You can use the [Azure Backup service](backup-overview.md) to back up on-premises machines and workloads, and Azure virtual machines (VMs). This article summarizes support settings and limitations for backing up machines by using Microsoft Azure Backup Server (MABS) or System Center Data Protection Manager (DPM), and Azure Backup.
## About DPM/MABS
[System Center DPM](/system-center/dpm/dpm-overview) is an enterprise solution that configures, facilitates, and manages backup and recovery of enterprise machines and data. It's part of the [System Center](https://www.microsoft.com/system-center/pricing) suite of products.
MABS is a server product that can be used to back up on-premises physical servers, VMs, and apps running on them.
MABS is based on System Center DPM and provides similar functionality with a few differences:
- No System Center license is required to run MABS.
- For both MABS and DPM, Azure provides long-term backup storage. In addition, DPM allows you to back up data for long-term storage on tape. MABS doesn't provide this functionality.
- [You can back up a primary DPM server with a secondary DPM server](/system-center/dpm/back-up-the-dpm-server). The secondary server will protect the primary server database and the data source replicas stored on the primary server. If the primary server fails, the secondary server can continue to protect workloads that are protected by the primary server, until the primary server is available again. MABS doesn't provide this functionality.
You can download MABS from the [Microsoft Download Center](https://go.microsoft.com/fwLink/?LinkId=626082). It can be run on-premises or on an Azure VM.
DPM and MABS support backing up a wide variety of apps, and server and client operating systems. They provide multiple backup scenarios:
- You can back up at the machine level with system-state or bare-metal backup.
- You can back up specific volumes, shares, folders, and files.
- You can back up specific apps by using optimized app-aware settings.
## DPM/MABS backup
Backup using DPM/MABS and Azure Backup works as follows:
1. DPM/MABS protection agent is installed on each machine that will be backed up.
1. Machines and apps are backed up to local storage on DPM/MABS.
1. The Microsoft Azure Recovery Services (MARS) agent is installed on the DPM server/MABS.
1. The MARS agent backs up the DPM/MABS disks to a backup Recovery Services vault in Azure by using Azure Backup.
For more information:
- [Learn more](backup-architecture.md#architecture-back-up-to-dpmmabs) about MABS architecture.
- [Review what's supported](backup-support-matrix-mars-agent.md) for the MARS agent.
## Supported scenarios
**Scenario** | **Agent** | **Location**
--- | --- | ---
**Back up on-premises machines/workloads** | DPM/MABS protection agent runs on the machines that you want to back up.<br/><br/> The MARS agent on DPM/MABS server.<br/> The minimum version of the Microsoft Azure Recovery Services agent, or Azure Backup agent, required to enable this feature is 2.0.8719.0. | DPM/MABS must be running on-premises.
## Supported deployments
DPM/MABS can be deployed as summarized in the following table.
**Deployment** | **Support** | **Details**
--- | --- | ---
**Deployed on-premises** | Physical server, but not in a physical cluster.<br/><br/>Hyper-V VM. You can deploy MABS as a guest machine on a standalone hypervisor or cluster. It can’t be deployed on a node of a cluster or standalone hypervisor. The Azure Backup Server is designed to run on a dedicated, single-purpose server.<br/><br/> As a Windows virtual machine in a VMware environment. | On-premises MABS servers can't protect Azure-based workloads. <br><br> For more information, see [protection matrix](backup-mabs-protection-matrix.md).
**Deployed as an Azure Stack VM** | MABS only | DPM can't be used to back up Azure Stack VMs.
**Deployed as an Azure VM** | Protects Azure VMs and workloads that are running on those VMs | DPM/MABS running in Azure can't back up on-premises machines. It can only protect workloads that are running in Azure IaaS VMs.
## Supported MABS and DPM operating systems
Azure Backup can back up DPM/MABS instances that are running any of the following operating systems. Operating systems should be running the latest service packs and updates.
**Scenario** | **DPM/MABS**
--- | ---
**MABS on an Azure VM** | MABS v4 and later: Windows 2022 Datacenter, Windows 2019 Datacenter <br><br> MABS v3, UR1 and UR2: Windows 2019 Datacenter, Windows 2016 Datacenter <br/><br/> We recommend that you start with an image from the marketplace.<br/><br/> Minimum Standard_A4_v2 with four cores and 8-GB RAM.
**DPM on an Azure VM** | System Center 2012 R2 with Update 3 or later<br/><br/> Windows operating system as [required by System Center](/system-center/dpm/prepare-environment-for-dpm#dpm-server).<br/><br/> We recommend that you start with an image from the marketplace.<br/><br/> Minimum Standard_A4_v2 with four cores and 8-GB RAM.
**MABS on-premises** | MABS v4 and later: Windows Server 2022 or Windows Server 2019 <br><br> MABS v3, UR1 and UR2: Windows Server 2019 and Windows Server 2016
**DPM on-premises** | Physical server/Hyper-V VM: System Center 2012 SP1 or later.<br/><br/> VMware VM: System Center 2012 R2 with Update 5 or later.
>[!NOTE]
>Installing Azure Backup Server isn't supported on Windows Server Core or Microsoft Hyper-V Server.
## Management support
**Issue** | **Details**
--- | ---
**Installation** | Install DPM/MABS on a single-purpose machine.<br/><br/> Don't install DPM/MABS on a domain controller, on a machine with the Application Server role installation, on a machine that's running Microsoft Exchange Server or System Center Operations Manager, or on a cluster node.<br/><br/> [Review all DPM system requirements](/system-center/dpm/prepare-environment-for-dpm#dpm-server).
**Domain** | The server on which DPM/MABS will be installed should be joined to a domain before the installation begins. Moving DPM/MABS to a new domain after deployment isn't supported.
**Storage** | Modern backup storage (MBS) is supported from DPM 2016/MABS v2 and later. It isn't available for MABS v1.
**MABS upgrade** | You can directly install MABS v4, or upgrade to MABS v4 from MABS v3 UR1 and UR2. [Learn more](backup-azure-microsoft-azure-backup.md#upgrade-mabs).
**Moving MABS** | Moving MABS to a new server while retaining the storage is supported if you're using MBS.<br/><br/> The server must have the same name as the original. You can't change the name if you want to keep the same storage pool, and use the same MABS database to store data recovery points.<br/><br/> You'll need a backup of the MABS database because you'll need to restore it.
>[!NOTE]
>Renaming the DPM/MABS server isn't supported.
## MABS support on Azure Stack
You can deploy MABS on an Azure Stack VM so that you can manage backup of Azure Stack VMs and workloads from a single location.
**Component** | **Details**
--- | ---
**MABS on Azure Stack VM** | At least size A2. We recommend you start with a Windows Server 2019 or Windows Server 2022 image from Azure Marketplace.<br/><br/> Don't install anything else on the MABS VM.
**MABS storage** | Use a separate storage account for the MABS VM. The MARS agent running on MABS needs temporary storage for a cache location and to hold data restored from the cloud.
**MABS storage pool** | The size of the MABS storage pool is determined by the number and size of disks that are attached to the MABS VM. Each Azure Stack VM size has a maximum number of disks. For example, A2 is four disks.
**MABS retention** | Don't retain backed up data on the local MABS disks for more than five days.
**MABS scale up** | To scale up your deployment, you can increase the size of the MABS VM. For example, you can change from A to D series.<br/><br/> You can also ensure that you're offloading data with backup to Azure regularly. If necessary, you can deploy additional MABS servers.
**.NET Framework on MABS** | The MABS VM needs .NET Framework 4.5 or later installed on it.
**MABS domain** | The MABS VM must be joined to a domain. A domain user with admin privileges must install MABS on the VM.
**Azure Stack VM data backup** | You can back up files, folders, and apps.
**Supported backup** | These operating systems are supported for VMs that you want to back up: <br/><br/> Windows Server 2022, Windows Server 2019, Windows Server 20016, Windows Server 2012, Windows Server 2012 R2
**SQL Server support for Azure Stack VMs** | Back up SQL Server 2022, SQL Server 2019, SQL Server 2017, SQL Server 2016 (SPs), and SQL Server 2014 (SPs).<br/><br/> Back up and recover a database.
**SharePoint support for Azure Stack VMs** | SharePoint 2019, SharePoint 2016 with latest SPs.<br/><br/> Back up and recover a farm, database, front end, and web server.
**Network requirements for backed up VMs** | All VMs in Azure Stack workload must belong to the same virtual network and belong to the same subscription.
## Networking and access support
[!INCLUDE [Configuring network connectivity](../../includes/backup-network-connectivity.md)]
### DPM/MABS connectivity to Azure Backup
Connectivity to the Azure Backup service is required for backups to function properly, and the Azure subscription should be active. The following table shows the behavior if these two things don't occur.
**MABS to Azure** | **Subscription** | **Backup/Restore**
--- | --- | ---
Connected | Active | Back up to DPM/MABS disk.<br/><br/> Back up to Azure.<br/><br/> Restore from disk.<br/><br/> Restore from Azure.
Connected | Expired/deprovisioned | No backup to disk or Azure.<br/><br/> If the subscription is expired, you can restore from disk or Azure.<br/><br/> If the subscription is decommissioned, you can't restore from disk or Azure. The Azure recovery points are deleted.
No connectivity for more than 15 days | Active | No backup to disk or Azure.<br/><br/> You can restore from disk or Azure.
No connectivity for more than 15 days | Expired/deprovisioned | No backup to disk or Azure.<br/><br/> If the subscription is expired, you can restore from disk or Azure.<br/><br/> If the subscription is decommissioned, you can't restore from disk or Azure. The Azure recovery points are deleted.
## Domain and Domain trusts support
|Requirement |Details |
|---------|---------|
|Domain | The DPM/MABS server should be in a Windows Server 2022, Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 domain. |
|Domain trust | DPM/MABS supports data protection across forests, as long as you establish a forest-level, two-way trust between the separate forests. <BR><BR> DPM/MABS can protect servers and workstations across domains, within a forest that has a two-way trust relationship with the DPM/MABS server domain. To protect computers in workgroups or untrusted domains, see [Back up and restore workloads in workgroups and untrusted domains.](/system-center/dpm/back-up-machines-in-workgroups-and-untrusted-domains) <br><br> To back up Hyper-V server clusters, they must be located in the same domain as the MABS server or in a trusted or child domain. You can back up servers and clusters in an untrusted domain or workload using NTLM or certificate authentication for a single server, or certificate authentication only for a cluster. |
## DPM/MABS storage support
Data that's backed up to DPM/MABS is stored on local disk storage.
USB or removable drives aren't supported.
NTFS compression isn't supported on DPM/MABS volumes.
BitLocker can only be enabled after you add the disk the storage pool. Don't enable BitLocker before adding it.
Network-attached storage (NAS) isn't supported for use in the DPM storage pool.
**Storage** | **Details**
--- | ---
**MBS** | Modern backup storage (MBS) is supported from DPM 2016/MABS v2 and later. It isn't available for MABS v1.
**MABS storage on Azure VM** | Data is stored on Azure disks that are attached to the DPM/MABS VM, and that are managed in DPM/MABS. The number of disks that can be used for DPM/MABS storage pool is limited by the size of the VM.<br/><br/> A2 VM: 4 disks; A3 VM: 8 disks; A4 VM: 16 disks, with a maximum size of 1 TB for each disk. This determines the total backup storage pool that's available.<br/><br/> The amount of data you can back up depends on the number and size of the attached disks.
**MABS data retention on Azure VM** | We recommend that you retain data for one day on the DPM/MABS Azure disk, and back up from DPM/MABS to the vault for longer retention. This way you can protect a larger amount of data by offloading it to Azure Backup.
### Modern backup storage (MBS)
From DPM 2016/MABS v2 (running on Windows Server 2016) and later, you can take advantage of modern backup storage (MBS).
- MBS backups are stored on a Resilient File System (ReFS) disk.
- MBS uses ReFS block cloning for faster backup and more efficient use of storage space.
- When you add volumes to the local DPM/MABS storage pool, you configure them with drive letters. You can then configure workload storage on different volumes.
- When you create protection groups to back up data to DPM/MABS, you select the drive you want to use. For example, you might store backups for SQL or other high IOPS workloads on a high-performance drive, and store workloads that are backed up less frequently on a lower performance drive.
## Supported backups to MABS
For information on the various servers and workloads that you can protect with Azure Backup Server, refer to the [Azure Backup Server Protection Matrix](./backup-mabs-protection-matrix.md#protection-support-matrix).
## Supported backups to DPM
For information on the various servers and workloads that you can protect with Data Protection Manager, refer to the article [What can DPM back up?](/system-center/dpm/dpm-protection-matrix).
- Clustered workloads backed up by DPM/MABS should be in the same domain as DPM/MABS or in a child/trusted domain.
- You can use NTLM/certificate authentication to back up data in untrusted domains or workgroups.
## Deduplicated volumes support
Deduplication support for MABS depends on operating system support.
### For NTFS volumes with MABS v4
| Operating system of protected server | Operating system of MABS server | MABS version | Dedupe support |
| --- | --- | --- | --- |
| Windows Server 2022 | Windows Server 2022 | MABS v4 | Y |
| Windows Server 2019 | Windows Server 2022 | MABS v4 | Y |
| Windows Server 2016 | Windows Server 2022 | MABS v4 | Y* |
| Windows Server 2022 | Windows Server 2019 | MABS v4 | N |
| Windows Server 2019 | Windows Server 2019 | MABS v4 | Y |
| Windows Server 2016 | Windows Server 2019 | MABS v4 | Y* |
**Deduped NTFS volumes in Windows Server 2016 Protected Servers are non-deduplicated during restore.*
### For NTFS volumes with MABS v3
| Operating system of protected server | Operating system of MABS server | MABS version | Dedupe support |
| ------------------------------------------ | ------------------------------------- | ------------------ | -------------------- |
| Windows Server 2019 | Windows Server 2019 | MABS v3 | Y |
| Windows Server 2016 | Windows Server 2019 | MABS v3 | Y* |
| Windows Server 2012 R2 | Windows Server 2019 | MABS v3 | N |
| Windows Server 2012 | Windows Server 2019 | MABS v3 | N |
| Windows Server 2019 | Windows Server 2016 | MABS v3 | Y** |
| Windows Server 2016 | Windows Server 2016 | MABS v3 | Y |
| Windows Server 2012 R2 | Windows Server 2016 | MABS v3 | Y |
| Windows Server 2012 | Windows Server 2016 | MABS v3 | Y |
- \* When protecting a WS 2016 NTFS deduped volume with MABS v3 running on WS 2019, the recoveries may be affected. We have a fix for doing recoveries in a non-deduped way. Reach out to MABS support if you need this fix on MABS v3 UR1.
- \** When protecting a WS 2019 NTFS deduped volume with MABS v3 on WS 2016, the backups and restores will be non-deduped. This means that the backups will consume more space on the MABS server than the original NTFS deduped volume.
**Issue**: If you upgrade the protected server operating system from Windows Server 2016 to Windows Server 2019, then the backup of the NTFS deduped volume will be affected due to changes in the deduplication logic.
**Workaround**: Reach out to MABS support in case you need this fix for MABS v3 UR1.
### For ReFS Volumes
- We've identified a few issues with backups of deduplicated ReFS volumes. We're working on fixing these, and will update this section as soon as we have a fix available. Until then, we're removing the support for backup of deduplicated ReFS volumes from MABS v3 and v4.
- MABS v3 UR1, MABS v4, and later continues to support protection and recovery of normal ReFS volumes.
## Next steps
- [Learn more](backup-architecture.md#architecture-back-up-to-dpmmabs) about MABS architecture.
- [Review](backup-support-matrix-mars-agent.md) what's supported for the MARS agent.
- [Set up](backup-azure-microsoft-azure-backup.md) a MABS server.
- [Set up DPM](/system-center/dpm/install-dpm).
|
Java | UTF-8 | 24,516 | 1.898438 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.agnux.kemikal.reportes;
import com.agnux.common.helpers.StringHelper;
import java.net.URISyntaxException;
import java.util.Iterator;
import org.apache.commons.lang.StringEscapeUtils;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* @author agnux
*/
public class PdfProSimulacionProduccion {
private HashMap<String, String> datosHeaderFooter = new HashMap<String, String>();
private ArrayList<HashMap<String, String>> lista_componentes = new ArrayList<HashMap<String, String>>();
private String fileout;
private String emp_razon_social;
private String tipo_simulacion;
private String codigo;
private String descripcion;
private String cantidad;
private String cantidad_lt;
private String densidad;
private String version;
private String usuario_elaboracion;
public PdfProSimulacionProduccion(HashMap<String, String> datos, ArrayList<HashMap<String, String>> componentes) {
HashMap<String, String> data = new HashMap<String, String>();
this.setFileout(datos.get("fileout"));
this.setEmp_razon_social(datos.get("emp_razon_social"));
this.setTipo_simulacion(datos.get("tipo"));
this.setCantidad(datos.get("cantidad"));
this.setCantidad_lt(datos.get("cantidad_lt"));
this.setDensidad(datos.get("densidad"));
this.setCodigo(datos.get("codigo"));
this.setDescripcion(datos.get("descripcion"));
this.setVersion(datos.get("version"));
this.setUsuario_elaboracion(datos.get("usuario_elaboracion"));
this.setLista_componentes(componentes);
//datos para el encabezado, no se esta utilizando
data.put("empresa", datos.get("nombre_empresa_emisora"));
data.put("titulo_reporte", datos.get("titulo_reporte"));
data.put("periodo", datos.get("periodo"));
//datos para el pie de pagina
data.put("codigo1", datos.get("codigo1"));
data.put("codigo2", datos.get("codigo2"));
this.setDatosHeaderFooter(data);
}
public void ViewPDF() throws URISyntaxException {
HashMap<String, String> datos = new HashMap<String, String>();
Font smallsmall = new Font(Font.FontFamily.HELVETICA,5,Font.NORMAL,BaseColor.BLACK);
Font smallFont = new Font(Font.FontFamily.HELVETICA,7,Font.NORMAL,BaseColor.BLACK);
Font smallFontBold = new Font(Font.FontFamily.HELVETICA,7,Font.BOLD,BaseColor.BLACK);
Font smallBoldFontWhite = new Font(Font.FontFamily.HELVETICA,8,Font.BOLD,BaseColor.WHITE);
Font largeBoldFont = new Font(Font.FontFamily.HELVETICA,10,Font.BOLD,BaseColor.BLACK);
PdfPTable tablaPrincipal;
PdfPTable table2;
PdfPTable tableElaboro;
PdfPCell cell;
try {
HeaderFooter event = new HeaderFooter(this.getDatosHeaderFooter());
Document document = new Document(PageSize.LETTER, -50, -50, 60, 30);
// Document document = new Document(PageSize.LETTER.rotate(), -50, -50, 60, 30);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(this.getFileout()));
writer.setPageEvent(event);
System.out.println("PDF: "+this.getFileout());
document.open();
float [] widths1 = {2f,4.8f,0.5f,2f,4.8f};
PdfPTable tableHelper = new PdfPTable(widths1);
//Fila 1
cell = new PdfPCell(new Paragraph("Código:",smallFontBold));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph(this.getCodigo(),smallFont));
cell.setBorderWidthBottom(1);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph("",smallFont));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph("Cantidad en Kilo:",smallFontBold));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph(this.getCantidad(),smallFont));
cell.setBorderWidthBottom(1);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
//Fila 2
cell = new PdfPCell(new Paragraph("Descripción:",smallFontBold));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph(this.getDescripcion(),smallFont));
cell.setBorderWidthBottom(1);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph("",smallFont));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph("Cantidad en Litro:",smallFontBold));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph(this.getCantidad_lt(),smallFont));
cell.setBorderWidthBottom(1);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
//Fila 3
cell = new PdfPCell(new Paragraph("Densidad:",smallFontBold));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph(this.getDensidad(),smallFont));
cell.setBorderWidthBottom(1);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph("",smallFont));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph("",smallFontBold));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
cell = new PdfPCell(new Paragraph("",smallFont));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableHelper.addCell(cell);
tableHelper.setSpacingAfter(10f);
//Agregar tabla al documento
document.add(tableHelper);
//float [] widths = {2f, 5.5f, 3f, 2f, 1.5f, 2f,2f,2f,2f};
float [] widths = {
2.5f, //codigo
6f, //descripcion
3f, //Unidad
2f, //Cantidad
2f //Descripcion
};
PdfPTable tablaComponentes = new PdfPTable(widths);
Iterator it;
tablaComponentes.setKeepTogether(false);
tablaComponentes.setHeaderRows(1);
cell = new PdfPCell(new Paragraph("Código",smallBoldFontWhite));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setUseDescender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBackgroundColor(BaseColor.BLACK);
tablaComponentes.addCell(cell);
cell = new PdfPCell(new Paragraph("Descripción",smallBoldFontWhite));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setUseDescender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBackgroundColor(BaseColor.BLACK);
tablaComponentes.addCell(cell);
cell = new PdfPCell(new Paragraph("Unidad",smallBoldFontWhite));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setUseDescender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBackgroundColor(BaseColor.BLACK);
tablaComponentes.addCell(cell);
cell = new PdfPCell(new Paragraph("Cantidad",smallBoldFontWhite));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setUseDescender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBackgroundColor(BaseColor.BLACK);
tablaComponentes.addCell(cell);
cell = new PdfPCell(new Paragraph("Existencia",smallBoldFontWhite));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setUseDescender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBackgroundColor(BaseColor.BLACK);
tablaComponentes.addCell(cell);
it = this.getLista_componentes().iterator();
while(it.hasNext()){
HashMap<String,String> map = (HashMap<String,String>)it.next();
cell = new PdfPCell(new Paragraph(esteAtributoSeDejoNulo(map.get("sku")), smallFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
tablaComponentes.addCell(cell);
String descripcion = map.get("descripcion");
descripcion = StringEscapeUtils.unescapeHtml(descripcion);
cell = new PdfPCell(new Paragraph(StringHelper.capitalizaString(descripcion), smallFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
tablaComponentes.addCell(cell);
//cell = new PdfPCell(new Paragraph(StringHelper.capitalizaString(esteAtributoSeDejoNulo(map.get("titulo"))), smallFont));
cell = new PdfPCell(new Paragraph("KILO", smallFont));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
tablaComponentes.addCell(cell);
Double cantidad = Double.parseDouble(map.get("cantidad"))/100;
Double cantCalculada = Double.parseDouble(this.getCantidad()) * cantidad;
String nuevaCantidad = StringHelper.AgregaComas(StringHelper.roundDouble(cantCalculada,4));
//cantidad
cell = new PdfPCell(new Paragraph(nuevaCantidad, smallFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
tablaComponentes.addCell(cell);
//Existencia
cell = new PdfPCell(new Paragraph(StringHelper.AgregaComas(map.get("existencia")), smallFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
tablaComponentes.addCell(cell);
}
cell = new PdfPCell(new Paragraph("", smallFont));
cell.setBorderWidthBottom(0);
cell.setBorderWidthTop(1);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
cell.setColspan(5);
tablaComponentes.addCell(cell);
tablaComponentes.setSpacingAfter(12f);
//Agregar tabla de componentes al documento
document.add(tablaComponentes);
float [] widths3 = {5,3.5f,5};
tableElaboro = new PdfPTable(widths3);
tableElaboro.setKeepTogether(true);
//FILA 1
cell = new PdfPCell(new Paragraph("ELABORÓ",smallFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_TOP);
cell.setBorder(0);
cell.setColspan(3);
tableElaboro.addCell(cell);
//FILA 2
cell = new PdfPCell(new Paragraph("",smallFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
cell.setFixedHeight(25);
cell.setBorder(0);
tableElaboro.addCell(cell);
cell = new PdfPCell(new Paragraph(this.getUsuario_elaboracion().toUpperCase(),smallFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
cell.setFixedHeight(25);
cell.setBorderWidthBottom(1);
cell.setBorderWidthTop(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthLeft(0);
tableElaboro.addCell(cell);
cell = new PdfPCell(new Paragraph("",smallFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
cell.setFixedHeight(25);
cell.setBorder(0);
tableElaboro.addCell(cell);
//Agregar tableElaboro al documento
document.add(tableElaboro);
document.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public String esteAtributoSeDejoNulo(String atributo){
return (atributo != null) ? (atributo) : new String();
}
public HashMap<String, String> getDatosHeaderFooter() {
return datosHeaderFooter;
}
public void setDatosHeaderFooter(HashMap<String, String> datosHeaderFooter) {
this.datosHeaderFooter = datosHeaderFooter;
}
public String getEmp_razon_social() {
return emp_razon_social;
}
public void setEmp_razon_social(String emp_razon_social) {
this.emp_razon_social = emp_razon_social;
}
public String getFileout() {
return fileout;
}
public void setFileout(String fileout) {
this.fileout = fileout;
}
public ArrayList<HashMap<String, String>> getLista_componentes() {
return lista_componentes;
}
public void setLista_componentes(ArrayList<HashMap<String, String>> lista_componentes) {
this.lista_componentes = lista_componentes;
}
public String getTipo_simulacion() {
return tipo_simulacion;
}
public void setTipo_simulacion(String tipo_simulacion) {
this.tipo_simulacion = tipo_simulacion;
}
public String getCantidad() {
return cantidad;
}
public void setCantidad(String cantidad) {
this.cantidad = cantidad;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getUsuario_elaboracion() {
return usuario_elaboracion;
}
public void setUsuario_elaboracion(String usuario_elaboracion) {
this.usuario_elaboracion = usuario_elaboracion;
}
public String getCantidad_lt() {
return cantidad_lt;
}
public void setCantidad_lt(String cantidad_lt) {
this.cantidad_lt = cantidad_lt;
}
public String getDensidad() {
return densidad;
}
public void setDensidad(String densidad) {
this.densidad = densidad;
}
static class HeaderFooter extends PdfPageEventHelper {
protected PdfTemplate total;
protected BaseFont helv;
protected PdfContentByte cb;
Font largeBoldFont = new Font(Font.FontFamily.HELVETICA,10,Font.BOLD,BaseColor.BLACK);
Font largeFont = new Font(Font.FontFamily.HELVETICA,10,Font.NORMAL,BaseColor.BLACK);
Font smallFont = new Font(Font.FontFamily.HELVETICA,7,Font.NORMAL,BaseColor.BLACK);
//ESTAS SON VARIABLES PRIVADAS DE LA CLASE, SE LE ASIGNA VALOR EN EL CONSTRUCTOR SON SETER
private String empresa;
private String periodo;
private String titulo_reporte;
private String codigo1;
private String codigo2;
//ESTOS SON LOS GETER Y SETTER DE LAS VARIABLES PRIVADAS DE LA CLASE
public String getCodigo1() {
return codigo1;
}
public void setCodigo1(String codigo1) {
this.codigo1 = codigo1;
}
public String getCodigo2() {
return codigo2;
}
public void setCodigo2(String codigo2) {
this.codigo2 = codigo2;
}
public String getTitulo_reporte() {
return titulo_reporte;
}
public void setTitulo_reporte(String titulo_reporte) {
this.titulo_reporte = titulo_reporte;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public String getPeriodo() {
return periodo;
}
public void setPeriodo(String periodo) {
this.periodo = periodo;
}
//ESTE ES EL CONSTRUCTOR DE LA CLASE QUE RECIBE LOS PARAMETROS
HeaderFooter( HashMap<String, String> datos ){
this.setEmpresa(datos.get("empresa"));
this.setTitulo_reporte(datos.get("titulo_reporte"));
this.setPeriodo(datos.get("periodo"));
this.setCodigo1(datos.get("codigo1"));
this.setCodigo2(datos.get("codigo2"));
}
/*Añadimos una tabla con una imagen del logo de megestiono y creamos la fuente para el documento, la imagen esta escalada para que no se muestre pixelada*/
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
try {
total = writer.getDirectContent().createTemplate(100, 100);
//public Rectangle(int x, int y, int width, int height)
total.setBoundingBox(new Rectangle(-20, -20, 100, 100));
total.fill();
helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
}
catch(Exception e) {
throw new ExceptionConverter(e);
}
}
/*añdimos pie de pagina, borde y mas propiedades*/
@Override
public void onEndPage(PdfWriter writer, Document document) {
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, new Phrase(this.getEmpresa(),largeBoldFont),document.getPageSize().getWidth()/2, document.getPageSize().getTop() -25, 0);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, new Phrase(this.getTitulo_reporte(),largeBoldFont),document.getPageSize().getWidth()/2, document.getPageSize().getTop()-38, 0);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, new Phrase(this.getPeriodo(),largeFont),document.getPageSize().getWidth()/2, document.getPageSize().getTop()-50, 0);
cb = writer.getDirectContent();
float textBase = document.bottom() - 15;
//texto inferior izquieda pie de pagina
String text_left = this.getCodigo1();
float text_left_Size = helv.getWidthPoint(text_left, 7);
cb.beginText();
cb.setFontAndSize(helv, 7);
cb.setTextMatrix(document.left()+85, textBase ); //definir la posicion de text
cb.showText(text_left);
cb.endText();
//texto centro pie de pagina
String text_center ="Página " + writer.getPageNumber() + " de ";
float text_center_Size = helv.getWidthPoint(text_center, 7);
float pos_text_center = (document.getPageSize().getWidth()/2)-(text_center_Size/2);
float adjust = text_center_Size + 3;
cb.beginText();
cb.setFontAndSize(helv, 7);
cb.setTextMatrix(pos_text_center, textBase ); //definir la posicion de text
cb.showText(text_center);
cb.endText();
cb.addTemplate(total, pos_text_center + adjust, textBase);
//texto inferior derecha pie de pagina
String text_right = this.getCodigo2();
float textRightSize = helv.getWidthPoint(text_right, 7);
float pos_text_right = document.getPageSize().getWidth()-textRightSize - 40;
cb.beginText();
cb.setFontAndSize(helv, 7);
cb.setTextMatrix(pos_text_right, textBase);
cb.showText(text_right);
cb.endText();
//cb.restoreState();
}
/*aqui escrimos ls paginas totales, para que nos salga de pie de pagina Pagina x de y*/
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
total.beginText();
total.setFontAndSize(helv, 7);
total.setTextMatrix(0,0);
total.showText(String.valueOf(writer.getPageNumber() -1));
total.endText();
}
}//termina clase HeaderFooter
}
|
Python | UTF-8 | 2,050 | 2.5625 | 3 | [
"MIT"
] | permissive |
from .base import Distribution
import tensorflow as tf
import numpy as np
TINY = 1e-8
class Bernoulli(Distribution):
def __init__(self, dim):
self._dim = dim
@property
def dim(self):
return self._dim
def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
old_p = old_dist_info_vars["p"]
new_p = new_dist_info_vars["p"]
kl = old_p * (tf.log(old_p + TINY) - tf.log(new_p + TINY)) + \
(1 - old_p) * (tf.log(1 - old_p + TINY) - tf.log(1 - new_p + TINY))
ndims = kl.get_shape().ndims
return tf.reduce_sum(kl, axis=ndims - 1)
def kl(self, old_dist_info, new_dist_info):
old_p = old_dist_info["p"]
new_p = new_dist_info["p"]
kl = old_p * (np.log(old_p + TINY) - np.log(new_p + TINY)) + \
(1 - old_p) * (np.log(1 - old_p + TINY) - np.log(1 - new_p + TINY))
return np.sum(kl, axis=-1)
def sample(self, dist_info):
p = np.asarray(dist_info["p"])
return np.cast['int'](np.random.uniform(low=0., high=1., size=p.shape) < p)
def likelihood_ratio_sym(self, x_var, old_dist_info_vars, new_dist_info_vars):
old_p = old_dist_info_vars["p"]
new_p = new_dist_info_vars["p"]
ndims = old_p.get_shape().ndims
return tf.reduce_prod(x_var * new_p / (old_p + TINY) + (1 - x_var) * (1 - new_p) / (1 - old_p + TINY),
axis=ndims - 1)
def log_likelihood_sym(self, x_var, dist_info_vars):
p = dist_info_vars["p"]
ndims = p.get_shape().ndims
return tf.reduce_sum(x_var * tf.log(p + TINY) + (1 - x_var) * tf.log(1 - p + TINY), axis=ndims - 1)
def log_likelihood(self, xs, dist_info):
p = dist_info["p"]
return np.sum(xs * np.log(p + TINY) + (1 - xs) * np.log(1 - p + TINY), axis=-1)
def entropy(self, dist_info):
p = dist_info["p"]
return np.sum(- p * np.log(p + TINY) - (1 - p) * np.log(1 - p + TINY), axis=-1)
@property
def dist_info_keys(self):
return ["p"]
|
Go | UTF-8 | 8,814 | 3.265625 | 3 | [] | no_license | package donothing
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"strings"
)
// A Procedure is a sequence of Steps that can be executed or rendered to markdown.
type Procedure struct {
// The root step of the procedure, of which all other steps are descendants.
rootStep *Step
stdin io.Reader
stdout io.Writer
}
// Short provides the procedure with a short description.
//
// The short description will be the title of the rendered markdown document when Render is called,
// so it should be concise and accurate.
func (pcd *Procedure) Short(s string) {
pcd.rootStep.Short(s)
}
// GetShort returns the procedure's short description.
func (pcd *Procedure) GetShort() string {
return pcd.rootStep.GetShort()
}
// Long provides the procedure with a long description.
//
// The long description will be shown to the user when they first execute the procedure. It will
// also be included in the opening section of the procedure's Markdown documentation.
//
// It should give an overview of the procedure's purpose and any important assumptions the procedure
// makes about the state of the world at the beginning of execution.
func (pcd *Procedure) Long(s string) {
pcd.rootStep.Long(s)
}
// AddStep adds a step to the procedure.
//
// A new Step will be instantiated and passed to fn to be defined.
func (pcd *Procedure) AddStep(fn func(*Step)) {
pcd.rootStep.AddStep(fn)
}
// GetStepByName returns the step with the given (absolute) name.
func (pcd *Procedure) GetStepByName(stepName string) (*Step, error) {
var foundStep *Step
err := pcd.rootStep.Walk(func(step *Step) error {
absNmae := step.AbsoluteName()
if absNmae == stepName {
//if step.AbsoluteName() == stepName {
foundStep = step
// Return error to end walk. This error will be ignored since we have set foundStep to
// something other than nil.
return fmt.Errorf("")
}
return nil
})
if foundStep != nil {
return foundStep, nil
}
if err != nil {
return nil, err
}
return nil, fmt.Errorf("No step with name '%s'", stepName)
}
// Check validates that the procedure makes sense.
//
// If problems are found, it returns the list of problems along with an error.
//
// It checks the procedure against the following expectations:
//
// 1. Every step has a unique absolute name with no empty parts.
// 2. Every step has a short description
// 3. Every input has a name that matches the name of an output from a previous step.
func (pcd *Procedure) Check() ([]string, error) {
steps := make(map[string]*Step)
outputs := make(map[string]OutputDef)
problems := make([]string, 0)
err := pcd.rootStep.Walk(func(step *Step) error {
absName := step.AbsoluteName()
if absName[len(absName)-1:] == "." {
if step.parent == nil {
// I really hope this never happens. The root step should get its name from
// donothing, not from the calling code.
problems = append(problems, "Root step does not have name")
} else {
problems = append(problems, fmt.Sprintf("Child step of '%s' does not have name", step.parent.AbsoluteName()))
}
}
if steps[absName] != nil {
problems = append(problems, fmt.Sprintf("More than one step with name '%s'", absName))
}
steps[step.AbsoluteName()] = step
if step.GetShort() == "" {
problems = append(problems, fmt.Sprintf("Step '%s' has no Short value", absName))
}
for _, inputDef := range step.GetInputDefs() {
matchingOutputDef, ok := outputs[inputDef.Name]
if !ok {
problems = append(problems, fmt.Sprintf(
"Input '%s' of step '%s' does not refer to an output from any previous step",
inputDef.Name,
absName,
))
continue
}
if matchingOutputDef.ValueType != inputDef.ValueType {
problems = append(problems, fmt.Sprintf(
"Input '%s' of step '%s' has type '%s', but output '%s' has type '%s'",
inputDef.Name,
absName,
inputDef.ValueType,
matchingOutputDef.Name,
matchingOutputDef.ValueType,
))
}
}
for _, outputDef := range step.GetOutputDefs() {
outputs[outputDef.Name] = outputDef
}
return nil
})
if err != nil {
return []string{}, fmt.Errorf("Error while checking procedure: %w", err)
}
if len(problems) > 0 {
return problems, errors.New("Problems were found in the procedure")
}
return []string{}, nil
}
// Render prints the procedure's Markdown representation to f.
//
// Any occurrence of the string "@@" in the executed template output will be replaced with a
// backtick.
func (pcd *Procedure) Render(f io.Writer) error {
return pcd.RenderStep(f, "root")
}
// RenderStep prints the given step from the procedure as Markdown to f.
//
// Any occurrence of the string "@@" in the executed template output will be replaced with a
// backtick.
func (pcd *Procedure) RenderStep(f io.Writer, stepName string) error {
if _, err := pcd.Check(); err != nil {
return err
}
tpl, err := DocTemplate()
if err != nil {
return err
}
step, err := pcd.GetStepByName(stepName)
if err != nil {
return err
}
tplData := NewStepTemplateData(step, nil, true)
var b strings.Builder
err = tpl.Execute(&b, tplData)
if err != nil {
return err
}
fmt.Fprintf(f, "%s", strings.Replace(b.String(), "@@", "`", -1))
return nil
}
// Execute runs through the procedure step by step.
//
// The user will be prompted as necessary.
func (pcd *Procedure) Execute() error {
return pcd.ExecuteStep("root")
}
// ExecuteStep runs through the given step.
//
// The user will be prompted as necessary.
func (pcd *Procedure) ExecuteStep(stepName string) error {
if _, err := pcd.Check(); err != nil {
return err
}
step, err := pcd.GetStepByName(stepName)
if err != nil {
return err
}
tpl, err := ExecTemplate()
if err != nil {
return err
}
step, err = pcd.GetStepByName(stepName)
if err != nil {
return err
}
var skipTo string
step.Walk(func(walkStep *Step) error {
if skipTo != "" && walkStep.AbsoluteName() != skipTo {
fmt.Fprintf(pcd.stdout, "Skipping step '%s' on the way to '%s'\n", walkStep.AbsoluteName(), skipTo)
return nil
}
tplData := NewStepTemplateData(walkStep, nil, false)
var b bytes.Buffer
err = tpl.Execute(&b, tplData)
if err != nil {
return err
}
fmt.Fprintf(pcd.stdout, "%s", strings.Replace(b.String(), "@@", "`", -1))
promptResult := pcd.prompt()
if promptResult.SkipOne {
fmt.Fprintf(pcd.stdout, "Skipping step '%s' and its descendants\n", walkStep.AbsoluteName())
return NoRecurse
}
skipTo = promptResult.SkipTo
return nil
})
fmt.Fprintln(pcd.stdout, "Done.")
return nil
}
// promptResult is the struct returned by Procedure.prompt.
//
// Procedure.Execute uses the contents of a promptResult to decide what to do next.
type promptResult struct {
// Whether to skip this step and its descendants.
SkipOne bool
// The absolute name of the next step that should be executed.
//
// If empty, Execute should proceed normally in its walk.
SkipTo string
}
// prompt prompts the user for the next action to take.
//
// If the user enters an invalid choice, prompt will inform them of this and re-prompt until a valid
// choice is entered.
func (pcd *Procedure) prompt() promptResult {
// promptOnce prompts the user for input. It returns their input, trimmed of leading and
// trailing whitespace.
promptOnce := func() (string, error) {
fmt.Fprintf(pcd.stdout, "\n\n[Enter] to proceed (or \"help\"): ")
entry, err := bufio.NewReader(pcd.stdin).ReadBytes('\n')
fmt.Fprintf(pcd.stdout, "\n")
return strings.TrimSpace(string(entry)), err
}
for {
entry, err := promptOnce()
if err != nil {
fmt.Fprintf(pcd.stdout, "Error reading input: %s\n", err.Error())
continue
}
if entry == "" {
// Proceed to the next step as normal
return promptResult{}
}
if entry == "help" {
// Print the help message and prompt again
pcd.printPromptHelp()
}
if entry == "skip" {
return promptResult{SkipOne: true}
}
if strings.HasPrefix(entry, "skipto ") {
parts := strings.Split(entry, " ")
if len(parts) != 2 || len(parts[1]) == 0 {
fmt.Fprintf(pcd.stdout, "Invalid 'skipto' syntax; enter \"help\" for help\n")
}
return promptResult{SkipTo: parts[1]}
}
fmt.Fprintf(pcd.stdout, "Invalid choice; enter \"help\" for help\n")
}
}
// printPromptHelp prints the help message for the Execute prompt.
func (pcd *Procedure) printPromptHelp() {
fmt.Fprintf(pcd.stdout, `Options:
[Enter] Proceed to the next step
skip Skip this step and its descendants
skipto STEP Skip to the given step by absolute name
help Print this help message`)
}
// NewProcedure returns a new procedure, ready to be given steps.
func NewProcedure() *Procedure {
pcd := new(Procedure)
pcd.rootStep = NewStep()
pcd.rootStep.Name("root")
pcd.stdin = os.Stdin
pcd.stdout = os.Stdout
return pcd
}
|
JavaScript | UTF-8 | 454 | 2.59375 | 3 | [] | no_license | import * as type from './actions';
const initialState = {
visibleBlocks: []
}
export default function (state = initialState, action){
switch(action.type){
case type.GET_BLOCKS: {
const shuffled = action.payload.sort(() => 0.5 - Math.random());
const random = shuffled.slice(0, 6);
return {...state, visibleBlocks: random}
}
default:
return state
}
} |
C# | UTF-8 | 6,109 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.Fonts.WellKnownIds
{
/// <summary>
/// Provides enumeration of common name ids
/// <see href="https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids"/>
/// </summary>
public enum KnownNameIds : ushort
{
/// <summary>
/// The copyright notice
/// </summary>
CopyrightNotice = 0,
/// <summary>
/// The font family name; Up to four fonts can share the Font Family name, forming a font style linking
/// group (regular, italic, bold, bold italic — as defined by OS/2.fsSelection bit settings).
/// </summary>
FontFamilyName = 1,
/// <summary>
/// The font subfamily name; The Font Subfamily name distinguishes the font in a group with the same Font Family name (name ID 1).
/// This is assumed to address style (italic, oblique) and weight (light, bold, black, etc.). A font with no particular differences
/// in weight or style (e.g. medium weight, not italic and fsSelection bit 6 set) should have the string "Regular" stored in this position.
/// </summary>
FontSubfamilyName = 2,
/// <summary>
/// The unique font identifier
/// </summary>
UniqueFontID = 3,
/// <summary>
/// The full font name; a combination of strings 1 and 2, or a similar human-readable variant. If string 2 is "Regular", it is sometimes omitted from name ID 4.
/// </summary>
FullFontName = 4,
/// <summary>
/// Version string. Should begin with the syntax 'Version <number>.<number>' (upper case, lower case, or mixed, with a space between "Version" and the number).
/// The string must contain a version number of the following form: one or more digits (0-9) of value less than 65,535, followed by a period, followed by one or more
/// digits of value less than 65,535. Any character other than a digit will terminate the minor number. A character such as ";" is helpful to separate different pieces of version information.
/// The first such match in the string can be used by installation software to compare font versions.
/// Note that some installers may require the string to start with "Version ", followed by a version number as above.
/// </summary>
Version = 5,
/// <summary>
/// Postscript name for the font; Name ID 6 specifies a string which is used to invoke a PostScript language font that corresponds to this OpenType font.
/// When translated to ASCII, the name string must be no longer than 63 characters and restricted to the printable ASCII subset, codes 33 to 126,
/// except for the 10 characters '[', ']', '(', ')', '{', '}', '<', '>', '/', '%'.
/// In a CFF OpenType font, there is no requirement that this name be the same as the font name in the CFF’s Name INDEX.
/// Thus, the same CFF may be shared among multiple font components in a Font Collection. See the 'name' table section of
/// Recommendations for OpenType fonts "" for additional information.
/// </summary>
PostscriptName = 6,
/// <summary>
/// Trademark; this is used to save any trademark notice/information for this font. Such information should
/// be based on legal advice. This is distinctly separate from the copyright.
/// </summary>
Trademark = 7,
/// <summary>
/// The manufacturer
/// </summary>
Manufacturer = 8,
/// <summary>
/// Designer; name of the designer of the typeface.
/// </summary>
Designer = 9,
/// <summary>
/// Description; description of the typeface. Can contain revision information, usage recommendations, history, features, etc.
/// </summary>
Description = 10,
/// <summary>
/// URL Vendor; URL of font vendor (with protocol, e.g., http://, ftp://). If a unique serial number is embedded in
/// the URL, it can be used to register the font.
/// </summary>
VendorUrl = 11,
/// <summary>
/// URL Designer; URL of typeface designer (with protocol, e.g., http://, ftp://).
/// </summary>
DesignerUrl = 12,
/// <summary>
/// License Description; description of how the font may be legally used, or different example scenarios for licensed use.
/// This field should be written in plain language, not legalese.
/// </summary>
LicenseDescription = 13,
/// <summary>
/// License Info URL; URL where additional licensing information can be found.
/// </summary>
LicenseInfoUrl = 14,
/// <summary>
/// Typographic Family name: The typographic family grouping doesn't impose any constraints on the number of faces within it,
/// in contrast with the 4-style family grouping (ID 1), which is present both for historical reasons and to express style linking groups.
/// If name ID 16 is absent, then name ID 1 is considered to be the typographic family name.
/// (In earlier versions of the specification, name ID 16 was known as "Preferred Family".)
/// </summary>
TypographicFamilyName = 16,
/// <summary>
/// Typographic Subfamily name: This allows font designers to specify a subfamily name within the typographic family grouping.
/// This string must be unique within a particular typographic family. If it is absent, then name ID 2 is considered to be the
/// typographic subfamily name. (In earlier versions of the specification, name ID 17 was known as "Preferred Subfamily".)
/// </summary>
TypographicSubfamilyName = 17,
/// <summary>
/// Sample text; This can be the font name, or any other text that the designer thinks is the best sample to display the font in.
/// </summary>
SampleText = 19,
}
}
|
Java | UTF-8 | 465 | 3 | 3 | [] | no_license | package ru.job4j.oop;
/**
* Class College
* @author Dmitry Razumov
* @version 1
*/
public class College {
/**
* Главный метод программы. В методе практикуется приведение типов.
* @param args Параметры командной строки
*/
public static void main(String[] args) {
Freshman tom = new Freshman();
Student student = tom;
Object obj = tom;
}
}
|
Python | UTF-8 | 2,401 | 2.671875 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import smtplib
import time
import os
import pathlib
URL = 'https://www.amazon.com.au/gp/product/B079HYCWR1/ref=ox_sc_act_title_1?smid=A2NLI3B5IXPZVP&psc=1'
headers = {
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}
creditential_files_dir = str(pathlib.Path(__file__).parent.absolute()) + '\\data\\login_details.txt'
def send_mail(gmail, password, recipant_email, senders_email):
print('sending gmail')
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(gmail, password)
print('login successfully')
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
name = soup.find(id='productTitle').get_text()
price = soup.find(id='priceblock_ourprice').get_text()
title = name.strip()
print(title, '|', price)
subject = 'hey, the price fell down (under $100)'
body = 'check the amazon link: https://www.amazon.com.au/gp/product/B079HYCWR1/ref=ox_sc_act_title_1?smid=A2NLI3B5IXPZVP&psc=1'
part1 = '|'
body2 = title + part1 + price
msg = f'subject: {subject}\n\n{body2}\n\n{body}'
server.sendmail(recipant_email, senders_email, msg)
print('GMAIL HAS BEEN SENT SUCSESSFULLY!')
server.quit()
def check_price(g, p, re, se):
print('checking price')
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
price = soup.find(id='priceblock_ourprice').get_text()
converted_price = float(price.replace('$', ''))
if (converted_price <= 100.00):
send_mail(g, p, re, se)
else:
print('still too expensive')
login_file = open(creditential_files_dir, "r")
if not os.path.exists(creditential_files_dir):
print("login_details.txt does not exist, please full in login details")
create_login_file = open("login_details.txt", "x")
exit()
elif not os.path.getsize(creditential_files_dir) > 0:
print("Theres no login information, please enter your login details")
login_file = open(creditential_files_dir, "r")
print("Got login details, initalizing.....")
line = login_file.readlines()
gmail = str(line[0])
password = str(line[1])
sender_email = str(line[2])
while True:
check_price(gmail, password, gmail, sender_email)
time.sleep(30)
|
Shell | UTF-8 | 719 | 3.15625 | 3 | [] | no_license | #!/bin/bash
function getUrlOfLastPage() {
#http://www.collectedcurios.com/battlebunnies.php?s=38
wget http://www.collectedcurios.com/battlebunnies.php?s=1 -O /tmp/battlebunniescollectedcurios
lastpage=$( grep 'title="Last"' /tmp/battlebunniescollectedcurios | sed 's/title="Forward ten"//;s/.*s=//;s/".*//' )
echo ${lastpage}
}
counter=1
lastpage=$( getUrlOfLastPage )
while [ $counter -le ${lastpage} ]
do
fileNumber=$( printf "%03d" ${counter} )
wget -nv -U "Mozilla" http://www.collectedcurios.com/BBTSN_${fileNumber}_Small.jpg
let 'counter+=1'
done
zip Battlebunniescollectedcurios BBTSN*.jpg
mv Battlebunniescollectedcurios.zip Battlebunniescollectedcurios.cbz
evince Battlebunniescollectedcurios.cbz &
|
Java | UTF-8 | 301 | 1.65625 | 2 | [] | no_license | package com.ccms.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.ccms.domain.AccountLengthSetup;
@Repository
public interface AccountLengthSetupRepository extends JpaRepository<AccountLengthSetup, Integer> {
}
|
Markdown | UTF-8 | 3,446 | 2.796875 | 3 | [] | no_license | ---
title: "Moodle"
class_name: docs
full_width: true
---
Please be sure to check out the [Codio LTI App](/docs/classes/lti/lti1_0/ltiapp) which allows for an easy way to integrate and to map Codio class units to your LMS system. Moodle added support for LTI™ apps in version 2.2. The [following page](https://docs.moodle.org/32/en/External_tool_settings) explains how to set up external apps in Moodle.
### Authentication and account creation
Once you have configured the LTI/LMS settings, Moodle manages all aspects of signing in to Codio as well as account creation. All your teachers and students need is a Moodle account.
If a Moodle user has never used Codio before then an account will automatically be created when they access their first Codio course materials.
If a Moodle user already has a Codio account then **provided the email address of their Codio account matches the email address of their LMS account** the same Codio account will be used. If, however, the user has used a different email address within Codio, then a new Codio account will be created that matches that of the Moodle account.
## Setup, configuration and usage
The following instructions are provided as short videos.
### One time setup
You will not have access to the Moodle/LMS features unless you have an educational organization setup as explained in the video.
**Important** : Codio needs the User Role, Email Address and Name of the Moodle user in order to work. It is important that you access the LTI security settings and ensure that these three fields are always enabled.
**Please note** : Since these videos were created, the Codio keys are now found on the **LTI Integration** tab in your organisation **My Organistaions** area
<iframe src="https://player.vimeo.com/video/170350745" width="640" height="442" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
### Mapping Moodle Courses and creating Moodle Activities
This video covers the two key aspects of Moodle->Codio mapping...
- mapping your Moodle **Course** to a Codio **Class**, a one-time only configuration for a new class
- creating a Moodle **Activity** within a Course and mapping it to a Codio **Unit**
<iframe src="https://player.vimeo.com/video/170350816" width="640" height="442" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
### Using Codio from Moodle - student view
Explains how students access Codio from within the LMS.
<iframe src="https://player.vimeo.com/video/170350928" width="640" height="442" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
### Using Codio from your LMS - teacher view
Explains how teachers can access students' Codio projects from the Codio Classroom or from Moodle.
<iframe src="https://player.vimeo.com/video/170354127" width="640" height="442" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
### Grading student work and grade transfer to the Moodle gradebook
This video shows
- how teachers grade student work in Codio
- how grades are not released to students either in Codio or the LMS until the teacher says so
- how grades are transferred to the Moodle gradebook once the teacher selects the **Release Grades** option
<iframe src="https://player.vimeo.com/video/170354128" width="640" height="442" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
|
Java | UTF-8 | 889 | 2.15625 | 2 | [] | no_license | public abstract class cke
extends ckc
{
public final chi b;
public cke(chi paramchi, chj paramchj)
{
super(paramchj);
if (paramchi == null) {
throw new IllegalArgumentException("The field must not be null");
}
if (!paramchi.c()) {
throw new IllegalArgumentException("The field must be supported");
}
b = paramchi;
}
public int a(long paramLong)
{
return b.a(paramLong);
}
public long b(long paramLong, int paramInt)
{
return b.b(paramLong, paramInt);
}
public long d(long paramLong)
{
return b.d(paramLong);
}
public chn d()
{
return b.d();
}
public chn e()
{
return b.e();
}
public int g()
{
return b.g();
}
public int h()
{
return b.h();
}
}
/* Location:
* Qualified Name: cke
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
Python | UTF-8 | 264 | 3.484375 | 3 | [] | no_license | def reverseString(s):
return s[::-1]
def reverseString_2(s):
str = ''
long = len(s) - 1
while long != -1:
str += s[long]
long -= 1
return str
def reverseString_3(s):
return ''.join(s[i] for i in range(len(s) - 1, -1, -1))
|
Python | UTF-8 | 331 | 4 | 4 | [
"Apache-2.0"
] | permissive | from random import randint
numeros = (randint(0,10),randint(0,10),randint(0,10),randint(0,10),randint(0,10))
print('Os valores sorteados foram: ', end='')
for n in numeros:
print(f'{n} ', end='')
print('\nO maior valor sorteado foi {}'.format(max(numeros)))
print('O menor valor sorteado foi {}'.format(min(numeros)))
|
TypeScript | UTF-8 | 218 | 2.625 | 3 | [] | no_license | export interface Category {
name: string;
id: string;
songs: Song[];
selected?: boolean;
}
export interface Song {
id: string;
src: string;
point: number;
isPlaying?: boolean;
isPlayed?: boolean;
}
|
Java | UTF-8 | 4,074 | 3.5 | 4 | [] | no_license | /*****************************************************
Team Over The Moon (Sachal Malick and Kyle Moon)
APCS2 pd10
HW27 -- You Lot at Fake Terrys
2016--04--06
******************************************************/
public class RQueue<T> implements Queue<T> {
private LLNode<T> _front, _end;
private int _size;
// default constructor creates an empty queue
public RQueue()
{
_size=0;
_front = _end = null;
}//end default constructor
public void enqueue( T enQVal )
{
LLNode<T> temp = new LLNode<T>(enQVal, null);
if (this.isEmpty())
{
_front = temp;
_end = temp;
}
else
{
_end.setNext(temp);
_end = temp;
}
_size++;
}
// remove and return thing at front of queue
// assume _queue ! empty
public T dequeue()
{
if (this.isEmpty())
{
System.out.println("***Cannot dequeue from empty queue***");
return null;
}
sample();
T retV = _front.getValue();
_front = _front.getNext();
_size--;
return retV;
}//end dequeue()
public T peekFront()
{
T retV = _front.getValue();
return retV;
}
public T get( int index )
{
if ( index < 0 || index >= size() )
throw new IndexOutOfBoundsException();
T retVal;
LLNode<T> tmp = _front; //create alias to head
//walk to desired node
for( int i=0; i < index; i++ )
tmp = tmp.getNext();
//check target node's cargo hold
retVal = tmp.getValue();
return retVal;
}
public int size() {return _size;}
public T set( int index, T newVal )
{
if ( index < 0 || index >= size() )
throw new IndexOutOfBoundsException();
LLNode<T> tmp = _front; //create alias to head
//walk to desired node
for( int i=0; i < index; i++ )
tmp = tmp.getNext();
//store target node's cargo
T oldVal = tmp.getValue();
//modify target node's cargo
tmp.setValue( newVal );
return oldVal;
}
/******************************************
* void sample() -- a means of "shuffling" the queue
* Algo:
* ...
*
******************************************/
public void sample ()
{
LLNode<T> temp = _front;
while (temp != null)
{
int n = (int)(Math.random() * _size);
T r = temp.getValue();
temp.setValue(get(n));
set(n,r);
temp = temp.getNext();
}
}
public boolean isEmpty()
{
return _size==0;
} //O(?)
// print each node, separated by spaces
public String toString()
{
String retS = "";
LLNode<T> temp = _front;
while (temp != null)
{
retS += temp + " ";
temp = temp.getNext();
}
return retS;
}//end toString()
//main method for testing
public static void main( String[] args ) {
Queue<String> PirateQueue = new RQueue<String>();
System.out.println("\nnow enqueuing...");
PirateQueue.enqueue("Dread");
PirateQueue.enqueue("Pirate");
PirateQueue.enqueue("Robert");
PirateQueue.enqueue("Blackbeard");
PirateQueue.enqueue("Peter");
PirateQueue.enqueue("Stuyvesant");
System.out.println("\nnow testing toString()...");
System.out.println( PirateQueue ); //for testing toString()...
System.out.println("\nnow dequeuing...");
System.out.println( PirateQueue.dequeue() );
System.out.println( PirateQueue.dequeue() );
System.out.println( PirateQueue.dequeue() );
System.out.println( PirateQueue.dequeue() );
System.out.println( PirateQueue.dequeue() );
System.out.println( PirateQueue.dequeue() );
System.out.println("\nnow dequeuing fr empty queue...");
System.out.println( PirateQueue.dequeue() );
}//end main
}//end class RQueue
|
Java | UTF-8 | 13,166 | 2.296875 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2002, 2011 Innoopract Informationssysteme GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Innoopract Informationssysteme GmbH - initial API and implementation
* EclipseSource - ongoing development
******************************************************************************/
package org.eclipse.swt.widgets;
import org.eclipse.rwt.graphics.Graphics;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.internal.widgets.ILinkAdapter;
/**
* Instances of this class represent a selectable
* user interface object that displays a text with
* links.
* <p>
* <dl>
* <dt><b>Styles:</b></dt>
* <dd>(none)</dd>
* <dt><b>Events:</b></dt>
* <dd>Selection</dd>
* </dl>
* <p>
* IMPORTANT: This class is <em>not</em> intended to be subclassed.
* </p>
*
* @since 1.0
*/
public class Link extends Control {
// Must be kept in sync with appearance value in AppearancesBase.js
private final static int PADDING = 2;
private String text = "";
private String displayText = "";
private Point[] offsets;
private String[] ids;
private int[] mnemonics;
private transient ILinkAdapter linkAdapter;
/**
* Constructs a new instance of this class given its parent
* and a style value describing its behavior and appearance.
* <p>
* The style value is either one of the style constants defined in
* class <code>SWT</code> which is applicable to instances of this
* class, or must be built by <em>bitwise OR</em>'ing together
* (that is, using the <code>int</code> "|" operator) two or more
* of those <code>SWT</code> style constants. The class description
* lists the style constants that are applicable to the class.
* Style bits are also inherited from superclasses.
* </p>
*
* @param parent a composite control which will be the parent of the new instance (cannot be null)
* @param style the style of control to construct
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
* <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
* </ul>
*
* @see Widget#checkSubclass
* @see Widget#getStyle
*/
public Link( Composite parent, int style ) {
super( parent, style );
}
void initState() {
state |= THEME_BACKGROUND;
}
/**
* Sets the receiver's text.
* <p>
* The string can contain both regular text and hyperlinks. A hyperlink
* is delimited by an anchor tag, <A> and </A>. Within an
* anchor, a single HREF attribute is supported. When a hyperlink is
* selected, the text field of the selection event contains either the
* text of the hyperlink or the value of its HREF, if one was specified.
* In the rare case of identical hyperlinks within the same string, the
* HREF tag can be used to distinguish between them. The string may
* include the mnemonic character and line delimiters.
* </p>
*
* @param string the new text
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the text is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public void setText( String string ) {
checkWidget();
if( string == null ) {
SWT.error( SWT.ERROR_NULL_ARGUMENT );
}
if( !string.equals( text ) ) {
displayText = parse( string );
text = string;
}
}
/**
* Returns the receiver's text, which will be an empty
* string if it has never been set.
*
* @return the receiver's text
*
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*/
public String getText() {
checkWidget();
return text;
}
///////////////////////////////////////
// Listener registration/deregistration
/**
* Adds the listener to the collection of listeners who will
* be notified when the control is selected, by sending
* it one of the messages defined in the <code>SelectionListener</code>
* interface.
* <p>
* <code>widgetSelected</code> is called when the control is selected.
* <code>widgetDefaultSelected</code> is not called.
* </p>
*
* @param listener the listener which should be notified
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see SelectionListener
* @see #removeSelectionListener
* @see SelectionEvent
*/
public void addSelectionListener( SelectionListener listener ) {
checkWidget();
SelectionEvent.addListener( this, listener );
}
/**
* Removes the listener from the collection of listeners who will
* be notified when the control is selected.
*
* @param listener the listener which should no longer be notified
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see SelectionListener
* @see #addSelectionListener
*/
public void removeSelectionListener( SelectionListener listener ) {
checkWidget();
SelectionEvent.removeListener( this, listener );
}
public Point computeSize( int wHint, int hHint, boolean changed ) {
checkWidget();
int width = 0;
int height = 0;
int border = getBorderWidth();
if( ( displayText.length() > 0 ) ) {
// Replace '&' with '&&' to ensure proper size calculation with one '&',
// because the other will be escaped in
// TextSizeUtil#createMeasureString()
String string = escapeAmpersand( displayText );
Point extent = Graphics.textExtent( getFont(), string, wHint );
width = extent.x;
height = extent.y;
}
if( wHint != SWT.DEFAULT ) {
width = wHint;
}
if( hHint != SWT.DEFAULT ) {
height = hHint;
}
width += border * 2 + PADDING * 2;
height += border * 2 + PADDING * 2;
return new Point( width, height );
}
private static String escapeAmpersand( String string ) {
StringBuffer result = new StringBuffer();
for( int i = 0; i < string.length(); i++ ) {
if( string.charAt( i ) == '&' ) {
result.append( "&&" );
} else {
result.append( string.charAt( i ) );
}
}
return result.toString();
}
public Object getAdapter( Class adapter ) {
Object result;
if( adapter == ILinkAdapter.class ) {
if( linkAdapter == null ) {
linkAdapter = new ILinkAdapter() {
public String getDisplayText() {
return displayText;
}
public Point[] getOffsets() {
return offsets;
}
public String[] getIds() {
return ids;
}
};
}
result = linkAdapter;
} else {
result = super.getAdapter( adapter );
}
return result;
}
boolean isTabGroup() {
return true;
}
String getNameText() {
return getText();
}
/* verbatim copy from SWT */
@SuppressWarnings("all")
String parse (String string) {
int length = string.length ();
offsets = new Point [length / 4];
ids = new String [length / 4];
mnemonics = new int [length / 4 + 1];
StringBuffer result = new StringBuffer ();
char [] buffer = new char [length];
string.getChars (0, string.length (), buffer, 0);
int index = 0, state = 0, linkIndex = 0;
int start = 0, tagStart = 0, linkStart = 0, endtagStart = 0, refStart = 0;
while (index < length) {
char c = Character.toLowerCase (buffer [index]);
switch (state) {
case 0:
if (c == '<') {
tagStart = index;
state++;
}
break;
case 1:
if (c == 'a') state++;
break;
case 2:
switch (c) {
case 'h':
state = 7;
break;
case '>':
linkStart = index + 1;
state++;
break;
default:
if (Character.isWhitespace(c)) break;
else state = 13;
}
break;
case 3:
if (c == '<') {
endtagStart = index;
state++;
}
break;
case 4:
state = c == '/' ? state + 1 : 3;
break;
case 5:
state = c == 'a' ? state + 1 : 3;
break;
case 6:
if (c == '>') {
mnemonics [linkIndex] = parseMnemonics (buffer, start, tagStart, result);
int offset = result.length ();
parseMnemonics (buffer, linkStart, endtagStart, result);
offsets [linkIndex] = new Point (offset, result.length () - 1);
if (ids [linkIndex] == null) {
ids [linkIndex] = new String (buffer, linkStart, endtagStart - linkStart);
}
linkIndex++;
start = tagStart = linkStart = endtagStart = refStart = index + 1;
state = 0;
} else {
state = 3;
}
break;
case 7:
state = c == 'r' ? state + 1 : 0;
break;
case 8:
state = c == 'e' ? state + 1 : 0;
break;
case 9:
state = c == 'f' ? state + 1 : 0;
break;
case 10:
state = c == '=' ? state + 1 : 0;
break;
case 11:
if (c == '"') {
state++;
refStart = index + 1;
} else {
state = 0;
}
break;
case 12:
if (c == '"') {
ids[linkIndex] = new String (buffer, refStart, index - refStart);
state = 2;
}
break;
case 13:
if (Character.isWhitespace (c)) {
state = 0;
} else if (c == '='){
state++;
}
break;
case 14:
state = c == '"' ? state + 1 : 0;
break;
case 15:
if (c == '"') state = 2;
break;
default:
state = 0;
break;
}
index++;
}
if (start < length) {
int tmp = parseMnemonics (buffer, start, tagStart, result);
int mnemonic = parseMnemonics (buffer, Math.max (tagStart, linkStart), length, result);
if (mnemonic == -1) mnemonic = tmp;
mnemonics [linkIndex] = mnemonic;
} else {
mnemonics [linkIndex] = -1;
}
if (offsets.length != linkIndex) {
Point [] newOffsets = new Point [linkIndex];
System.arraycopy (offsets, 0, newOffsets, 0, linkIndex);
offsets = newOffsets;
String [] newIDs = new String [linkIndex];
System.arraycopy (ids, 0, newIDs, 0, linkIndex);
ids = newIDs;
int [] newMnemonics = new int [linkIndex + 1];
System.arraycopy (mnemonics, 0, newMnemonics, 0, linkIndex + 1);
mnemonics = newMnemonics;
}
return result.toString ();
}
/* verbatim copy from SWT */
int parseMnemonics (char[] buffer, int start, int end, StringBuffer result) {
int mnemonic = -1, index = start;
while (index < end) {
if (buffer [index] == '&') {
if (index + 1 < end && buffer [index + 1] == '&') {
result.append (buffer [index]);
index++;
} else {
mnemonic = result.length();
}
} else {
result.append (buffer [index]);
}
index++;
}
return mnemonic;
}
}
|
C# | UTF-8 | 634 | 3.3125 | 3 | [] | no_license | using System;
namespace reversi
{
public class Cell
{
public int State;
public int Row;
public int Col;
public Cell(int row, int col)
{
this.State = 0;
this.Row = row;
this.Col = col;
}
public char GetMark()
{
return "o-x"[this.State + 1];
}
public void Put(int player)
{
this.State = player;
}
public void Flip()
{
this.State *= -1;
}
public bool CanPut()
{
return this.State == 0;
}
}
}
|
TypeScript | UTF-8 | 223 | 2.890625 | 3 | [] | no_license | /**
* Model Class to log messages on server
*/
export class Log {
message: any;
logLevel: any;
constructor(
message: any,
logLevel: any
) {
this.message = message;
this.logLevel = logLevel;
}
}
|
Python | UTF-8 | 861 | 3.21875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import urllib.request
URL = 'https://www.codewars.com/users/leaderboard'
def solution():
# do it
return Leaderboard()
class dotdict(dict):
__getattr__ = dict.get
class Leaderboard:
def __init__(self):
self.position = {}
for i, tr_tag in enumerate(
BeautifulSoup(urllib.request.urlopen(URL).read(), 'html.parser')("tr", limit=11)[1:]):
user = {'name': tr_tag['data-username']}
# print(tr_tag)
user['clan'], user['honor'] = [tag.text for tag in tr_tag('td')[2:]]
user['honor'] = int(user['honor'].replace(',', ''))
self.position[i + 1] = dotdict(user)
# print(user)
print(len(self.position), self.position[10])
if __name__ == '__main__':
leaderboard = Leaderboard()
|
Python | UTF-8 | 3,001 | 2.75 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
from . import market_data_crawler
from bot.shared_config import *
import time
import sys
import operator
import pprint
def calculate_arbitrage_opportunities(exchanges):
start_time = time.time()
market_data = market_data_crawler.update_market_data_for_symbol_and_exchange(exchanges)
sorted_market_data = {}
for exchange_name, order_books in market_data.items():
for order_book in order_books:
symbol = order_book['symbol']
new_dictionary = {symbol:
{exchange_name:
{"bids": order_book['bids'][:5],
"asks": order_book['asks'][:5],
"timestamp": order_book['timestamp']}}}
if symbol not in sorted_market_data.keys():
sorted_market_data.update(new_dictionary)
else:
sorted_market_data[symbol].update(new_dictionary[symbol])
dump(green(str(len(sorted_market_data))), "possible symbols found in total:", ' '.join(sorted_market_data.keys()))
market_opport = {}
for symbol, exchanges in sorted_market_data.items():
lowest_ask = None
highest_bid = None
market_opport.update({symbol: {}})
for exchange_name, order_book in exchanges.items():
if lowest_ask is None or lowest_ask['value'] < order_book['asks'][0]:
lowest_ask = {"exchange_name":exchange_name,
"value":order_book['asks'][0],
"order_book": order_book['asks'][:3]}
if highest_bid is None or highest_bid['value'] > order_book['bids'][0]:
highest_bid = {"exchange_name": exchange_name,
"value": order_book['bids'][0],
"order_book": order_book['bids'][:3]}
spread = float(highest_bid['value'][0]) - float(lowest_ask['value'][0])
market_opport[symbol].update({"highest_bid": highest_bid,
"lowest_ask": lowest_ask,
"spread": spread,
"spread_perc": round((spread / float(highest_bid['value'][0])) * 100, 2),
"symbol": symbol})
if spread > 0:
with open("market_opportunity_found.txt", "a") as file:
file.write("\n+n--- Arbitrage oppportunity found! ---\n\n")
pprint.pprint(market_opport[symbol], stream=file)
sorted_list = sorted(market_opport.values(), key=operator.itemgetter("spread_perc"), reverse=True)
with open("market_analyzation.txt", "w") as file:
pprint.pprint(sorted_list, stream=file)
print("--- Arbitrage oportunities calculated in {0:.3f}ms ---".format((time.time() - start_time)*100))
return market_opport
if __name__ == '__main__':
calculate_arbitrage_opportunities(sys.argv[1:])
|
Markdown | UTF-8 | 36,004 | 2.828125 | 3 | [] | no_license | # deep_learning_final_assignment
# 2048实验报告
18373105 童涛 18373676 黎昊轩 https://github.com/LeavesLi1015/deep_learning_final_assignment
18373528 杨凌华 https://github.com/LarryHawkingYoung/deep_learning_final_assignment
18373542 胥浩宇 https://github.com/cpxhylty/deep_learning_final_assignment
## 绪论
在进行调研之后,我们从两个方向分别展开了实验
方向一是对baseline中的DQN方法进行改进,目前能够达到的最高平均分数是**3045.63**
方向二是实现了文献[1]中的N-Tuple Network方法,目前能够达到的最高平均分数是**4482.86**
**平均分数的计算方式**
采用与baseline相同的方式进行分数计算,两个x tile合并时只加x分
平均分数avg_score首先设置为结束的第一局游戏的分数,然后每局游戏结束时按照avg_score = avg_score * 0.99 + game.score * 0.01的公式进行更新
[TOC]
## 方法一:DQN
给出的baseline使用的是Double-DQN方法,我们在baseline的基础上实现了多个tricks,探究不同改动对性能的影响。
参数方面,该模型几个较为重要的参数为:记忆内存大小、学习率、Soft Target Update更新系数(0.99).
首先要说明的是,由于GPU计算时长有限,并且使用CPU训练时间过长(一次5小时),我们并不能将所有的组合都进行尝试,也不能无限制的增加模型的复杂度和训练的时长。
### 1 实现的tricks
#### 1.1 网络改进
在baseline中,神经网络的输出只有三个元素。这就意味着,神经网络只会给出三种可能的步骤。
~~~python
self.fc2 = M.Linear(16, 3)
~~~
我们将网络的输出改为4。即,
~~~python
self.fc2 = M.Linear(16, 4)
~~~
从结果来看,改进之后的分数并没有太多的改变。很可能是因为神经网络给出的三个种可能已经够用了(在后面的action选择中也可以看到),基本上最优选择都可以执行。
在最优选择无法执行的情况下,才会选择其他两种action。而另外两种action基本不会出现无法执行的情况。所以,单纯的增加一个选择似乎对于模型的选择没有太大的影响。
所以只输出三种可能可以降低模型的复杂度和训练时的难度。
#### 1.2 为网络增加一个全连接层
Baseline的网络中,只有两个全连接层。
~~~python
self.conv3 = M.Conv2d(256, 256, kernel_size=(1, 2), stride=1, padding=0)
self.relu3 = M.ReLU()
self.fc1 = M.Linear(1024, 16)
self.relu5 = M.ReLU()
self.fc2 = M.Linear(16, 3)
~~~
我们为网络添加了一个全连接层
~~~python
self.conv3 = M.Conv2d(256, 256, kernel_size=(1, 2), stride=1, padding=0)
self.relu3 = M.ReLU()
self.fc1 = M.Linear(1024, 128)
self.relu5 = M.ReLU()
self.fc2 = M.Linear(128, 16)
self.relu6 = M.ReLU()
self.fc3 = M.Linear(16, 4) # changed to 4 outputs
~~~
#### 1.3 Priority Steps
在baseline中,关于下一个`action`的选择规则是:选取最大可能分数最高的点,如果这个`action`无法执行(即游戏里卡住),则执行`action+1`步骤。
~~~python
‘’’Choose the action with the highest probability’’’
a = F.argmax(model(status).detach(), 1)
a = a.numpy()
action = a[k]
while (game[k].grid == pre_grid).all():
action = (action + 1) % 4
game[k].move(action)
~~~
根据如下情况,我们给出了一定的改进方法:
在最优选择无法执行时,选择次优的`action`,如果次优移动无法执行,则选择第三优,以此类推。
我们根据该网络的特征(每次同时执行32盘游戏),写出了对步骤的排序函数:
~~~python
def sortSteps(games_steps): # steps->(32,4), 32 games, each game with 4 possiable steps
sortSteps = [[],[],[],[]]
# 4 lists means 4 steps, each list with 32 games.
# The first list is the best. The last is the worst.
for game_steps in games_steps: # 32 games
temp = np.array(game_steps)
for i in range(4):
temp_ = temp[:]
# print(temp_)
s = np.argmax(temp_)
# print(s)
sortSteps[i].append(s)
temp_[s] = np.min(temp) - 1
temp = temp_[:]
return sortSteps[0], sortSteps[1], sortSteps[2], sortSteps[3] # best, second, third, worst
~~~
在选择下一步时,将单纯的`action+1`改成了按照优先级进行选择。
~~~python
while (game[k].grid == pre_grid).all():
action = actions[count][k]
game[k].move(action)
count = (count + 1) % 4
~~~
#### 1.4 Dropout Layer
在原baseline的网络中,并没有采用Dropout层对神经元进行丢弃。
~~~python
self.conv3 = M.Conv2d(256, 256, kernel_size=(1, 2), stride=1, padding=0)
self.relu3 = M.ReLU()
self.fc1 = M.Linear(1024, 16)
self.relu5 = M.ReLU()
self.fc2 = M.Linear(16, 3)
~~~
我们尝试了在倒数第二层全联接层后加入Dropout层。加入全联接层可以在一定程度上防止神经元之间的相互依赖,可以防止模型过拟合。
~~~python
self.conv3 = M.Conv2d(256, 256, kernel_size=(1, 2), stride=1, padding=0)
self.relu3 = M.ReLU()
self.fc1 = M.Linear(1024, 16)
self.drop1 = M.Dropout(0.3)
self.relu5 = M.ReLU()
self.fc2 = M.Linear(16, 3)
~~~
但是加入了Dropout层之后效果不加,loss函数一直无法收敛到一个较小的值。推测原因:加入Dropout层后,模型欠拟合。
所以决定放弃使用Dropout层。
#### 1.5 Randomly Fill Buffer
在原模型中,填充记忆模块用的是顺序填充,即当模块被填满时,最先填充的模块会被最先覆盖。
~~~python
def append(self, obj):
if self.size() > self.buffer_size:
print('buffer size larger than set value, trimming...')
self.buffer = self.buffer[(self.size() - self.buffer_size):]
elif self.size() == self.buffer_size:
self.buffer[self.index] = obj
self.index += 1
self.index %= self.buffer_size
else:
self.buffer.append(obj)
~~~
随机模块填充,并不是将先填充的模块先覆盖,而是随机的将位置填充。
~~~python
def append(self, obj):
if self.size() > self.buffer_size:
print('buffer size larger than set value, trimming...')
self.buffer = self.buffer[(self.size() - self.buffer_size):]
elif self.size() == self.buffer_size:
self.buffer[self.index] = obj
self.index = np.random.randint(0,self.buffer_size)
# self.index += 1
# self.index %= self.buffer_size
else:
self.buffer.append(obj)
~~~
这样填充模块能够使得模块中保留一些“历史久远”的信息,可以防止所有的信息都来源于近期,避免模型陷入局部最优。
#### 1.6 Epsilon Decay($\epsilon$ Decay)
Epsilon Decay是一种常用在DQN中的贪心策略。这个贪心策略作用于action的选择上,算法步骤如下:
>1)投一枚硬币,该硬币正面朝上的概率为$\epsilon$
>2)当这个硬币正面朝上时,选择纯随机策略
>3)当这个硬币反面朝上时,采用最优action策略
在baseline中,epsilon可以看作取0。因为此时所有的选择都在采用最优策略,这会使得模型训练时容易跌入局部最优。
加入Epsilon后,在一定程度上,用随机的action取代了最优的action,能够避免陷入局部最优。
而为了模型的稳定性,epsilon应该随着迭代次数的增加而减小。这样有助于模型趋于稳定,并且让所得到的模型趋向于最优解。这里我们采用了线性递减的方式。
~~~python
init_epsilon = 0.10
epsilon = init_epsilon * (1 - epoch/epochs)
'''''
when memory is enough, randomly action. when memory is full, at epsilon percentage take best action.
'''
if data.size() == max_size and np.random.random() > epsilon: # greedy action
while (game[k].grid == pre_grid).all():
action = actions[count][k]
game[k].move(action)
count = (count + 1) % 4
else:
action = np.random.randint(0,4)
~~~
#### 1.7 AdamW优化器
baseline使用的优化器是Adam。在此基础上,我们选择了AdamW进行改进。AdamW相比于Adam增加了一个L2的惩罚值。他能够有效地防止梯度爆炸的出现,但是带来的坏处就是,相比使用Adam,模型的成长速度减缓了不少。
~~~python
opt = AdamW(model.parameters(), lr = 1e-4)
~~~
### 2 可调整参数
这里列举了几个比较重要的参数,还有许多参数没有举例。
#### 2.1 记忆规模,默认5000
~~~python
data = rpm(5000)
~~~
#### 2.2 学习率,默认0.0001;学习器(Adam)
~~~python
opt = Adam(model.parameters(), lr = 1e-4)
~~~
#### 2.3 Soft Target Update(0.99)
~~~python
loss += F.loss.square_loss(Q, pred_s1[i].detach() * 0.99 * (1 - d[i]) + reward[i])
~~~
#### 2.4 同时可开展的游戏次数(32)
~~~
for game in games: # 32 games
~~~
### 3 总结
总的来说,Baseline所实现的Double-DQN较为简单,使用的技巧并不多。
在方法一中,我们主要添加了一些在DQN训练时较为常见的几个tricks。添加的tricks所达到的效果已经记录在了训练日志当中。部分trick在添加后反而起到了副作用,原因很可能是模型本身的特点所决定的。比如这个模型比较容易陷入局部最优;不适合添加Dropout层...
但总的来说,目前所有选择实现的tricks能够帮助模型训练出更好的结果。在算力资源有限的情况下,虽然avg_score提升并不明显(最高也只有3000出头),但是可以明显的发现,模型是有提升空间的。这一点体现在Q值上:如果Q值在训练过程中无法持续增加,意味着模型选择一次移动,所获得的分数很少。而我们的模型在有限的迭代次数中,Q值不断上升,成绩也稳步提升。这也进一步证明了我们添加的tricks能够更好的完成任务。
### 4 训练日志
#### 4.1 所有Tricks开启
这应该是最有潜力的一组,因为得分稳步增长,并且Q值一直处于增长阶段。证明如果加大迭代次数,这个模型还有很大的提升空间。
~~~
epoch: 0%| | 5/100000 [00:00<1:08:47, 24.23it/s, loss=0.00028, Q=0.03781, reward=0.56250, avg_score=0.00000]
epoch: 5%|▌ | 5004/100000 [03:23<1:05:58, 24.00it/s, loss=0.08359, Q=4.32059, reward=3.25000, avg_score=529.71293]
epoch: 10%|█ | 10004/100000 [06:49<1:02:30, 24.00it/s, loss=0.17213, Q=9.23870, reward=5.43750, avg_score=728.29572]
epoch: 15%|█▌ | 15005/100000 [10:16<57:54, 24.46it/s, loss=0.12767, Q=16.17513, reward=3.43750, avg_score=990.61025]
epoch: 20%|██ | 20004/100000 [13:41<56:34, 23.57it/s, loss=0.32310, Q=21.93606, reward=3.12500, avg_score=1188.41061]
epoch: 25%|██▌ | 25004/100000 [17:06<51:19, 24.35it/s, loss=0.48368, Q=25.01408, reward=4.68750, avg_score=1251.10009]
epoch: 30%|███ | 30005/100000 [20:32<47:59, 24.31it/s, loss=1.41843, Q=25.20588, reward=4.06250, avg_score=1518.52155]
epoch: 35%|███▌ | 35004/100000 [23:57<45:42, 23.70it/s, loss=1.07101, Q=31.44183, reward=2.00000, avg_score=1545.66837]
epoch: 40%|████ | 40004/100000 [27:24<40:35, 24.64it/s, loss=0.39668, Q=28.92669, reward=3.43750, avg_score=1667.49770]
epoch: 45%|████▌ | 45005/100000 [30:49<37:17, 24.57it/s, loss=2.69036, Q=33.33669, reward=2.87500, avg_score=1910.70973]
epoch: 50%|█████ | 50004/100000 [34:14<34:57, 23.84it/s, loss=1.25572, Q=36.33077, reward=3.25000, avg_score=1891.38512]
epoch: 55%|█████▌ | 55004/100000 [37:40<31:00, 24.18it/s, loss=0.81370, Q=36.35245, reward=5.00000, avg_score=1848.78859]
epoch: 60%|██████ | 60005/100000 [41:05<27:04, 24.62it/s, loss=3.28809, Q=37.84313, reward=7.12500, avg_score=1918.86686]
epoch: 65%|██████▌ | 65004/100000 [44:31<24:40, 23.64it/s, loss=1.95699, Q=39.52359, reward=7.56250, avg_score=2253.00424]
epoch: 70%|███████ | 70004/100000 [47:58<20:26, 24.45it/s, loss=0.92885, Q=37.58751, reward=4.62500, avg_score=2278.98536]
epoch: 75%|███████▌ | 75005/100000 [51:25<17:15, 24.13it/s, loss=1.57380, Q=41.51716, reward=6.12500, avg_score=2280.92122]
epoch: 80%|████████ | 80004/100000 [54:50<14:02, 23.74it/s, loss=1.11217, Q=46.57273, reward=7.81250, avg_score=2260.62683]
epoch: 85%|████████▌ | 85004/100000 [58:16<10:13, 24.45it/s, loss=1.25295, Q=41.03788, reward=6.93750, avg_score=2278.10763]
epoch: 90%|█████████ | 90005/100000 [1:01:43<06:50, 24.33it/s, loss=0.56762, Q=47.11993, reward=6.50000, avg_score=2461.73157]
epoch: 95%|█████████▌| 95004/100000 [1:05:10<03:32, 23.53it/s, loss=0.77186, Q=47.28543, reward=3.93750, avg_score=2581.67211]
epoch: 100%|██████████| 100000/100000 [1:08:36<00:00, 24.29it/s, loss=3.40540, Q=56.12973, reward=6.18750, avg_score=2453.03791]
maxscore:7760
avg_score:2453.0379128732407
+------+------+------+------+
| 2 | 4 | 1024 | 512 |
+------+------+------+------+
| 16 | 64 | 256 | 32 |
+------+------+------+------+
| 4 | 16 | 4 | 16 |
+------+------+------+------+
| 2 | 32 | 2 | 4 |
+------+------+------+------+
~~~
<img src="./image/3-1.png" alt="3-1" style="zoom:33%;" />
#### 4.2(从baseline开始)网络输出改为4
~~~
epoch: 100%|██████████| 50000/50000 [37:46<00:00, 22.06it/s, loss=0.05948, Q=5.44860, reward=12.56250, avg_score=2651.80934]
maxscore:7896
avg_score:2651.8093411440545
~~~
#### 4.3 无效移动`action+1`—>次优移动
- reward震荡严重,范围2~10
- loss震荡,0.01~0.09
- avg_score增大到2000左右开始震荡,下降到1600,开始慢慢上升到1900左右
后来发现是有一个地方没有改好,导致效果不增反降。
~~~
epoch: 100%|██████████| 50000/50000 [38:42<00:00, 21.53it/s, loss=0.05070, Q=4.89405, reward=3.81250, avg_score=1893.23744]
maxscore:6434
avg_score:1893.2374433444083
~~~
#### 4.4 在上一步的基础上,调整SoftTargetUpdate参数为0.999
~~~
epoch: 0%| | 4/50000 [00:00<44:43, 18.63it/s, loss=0.10281, Q=4.65261, reward=4.87500, avg_score=0.00000]
epoch: 10%|█ | 5004/50000 [03:53<37:53, 19.79it/s, loss=0.08687, Q=8.16222, reward=5.00000, avg_score=1388.10020]
epoch: 20%|██ | 10005/50000 [07:46<32:10, 20.72it/s, loss=0.32168, Q=12.84697, reward=5.25000, avg_score=2097.89126]
epoch: 30%|███ | 15004/50000 [11:39<29:24, 19.84it/s, loss=0.46031, Q=18.53462, reward=8.93750, avg_score=2197.32582]
epoch: 40%|████ | 20004/50000 [15:32<25:03, 19.95it/s, loss=0.20618, Q=20.43308, reward=6.37500, avg_score=2372.96677]
epoch: 50%|█████ | 25004/50000 [19:25<21:01, 19.81it/s, loss=0.27678, Q=22.43907, reward=4.81250, avg_score=2648.55656]
epoch: 60%|██████ | 30004/50000 [23:19<16:17, 20.45it/s, loss=0.61412, Q=26.37881, reward=9.93750, avg_score=2901.75986]
epoch: 70%|███████ | 35005/50000 [27:11<11:47, 21.20it/s, loss=0.33737, Q=29.13754, reward=6.56250, avg_score=2661.33176]
epoch: 80%|████████ | 40004/50000 [31:04<08:09, 20.41it/s, loss=0.38669, Q=30.04513, reward=3.43750, avg_score=2736.06205]
epoch: 90%|█████████ | 45004/50000 [34:57<04:06, 20.24it/s, loss=0.35807, Q=31.68990, reward=4.00000, avg_score=2924.52263]
epoch: 100%|██████████| 50000/50000 [38:49<00:00, 21.46it/s, loss=1.38336, Q=31.83402, reward=10.37500, avg_score=3045.63207]
maxscore:8142
avg_score:3045.6320680842
~~~
<img src="./image/3-4.png" alt="3-4" style="zoom:33%;" />
#### 4.5 采用Epsilon Decay
~~~
epoch: 0%| | 5/50000 [00:00<39:19, 21.19it/s, loss=0.00226, Q=1.24186, reward=3.37500, avg_score=0.00000]
epoch: 10%|█ | 5005/50000 [03:46<34:25, 21.79it/s, loss=0.03849, Q=4.79506, reward=5.87500, avg_score=982.02194]
epoch: 20%|██ | 10004/50000 [07:32<31:22, 21.25it/s, loss=0.10363, Q=9.03690, reward=6.25000, avg_score=1396.17066]
epoch: 30%|███ | 15004/50000 [11:19<28:19, 20.59it/s, loss=0.30082, Q=10.05284, reward=5.25000, avg_score=1500.18189]
epoch: 40%|████ | 20004/50000 [15:04<23:33, 21.22it/s, loss=0.09822, Q=10.43662, reward=1.43750, avg_score=1605.74873]
epoch: 50%|█████ | 25005/50000 [18:50<19:17, 21.60it/s, loss=0.05739, Q=12.12671, reward=5.06250, avg_score=1596.09813]
epoch: 60%|██████ | 30005/50000 [22:36<15:45, 21.14it/s, loss=0.10602, Q=11.82512, reward=3.75000, avg_score=1724.11383]
epoch: 70%|███████ | 35004/50000 [26:21<11:41, 21.36it/s, loss=0.32748, Q=12.68642, reward=7.06250, avg_score=1746.96458]
epoch: 80%|████████ | 40004/50000 [30:11<07:48, 21.34it/s, loss=0.17132, Q=13.03945, reward=4.12500, avg_score=1761.15174]
epoch: 90%|█████████ | 45004/50000 [33:58<03:48, 21.88it/s, loss=0.16110, Q=10.59168, reward=6.06250, avg_score=1867.21660]
epoch: 100%|██████████| 50000/50000 [37:43<00:00, 22.09it/s, loss=0.09503, Q=12.31988, reward=6.50000, avg_score=1919.71672]
maxscore:5644
avg_score:1919.7167232776671
~~~
<img src="./image/3-5.png" alt="3-5" style="zoom:33%;" />
#### 4.6 Epsilon Decay参数调整(buff-size:5000->2000,init_epsilon:0.15-0.1)
~~~
epoch: 0%| | 4/50000 [00:00<47:16, 17.63it/s, loss=0.00057, Q=0.08594, reward=0.25000, avg_score=0.00000]
epoch: 10%|█ | 5005/50000 [03:47<35:18, 21.23it/s, loss=0.00279, Q=1.18189, reward=2.68750, avg_score=410.57400]
epoch: 15%|█▍ | 7270/50000 [05:31<32:26, 21.95it/s, loss=0.00828, Q=1.08324, reward=2.37500, avg_score=384.83023]
~~~
效果不好,提前终止。
#### 4.7 Epsilon Decay参数调整(buffer_size:2000->8000,epochs:10000->15000)
~~~
epoch: 0%| | 5/75000 [00:00<57:26, 21.76it/s, loss=0.00035, Q=0.03386, reward=0.25000, avg_score=0.00000]
epoch: 7%|▋ | 5004/75000 [03:52<59:08, 19.73it/s, loss=0.02977, Q=4.74931, reward=4.75000, avg_score=884.16725]
epoch: 13%|█▎ | 10004/75000 [07:49<53:27, 20.26it/s, loss=0.03363, Q=8.03254, reward=6.50000, avg_score=1371.69223]
epoch: 20%|██ | 15005/75000 [11:44<47:45, 20.94it/s, loss=0.04327, Q=9.44598, reward=2.31250, avg_score=1738.48894]
epoch: 27%|██▋ | 20004/75000 [15:40<46:48, 19.58it/s, loss=0.06418, Q=10.42684, reward=4.00000, avg_score=1960.57912]
epoch: 33%|███▎ | 25004/75000 [19:38<40:16, 20.69it/s, loss=0.05436, Q=11.12187, reward=4.37500, avg_score=2170.28065]
epoch: 40%|████ | 30004/75000 [23:35<37:35, 19.95it/s, loss=0.41796, Q=10.51460, reward=6.18750, avg_score=2067.08620]
epoch: 47%|████▋ | 35004/75000 [27:33<33:28, 19.91it/s, loss=0.11905, Q=11.30016, reward=4.00000, avg_score=1852.44310]
epoch: 53%|█████▎ | 40005/75000 [31:31<28:56, 20.15it/s, loss=0.12435, Q=11.13156, reward=3.43750, avg_score=2020.26731]
epoch: 57%|█████▋ | 42610/75000 [33:35<25:31, 21.15it/s, loss=0.24599, Q=9.34995, reward=6.93750, avg_score=2037.64702]
~~~
发生震荡,提前终止。
#### 4.8 Dropout(全连接层最后加入Dropout层,概率0.2)
~~~
epoch: 0%| | 4/50000 [00:00<51:29, 16.18it/s, loss=0.00101, Q=0.02423, reward=0.12500, avg_score=0.00000]
epoch: 10%|█ | 5004/50000 [04:14<39:04, 19.20it/s, loss=0.19428, Q=1.38549, reward=4.81250, avg_score=847.36938]
epoch: 20%|██ | 10004/50000 [08:33<35:59, 18.52it/s, loss=0.07778, Q=1.36181, reward=3.43750, avg_score=1125.10873]
epoch: 30%|███ | 15004/50000 [12:51<31:18, 18.63it/s, loss=0.05483, Q=1.52981, reward=4.31250, avg_score=1263.07748]
epoch: 40%|████ | 20004/50000 [17:13<27:59, 17.86it/s, loss=0.10145, Q=1.69371, reward=8.68750, avg_score=1242.19591]
epoch: 50%|█████ | 25004/50000 [21:37<22:45, 18.30it/s, loss=0.08980, Q=1.58534, reward=6.93750, avg_score=1267.76650]
epoch: 60%|██████ | 30004/50000 [26:02<18:14, 18.27it/s, loss=0.01866, Q=1.82084, reward=4.43750, avg_score=1424.65073]
epoch: 70%|███████ | 35004/50000 [30:26<13:29, 18.52it/s, loss=0.01345, Q=1.95794, reward=3.06250, avg_score=1461.52375]
epoch: 80%|████████ | 40004/50000 [34:47<09:10, 18.17it/s, loss=0.00803, Q=2.11296, reward=3.43750, avg_score=1468.78108]
epoch: 90%|█████████ | 45003/50000 [39:08<04:37, 18.00it/s, loss=0.02391, Q=2.50486, reward=6.62500, avg_score=1521.40200]
epoch: 90%|█████████ | 45007/50000 [39:08<04:37, 18.00it/s, loss=0.02452, Q=2.31132, reward=2.62500, avg_score=1521.40200]
epoch: 100%|██████████| 50000/50000 [43:27<00:00, 19.18it/s, loss=0.03553, Q=2.53317, reward=3.31250, avg_score=1521.32538]
maxscore:4076
avg_score:1521.3253815767862
~~~
<img src="./image/3-8.png" alt="3-8" style="zoom:33%;" />
#### 4.9 Memory buff-size->5000 学习率0.001
~~~
epoch: 0%| | 5/50000 [00:00<40:57, 20.34it/s, loss=0.00143, Q=0.00167, reward=0.50000, avg_score=0.00000]
epoch: 10%|█ | 5004/50000 [03:57<35:58, 20.84it/s, loss=0.03674, Q=0.30084, reward=6.43750, avg_score=743.03215]
loss 0.03385 Q 0.38043 reward 5.68750 avg_score 743.03215
loss 0.00131 Q 0.27179 reward 1.62500 avg_score 743.03215
loss 0.00658 Q 0.26482 reward 3.93750 avg_score 743.03215
loss 0.00288 Q 0.26978 reward 3.37500 avg_score 743.03215
loss 0.03674 Q 0.30084 reward 6.43750 avg_score 743.03215
epoch: 20%|██ | 10004/50000 [07:44<32:45, 20.34it/s, loss=0.00180, Q=0.32779, reward=4.25000, avg_score=889.44966]
epoch: 30%|███ | 15005/50000 [11:37<27:48, 20.97it/s, loss=0.00194, Q=0.32432, reward=3.06250, avg_score=847.49260]
epoch: 34%|███▍ | 17238/50000 [13:22<25:24, 21.49it/s, loss=0.00214, Q=0.32978, reward=1.87500, avg_score=852.40793]
~~~
~~~
epoch: 0%| | 5/50000 [00:00<43:39, 19.08it/s, loss=0.00568, Q=-0.00817, reward=4.00000, avg_score=0.00000]
epoch: 10%|█ | 5004/50000 [03:57<38:02, 19.71it/s, loss=15.61639, Q=17.59051, reward=3.43750, avg_score=573.86230]
epoch: 20%|██ | 10004/50000 [07:55<33:55, 19.65it/s, loss=16.37549, Q=21.63450, reward=3.75000, avg_score=596.82945]
epoch: 30%|███ | 15004/50000 [11:54<28:56, 20.15it/s, loss=1.99956, Q=9.41308, reward=3.06250, avg_score=778.82203]
epoch: 40%|████ | 20005/50000 [15:51<24:26, 20.46it/s, loss=1.07725, Q=4.58631, reward=2.56250, avg_score=1058.85101]
epoch: 50%|█████ | 25004/50000 [19:46<20:38, 20.18it/s, loss=0.26071, Q=2.99617, reward=3.43750, avg_score=1088.28699]
epoch: 60%|██████ | 30005/50000 [23:40<16:06, 20.68it/s, loss=0.03816, Q=1.78495, reward=2.00000, avg_score=1046.60566]
epoch: 70%|███████ | 35004/50000 [27:35<12:17, 20.34it/s, loss=0.16492, Q=1.88245, reward=2.81250, avg_score=1107.96531]
epoch: 80%|████████ | 40005/50000 [31:28<08:13, 20.27it/s, loss=0.10913, Q=2.43369, reward=3.25000, avg_score=1114.48686]
epoch: 90%|█████████ | 45005/50000 [35:25<04:08, 20.08it/s, loss=0.11077, Q=2.36197, reward=4.12500, avg_score=1168.30842]
epoch: 100%|██████████| 50000/50000 [39:17<00:00, 21.21it/s, loss=0.09077, Q=2.54650, reward=2.37500, avg_score=1179.09103]
maxscore:3808
avg_score:1179.0910284435654
~~~
#### 4.10 双Dropout,多一层全连接
~~~
epoch: 0%| | 4/100000 [00:00<1:54:03, 14.61it/s, loss=0.00279, Q=0.07822, reward=0.43750, avg_score=0.00000]
epoch: 10%|█ | 10004/100000 [07:38<1:17:00, 19.48it/s, loss=91.05108, Q=36.70674, reward=2.43750, avg_score=1014.30940]
epoch: 15%|█▌ | 15004/100000 [11:47<1:08:40, 20.63it/s, loss=118.83199, Q=49.29102, reward=7.87500, avg_score=1107.39320]
epoch: 20%|██ | 20005/100000 [15:43<1:04:11, 20.77it/s, loss=107.27513, Q=52.40406, reward=4.56250, avg_score=1085.97321]
epoch: 20%|██ | 20067/100000 [15:46<1:02:49, 21.21it/s, loss=125.23623, Q=59.71001, reward=2.81250, avg_score=1095.15348]
~~~
loss太高,正则化过度。
<img src="./image/3-10.png" alt="3-10" style="zoom:33%;" />
#### 4.11 取消Dropout层
~~~
epoch: 0%| | 4/100000 [00:00<1:31:59, 18.12it/s, loss=0.00008, Q=0.02717, reward=0.43750, avg_score=0.00000]
epoch: 5%|▌ | 5004/100000 [03:48<1:17:17, 20.48it/s, loss=0.07178, Q=3.61712, reward=4.50000, avg_score=936.56982]
epoch: 10%|█ | 10005/100000 [07:40<1:12:50, 20.59it/s, loss=0.04467, Q=8.96950, reward=4.18750, avg_score=1447.23755]
epoch: 15%|█▌ | 15004/100000 [11:29<1:06:52, 21.18it/s, loss=0.22352, Q=11.00501, reward=8.62500, avg_score=1682.09863]
epoch: 20%|██ | 20004/100000 [15:08<1:03:30, 20.99it/s, loss=0.19563, Q=13.07572, reward=7.81250, avg_score=1742.00251]
epoch: 25%|██▌ | 25005/100000 [18:56<1:00:02, 20.82it/s, loss=0.20120, Q=13.88394, reward=13.18750, avg_score=1699.06435]
epoch: 25%|██▌ | 25496/100000 [19:19<56:29, 21.98it/s, loss=0.48355, Q=11.37489, reward=1.81250, avg_score=1663.97994]
~~~
提前终止。
#### 4.12 无效移动更正
~~~
epoch: 0%| | 4/50000 [00:00<1:21:46, 10.19it/s, loss=0.00006, Q=-0.00286, reward=0.31250, avg_score=0.00000]
epoch: 10%|█ | 5005/50000 [04:03<38:08, 19.66it/s, loss=0.02044, Q=5.44548, reward=4.18750, avg_score=565.59711]
epoch: 20%|██ | 10004/50000 [08:07<34:04, 19.56it/s, loss=1.85931, Q=14.43054, reward=5.00000, avg_score=1010.96392]
epoch: 30%|███ | 15005/50000 [12:11<29:07, 20.03it/s, loss=1.90816, Q=24.35327, reward=4.25000, avg_score=1279.26304]
epoch: 40%|████ | 20004/50000 [16:13<24:50, 20.12it/s, loss=7.25223, Q=32.56019, reward=3.87500, avg_score=1507.22472]
epoch: 50%|█████ | 25005/50000 [20:15<20:32, 20.29it/s, loss=1.50292, Q=37.33854, reward=7.68750, avg_score=1751.96377]
epoch: 60%|██████ | 30005/50000 [24:19<16:52, 19.74it/s, loss=3.57725, Q=47.99241, reward=4.43750, avg_score=1901.75718]
epoch: 70%|███████ | 35005/50000 [28:22<12:27, 20.06it/s, loss=2.01264, Q=55.13494, reward=2.75000, avg_score=1911.88897]
epoch: 80%|████████ | 40004/50000 [32:26<08:39, 19.23it/s, loss=5.17427, Q=64.48306, reward=7.93750, avg_score=2264.89807]
epoch: 90%|█████████ | 45005/50000 [36:29<04:12, 19.81it/s, loss=1.54954, Q=64.72044, reward=3.68750, avg_score=2515.44872]
epoch: 100%|██████████| 50000/50000 [40:33<00:00, 20.55it/s, loss=1.27439, Q=77.06068, reward=3.93750, avg_score=2650.08703]
maxscore:8148
avg_score:2650.087027050852
+------+------+------+------+
| 2 | 1024 | 512 | 2 |
+------+------+------+------+
| 32 | 128 | 64 | 256 |
+------+------+------+------+
| 4 | 2 | 16 | 64 |
+------+------+------+------+
| 2 | 8 | 2 | 4 |
+------+------+------+------+
~~~
<img src="./image/3-12.png" alt="3-12" style="zoom:33%;" />
#### 4.13 将lr修改为0.002
```
epoch: 100%|██████████| 50000/50000 [34:46<00:00, 23.97it/s, loss=0.00120, Q=3.35089, reward=3.18750, avg_score=1322.43493]
maxscore:4088
avg_score:1322.4349255205716
```
#### 4.14 将lr改为0.0005
效果不佳,提前终止。
```
epoch: 40%|████ | 20004/50000 [14:02<20:56, 23.87it/s, loss=0.00825, Q=1.76280, reward=1.93750, avg_score=433.00770]
loss 0.03105 Q 1.84764 reward 2.62500 avg_score 433.00770
loss 0.00339 Q 1.51040 reward 2.43750 avg_score 433.00770
loss 0.00949 Q 1.68409 reward 2.43750 avg_score 433.00770
loss 0.00670 Q 1.79042 reward 1.25000 avg_score 433.00770
loss 0.00825 Q 1.76280 reward 1.93750 avg_score 433.00770
```
#### 4.15 lr=0.001
```
epoch: 100%|██████████| 50000/50000 [34:49<00:00, 23.93it/s, loss=0.22029, Q=10.75897, reward=2.56250, avg_score=1358.40334]
maxscore:4562
avg_score:1358.4033414286516
```
## 方法二:N-Tuple Temporal Difference Learning
### 1 原理阐述
#### 1.1 Markov Decision Processes
马尔科夫决策过程
引入如下符号:
> $S:$ 游戏的局面状态集
>
> $A(s) \subseteq \{N, E, S, W\},s \in S:$ 游戏局面状态 s 的下一步可行操作集,本游戏中为上、下、左、右四个方向的滑动
>
> $R(s, a),s \in S, a \in A(s):$ 状态 s 经过操作 a 后,这一步得到的分数
>
> $N(s, a),s \in S, a \in A(s):$ 状态 s 经过操作 a 后的下一个状态 (经过随机填充1个数后的局面状态)
>
> $V(s),s \in S:$ 由状态 s 开始一直到游戏结束,得到的总分数回报的期望
其中对于任何一个状态 s ,其总分回报期望 V(s) 都可以通过搜索树来进行准确计算,但这样的算法复杂度过高,对存储空间需求过大,不切合实际。因此采用函数近似(Function Approximation)的思想,构造神经网络模型来预测 V(s),并对参数进行学习优化,以实现较准确预测每个状态 s 的期望回报 V(s) 值。通过比较每个 $a \in A(s)$ 操作得到的总回报期望 $R(s, a) + V(N(s, a))$ ,取总回报期望最大的 a 作为当前状态的下一步操作,即:
$$
\arg\max\limits_{a \in A(s)}(R(s, a) + V(N(s, a)))
$$
#### 1.2 N-Tuple Network
采用 N-Tuple 神经网络来构造期望回报 V(s) 的函数近似,形式化表示为:
$$
V_\theta : S \rightarrow R
$$
其计算方式如下:
首先定义 m 个 n-tuples,图1中以m=2,n=3为例。游戏四宫格如图1所示标号为0~15,则每个n-tuple可以用一个n元序列来表示,例如图1(a)中,两个3-tuples可以表示为(0, 1, 2)和(0, 1, 4). 我们认为每一个格子的取值在2<sup>0</sup>到2<sup>15</sup>之间,即每个格子有16种可能的取值。为每一个n-tuple覆盖区域的每一种可能取值分配一个weight值,则一个n-tuple的weight包含16<sup>n</sup>个值。
如图1(b), 每一种盘面 s 经过旋转和翻转变换后共有8种等价的形式,计算 V(s) 的方法是对每一个 n-tuple 在每一种 s 的等价情况下的权重之和,如图1(c). 每个tuple的weight值将采用下一小节所述方式进行训练。
<img src="./image/图1.png" style="zoom:50%;" />
<center>图1 n-tuple的定义和使用</center>
#### 1.3 Temporal Difference Learning
设 $s_t$ 表示t 时刻的游戏局面状态。
机器玩家通过上文所述公式:$\arg\max\limits_{a \in A(s)}(R(s_t, a) + V(N(s_t, a)))$ 来选出下一步的a.
得到下一状态以及单步回报分别为: $s_{t+1} = N(s_t, a), r = R(s_t, a)$.
定义 TD Error为 $\triangle = r + V(s_{t+1}) - V(s_t)$ (不用加绝对值)
优化目标为降低 TD Error 的值,因此参数更新方式为: $V^*(s_t) = V(s_t) + \alpha \triangle$
其中 $V^*(s_t)$ 为更新 weight 之后新的回报期望值,$\alpha$是学习率。
### 2 实验
#### 2.1 实验配置
采取与baseline类似的方法进行训练:首先实例化32局游戏,然后进行若干个iteration。
每个iteration中,根据weights为这32局游戏分别选取移动的方向,进行一步移动,将对应的32个五元组(移动前的状态,移动后的状态,移动方向,移动得分,游戏是否结束)放入记忆体中;然后从记忆体中进行5次随机抽样,每次抽取32个样例,对weights进行更新。
考虑到时间和效果的权衡,参考论文中的结果,我们选择了4个6-tuple组成N-tuple network,tuple的具体形态如图2所示.
<img src="./image/图2.png" />
<center>图2 本次实验中选择的4个6-tuple</center>
#### 2.2 关键代码
##### 2.2.1 Tuple类
```python
class Tuple():
def __init__(self, dots):
self.n = len(dots)
self.weights = [0]*(16**self.n)
self.dots8 = []
self.dots8.append([(x, y) for x, y in dots])
self.dots8.append([(x, 3-y) for x, y in dots])
self.dots8.append([(3-x, y) for x, y in dots])
self.dots8.append([(y, 3-x) for x, y in dots])
self.dots8.append([(y, x) for x, y in dots])
self.dots8.append([(3-y, 3-x) for x, y in dots])
self.dots8.append([(3-x, 3-y) for x, y in dots])
self.dots8.append([(3-y, x) for x, y in dots])
def forward(self, grid):
res = 0
idxs = []
for ds in self.dots8:
idx = 0
for x, y in ds:
idx = idx * 16 + grid[x][y]
res += self.weights[idx]
idxs.append(idx)
return res, idxs
def backward(self, idxs, error):
delta = error / 8
for idx in idxs:
self.weights[idx] += delta
```
Tuple类构造方法输入坐标形式表示的点列,例如[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (2, 0)].
weights使用一个长度为16\^n的列表存储。
1.2节中提到计算V时需要对网格的8种对称形式分别计算。为了减小计算的开销,我们将点列的八种对称形式计算并存在Tuple类中,这样做的好处是只需要在实例化时计算一次。
forward方法输入4\*4数组表示的盘面,盘面上的数用0-15表示;返回V(s)和计算过程用到的weights中的值对应的下标序列。
backward方法输入下标序列和TD error,对weights进行更新。
##### 2.2.2 训练过程
```python
for _ in range(5):
s0, s1, a, reward, d = data.sample_batch(32)
for i in range(32):
for t in tuples:
v0, idxs0 = t.forward(s0[i])
v1, _ = t.forward(s1[i])
delta = alpha * (v1 + reward[i] - v0)
t.backward(idxs0, delta)
```
对于记忆体中的每个样例,对每个tuple分别进行计算V(s), 计算TD error, 更新weights的过程。
#### 2.3 运行时间和空间
使用MegStudio的普通版或高级版CPU环境,在4个6-tuple的环境下,运行时间约为9 iterations每秒。对于每个tuple,其weight包含16<sup>6</sup>个值,每个值使用32位浮点数存储,4个tuple占用总空间约为256MB.
#### 2.4 结果与分析
采用与baseline相同的方式进行分数计算,两个x tile合并时加x分;平均分数avg_score首先设置为结束的第一局游戏的分数,然后每局游戏结束时按照avg_score = avg_score * 0.99 + game.score * 0.01的公式进行更新。
我们基于不同的学习率开展了两次实验。第一次实验中,学习率初始1e-1, 随后设置为1e-2, 随后设置为1e-3, 结果如图3. 每100 iterations记录一次平均分,平均分最高达到**4482.86**.
<img src="./image/图3.png" style="zoom:33%;" />
<center>图3 第一次实验的average score变化图</center>
第二次实验中,学习率初始1e-3, 随后设置为1e-4, 结果如图4. 每100 iterations记录一次平均分,平均分最高达到**4052.18**.
<img src="./image/图4.png" style="zoom:33%;" />
<center>图4 第二次实验的average score变化图</center>
按照一局游戏500步进行估算,每次实验中我们大约模拟了40000局游戏,这与文献当中数百万的游戏局数还有一定差距。因此,如果投入更多时间进行训练,这个模型仍有一定的上升空间。
## 参考文献
[1] Hasselt H V , Guez A , Silver D . Deep Reinforcement Learning with Double Q-learning[J]. Computer ence, 2015.
[2] Oka K , Matsuzaki K . Systematic Selection of N-Tuple Networks for 2048[C]// International Conference on Computers and Games. Springer International Publishing, 2016.
[3] Jaskowski, Wojciech. Mastering $2048$ with Delayed Temporal Coherence Learning, Multi-State Weight Promotion, Redundant Encoding and Carousel Shaping[J]. IEEE Transactions on Computational Intelligence and AI in Games, 2016, PP(99):1-1. |
Python | UTF-8 | 2,946 | 2.625 | 3 | [] | no_license | import pytest
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
@pytest.mark.usefixtures("driver_init")
class BaseTest:
url = "https://uat.ormuco.com/login"
email = "qa@ormuco.com"
password = "testpass"
errorMessage = "The user or password is incorrect."
def parse_element(self, ele):
text = [i.text for i in ele]
text = " ".join(text)
return text
class TestLogin(BaseTest):
# Test not part of technical test case.
def test_open_url(self):
self.driver.get(self.url)
title = self.driver.title
assert title == "Portal - stratosphere"
def test_blank_password_and_wrong_email(self):
wait = WebDriverWait(self.driver, 3)
self.driver.get(self.url)
wait.until(EC.element_to_be_clickable((By.NAME, 'username'))
).send_keys(self.email)
wait.until(EC.visibility_of_element_located(
(By.CSS_SELECTOR, ".button-login"))).click()
warning = self.driver.find_elements_by_xpath(
"//span[@class='warning']")
warning_text = self.parse_element(warning)
assert warning_text == self.errorMessage
def test_blank_email_and_wrong_password(self):
wait = WebDriverWait(self.driver, 3)
self.driver.get(self.url)
wait.until(EC.element_to_be_clickable((By.NAME, 'password'))
).send_keys(self.password)
wait.until(EC.visibility_of_element_located(
(By.CSS_SELECTOR, ".button-login"))).click()
warning = self.driver.find_elements_by_xpath(
"//span[@class='warning']")
warning_text = self.parse_element(warning)
assert warning_text == self.errorMessage
def test_blank_email_and_blank_password(self):
wait = WebDriverWait(self.driver, 3)
self.driver.get(self.url)
wait.until(EC.visibility_of_element_located(
(By.CSS_SELECTOR, ".button-login"))).click()
warning = self.driver.find_elements_by_xpath(
"//span[@class='warning']")
warning_text = self.parse_element(warning)
assert warning_text == self.errorMessage
def test_wrong_email_and_wrong_password(self):
wait = WebDriverWait(self.driver, 3)
self.driver.get(self.url)
wait.until(EC.element_to_be_clickable((By.NAME, 'username'))
).send_keys(self.email)
wait.until(EC.element_to_be_clickable((By.NAME, 'password'))
).send_keys(self.password)
wait.until(EC.visibility_of_element_located(
(By.CSS_SELECTOR, ".button-login"))).click()
warning = self.driver.find_elements_by_xpath(
"//span[@class='warning']")
warning_text = self.parse_element(warning)
assert warning_text == self.errorMessage
|
C# | UTF-8 | 3,488 | 2.734375 | 3 | [] | no_license | using EShopWebAPI.DTO;
using EShopWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace EShopWebAPI.Controllers
{
public class CategoryController : ApiController
{
// GET: Category
public HttpResponseMessage Get()
{
using (EshopEntities db = new EshopEntities())
{
var result = db.Categories.ToList();
if (result != null)
{
return Request.CreateResponse(HttpStatusCode.OK, result.ToList());
}
else
{
return null;
}
}
}
// GET: api/Category/5
public CategoryDTO Get(int id)
{
using (EshopEntities db = new EshopEntities())
{
Category c = db.Categories.SingleOrDefault(x => x.CategoryID == id);
if (c != null)
{
return new CategoryDTO(c.CategoryID, c.CategoryName, c.Description);
}
else
{
return null;
}
}
}
// POST: api/Category
public HttpResponseMessage Post([FromBody] Category cate)
{
try
{
using (EshopEntities db = new EshopEntities())
{
db.Categories.Add(cate);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.Created);
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
// PUT: api/Category/5
public HttpResponseMessage Put(int id, [FromBody] Category value)
{
try
{
using (EshopEntities db = new EshopEntities())
{
Category s = db.Categories.SingleOrDefault(b => b.CategoryID == id);
if (s != null)
{
s.CategoryID = id;
s.CategoryName = value.CategoryName;
s.Description = value.Description;
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, s);
}
else
{
return null;
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
// DELETE: api/Category/5
public HttpResponseMessage Delete(int id)
{
try
{
using (EshopEntities db = new EshopEntities())
{
Category s = db.Categories.SingleOrDefault(x => x.CategoryID == id);
db.Categories.Remove(s);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
}
} |
Java | UTF-8 | 1,870 | 2.90625 | 3 | [] | no_license | package com.chengguo.zhy.utils;
import android.content.Context;
import android.content.SharedPreferences;
/*
*
* 本地文件 存取工具类
*
* */
public class PrefUtils {
//本地文件名
public static final String PREF_NAME="config";
/**
* @param ctx 上下文对象
* @param key 要获取的数据名(键)
* @param defaultValue 默认返回值
* @return
*
* 获取SharedPreferences中指定布尔值的方法
*/
public static boolean getBoolean(Context ctx,String key,boolean defaultValue){
SharedPreferences sp=ctx.getSharedPreferences("config",Context.MODE_PRIVATE);
return sp.getBoolean(key, defaultValue);
}
/**
* @param ctx 上下文对象
* @param key 要获取的数据名(键)
* @param Value 要设置的值
*
* 设置一个boolean值
*/
public static void setBoolean(Context ctx,String key,boolean Value){
SharedPreferences sp=ctx.getSharedPreferences("config",Context.MODE_PRIVATE);
sp.edit().putBoolean(key, Value).commit();
}
/**
* @param ctx 上下文
* @param key 键
* @param defaultValue 默认值
* @return
*
* 获取一个已储存的字符串
*/
public static String getString (Context ctx,String key,String defaultValue){
SharedPreferences sp=ctx.getSharedPreferences("config",Context.MODE_PRIVATE);
return sp.getString(key, defaultValue);
}
/**
* @param ctx 上下文
* @param key 键
* @param Value 值
*
* 设置一个字符串
*/
public static void setString (Context ctx,String key,String Value){
SharedPreferences sp=ctx.getSharedPreferences("config",Context.MODE_PRIVATE);
sp.edit().putString(key, Value).commit();
}
}
|
PHP | UTF-8 | 1,822 | 2.640625 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<?php
session_start();
if(!isset($_SESSION['membre_connected']))
{
header('Location: index.php');
}
$id_membre = $_SESSION['id'];
?>
<head>
<meta charset="utf-8" />
<title>ExpliqueSimplement</title>
</head>
<body>
<h1>ExpliqueSimplement</h1>
<p>
<a href="nouveau_sujet.php">Nouveau sujet</a><br />
<a href="mes_sujets.php">Mes sujets</a><br />
<a href="autres_sujets.php">Autres sujets</a><br />
<a href="deconnecter.php">Se deconnecter</a><br />
</p>
<?php
$id_sujet = $_GET['id'];
$db = new PDO('mysql:host=localhost; dbname=explique_simplement','root', '');
$str = 'SELECT * FROM sujet WHERE id = :id';
$req = $db->prepare($str);
$val = array(
'id' => $id_sujet
);$req->execute($val);
$s = $req->fetch(PDO::FETCH_OBJ);
echo '<h2>'.$s->contenu.' ?</h2>';
?>
<strong>Explications:</strong><br/><br/>
<?php
$db = new PDO('mysql:host=localhost; dbname=explique_simplement','root', '');
$str = 'SELECT * FROM explication WHERE id_sujet = :id_sujet';
$req = $db->prepare($str);
$val = array('id_sujet' => $id_sujet);
$req->execute($val);
while($s = $req->fetch(PDO::FETCH_OBJ))
{
echo $s->contenu.'. <em>Posté le '.$s->date_publication.'</em><br/><br/>';
}
?>
<strong>Nouvelle explication</strong>
<form method="post" action="nouvelle_explication.php">
<input type="hidden" name="id_sujet" value="<?php echo $id_sujet; ?>"
/>
<textarea name="explication" placeholder="taper votre expliction
ici"></textarea>
<br/>
<input type="submit" value="Publier" />
<br/>
<em>300 caractères maximum</em>
</form>
</body>
</html>
|
C | UTF-8 | 1,765 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "PCA9685.h"
#include <stdio.h>
#include <math.h>
#define BASE_ADDRESS 0b10000000
#define CHIPCLK 25000000
struct __attribute__((__packed__)) pca9685datareg {
uint8_t registeraddress;
uint16_t start;
uint16_t stop;
};
struct __attribute__((__packed__)) pca9685setupreg {
uint8_t registeraddress;
uint8_t registerdata;
};
int PCA9685_Init(struct PCA9685_t* instance, uint8_t address, uint16_t pwmfrequency, enum PCA9685_OutputMode_t outputMode, bool invertOutputs)
{
instance->I2CAddress = BASE_ADDRESS | (address << 1); //shift one bit to the left for R/W bit
struct pca9685setupreg rd;
rd.registeraddress = 0xFE; //prescaler
rd.registerdata = (uint8_t)round(CHIPCLK / (4096 * pwmfrequency));
instance->i2cWriteDataMethod(instance->I2CAddress, &rd, 2);
rd.registeraddress = 0x00; //MODE1
rd.registerdata = 0b00100000;
instance->i2cWriteDataMethod(instance->I2CAddress, &rd, 2);
rd.registeraddress = 0x01; //MODE2
rd.registerdata = invertOutputs ? 1 << 4 : 0; //set output invert bit
rd.registerdata |= (outputMode == PCA9685_OutputMode_TotemPole) ? 1 << 2 : 0; //set output drive bit
instance->i2cWriteDataMethod(instance->I2CAddress, &rd, 2);
return 0;
}
void PCA9685_WritePWM(struct PCA9685_t* instance, uint8_t channel,uint16_t pwm)
{
struct pca9685datareg outdata;
uint16_t start = channel * 256;
uint16_t stop = start + pwm;
if (stop > 4095)
{
start = start - (stop - 4096);
stop = 4095;
}
outdata.start = start;
outdata.stop = stop;
if (pwm == 0)
{
outdata.start = 0;
outdata.stop = 0b0001000000000000;
}
if (pwm > 4094)
{
outdata.start = 0b0001000000000000;
outdata.stop = 0;
}
outdata.registeraddress = 6 + (4 * channel);
instance->i2cWriteDataMethod(instance->I2CAddress, &outdata, 5);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.