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>daniel-farlow/calculus-sandbox<file_sep>/seed-data.sql
CREATE TABLE problems(
id SERIAL PRIMARY KEY,
problem_statement VARCHAR
);
INSERT INTO problems (id, problem_statement)
VALUES
(DEFAULT, 'This would be the first problem.'),
(DEFAULT, 'Solve the following equation: $x^2+4=3$.'),
(DEFAULT, '\begin{align}
\text{LHS} &\equiv [p_1\to p_2]\land\cdots\land[p_{k+1}\to p_{k+2}]\land[p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(definition of conjunction)}\\[0.5em]
&[[p_1\to p_2]\land[p_2\to p_3]\land\cdots\land[p_{k+1}\to p_{k+2}]]\land[p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(by $S(k)$ with each $q_i = p_i$)}\\[0.5em]
&[(p_1\land p_2\land\cdots\land p_k)\to p_{k+1}]\land[p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(by $S(1)$ with $q_1=p_1\land\cdots\land p_k)$ and $q_2=p_{k+1}$)}\\[0.5em]
&[[(p_1\land p_2\land\cdots\land p_k)\land p_{k+1}]\to p_{k+1}]\land [p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(by definition of conjunction)}\\[0.5em]
&[(p_1\land p_2\land\cdots\land p_k\land p_{k+1}]\to p_{k+1}]\land [p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(since $a\land b\to b$ with $b=[p_{k+1}\to p_{k+2}]$)}\\[0.5em]
&[(p_1\land p_2\land\cdots\land p_k\land p_{k+1})\to p_{k+2}]\land[p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(since $a\land b\to a$)}\\[0.5em]
&(p_1\land p_2\land\cdots\land p_k\land p_{k+1})\to p_{k+2}\\[0.5em]
&\equiv \text{RHS},
\end{align}
');
<file_sep>/models/problemsModel.js
const db = require('./conn');
const base64js = require('base64-js');
const TextDecoder = require('text-encoder-lite').TextDecoderLite;
const TextEncoder = require('text-encoder-lite').TextEncoderLite;
function Base64Encode(str, encoding = 'utf-8') {
var bytes = new (typeof TextEncoder === "undefined" ? TextEncoderLite : TextEncoder)(encoding).encode(str);
return base64js.fromByteArray(bytes);
}
function Base64Decode(str, encoding = 'utf-8') {
var bytes = base64js.toByteArray(str);
return new (typeof TextDecoder === "undefined" ? TextDecoderLite : TextDecoder)(encoding).decode(bytes);
}
const jank = 'Bob';
const problemStatementEncoded = Base64Encode(
String.raw`
$5 + 4\rho + \sum_{i=1}^\infty$ and ${jank.toUpperCase()}
\begin{align}
\text{LHS} &\equiv [p_1\to p_2]\land\cdots\land[p_{k+1}\to p_{k+2}]\land[p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(definition of conjunction)}\\[0.5em]
&[[p_1\to p_2]\land[p_2\to p_3]\land\cdots\land[p_{k+1}\to p_{k+2}]]\land[p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(by $S(k)$ with each $q_i = p_i$)}\\[0.5em]
&[(p_1\land p_2\land\cdots\land p_k)\to p_{k+1}]\land[p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(by $S(1)$ with $q_1=p_1\land\cdots\land p_k)$ and $q_2=p_{k+1}$)}\\[0.5em]
&[[(p_1\land p_2\land\cdots\land p_k)\land p_{k+1}]\to p_{k+1}]\land [p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(by definition of conjunction)}\\[0.5em]
&[(p_1\land p_2\land\cdots\land p_k\land p_{k+1}]\to p_{k+1}]\land [p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(since $a\land b\to b$ with $b=[p_{k+1}\to p_{k+2}]$)}\\[0.5em]
&[(p_1\land p_2\land\cdots\land p_k\land p_{k+1})\to p_{k+2}]\land[p_{k+1}\to p_{k+2}]\\[0.5em]
&\Downarrow\qquad \text{(since $a\land b\to a$)}\\[0.5em]
&(p_1\land p_2\land\cdots\land p_k\land p_{k+1})\to p_{k+2}\\[0.5em]
&\equiv \text{RHS},
\end{align}
`
)
const problemStatementDecoded = Base64Decode(problemStatementEncoded);
// console.log(problemStatementEncoded);
// console.log(problemStatementDecoded);
db.result(`
INSERT INTO problems
VALUES
(DEFAULT, '${problemStatementEncoded}')
`)
class ProblemsList {
constructor(id, problemStatement) {
this.id = id;
this.problemStatement = problemStatement;
}
static async getAll() {
try {
const response = await db.query(`SELECT * FROM problems;`);
// console.log(Array.from(response));
// response.forEach(problem => problem.problem_statement = Base64Decode(problem.problem_statement));
// for (let problem of response) {
// problem.problem_statement = Base64Decode(problem.problem_statement);
// }
// console.log(response);
// console.log(decodedResponses);
const decodedResponses = response.map(problem => Base64Decode(problem.problem_statement))
// console.log('response: ', decodedResponses);
return decodedResponses;
} catch(error) {
console.log('error.message');
return error.message;
}
}
}
module.exports = ProblemsList;<file_sep>/routes/problems.js
const express = require('express');
const router = express.Router();
const problemsModel = require('../models/problemsModel');
router.get('/', async function(req, res, next) {
const problemsData = await problemsModel.getAll();
res.render('template', {
locals: {
title: "Problems Page",
data: problemsData
},
partials: {
partial: "problems.partial"
}
});
});
module.exports = router; | 16af339e511b19e8d7411e06714585d7e900b498 | [
"JavaScript",
"SQL"
] | 3 | SQL | daniel-farlow/calculus-sandbox | 95da0ed4bff628ea0a0267e6a45759611cc4f4ba | d17c7e2eb6a8ce69db33500d59506d33f3cf354b |
refs/heads/master | <repo_name>duochen13/Algo<file_sep>/attendenceCheck/opencv_playground.py
import numpy as np
import cv2
# https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html#display-image
img = cv2.imread('test.png', 0)
cv2.imshow('window name', img)
<file_sep>/README.md
### `Exponential run-time for fib time analysis in multiple languages`


### `./run.sh > result.txt`
### `python3 plot.py`
| 979bce80a572ba3c9c796e9bc07f06052189c6a6 | [
"Markdown",
"Python"
] | 2 | Python | duochen13/Algo | 4ec6834297a1a9a217d4e704de804eb41282e1d5 | b109d56d59b0b0e5a5142a53f2f2353fe2268474 |
refs/heads/master | <repo_name>amankedia/Python<file_sep>/Data Science in Python/Numpy & It's Array Operations/records&dates.py
import numpy as np
reca = np.array([(1,(2.0,3.0),'hey'),(2,(3.5,4.0),'n')],dtype=[('x',np.int32),('y',np.float64,2),('z',np.str,4)])
print(reca)
print(reca[0])
print(reca['x'])
print(reca['x'][0])
print(reca[0]['x'])
print(np.datetime64('2015'))
print(np.datetime64('2015-01'))
print(np.datetime64('2015-02-03 12:00:00'))
print(np.datetime64('2015-02-03 12:00:00+0700'))
print(np.datetime64('2015-01-01') < np.datetime64('2015-04-03'))
print(np.datetime64('2015-04-03') - np.datetime64('2015-01-01'))
print(np.datetime64('2015-01-01') + np.timedelta64(5,'D'))
print(np.datetime64('2015-01-01') + np.timedelta64(5,'h'))
print(np.datetime64('2015-01-01').astype(float))
print(np.datetime64('1970-01-01').astype(float))
r = np.arange(np.datetime64('2016-02-01'),np.datetime64('2016-03-01'))
print(r)
<file_sep>/Data Science in Python/Numpy & It's Array Operations/indexing&slicing.py
import numpy as np
v = np.linspace(0,10,5)
print(v[0])
vv = np.random.random((5,4))
print(vv)
print(vv[4,3])
ll = [[1,2,3],[4,5,6],[7,8,9]]
ll[1][2]
v[2:4]
<file_sep>/Programming Basics/queue.py
import queue
q = queue.Queue()
q.empty()
q.put('bag1')
q.empty()
q.put('bag2')
q.put('bag3')
q.get()
q.get()
q.get()
p = queue.Queue(3)
p.empty()
p.put('bag1')
p.empty()
p.put('bag2')
p.put('bag3')
print(p.full())
p.put_nowait('bag4')
p.get()
p.get()
print(p.get())
<file_sep>/Programming Basics/module_random_urllib.py
import random
print(random.randint(1,20))
#randint(1,20) #error
from random import randint
print(randint(1,20)) #now no error
from random import random #random is a method in random package
random()
#print(randint(1,20)) #would give error as random now referes to method
#to resolve use following
import random as rand
print(rand.randint(1,100))
import urllib.request
urllib.request.urlopen('http://www.google.com')
urllib.__path__
<file_sep>/Programming Basics/For_Loop_While_Loop_Break.py
""" Loading the Dishwasher """
#For Loop
# dirty dishes in the sink
sink = ['bowl','plate','cup']
for dish in list(sink):
print('Putting {} in the dishwasher'.format(dish))
sink.remove(dish)
# check that the sink is empty
print(sink)
""" Scrubbing A Stuborn Pan """
#While Loop
import random
dirty = True # state of the pan
scrub_count = 0 # number of scrubs
while(dirty):
scrub_count += 1
print('Scrub the pan: {}'.format(scrub_count))
if not random.randint(0,9):
print('All clean!')
dirty = False
else:
print('Still dirty...')
print('Rinse & check if the pan is clean.')
""" Putting Away Clean Dishes """
#Break Statement
import random
# 20 clean dishes in dishwasher
dishwasher = ['plate','bowl','cup','knife','fork',
'spoon','plate','spoon','bowl','cup',
'knife','cup','cup','fork','bowl',
'fork','plate','cup','spoon','knife']
for dish in list(dishwasher):
# check space left in cabinet
if not random.randint(0,19):
print('Out of space!')
break
else:
print('Putting {} in the cabinet'.format(dish))
dishwasher.remove(dish)
<file_sep>/Data Science in Python/Basic_Operations_using_pandas/Basic_operations_dataframe_series.py
import panda as pd
from pandas import Series, DataFrame
data1 = Series([6,77,888,9999])
data1.index
data2 = Series([8, 9, 11], index=["Joe", "Jane", "John"])
data2["Joe"]
data3["Joe"]
data2
data2 += 1
data2
data2[data2 > 10]
import numpy as np
np.random.rand(20)
data4 = Series(np.random.rand(20))
data4
data4[data4 <= 0.75]
data = {'school': ['Baxters', 'Racine'],'test scores': [90, 96]}
data
table = DataFrame(data, index =['School 1', 'School 2'])
table
data = {'name': ['James', 'Jane', 'John', 'Jake', 'Audrey'], 'sex': ['M', 'F', 'M', 'M', 'F']}
table1 = DataFrame(data)
table
datan= {'name' : ['James', 'Jane', 'John', 'Jake', 'Audrey'], 'sex' : ['M', 'F', 'M', 'M', 'F']}
table1 = DataFrame(datan)
table1
tablefull = DataFrame(datafull, columns=['name', 'age', 'sex', 'height'])
tablefull
tablefull.mean()
tablefull['height'].mean()<file_sep>/Data Science in Python/Data Containers in Python/dictionary.py
capitals = {'United States': 'Washington, DC','France': 'Paris','Italy': 'Rome'}
capitals['Italy']
capitals['Spain'] = 'Madrid'
capitals
'Germany' in capitals
'Italy' in capitals
morecapitals = {'Germany': 'Berlin','United Kingdom': 'London'}
capitals.update(morecapitals)
capitals
del capitals['United States']
for key in capitals:
print(key,capitals[key])
for key in capitals.keys():
print(key)
for value in capitals.values():
print(value)
for key,value in capitals.items():
print(key,value)<file_sep>/Data Science in Python/Numpy & It's Array Operations/arrays_numpy.py
import numpy as np
a = np.array([1,2,3,4,5])
print(a)
print(a.dtype)
a = np.array([1,2,3,4,5],dtype=np.float64)
print(a)
print(a.ndim, a.shape, a.size)
b = np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype=np.float64)
print(b)
print(b.dtype)
print(b.ndim, b.shape, b.size)
print(np.zeros((3,3),'d'))
print(np.empty((4,4),'d'))
print(np.linspace(0,10,5))
print(np.arange(0,10,2))
print(np.random.standard_normal((2,4)))
a = np.random.standard_normal((2,3))
b = np.random.standard_normal((2,3))
np.vstack([a,b])
np.hstack([a,b])
a.transpose()
np.save('example.npy',a)
a1 = np.load('example.npy')
print("HI")
print(a1)
<file_sep>/Data Science in Python/Data Containers in Python/comprehension.py
squares = []
for i in range(10):
squares.append(i**2)
squares
squares = [i**2 for i in range(10)]
squares
squares = [i**2 for i in range(10) if i % 3 == 0]
squares
squares_dict = {i: i**2 for i in range(30) if i % 3 == 0}
squares_dict
sum([i**2 for i in range(10)])
<file_sep>/Data Science in Python/Data Containers in Python/lists.py
nephews = ["Huey","Dewey","Louie"]
nephews
nephews[0]
nephews[2]
len(nephews)
nephews[3] #error
for i in range(3):
nephews[i] = nephews[i] + ' Duck'
nephews
mix_it_up = [1,[2,3],'alpha']
mix_it_up
nephews.append('April Duck')
nephews
nephews.extend(['May Duck','June Duck'])
nephews
ducks = nephews + ['<NAME>','<NAME>']
ducks
ducks.insert(0,'<NAME>')
ducks
del ducks[0]
ducks
ducks.remove('<NAME>')
ducks
ducks.sort()
ducks
squares = [0,1,4,9,16,25,36,49]
squares
squares[0:2]
squares[:3]
squares[:]
squares[-1]
squares[-3:-1]
squares[0::2]
for value in squares:
print("Element",value)
for index, value in enumerate(squares):
print("Element",index,"-> ",value)
<file_sep>/Programming Basics/Sets.py
""" Creating and Combining Sets of Friends """
college = set(['Bill', 'Katy', 'Verne', 'Dillon',
'Bruce', 'Olivia', 'Richard', 'Jim'])
coworker = set(['Aaron', 'Bill', 'Brandon', 'David',
'Frank', 'Connie', 'Kyle', 'Olivia'])
family = set(['Garry', 'Landon', 'Larry', 'Mark',
'Olivia', 'Katy', 'Rae', 'Tom'])
# combine all friends into a single set
friends = college.union(coworker, family)
# print out friends in each set
print('I have {} college buddies:'.format(len(college)))
print(college)
print('I have {} coworkers:'.format(len(coworker)))
print(coworker)
print('I have {} family friends:'.format(len(family)))
print(family)
print('I have {} total friends:'.format(len(friends)))
print(friends)
""" Sorting Friends into Sets """
# set of all friends
friends = set(['Mark', 'Rae', 'Verne', 'Richard',
'Aaron', 'David', 'Bruce', 'Garry',
'Bill', 'Connie', 'Larry', 'Jim',
'Landon', 'Dillon', 'Frank', 'Tom',
'Kyle', 'Katy', 'Olivia', 'Brandon'])
# set of people who live in my zip code
zipcode = set(['Jerry', 'Elaine', 'Cindy', 'Verne',
'Rudolph', 'Bill', 'Olivia', 'Jim',
'Lindsay', 'Rae', 'Mark', 'Kramer',
'Landon', 'Newman', 'George'])
# set of people who play Munchkin
munchkins = set(['Steve', 'Jackson', 'Frank', 'Bill',
'Mark', 'Landon', 'Rae'])
# set of Olivia's friends
olivia = set(['Jim', 'Amanda', 'Verne', 'Nestor'])
# choose just the friends who live nearby
local = friends.intersection(zipcode)
print('I have {} local friends:'.format(len(local)))
print(local)
# remove the Munchkin players
invite = local.difference(munchkins)
print('I have {} friends to invite:'.format(len(invite)))
print(invite)
# revise the friends to invite set
invite = invite.symmetric_difference(olivia)
print('My revise set has {} friends:'.format(len(invite)))
print(invite)
""" Adding and Removing Friends from Sets """
# revised set of friends to invite
invite = set(['Nestor', 'Amanda', 'Olivia'])
# invite Verne
print('Verne' in invite)
invite.add('Verne')
print(invite)
# make sure Olivia is invited
invite.add('Olivia')
print(invite)
# remove Nestor from invite set
invite.remove('Nestor')
print(invite)
# invite.remove('Nestor') # will throw an error
# start inviting friends
print(invite.pop())
print(invite.pop())
print(invite.pop())
print(invite.pop()) # will throw an error
<file_sep>/Programming Basics/If_Else_Switch.py
""" Ordering A Pizza That Verne Can Eat """
# things that Verne does not eat
diet_restrictions = set(['meat','cheese'])
# decide which pizza to order
if 'meat' and 'cheese' in diet_restrictions:
print('Get a vegan pizza.')
elif 'meat' in diet_restrictions:
print('Get a cheese pizza.')
else:
print('Get something else.')
""" Switch """
specials = {'Sunday' : 'spinach',
'Monday' : 'mushroom',
'Tuesday' : 'pepperoni',
'Wednesday' : 'veggie',
'Thursday' : 'bbq chicken',
'Friday' : 'sausage',
'Saturday' : 'Hawaiian'}
def order(day):
pizza = specials[day]
print('Order the {} pizza.'.format(pizza))
# order the Saturday special!
order('Saturday')
<file_sep>/Data Science in Python/Numpy & It's Array Operations/numpy_operations.py
import numpy as np
import matplotlib.pyplot as pp
from pylab import *
x = np.linspace(0,10,40)
sinx = np.sin(x)
cosx = np.cos(x)
ion()
y = sinx * cosx
z = cosx**2 - sinx**2
pp.plot(x,sinx)
pp.plot(x,cosx)
pp.plot(x,y)
pp.plot(x,z)
pp.legend(['sin(x)','cos(x)','sin(x)cos(x)','cos(x)^2-sin(x)^2'])
pp.show()
print(np.dot(sinx,cosx))
print(np.outer(sinx,cosx))
v = np.linspace(0,10,5)
print(v + 1)
vv = np.outer(v,v)
print(vv + v)
print(vv + v[:,np.newaxis])
<file_sep>/Data Science in Python/Basic_Operations_using_pandas/Working_With_CPS_Data.py
db = pd.read_csv('file_location\\algexit2009.csv')
db
db.values
db
db.head(15)
db.tail(5)
db.sort(columns=["total_pass"])
db.sort(columns=["total_pass"], inplace=True)
db.sort(columns=["total_pass"], inplace=True, ascending=False)
db.sort(columns=["total_highpass"], inplace=True, ascending=False)
db.iat[0,2]
db.iat[0,2] / float(db.iat[0,3])
passpercent = []
for i in range(len(db)):
passpercent.append(db.iat[i,2] / float(db.iat[i,3]))
db['pass percent'] = passpercent
highpasspercent = []
for i in range(len(db)):
highpasspercent.append(db.iat[i,1] / float(db.iat[i,3]))
db['high pass percent'] = highpasspercent
db.sort(columns=['pass percent'], inplace=True, ascending=False)
totalpass = []
for i in range(len(db)):
totalpass.append(db.iat[i,1] + db.iat[i,2])
db.['total pass'] = totalpass
db.sort(columns=['total pass'], inplace=True, ascending=False)
totalpasspercent = []
for i in range(len(db)):
totalpasspercent.append(db.iat[i,6] / float(db.iat[i,3]))
db['total pass percent'] = totalpasspercent
db.sort(columns=['total pass percent'], inplace=True, ascending=False)<file_sep>/Data Science in Python/Weather Data in Python/Temperature_Analysis.py
import numpy as np
import matplotlib.pyplot as pp
import seaborn
import urllib
urllib.urlretrieve('ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt','stations.txt')
open('stations.txt','r').readlines()[:10]
stations = {}
for line in open('stations.txt','r'):
if 'GSN' in line:
fields = line.split()
stations[fields[0]] = ' '.join(fields[4:])
len(stations)
def findstation(s):
found = {code: name for code,name in stations.items() if s in name}
print(found)
print(findstation('LIHUE'))
findstation('SAN DIEGO')
findstation('IRKUTSK')
datastations = ['USW00022536','USW00023188','USW00014922','RSM00030710']
open('USW00022536.dly','r').readlines()[:10]
open('readme.txt','r').readlines()[98:121]
def parsefile(filename):
return np.genfromtxt(filename,
delimiter = dly_delimiter,
usecols = dly_usecols,
dtype = dly_dtype,
names = dly_names)
dly_delimiter = [11,4,2,4] + [5,1,1,1] * 31
dly_usecols = [1,2,3] + [4*i for i in range(1,32)]
dly_dtype = [np.int32,np.int32,(np.str_,4)] + [np.int32] * 31
dly_names = ['year','month','obs'] + [str(day) for day in range(1,31+1)]
lihue = parsefile('USW00022536.dly')
def unroll(record):
startdate = np.datetime64('{}-{:02}'.format(record['year'],record['month']))
dates = np.arange(startdate,startdate + np.timedelta64(1,'M'),np.timedelta64(1,'D'))
rows = [(date,record[str(i+1)]/10) for i,date in enumerate(dates)]
return np.array(rows,dtype=[('date','M8[D]'),('value','d')])
| 7ab05972064f23c9d505d817aa8c9bfa99fcf676 | [
"Python"
] | 15 | Python | amankedia/Python | 5bf2edcc6bcdce882dd3f5d4d50f4b1af09f98b0 | 7be0f74dabf89d8ad17e80c79f0e16d31700e1d9 |
refs/heads/master | <repo_name>mizydorek/pands-problems-2020<file_sep>/Topic07-Files/csv-write.py
import csv
# writing to csv
'''
with open('employee.csv', 'w') as writer:
employee = csv.writer(writer, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)
employee.writerow(['<NAME>', 'Accounting', 'November'])
employee.writerow(['<NAME>', 'IT', 'March'])
'''
# writing to csv from dictionary
with open('employee.csv' , 'w') as emplyeee_file:
fieldnames = ['name', 'dept', 'month']
writer = csv.DictWriter(emplyeee_file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'name':'<NAME>', 'dept':'Accounting', 'month':'November'})
writer.writerow({'name':'<NAME>', 'dept':'IT', 'month':'March'})<file_sep>/Topic09-errors/myfunction.py
# Calculate factorial of a number
def factorial(n):
''' Returns the factorial of n.
e.g. factorial(7) = 7x76x5x4x3x2x1 = 5040.
'''
answer = 1
for i in range(1,n+1):
answer = answer * i
return answer
if __name__ == "__main__":
assert factorial(7) == 5040<file_sep>/README.md
# Programming and Scripting 2020
Repository contains weekly tasks in parent folder with number in front in their names that corresponds with sequential weeks as well as option labs in their own folders.
## Weekly Tasks
* [2-bmi](https://github.com/mizydorek/pands-problems-2020/blob/master/2-bmi.py)
* [3-secondstring](https://github.com/mizydorek/pands-problems-2020/blob/master/3-secondstring.py)
* [4-collatz](https://github.com/mizydorek/pands-problems-2020/blob/master/4-collatz.py)
* [5-weekday.py](https://github.com/mizydorek/pands-problems-2020/blob/master/5-weekday.py)
* [6-squareroot](https://github.com/mizydorek/pands-problems-2020/blob/master/6-squareroot.py)
* [7-read-a-file](https://github.com/mizydorek/pands-problems-2020/blob/master/7-read-a-file.py)
* [8-plots](https://github.com/mizydorek/pands-problems-2020/blob/master/8-plots.py)
### Additional or modified exercises
* [5-primes](https://github.com/mizydorek/pands-problems-2020/blob/master/5-primes.py)
* [6-functions](https://github.com/mizydorek/pands-problems-2020/blob/master/6-functions.py)
* [6-primes](https://github.com/mizydorek/pands-problems-2020/blob/master/6-primes.py)
### Optional Labs
* [Topic03: State](https://github.com/mizydorek/pands-problems-2020/tree/master/Topic03-variables%26state)
* [Topic 4: Controlling the flow](https://github.com/mizydorek/pands-problems-2020/tree/master/Topic04-flow)
* [Topic 5: Data](https://github.com/mizydorek/pands-problems-2020/tree/master/Topic05-datastructures)
* [Topic 6: Functions](https://github.com/mizydorek/pands-problems-2020/tree/master/Topic06-functions)
* [Topic 7: Files](https://github.com/mizydorek/pands-problems-2020/tree/master/Topic07-Files)
* [Topic 8: Looking ahead](https://github.com/mizydorek/pands-problems-2020/tree/master/Topic08-plots)
* [Topic 9: Errors](https://github.com/mizydorek/pands-problems-2020/tree/master/Topic09-errors)
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details<file_sep>/Topic04-flow/lab04.01-grade.py
# <NAME>
# Percentage
percentage = round(float(input("Enter the percentage: ")))
# Added round function to solve second problem
if percentage < 0 or percentage > 100:
print("Please enter a number between 0 and 100")
elif percentage < 40:
print("Fail")
elif percentage < 50:
print("Pass")
elif percentage < 60:
print("Merit1")
elif percentage < 70:
print("Merit2")
else:
print("Distinction") <file_sep>/Topic05-datastructures/lab05.04-student.py
# <NAME>
# Student program that stores a student name and
# a list of courses and grades
student = {}
name = input('enter your name: ')
student['name'] = name
course = input('enter course: ')
grade = input('enter grade: ')
while True:
student[course] = grade
if course == '':
break
course = input('enter course: ')
if grade == '':
break
grade = input('enter grade: ')
print(student)
#print('Student: {}'.format(student['name']))
<file_sep>/Topic05-datastructures/lab05.02-months.py
# <NAME>
# Print out summer months
months =("January",
"February",
"March",
"April",
"May",
"June",
"july",
"August",
"September",
"October",
"November",
"December"
)
summer = months[4:7]
# print out months as list
# print(summer)
for month in summer:
print(month)<file_sep>/main.py
try:
b = 2
a = b
b[10] = 'this is not good'
except NameError as ne:
print('a Name error occured')
print(ne)
except Exception as e:
print(e)<file_sep>/5-weekday.py
# <NAME>
# Checks if wheteher or not today is a weekday
import datetime
# Get today's date
now = datetime.datetime.now()
# check if wheteher or not today is a weekday knowing that
# Monday equals to 0 and Sunday equals 6
if now.weekday() < 5:
print('Yes, unfortunately today is a weekday.')
else:
print('It is the weekend, yay!')<file_sep>/Topic09-errors/lab09.02-check-input.py
# <NAME>
# read in a number from input, substract 10% and print out
# throw an error if the input is less then 0
sub = 0.90
number = float(input('input a number: '))
if ( number < 0 ):
raise ValueError("input should be greater than 0 ({})".format(number))
ans = number * sub
print("{} minus 10% is {}".format(number,ans))
<file_sep>/analysis.py
# plots
import matplotlib.pyplot as plt
import pandas
df = pandas.read_csv("http://www.biostat.jhsph.edu/~rpeng/useRbook/faithful.csv")
plt.plot(df["eruptions"], df["waiting"], 'b.')
plt.title('eruptions vs waiting')
plt.savefig("scatter.png")
plt.clf()
plt.hist(df['eruptions'])
plt.savefig("eruptions.png")
plt.clf()
plt.hist(df['waiting'])
plt.savefig("waiting.png")
plt.clf()<file_sep>/divides.py
# <NAME>
# Check if one number divides another.
p = 8
m = 3
if (p % m) == 0:
print(p, 'divided by', m, 'leaves a remainder of zero')
print("I'll be run too if the condition is True.")
else:
print(p, 'divided by', m, 'does not leave a remainder of zero')
print("I'll be run too if the condition is False.")
print("I'll run no matter what.")<file_sep>/Topic08-plots/rp-corelate.py
import matplotlib.pyplot as plt
import numpy as np
def main():
x = np.random.randint(low=1, high=11, size=50)
y = x + np.random.randint(1, 5, size=x.size)
data = np.column_stack((x, y))
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
ax1.scatter(x=x, y=y, marker='o', c='g', edgecolor='b')
ax1.set_title('Scatter: $x$ versus $y$')
ax1.set_xlabel('$x$')
ax1.set_ylabel('$y$')
ax1.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)
ax2.hist(data, bins=np.arange(data.min(), data.max()), label=('x', 'y'))
ax2.legend(loc=(0.65, 0.8))
ax2.set_title('Frequencies of $x$ and $y$')
ax2.yaxis.tick_right()
main()
plt.show()<file_sep>/2-bmi.py
# <NAME>
# Progam that calculates BMI
# two variables weight and height that hold user input and converts to float
weight = float(input('Enter weight in kg: '))
height = float(input('Enter height in cm: '))
#formula that calculates bmi and round the result to two decimal points
bmi = round( weight / ( height / 100 ) ** 2,2 )
#print out output of bmi
print('BMI is', bmi)<file_sep>/6-primes.py
# <NAME>
# Computing the primes
from functions import isprime
P = []
# loops through numbers from 0 to 100 and checking if it is prime
for i in range(2, 100):
# else i is prime, then append to P
if isprime(i):
P.append(i)
#print out list of primes
print(P)<file_sep>/Topic09-errors/exceptions.py
# <NAME>
# Topic09 errors and exceptions
import sys
try:
with open(sys.argv[1]) as f:
print(f.read())
a = 1 / 0
except FileNotFoundError:
print("File " + sys.argv[1] + ' does not exsist.')
except:
print('This is zero division error handler.')<file_sep>/Topic07-Files/lab07.03-json-write copy.py
# <NAME>
# function to store data in json
import json
filename = 'testdata.json'
d = dict(name = 'Fred', age=31, grades=[1,34,55])
def writeFile(obj):
with open(filename, 'w') as f:
json.dump(obj, f)
writeFile(d)<file_sep>/Topic03-variables&state/lab03.08-dictionary.py
# <NAME>
# creates dictionary, store hard coded book details
# outputs values in dictionary
currentBook = {
'title' : 'Atomic habits',
'author' : '<NAME>',
'price' : '9.99'
}
# print dictionary object
print(currentBook)
# print author
print(currentBook['author'])
# create and set attribute ISBN
currentBook['ISBN'] = '12345'
# print out all values in currentBook
print('---')
for book in currentBook.values():
print ("{}".format(book))
<file_sep>/Topic07-Files/lab07.05-student-management.py
# <NAME>
# Student management program
import json
students = []
filename = 'students.json'
def writeDict(obj):
with open(filename, 'wt') as f:
json.dump(obj,f)
def readDict():
with open(filename) as f:
return json.load(f)
# function that display menu
def displayMenu():
print('What would you like to do?')
print('\t(a) Add new student')
print('\t(v) View students')
print('\t(s) Save students')
print('\t(q) Quit')
choice = input('Type one letter (a/v/q):')
return choice
# add function
def doAdd():
print('in adding')
# view function
def doView():
print('in viewing')
# save function
def doSave():
writeDict(students)
print('students saved')
# load function
def doLoad():
global students
students = readDict()
print('students loaded')
# Main
# displays main menu and waits for user to choose an option
choice = displayMenu()
while choice != 'q':
if choice == 'a':
doAdd()
elif choice == 'v':
doView()
elif choice == 'l':
doLoad()
elif choice == 's':
doSave()
elif choice != 'q':
print('\nplease select either a,v,l,s or q')
choice = displayMenu()<file_sep>/Topic06-functions/lab06.01-student-management.py
# <NAME>
# Student management program
students = []
# function that display menu
def displayMenu():
print('What would you like to do?')
print('\t(a) Add new student')
print('\t(v) View students')
print('\t(q) Quit')
choice = input('Type one letter (a/v/q):')
return choice
# add function which creates current student dict, takes student
# name as an input and refers module field to add module function
def doAdd():
currentStudent = {}
currentStudent['name'] = input('enter name: ')
currentStudent['modules'] = addModules()
students.append(currentStudent)
# modules function that takes modules and grades as an input and
# quit the loop if module name equals blank
def addModules():
modules = []
moduleName = input('enter the first Module name(blank to quit): ')
while moduleName != '':
module = {}
module['name'] = moduleName
module['grade'] = int(input('enter grade: '))
modules.append(module)
moduleName = input('enter next module name(blank to quit): ')
return modules
# displays modules of student by looping through the modules dict
def displayModules(modules):
for module in modules:
print('{} : {}'.format(module['name'],module['grade']))
# display function that loops through students dict to output name
# refers to display modules function to output all modules
def doView():
for student in students:
print(student['name'])
displayModules(student['modules'])
# displays main menu and waits for user to choose an option
choice = displayMenu()
while choice != 'q':
if choice == 'a':
doAdd()
elif choice == 'v':
doView()
elif choice != 'q':
print('\nplease select either a,v or q')
choice = displayMenu()<file_sep>/Topic03-variables&state/lab03.04-random.py
# <NAME>
# prints out 10 random number
import random
# random function uses to draw random number from 1 to 10
number = random.randint(1,10)
print('This is a random number {}'.format(number))<file_sep>/5-primes.py
# <NAME>
# Computing the primes
P = []
# loops through numbers from 0 to 100 and checking if it is prime
for i in range(2, 100):
# loops through values of P
for j in P:
# see if j divides i
if i % j == 0:
# If it does, i is not a prime so exit loop
break
# else i is prime, then append to P
else:
P.append(i)
#print out list of primes
print(P)<file_sep>/Topic07-Files/lab07.02b-create-try.py
# <NAME>
# program counts how many times it was run
import os.path
filename = 'count.txt'
if not os.path.isfile(filename):
print('File does not exsist')
# init file here
writeNumber(0)
def readNumber():
try:
with open(filename, 'r') as reader:
number = int(reader.read()) # converts str to int
return number
except IOError:
# no file - first run
return 0
def writeNumber(number):
with open(filename, 'w') as writer:
writer.write(str(number)) # write takes str
# main
number = readNumber()
number += 1
print('Program has been run {} times'.format(number))
writeNumber(number)<file_sep>/Topic04-flow/lab04.03-avarage.py
# <NAME>
# Program reads in numbers until user enters 0
# then prints numbers and their avarage
numbers = []
# reads first number then we check if it is 0 in the while loop
number = int(input('enter number (0 to quit): '))
while number != 0:
numbers.append(number)
# read the next number and check if it is 0
number = int(input('enter number (0 to quit): '))
# print numbers
for value in numbers:
print(value)
# calculate their avarage
avarage = float(sum(numbers)) / len(numbers)
print('The avarage is {}'.format(avarage))<file_sep>/Topic03-variables&state/lab03.06-randomfruit.py
# <NAME>
# prints out a random fruit
import random
# lists of fruits
fruits = ['apple', 'banana', 'kiwi', 'orange', 'grapefruit', 'raspberry']
# random number starting at 0 up to length of list - 1 to do not get out of the list index
random = fruits[random.randint(0,len(fruits)-1)]
print('A random fruit: {}'.format(random))<file_sep>/functions.py
# <NAME>
# Function to square numbers
import math
#
def power(x, y):
ans = x
y = y - 1
while y > 0:
ans = ans * x
y = y - 1
return ans
def f(x):
ans = ((100 * power(x, 2)) + 10 * power(x, 3)) // 100
ans = ans - (power(x, 3)) // 10
return ans
def isprime(i):
# loops through values from 2 up to sqrt of the i
for j in range(2, math.floor(math.sqrt(i))):
# See if j divides i.
if i % j == 0:
# If it does, i is not a prime so return False
return False
return True<file_sep>/8-plots.py
# <NAME>
# week 8 task - comparison of three function
# f(x) = x, g(x) = x**2, h(x) = x**3
import matplotlib.pyplot as plt
import numpy as np
# generate 100 linearly spaced numbers in range 0-4
x = np.linspace(0.0, 4.0, 100)
# the functions
f = x
g = x**2
h = x**3
# plot the functions and add labels
plt.plot(x, f, 'b', label = 'f(x) = x')
plt.plot(x, g, 'g', label = 'g(x) = x**2')
plt.plot(x, h, 'r', label = 'h(x) = x**3')
# setting the plot
plt.title("Comparison of functions")
plt.legend()
plt.xlabel("x(in range 0-4)")
# create png and show the plot
plt.savefig("comparison.png")
plt.show()<file_sep>/4-collatz.py
# <NAME>
# Collatz conjecture
# variable to hold user input as integer
n = int(input("Please enter a positive number: "))
print(int(n), end=" ")
while n == 1: # validate if number is equal to one
n = 3 * n + 1 # apply formula
print(int(n), end=" ") # and print out n
else:
while n != 1: # statement that validates number from 2 up
if n % 2 == 0: # check if it is even number
n = n / 2 # apply formula
print(int(n), end=" ") # print out n
else: # check if it is odd number
n = 3 * n + 1 # apply formula
print(int(n), end=" ") # print out n
print('')<file_sep>/Topic03-variables&state/lab03.01-hello.py
# <NAME>
# Program reads in persons name and uses format function to output
name = input("Please enter your name: ")
print("Hello {}!".format(name)) <file_sep>/3-secondstring.py
# <NAME>
# Variables - string task
# s variable to hold user input and converts to string
s = str(input('Please enter a sentence: '))
# s = 'The quick brown fox jumps over the lazy dog.'
print(s[:]) # outputs the whole sentance
print(s[::-2]) # outputs every second letter in reverse order<file_sep>/Topic04-flow/lab04.05-topthree.py
# <NAME>
# Program generate and prints 10 random numbers from 0 to 100
# prints them out and then prints out top three
import random
numbers = []
for i in range(11):
# random function generates random number from 0 - 100
number = random.randint(1,101)
numbers.append(number)
print(numbers)
# sort numbers in reverse order and print top three
numbers.sort(reverse=True)
print(numbers[:3])<file_sep>/Topic03-variables&state/lab03.05-normalise.py
# <NAME>
# reads entered string, strips any leading or trailing spaces and
# outputs in lowercase. Outputs also lenght of the raw string and
# the normalised one
string = input("Please enter string: ")
normalised = string.strip().lower()
print("That String normalised is : {}".format(normalised))
print("We reduced the input string form {} to {} characters".format(len(string), len(normalised)))<file_sep>/7-read-a-file.py
# <NAME>
# Reads a text file entered by user and outputs the number of e's it contains.
# module that allows to specify file name from the command line
# found on stack overflow https://stackoverflow.com/questions/7033987/python-get-files-from-command-line
import fileinput
# reads file name entered by user and stores in filename variable
# filename = input('Enter text file name: ')
# counter variable to count e's in txt file
counter = 0
# with open... function to open file specified by user who typed the name of file
#with open(filename, 'r') as reader:
# lines = reader.readlines()
# for line in lines:
# for letter in line:
# if letter == 'e':
# counter += 1
# print(counter)
# for loop to get lines from the text and inner loop to get every letter from line
# if statement to count how many e's in the file
for line in fileinput.input():
for letter in line:
if letter == 'e':
counter += 1
print(counter)
<file_sep>/6-squareroot.py
# <NAME>
# Program which takes a positive float number as input and
# outputs an approximation of its square root
import math
# square root function which takes inputed float number
# outputs square root of it rounded to one decimal place
def sqrt(f):
num = round(math.sqrt(f),1)
return num
# stores inputed positive float number
f = float(input('Enter a positive number: '))
# Prints out the result in desired format
print('The square root of {} is approx. {}'.format(f,sqrt(f)))<file_sep>/Topic07-Files/lab07.04-json-read.py
# <NAME>
# function to store data in json
import json
filename = 'testdata.json'
def readFile():
with open(filename, 'r') as f:
return json.load(f)
print(readFile())<file_sep>/Topic09-errors/factorial.py
import sys
import myfunction
# Get n from the command line.
n = int(sys.argv[1])
# Calculate the factorial of n
ans = myfunction.factorial(n)
# print answer
print("The factorial of", n, "is:", ans)<file_sep>/prime.py
# <NAME>
# Check if a number is prime.
# The primes are 2, 3, 5, 7, 11, 13 ...
p = 347
m = 2
isprime = True
#while m < p:
# if p % m == 0:
# print(m, "divides", p, "and therefore", p, "is not a prime.")
# isprime = False
# break
# m = m + 1
for m in range(2, p-1):
if p % m == 0:
isprime = False
break
if isprime:
print(p, "is a prime number.")
else:
print(p, "is not a prime.")<file_sep>/Topic08-plots/rp-debt.py
import matplotlib.pyplot as plt
import numpy as np
def main():
rng = np.arange(50)
rnd = np.random.randint(0, 10, size=(3, rng.size))
yrs = 1950 + rng
fig, ax = plt.subplots(figsize=(5, 3))
ax.stackplot(yrs, rng + rnd, labels=['Eastasia', 'Eurasia', 'Oceania'])
ax.set_title('Combined debt growth over time')
ax.legend(loc='upper left')
ax.set_ylabel('Total debt')
ax.set_xlim(xmin=yrs[0], xmax=yrs[-1])
fig.tight_layout()
main()
plt.show()<file_sep>/Topic05-datastructures/lab05.03-queue.py
# <NAME>
# Queue program
import random
q = []
# Create q list filled in 10 random numbers from 0 to 100
for i in range(11):
number = random.randint(1,101)
q.append(number)
# print out q list
print('queue is', q)
# take and print out numbers from queue one at the time and
# current numbers still in the queue
# add one to lenght of q to check if list is empty and print out info
for i in range(len(q)+1):
if len(q) == 0:
print('the queue is now empty')
break
#Inserted pop() into print to meets task criteria
print('current Number is', q.pop(0), q)
# also added while loop which works and gives same output
#while len(q) != 0:
# print('current Number is', q.pop(0), q)
#else:
# print('the queue is now empty') <file_sep>/Topic07-Files/lab07.01-read-write.py
# <NAME>
# program counts how many times it was run
filename = 'count.txt'
def readNumber():
with open(filename, 'r') as reader:
number = int(reader.read())
return number
def writeNumber(number):
with open(filename, 'w') as writer:
writer.write(str(number))
writeNumber(0)
print(readNumber())<file_sep>/Topic03-variables&state/lab03.03-div.py
# <NAME>
# Reads in two numbers, divides them and outputs integer result and
# the remainder
x = int(input('enter first number: '))
y = int(input('enter second number: '))
# makes output more dynamic with if statement
if x % y == 0:
# convert result of division to int
z = int(x / y)
print("{} divided by {} is {} ".format(x, y, z))
else:
# convert result of division to int
z = int(x / y)
remainder = x % y
print("{} divided by {} is {} with remainder {}".format(x, y, z, remainder))<file_sep>/Topic07-Files/lab07.02a-count copy.py
# <NAME>
# program counts how many times it was run
filename = 'count.txt'
def readNumber():
with open(filename, 'r') as reader:
number = int(reader.read()) # converts str to int
return number
def writeNumber(number):
with open(filename, 'w') as writer:
writer.write(str(number)) # write takes str
# main
number = readNumber()
number += 1
print('Program has been run {} times'.format(number))
writeNumber(number)<file_sep>/Topic03-variables&state/lab03.02-sub.py
# <NAME>
# Reads in two numbers and substruct the first one
# from the second one and outputs result
# using int to convert inputs to integers
x = int(input('enter first number: '))
y = int(input('enter second number: '))
# Substraction
z = x - y
# output the result
print("{} minus {} is {}".format(x, y, z)) | 22d3a26a9ef13e8c9f2282c9b8311cb1b9e296b5 | [
"Markdown",
"Python"
] | 42 | Python | mizydorek/pands-problems-2020 | a418dcc58e49dfbcb269e4524f676c1c6a0a6255 | a462bb5831dcfc642289482438f35a403b0fd11e |
refs/heads/master | <file_sep>export const installed_blueprints = [
//@BlueprintInsertion
{ name: 'UserProfile185949', human_name: 'User Profile', access_route: 'UserProfile185949'},
{ name: 'Maps185930', human_name: 'Maps', access_route: 'Maps185930', icon: 'map'},
{ name: 'Settings185908', human_name: 'Settings', access_route: 'Settings185908'},
{ name: 'Settings185893', human_name: 'Settings', access_route: 'Settings185893'},
{ name: 'NotificationList185892', human_name: 'Notification List', access_route: 'NotificationList185892'},
{ name: 'Maps185891', human_name: 'Maps', access_route: 'Maps185891', icon: 'map'},
// you can add more installed blueprints here
// access route is the route nate given to navigator
];
| 545ecf9f71eca4ea709b568d0a8cb53e01eeafec | [
"JavaScript"
] | 1 | JavaScript | crowdbotics-apps/mishu-23394 | 2836b4841a867b5558085e19037197ad56d0800d | a96495392ae62373a83a3ec7e5f0018c95e99167 |
refs/heads/master | <file_sep>/**
******************************************************************************
* @file Project/STM32L1xx_StdPeriph_Templates/stm32l1xx_conf.h
* @author MCD Application Team
* @version V1.1.1
* @date 13-April-2012
* @brief Library configuration file.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.st.com/software_license_agreement_liberty_v2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32L1xx_CONF_H
#define __STM32L1xx_CONF_H
/* Includes ------------------------------------------------------------------*/
/* Uncomment/Comment the line below to enable/disable peripheral header file inclusion */
#include "include/stm32l1xx_adc.h"
#include "include/stm32l1xx_aes.h"
#include "include/stm32l1xx_comp.h"
#include "include/stm32l1xx_crc.h"
#include "include/stm32l1xx_dac.h"
#include "include/stm32l1xx_dbgmcu.h"
#include "include/stm32l1xx_dma.h"
#include "include/stm32l1xx_exti.h"
#include "include/stm32l1xx_flash.h"
#include "include/stm32l1xx_fsmc.h"
#include "include/stm32l1xx_gpio.h"
#include "include/stm32l1xx_i2c.h"
#include "include/stm32l1xx_iwdg.h"
#include "include/stm32l1xx_lcd.h"
#include "include/stm32l1xx_opamp.h"
#include "include/stm32l1xx_pwr.h"
#include "include/stm32l1xx_rcc.h"
#include "include/stm32l1xx_rtc.h"
#include "include/stm32l1xx_sdio.h"
#include "include/stm32l1xx_spi.h"
#include "include/stm32l1xx_syscfg.h"
#include "include/stm32l1xx_tim.h"
#include "include/stm32l1xx_usart.h"
#include "include/stm32l1xx_wwdg.h"
#include "include/misc.h" /* High level functions for NVIC and SysTick (add-on to CMSIS functions) */
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Uncomment the line below to expanse the "assert_param" macro in the
Standard Peripheral Library drivers code */
/* #define USE_FULL_ASSERT 1 */
/* Exported macro ------------------------------------------------------------*/
#ifdef USE_FULL_ASSERT
/*******************************************************************************
* Macro Name : assert_param
* Description : The assert_param macro is used for function's parameters check.
* Input : - expr: If expr is false, it calls assert_failed function
* which reports the name of the source file and the source
* line number of the call that failed.
* If expr is true, it returns no value.
* Return : None
*******************************************************************************/
#define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ------------------------------------------------------- */
void assert_failed(uint8_t* file, uint32_t line);
#else
#define assert_param(expr) ((void)0)
#endif /* USE_FULL_ASSERT */
#endif /* __STM32L1xx_CONF_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 6d00b9befc8df39959720e4b96a2b8851dc1813c | [
"C"
] | 1 | C | shangma/stm32 | 26135866b84da4340f4b2c25ef84a55771f8e4a7 | 048984765c90b51bf1e865ad8b685df390488197 |
refs/heads/master | <repo_name>drwrose/doctors<file_sep>/resources/make_palette.py
import PIL.Image
import sys
# First, define an image with a 64-color palette that corresponds
# exactly to the Pebble Time's color space.
pal = PIL.Image.new('RGB', (8, 8))
for yi in range(8):
for xi in range(8):
pi = yi * 8 + xi
r = pi & 3
g = (pi >> 2) & 3
b = (pi >> 4) & 3
pal.putpixel((xi, yi), (r * 0x55, b * 0x55, g * 0x55))
pal = pal.convert("P", palette = PIL.Image.ADAPTIVE)
#pal.save('palette_64.png')
def make_palette(filename):
im = PIL.Image.open(filename)
if im.mode != 'RGB':
print "skipping"
return
# First, convert it to the 64-color Pebble Time palette.
im2 = im.quantize(palette = pal)
# Then, find the 16 most common colors in the resulting image.
palette = im2.getpalette()
colors = sorted(im2.getcolors(), reverse = True)
# And build a palette with just those 16 colors.
pal2 = []
for count, index in colors[:16]:
index *= 3
pal2 += palette[index : index + 3]
while len(pal2) < 768:
pal2 += palette[index : index + 3]
im2.putpalette(pal2)
# Now convert it again to that palette.
im = im.quantize(palette = im2)
im.save('palette/' + filename)
for filename in sys.argv[1:]:
print filename
make_palette(filename)
<file_sep>/src/battery_gauge.c
#include "doctors.h"
#include <pebble.h>
#include "battery_gauge.h"
#include "config_options.h"
#include "bwd.h"
BitmapWithData battery_gauge_empty;
BitmapWithData battery_gauge_charged;
BitmapWithData battery_gauge_mask;
BitmapWithData charging;
BitmapWithData charging_mask;
Layer *battery_gauge_layer;
void battery_gauge_layer_update_callback(Layer *me, GContext *ctx) {
if (config.battery_gauge == IM_off) {
return;
}
BatteryChargeState charge_state = battery_state_service_peek();
#ifdef BATTERY_HACK
time_t now = time(NULL);
charge_state.charge_percent = 100 - ((now / 2) % 11) * 10;
#endif // BATTERY_HACK
bool show_gauge = (config.battery_gauge != IM_when_needed) || charge_state.is_charging || (charge_state.is_plugged || charge_state.charge_percent <= 20);
if (!show_gauge) {
return;
}
GRect box = layer_get_frame(me);
box.origin.x = 0;
box.origin.y = 0;
GCompOp fg_mode;
GColor fg_color, bg_color;
#ifdef PBL_BW
GCompOp mask_mode;
fg_mode = GCompOpSet;
bg_color = GColorBlack;
fg_color = GColorWhite;
mask_mode = GCompOpAnd;
#else // PBL_BW
// In Basalt, we always use GCompOpSet because the icon includes its
// own alpha channel.
fg_mode = GCompOpSet;
bg_color = GColorWhite;
fg_color = GColorBlack;
#endif // PBL_BW
bool fully_charged = (!charge_state.is_charging && charge_state.is_plugged && charge_state.charge_percent >= 80);
#ifdef PBL_BW
// Draw the background of the layer.
if (charge_state.is_charging) {
// Erase the charging icon shape.
if (charging_mask.bitmap == NULL) {
charging_mask = rle_bwd_create(RESOURCE_ID_CHARGING_MASK);
}
graphics_context_set_compositing_mode(ctx, mask_mode);
graphics_draw_bitmap_in_rect(ctx, charging_mask.bitmap, box);
}
#endif // PBL_BW
if (config.battery_gauge != IM_digital || fully_charged) {
#ifdef PBL_BW
// Erase the battery gauge shape.
if (battery_gauge_mask.bitmap == NULL) {
battery_gauge_mask = rle_bwd_create(RESOURCE_ID_BATTERY_GAUGE_MASK);
}
graphics_context_set_compositing_mode(ctx, mask_mode);
graphics_draw_bitmap_in_rect(ctx, battery_gauge_mask.bitmap, box);
#endif // PBL_BW
} else {
// Erase a rectangle for text.
graphics_context_set_fill_color(ctx, bg_color);
graphics_fill_rect(ctx, GRect(BATTERY_GAUGE_FILL_X, BATTERY_GAUGE_FILL_Y, BATTERY_GAUGE_FILL_W, BATTERY_GAUGE_FILL_H), 0, GCornerNone);
}
if (charge_state.is_charging) {
// Actively charging. Draw the charging icon.
if (charging.bitmap == NULL) {
charging = rle_bwd_create(RESOURCE_ID_CHARGING);
//remap_colors_date(&charging);
}
graphics_context_set_compositing_mode(ctx, fg_mode);
graphics_draw_bitmap_in_rect(ctx, charging.bitmap, box);
}
if (fully_charged) {
// Plugged in but not charging. Draw the charged icon.
if (battery_gauge_charged.bitmap == NULL) {
battery_gauge_charged = rle_bwd_create(RESOURCE_ID_BATTERY_GAUGE_CHARGED);
//remap_colors_date(&battery_gauge_charged);
}
graphics_context_set_compositing_mode(ctx, fg_mode);
graphics_draw_bitmap_in_rect(ctx, battery_gauge_charged.bitmap, box);
} else if (config.battery_gauge != IM_digital) {
// Not plugged in. Draw the analog battery icon.
if (battery_gauge_empty.bitmap == NULL) {
battery_gauge_empty = rle_bwd_create(RESOURCE_ID_BATTERY_GAUGE_EMPTY);
//remap_colors_date(&battery_gauge_empty);
}
graphics_context_set_compositing_mode(ctx, fg_mode);
graphics_context_set_fill_color(ctx, fg_color);
graphics_draw_bitmap_in_rect(ctx, battery_gauge_empty.bitmap, box);
int bar_width = charge_state.charge_percent * BATTERY_GAUGE_BAR_W / 100;
graphics_fill_rect(ctx, GRect(BATTERY_GAUGE_BAR_X, BATTERY_GAUGE_BAR_Y, bar_width, BATTERY_GAUGE_BAR_H), 0, GCornerNone);
} else {
// Draw the digital text percentage.
char text_buffer[4];
snprintf(text_buffer, 4, "%d", charge_state.charge_percent);
GFont font = fonts_get_system_font(BATTERY_GAUGE_SYSTEM_FONT);
graphics_context_set_text_color(ctx, fg_color);
graphics_draw_text(ctx, text_buffer, font, GRect(BATTERY_GAUGE_FILL_X, BATTERY_GAUGE_FILL_Y + BATTERY_GAUGE_FONT_VSHIFT, BATTERY_GAUGE_FILL_W, BATTERY_GAUGE_FILL_H),
GTextOverflowModeTrailingEllipsis, GTextAlignmentCenter,
NULL);
}
}
// Update the battery guage.
void handle_battery(BatteryChargeState charge_state) {
layer_mark_dirty(battery_gauge_layer);
}
void init_battery_gauge(Layer *window_layer, int x, int y) {
battery_gauge_layer = layer_create(GRect(x, y, BATTERY_GAUGE_FILL_X + BATTERY_GAUGE_FILL_W, BATTERY_GAUGE_FILL_Y + BATTERY_GAUGE_FILL_H));
layer_set_update_proc(battery_gauge_layer, &battery_gauge_layer_update_callback);
layer_add_child(window_layer, battery_gauge_layer);
battery_state_service_subscribe(&handle_battery);
}
void deinit_battery_gauge() {
battery_state_service_unsubscribe();
layer_destroy(battery_gauge_layer);
battery_gauge_layer = NULL;
bwd_destroy(&battery_gauge_empty);
bwd_destroy(&battery_gauge_charged);
bwd_destroy(&battery_gauge_mask);
bwd_destroy(&charging);
bwd_destroy(&charging_mask);
}
void refresh_battery_gauge() {
layer_mark_dirty(battery_gauge_layer);
}
<file_sep>/depebble.py
import sys, zipfile, json, cStringIO
sys.path.append('/Users/drose/pebble-dev/PebbleSDK-current/Pebble/common/tools')
import pbpack
#pbwFilename = '/Users/drose/Downloads/doctors (1).pbw'
#pbwFilename = '/Users/drose/Downloads/Tiny_Doctors.pbw'
#pbwFilename = '/Users/drose/src/pebble/stack/build/stack.pbw'
pbwFilename = sys.argv[1]
assert pbwFilename
platforms = [ 'aplite', 'basalt' ]
subdir_prefixes = { 'aplite' : '', 'basalt' : 'basalt/' }
pbw = zipfile.ZipFile(pbwFilename, 'r')
appinfo = pbw.open('appinfo.json', 'r')
aid = json.load(appinfo)
mlist = aid['resources']['media']
for platform in platforms:
prefix = subdir_prefixes[platform]
resourcesData = pbw.read(prefix + 'app_resources.pbpack', 'r')
resources = cStringIO.StringIO(resourcesData)
rpack = pbpack.ResourcePack()
rpd = rpack.deserialize(resources)
print rpd
mi = 0
ri = 0
while mi < len(mlist) and ri < rpd.num_files:
name = mlist[mi]['name']
filename = mlist[mi]['file']
type = mlist[mi]['type']
numElements = 1
if type == 'png-trans':
numElements += 1
mi += 1
data = []
for i in range(numElements):
data.append(rpd.contents[ri])
ri += 1
print '%s, %s, %s: %s' % (platform, name, filename, map(len, data))
print '%s, %s, %s' % (platform, mi, ri)
<file_sep>/src/js/pebble-js-app.js
// Define the initial config default values. These defaults are used
// only if the Pebble is connected to the phone at the time of launch;
// otherwise, the defaults in init_default_options() are used instead.
var default_battery_gauge = 1;
var default_bluetooth_indicator = 1;
var default_second_hand = 0;
var default_hour_buzzer = 0;
var default_bluetooth_buzzer = 1;
var default_hurt = 1;
var default_show_date = 0;
var default_show_hour = 0;
var default_display_lang = 'en_US';
var battery_gauge;
var bluetooth_indicator;
var second_hand;
var hour_buzzer;
var bluetooth_buzzer;
var hurt;
var show_date;
var show_hour;
var display_lang;
function sent_ack(e) {
console.log("Message sent");
}
function sent_nack(e) {
console.log("Message not sent: " + e.error);
//console.log(e.error.message);
}
function logLocalStorage() {
// var keys = Object.keys(localStorage);
// console.log(" localStorage = {");
// for (var key in keys) {
// console.log(' "' + keys[key] + '" : ' + localStorage[keys[key]] + ',');
// }
// console.log(" }");
}
function getIntFromStorage(keyword, default_value) {
var value = localStorage.getItem("doctors:" + keyword);
if (!value) {
value = default_value;
}
value = parseInt(value);
if (isNaN(value)) {
value = default_value;
}
console.log(" " + keyword + ": " + value);
return value;
}
function getStringFromStorage(keyword, default_value) {
var value = localStorage.getItem("doctors:" + keyword);
if (!value) {
value = default_value;
}
console.log(" " + keyword + ": '" + value + "'");
return value;
}
var initialized = false;
function initialize() {
console.log("initialize: " + initialized);
if (initialized) {
return;
}
logLocalStorage();
battery_gauge = getIntFromStorage('battery_gauge', default_battery_gauge);
bluetooth_indicator = getIntFromStorage('bluetooth_indicator', default_bluetooth_indicator);
second_hand = getIntFromStorage('second_hand', default_second_hand);
hour_buzzer = getIntFromStorage('hour_buzzer', default_hour_buzzer);
bluetooth_buzzer = getIntFromStorage('bluetooth_buzzer', default_bluetooth_buzzer);
hurt = getIntFromStorage('hurt', default_hurt);
show_date = getIntFromStorage('show_date', default_show_date);
show_hour = getIntFromStorage('show_hour', default_show_hour);
display_lang = getStringFromStorage('display_lang', default_display_lang);
console.log(" battery_gauge: " + battery_gauge);
console.log(" bluetooth_indicator: " + bluetooth_indicator);
console.log(" second_hand: " + second_hand);
console.log(" hour_buzzer: " + hour_buzzer);
console.log(" bluetooth_buzzer: " + bluetooth_buzzer);
console.log(" hurt: " + hurt);
console.log(" show_date: " + show_date);
console.log(" show_hour: " + show_hour);
console.log(" display_lang: " + display_lang);
// At startup, send the current configuration to the Pebble--the
// phone storage keeps the authoritative state. We delay by 1
// second to give the Pebble a chance to set itself up for
// receiving messages.
setTimeout(function() {
var configuration = {
'battery_gauge' : battery_gauge,
'bluetooth_indicator' : bluetooth_indicator,
'second_hand' : second_hand,
'hour_buzzer' : hour_buzzer,
'bluetooth_buzzer' : bluetooth_buzzer,
'hurt' : hurt,
'show_date' : show_date,
'show_hour' : show_hour,
'display_lang' : display_lang,
};
console.log("sending init config: " + JSON.stringify(configuration));
Pebble.sendAppMessage(configuration, sent_ack, sent_nack);
}, 1000)
initialized = true;
};
Pebble.addEventListener("ready", function(e) {
console.log("ready");
initialize();
});
Pebble.addEventListener("showConfiguration", function(e) {
console.log("showConfiguration starting");
initialize();
var url = "http://s3.amazonaws.com/us.ddrose/pebble/doctors/html/doctors_3_0_configure.html?battery_gauge=" + battery_gauge + "&bluetooth_indicator=" + bluetooth_indicator + "&second_hand=" + second_hand + "&hour_buzzer=" + hour_buzzer + "&bluetooth_buzzer=" + bluetooth_buzzer + "&hurt=" + hurt + "&show_date=" + show_date + "&show_hour=" + show_hour + "&display_lang=" + display_lang;
console.log("showConfiguration: " + url);
var result = Pebble.openURL(url);
console.log("openURL result: " + result);
});
Pebble.addEventListener("webviewclosed", function(e) {
console.log("Configuration window closed");
console.log(e.type);
console.log(e.response);
if (e.response && e.response != 'CANCELLED') {
// Get the configuration from the webpage
var configuration = JSON.parse(decodeURIComponent(e.response));
// And record the longterm storage in the phone app.
battery_gauge = configuration["battery_gauge"];
localStorage.setItem("doctors:battery_gauge", battery_gauge);
bluetooth_indicator = configuration["bluetooth_indicator"];
localStorage.setItem("doctors:bluetooth_indicator", bluetooth_indicator);
second_hand = configuration["second_hand"];
localStorage.setItem("doctors:second_hand", second_hand);
hour_buzzer = configuration["hour_buzzer"];
localStorage.setItem("doctors:hour_buzzer", hour_buzzer);
bluetooth_buzzer = configuration["bluetooth_buzzer"];
localStorage.setItem("doctors:bluetooth_buzzer", bluetooth_buzzer);
hurt = configuration["hurt"];
localStorage.setItem("doctors:hurt", hurt);
show_date = configuration["show_date"];
localStorage.setItem("doctors:show_date", show_date);
show_hour = configuration["show_hour"];
localStorage.setItem("doctors:show_hour", show_hour);
display_lang = configuration["display_lang"];
localStorage.setItem("doctors:display_lang", display_lang);
// And send it on to Pebble.
console.log("sending runtime config: " + JSON.stringify(configuration));
Pebble.sendAppMessage(configuration, sent_ack, sent_nack);
logLocalStorage();
}
});
<file_sep>/src/pebble_compat.h
#ifndef PEBBLE_COMPAT_H
#define PEBBLE_COMPAT_H
// Some definitions to aid in cross-compatibility between mono and
// color builds.
// GColor static initializers, slightly different syntax needed on Basalt.
#if 0
#define GColorBlackInit GColorBlack
#define GColorWhiteInit GColorWhite
#define GColorClearInit GColorClear
#else // PBL_PLATFORM_APLITE
#define GColorBlackInit { GColorBlackARGB8 }
#define GColorWhiteInit { GColorWhiteARGB8 }
#define GColorClearInit { GColorClearARGB8 }
#endif // PBL_PLATFORM_APLITE
#endif
<file_sep>/html/doctors_2_4_1_configure.js
function makeOption(keyword, label, options) {
var role = "slider";
if (options) {
role = "select";
} else {
options = [[0, 'Off'], [1, 'On']];
}
document.write('<div data-role="fieldcontain"><label for="' + keyword + '">' + label + '</label><select name="' + keyword + '" id="' + keyword + '" data-role="' + role + '">');
var key = $.url().param(keyword);
for (var oi in options) {
if (key == options[oi][0]) {
document.write('<option value="' + options[oi][0] + '" selected>' + options[oi][1] + '</option>');
} else {
document.write('<option value="' + options[oi][0] + '">' + options[oi][1] + '</option>');
}
}
document.write('</select></div>');
};
makeOption("keep_battery_gauge", "Keep battery visible");
makeOption("keep_bluetooth_indicator", "Keep bluetooth visible");
makeOption("second_hand", "Blinking colon");
makeOption("hour_buzzer", "Vibrate at each hour");
makeOption("hurt", 'Include "War Doctor" at 8:30');
makeOption("show_date", "Show day/date");
// This list is duplicated in resources/make_lang.py.
var langs = [
[ 'en_US', 'English' ],
[ 'fr_FR', 'French' ],
[ 'it_IT', 'Italian' ],
[ 'es_ES', 'Spanish' ],
[ 'pt_PT', 'Portuguese' ],
[ 'de_DE', 'German' ],
[ 'nl_NL', 'Dutch' ],
[ 'da_DK', 'Danish' ],
[ 'sv_SE', 'Swedish' ],
[ 'is_IS' ,'Icelandic' ],
];
makeOption("display_lang", "Language for day", langs);
function saveOptions() {
var options = {
'keep_battery_gauge': parseInt($("#keep_battery_gauge").val(), 10),
'keep_bluetooth_indicator': parseInt($("#keep_bluetooth_indicator").val(), 10),
'second_hand': parseInt($("#second_hand").val(), 10),
'hour_buzzer': parseInt($("#hour_buzzer").val(), 10),
'hurt': parseInt($("#hurt").val(), 10),
'show_date': parseInt($("#show_date").val(), 10),
'display_lang': $("#display_lang").val(),
}
return options;
}
<file_sep>/src/config_options.h
#ifndef CONFIG_OPTIONS_H
#define CONFIG_OPTIONS_H
#include <pebble.h>
// These keys are used to communicate with Javascript. They match
// similar names in appinfo.json.
typedef enum {
CK_battery_gauge = 0,
CK_bluetooth_indicator = 1,
CK_second_hand = 2,
CK_hour_buzzer = 3,
CK_hurt = 4,
CK_show_date = 5,
CK_display_lang = 6,
CK_bluetooth_buzzer = 7,
CK_show_hour = 8,
} ConfigKey;
// This key is used to record the persistent storage.
#define PERSIST_KEY 0x5150
typedef enum {
IM_off = 0,
IM_when_needed = 1,
IM_always = 2,
IM_digital = 3,
} IndicatorMode;
typedef enum {
DL_english,
DL_french,
DL_italian,
DL_spanish,
DL_portuguese,
DL_german,
DL_dutch,
DL_danish,
DL_swedish,
DL_icelandic,
DL_num_languages,
} DisplayLanguages;
typedef struct {
IndicatorMode battery_gauge;
IndicatorMode bluetooth_indicator;
bool second_hand;
bool hour_buzzer;
bool bluetooth_buzzer;
bool hurt;
bool show_date;
bool show_hour;
DisplayLanguages display_lang;
} __attribute__((__packed__)) ConfigOptions;
extern ConfigOptions config;
void init_default_options();
void save_config();
void load_config();
void dropped_config_handler(AppMessageResult reason, void *context);
void receive_config_handler(DictionaryIterator *received, void *context);
void apply_config(); // implemented in the main program
#endif // CONFIG_OPTIONS_H
<file_sep>/src/test_bwd.h
#ifndef TEST_BWD_H
#define TEST_BWD_H
// This file is a mock stand-in to simulate some of the Pebble SDK
// interfaces--particularly using resources--in a desktop environment,
// for the sole purpose of making it easier to debug the code in
// bwd.c.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#define SUPPORT_RLE 1
typedef enum {
APP_LOG_LEVEL_ERROR = 1,
APP_LOG_LEVEL_WARNING = 50,
APP_LOG_LEVEL_INFO = 100,
APP_LOG_LEVEL_DEBUG = 200,
APP_LOG_LEVEL_DEBUG_VERBOSE = 255,
} AppLogLevel;
void app_log(uint8_t log_level, const char* src_filename, int src_line_number, const char* fmt, ...)
__attribute__((format(printf, 4, 5)));
typedef struct GSize {
int16_t w;
int16_t h;
} GSize;
typedef struct GPoint {
int16_t x;
int16_t y;
} GPoint;
typedef struct GRect {
GPoint origin;
GSize size;
} GRect;
#define GRect(x, y, w, h) ((GRect){{(x), (y)}, {(w), (h)}})
typedef struct GBitmap {
} GBitmap;
static GBitmap *gbitmap_create_with_resource(int resource_id) {
return NULL;
}
static GBitmap *gbitmap_create_with_data(void *bitmap_data) {
return NULL;
}
static void gbitmap_destroy(GBitmap *bitmap) { }
static GRect gbitmap_get_bounds(GBitmap *bitmap) { return GRect(0, 0, 0, 0); }
static int gbitmap_get_bytes_per_row(GBitmap *bitmap) { return 0; }
static void *gbitmap_get_data(GBitmap *bitmap) { return NULL; }
static size_t heap_bytes_used(void) { return 0; }
static size_t heap_bytes_free(void) { return 0; }
// Here's where we mock up the resource stuff.
typedef struct ResHandle {
size_t _size;
uint8_t *_data;
} ResHandle;
ResHandle resource_get_handle(int resource_id);
size_t resource_load_byte_range(ResHandle h, uint32_t start_offset, uint8_t *buffer, size_t num_bytes);
static size_t resource_size(ResHandle h) { return h._size; }
#endif
<file_sep>/resources/make_lang.py
#! /usr/bin/env python
import sys
import os
import getopt
import locale
help = """
make_lang.py
Re-run this script to generate lang_table.c and lang_characters.py in
the resources directory, based on the system language data.
make_lang.py [opts]
"""
# This list is duplicated in html/doctors_X_configure.js.
langs = [
[ 'en_US', 'English' ],
[ 'fr_FR', 'French' ],
[ 'it_IT', 'Italian' ],
[ 'es_ES', 'Spanish' ],
[ 'pt_PT', 'Portuguese' ],
[ 'de_DE', 'German' ],
[ 'nl_NL', 'Dutch' ],
[ 'da_DK', 'Danish' ],
[ 'sv_SE', 'Swedish' ],
[ 'is_IS' ,'Icelandic' ],
];
# Non-standard font required for these:
#langs += [
# [ 'el_GR', 'Greek' ],
# [ 'hu_HU', 'Hungarian' ],
# [ 'ru_RU', 'Russian' ],
# [ 'pl_PL', 'Polish' ],
# [ 'cs_CZ', 'Czech' ],
# ]
# Attempt to determine the directory in which we're operating.
rootDir = os.path.dirname(__file__) or '.'
resourcesDir = rootDir
neededChars = set()
def makeDates(generatedTable, li):
localeName, langName = langs[li]
print localeName
locale.setlocale(locale.LC_ALL, localeName + '.UTF-8')
weekdayNames = []
for sym in [locale.ABDAY_1, locale.ABDAY_2, locale.ABDAY_3, locale.ABDAY_4, locale.ABDAY_5, locale.ABDAY_6, locale.ABDAY_7]:
name = locale.nl_langinfo(sym)
name = name.decode('utf-8')
if name[-1] == '.':
# Sometimes the abbreviation ends with a dot.
name = name[:-1]
# Ensure the first letter is uppercase for consistency.
name = name[0].upper() + name[1:]
for char in name:
neededChars.add(char)
name = name.encode('utf-8')
if '"' in name or name.encode('string_escape') != name:
# The text has some fancy characters. We can't just pass
# string_escape, since that's not 100% C compatible.
# Instead, we'll aggressively hexify every character.
name = ''.join(map(lambda c: '\\x%02x' % (ord(c)), name))
weekdayNames.append(' \"%s\",' % (name))
print >> generatedTable, """ { "%s", {%s } }, // %s = %s""" % (localeName, ''.join(weekdayNames), li, langName)
def makeLang():
generatedTable = open('%s/lang_table.c' % (resourcesDir), 'w')
print >> generatedTable, '// Generated by make_lang.py\n'
numLangs = len(langs)
print >> generatedTable, "LangDef lang_table[%s] = {" % (numLangs)
for li in range(numLangs):
makeDates(generatedTable, li)
print >> generatedTable, "};\n"
print >> generatedTable, "int num_langs = %s;\n" % (numLangs)
generatedChars = open('%s/lang_characters.py' % (resourcesDir), 'w')
print >> generatedChars, '# Generated by make_lang.py\n'
chars = list(neededChars)
chars.sort()
print >> generatedChars, "characters = %s" % (map(ord, chars),)
print >> generatedChars, "# %s chars" % (len(chars))
# Main.
try:
opts, args = getopt.getopt(sys.argv[1:], 'h')
except getopt.error, msg:
usage(1, msg)
for opt, arg in opts:
if opt == '-h':
usage(0)
makeLang()
<file_sep>/setup.py
#! /usr/bin/env python
import PIL.Image
import PIL.ImageChops
import sys
import os
import getopt
from resources.make_rle import make_rle
from resources.peb_platform import getPlatformShape, getPlatformColor, getPlatformFilename, screenSizes
help = """
setup.py
This script pre-populates the package.json file and resources
directory for correctly building the 12 Doctors watchface.
setup.py [opts]
Options:
-s slices
Specifies the number of vertical slices of each face.
-p platform[,platform...]
Specifies the build platform (aplite, basalt, chalk, diorite, emery).
-x
Perform RLE compression of images.
-d
Compile for debugging. Specifically this enables "fast time",
so the faces change quickly. It also enables logging.
"""
def usage(code, msg = ''):
print >> sys.stderr, help
print >> sys.stderr, msg
sys.exit(code)
# Attempt to determine the directory in which we're operating.
rootDir = os.path.dirname(__file__) or '.'
resourcesDir = os.path.join(rootDir, 'resources')
# These are the min_x and min_y pairs for each of the 180 rows of
# GBitmapFormat8BitCircular-format images in Chalk.
circularBufferSize = [
(76, 103),
(71, 108),
(66, 113),
(63, 116),
(60, 119),
(57, 122),
(55, 124),
(52, 127),
(50, 129),
(48, 131),
(46, 133),
(45, 134),
(43, 136),
(41, 138),
(40, 139),
(38, 141),
(37, 142),
(36, 143),
(34, 145),
(33, 146),
(32, 147),
(31, 148),
(29, 150),
(28, 151),
(27, 152),
(26, 153),
(25, 154),
(24, 155),
(23, 156),
(22, 157),
(22, 157),
(21, 158),
(20, 159),
(19, 160),
(18, 161),
(18, 161),
(17, 162),
(16, 163),
(15, 164),
(15, 164),
(14, 165),
(13, 166),
(13, 166),
(12, 167),
(12, 167),
(11, 168),
(10, 169),
(10, 169),
(9, 170),
(9, 170),
(8, 171),
(8, 171),
(7, 172),
(7, 172),
(7, 172),
(6, 173),
(6, 173),
(5, 174),
(5, 174),
(5, 174),
(4, 175),
(4, 175),
(4, 175),
(3, 176),
(3, 176),
(3, 176),
(2, 177),
(2, 177),
(2, 177),
(2, 177),
(2, 177),
(1, 178),
(1, 178),
(1, 178),
(1, 178),
(1, 178),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(0, 179),
(1, 178),
(1, 178),
(1, 178),
(1, 178),
(1, 178),
(2, 177),
(2, 177),
(2, 177),
(2, 177),
(2, 177),
(3, 176),
(3, 176),
(3, 176),
(4, 175),
(4, 175),
(4, 175),
(5, 174),
(5, 174),
(5, 174),
(6, 173),
(6, 173),
(7, 172),
(7, 172),
(7, 172),
(8, 171),
(8, 171),
(9, 170),
(9, 170),
(10, 169),
(10, 169),
(11, 168),
(12, 167),
(12, 167),
(13, 166),
(13, 166),
(14, 165),
(15, 164),
(15, 164),
(16, 163),
(17, 162),
(18, 161),
(18, 161),
(19, 160),
(20, 159),
(21, 158),
(22, 157),
(22, 157),
(23, 156),
(24, 155),
(25, 154),
(26, 153),
(27, 152),
(28, 151),
(29, 150),
(31, 148),
(32, 147),
(33, 146),
(34, 145),
(36, 143),
(37, 142),
(38, 141),
(40, 139),
(41, 138),
(43, 136),
(45, 134),
(46, 133),
(48, 131),
(50, 129),
(52, 127),
(55, 124),
(57, 122),
(60, 119),
(63, 116),
(66, 113),
(71, 108),
(76, 103),
]
# [fill_rect, bar_rect, (font, vshift)] where rect is (x, y, w, h)
batteryGaugeSizes = {
'rect' : [(6, 0, 18, 10), (10, 3, 10, 4), ('GOTHIC_14', -4)],
'round' : [(6, 0, 18, 10), (10, 3, 10, 4), ('GOTHIC_14', -4)],
'emery' : [(8, 0, 25, 14), (13, 3, 15, 8), ('GOTHIC_18', -5)],
}
def enquoteStrings(strings):
""" Accepts a list of strings, returns a list of strings with
embedded quotation marks. """
quoted = []
for str in strings:
quoted.append('"%s"' % (str))
return quoted
def circularizeImage(source):
# Apply a circular crop to a 180x180 image, constructing a
# GBitmapFormat4BitPaletteCircular image. This will leave us
# 25792 pixels, which we store consecutively into a 208x124 pixel
# image.
assert source.size == (180, 180)
dest_size = (208, 124)
dest = PIL.Image.new(source.mode, dest_size)
if source.mode in ['P', 'L']:
dest.putpalette(source.getpalette())
dy = 0
dx = 0
for sy in range(180):
min_x, max_x = circularBufferSize[sy]
for sx in range(min_x, max_x + 1):
dest.putpixel((dx, dy), source.getpixel((sx, sy)))
dx += 1
if dx >= dest_size[0]:
dx = 0
dy += 1
assert dy == dest_size[1] and dx == 0
return dest
def makeDoctors(platform):
""" Makes the resource string for the list of doctors images. """
basenames = ['twelve', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven', 'hurt']
shape = getPlatformShape(platform)
screenWidth, screenHeight = screenSizes[shape]
slicePoints = [0]
for slice in range(numSlices):
next = (slice + 1) * screenWidth / numSlices
slicePoints.append(next)
buildDir = '%s/build' % (resourcesDir)
if not os.path.isdir(buildDir):
os.mkdir(buildDir)
doctorsImages = ''
doctorsIds = ''
already_basenames = set()
for basename in basenames:
doctorsIds += '{\n'
sourceFilename = getPlatformFilename('%s/%s.png' % (resourcesDir, basename), platform)
## sourceFilename = '%s/%s.png' % (resourcesDir, basename)
source = PIL.Image.open(sourceFilename)
assert source.size == (screenWidth, screenHeight)
for slice in range(numSlices):
# Make a vertical slice of the image.
resource_base = '%s_%s' % (basename.upper(), slice + 1)
if numSlices != 1:
# Make slices.
xf = slicePoints[slice]
xt = slicePoints[slice + 1]
box = (xf, 0, xt, screenHeight)
image = source.crop(box)
filename = 'build/%s_%s_of_%s_%s.png' % (basename, slice + 1, numSlices, platform)
image.save('%s/%s' % (resourcesDir, filename))
else:
# Special case--no slicing needed; just use the
# original full-sized image. However, we still copy
# it into the build folder, because the ~color~round
# version (for Chalk) will need to get circularized.
if shape == 'round':
image = circularizeImage(source)
else:
image = source
filename = 'build/%s_%s.png' % (basename, platform)
image.save('%s/%s' % (resourcesDir, filename))
if basename not in already_basenames:
already_basenames.add(basename)
doctorsImages += make_rle(filename, name = resource_base, useRle = supportRle, platforms = [platform])
doctorsIds += 'RESOURCE_ID_%s, ' % (resource_base)
doctorsIds += '},\n'
return slicePoints, doctorsImages, doctorsIds
def configWatch():
configH = open('%s/generated_config.h' % (resourcesDir), 'w')
configIn = open('%s/generated_config.h.in' % (resourcesDir), 'r').read()
print >> configH, configIn % {
'numSlices' : numSlices,
'supportRle' : int(supportRle),
'compileDebugging' : int(compileDebugging),
}
configC = open('%s/generated_config.c' % (resourcesDir), 'w')
configIn = open('%s/generated_config.c.in' % (resourcesDir), 'r').read()
print >> configC, configIn % {
}
resourceStr = ''
for platform in targetPlatforms:
shape = getPlatformShape(platform)
color = getPlatformColor(platform)
screenWidth, screenHeight = screenSizes[shape]
slicePoints, doctorsImages, doctorsIds = makeDoctors(platform)
resourceStr += doctorsImages
for ti in [1, 2, 3, 4]:
filename = 'tardis_%02d.png' % (ti)
name = 'TARDIS_%02d' % (ti)
# For most platforms, we'd rather avoid compressing the
# Tardis images, because we pull them out of the resource
# file multiple times per second, and we want to minimize
# wasted CPU utilization. However, on Emery, resource
# size is scarce, so there we compress it anyway.
compress = (platform == 'emery')
resourceStr += make_rle(filename, name = name, useRle = False, platforms = [platform], compress = compress, requirePalette = False)
for basename in ['dalek', 'k9']:
filename = '%s.png' % (basename)
name = basename.upper()
resourceStr += make_rle(filename, name = name, useRle = supportRle, platforms = [platform], requirePalette = True)
if color == 'bw':
for basename in ['tardis', 'dalek', 'k9']:
filename = '%s_mask.png' % (basename)
name = '%s_MASK' % (basename.upper())
resourceStr += make_rle(filename, name = name, useRle = supportRle, platforms = [platform])
bluetoothFilename = getPlatformFilename('resources/bluetooth_connected.png', platform)
im = PIL.Image.open(bluetoothFilename)
bluetoothSizes[platform] = im.size
resourceStr += make_rle('bluetooth_connected.png', name = 'BLUETOOTH_CONNECTED', useRle = supportRle, platforms = [platform])
resourceStr += make_rle('bluetooth_disconnected.png', name = 'BLUETOOTH_DISCONNECTED', useRle = supportRle, platforms = [platform])
if platform != 'aplite':
resourceStr += make_rle('quiet_time.png', name = 'QUIET_TIME', useRle = supportRle, platforms = [platform])
if color == 'bw':
resourceStr += make_rle('bluetooth_mask.png', name = 'BLUETOOTH_MASK', useRle = supportRle, platforms = [platform])
if platform != 'aplite':
resourceStr += make_rle('quiet_time_mask.png', name = 'QUIET_TIME_MASK', useRle = supportRle, platforms = [platform])
resourceStr += make_rle('battery_gauge_empty.png', name = 'BATTERY_GAUGE_EMPTY', useRle = supportRle, platforms = [platform])
resourceStr += make_rle('battery_gauge_charged.png', name = 'BATTERY_GAUGE_CHARGED', useRle = supportRle, platforms = [platform])
resourceStr += make_rle('charging.png', name = 'CHARGING', useRle = supportRle, platforms = [platform])
if color == 'bw':
resourceStr += make_rle('battery_gauge_mask.png', name = 'BATTERY_GAUGE_MASK', useRle = supportRle, platforms = [platform])
resourceStr += make_rle('charging_mask.png', name = 'CHARGING_MASK', useRle = supportRle, platforms = [platform])
configIn = open('%s/generated_config.h.per_platform_in' % (resourcesDir), 'r').read()
print >> configH, configIn % {
'platformUpper' : platform.upper(),
'screenWidth' : screenWidth,
'screenHeight' : screenHeight,
'batteryGaugeFillX' : batteryGaugeSizes[shape][0][0],
'batteryGaugeFillY' : batteryGaugeSizes[shape][0][1],
'batteryGaugeFillW' : batteryGaugeSizes[shape][0][2],
'batteryGaugeFillH' : batteryGaugeSizes[shape][0][3],
'batteryGaugeBarX' : batteryGaugeSizes[shape][1][0],
'batteryGaugeBarY' : batteryGaugeSizes[shape][1][1],
'batteryGaugeBarW' : batteryGaugeSizes[shape][1][2],
'batteryGaugeBarH' : batteryGaugeSizes[shape][1][3],
'batteryGaugeFont' : batteryGaugeSizes[shape][2][0],
'batteryGaugeVshift' : batteryGaugeSizes[shape][2][1],
'bluetoothSizeX' : bluetoothSizes[platform][0],
'bluetoothSizeY' : bluetoothSizes[platform][1],
}
configIn = open('%s/generated_config.c.per_platform_in' % (resourcesDir), 'r').read()
print >> configC, configIn % {
'platformUpper' : platform.upper(),
'doctorsIds' : doctorsIds,
'slicePoints' : ', '.join(map(str, slicePoints)),
}
resourceStr += make_rle('mins_background.png', name = 'MINS_BACKGROUND', useRle = supportRle, platforms = targetPlatforms, color = 'bw')
resourceStr += make_rle('hours_background.png', name = 'HOURS_BACKGROUND', useRle = supportRle, platforms = targetPlatforms, color = 'bw')
resourceStr += make_rle('date_background.png', name = 'DATE_BACKGROUND', useRle = supportRle, platforms = targetPlatforms, color = 'bw')
resourceIn = open('%s/package.json.in' % (rootDir), 'r').read()
resource = open('%s/package.json' % (rootDir), 'w')
print >> resource, resourceIn % {
'targetPlatforms' : ', '.join(enquoteStrings(targetPlatforms)),
'resourceStr' : resourceStr,
}
# Main.
try:
opts, args = getopt.getopt(sys.argv[1:], 's:p:dxh')
except getopt.error, msg:
usage(1, msg)
numSlices = 1
compileDebugging = False
supportRle = False
targetPlatforms = [ ]
for opt, arg in opts:
if opt == '-s':
numSlices = int(arg)
elif opt == '-p':
targetPlatforms += arg.split(',')
elif opt == '-d':
compileDebugging = True
elif opt == '-x':
supportRle = True
elif opt == '-h':
usage(0)
if not targetPlatforms:
targetPlatforms = [ 'aplite', 'basalt', 'chalk', 'diorite', 'emery' ]
bluetoothSizes = {} # filled in by configWatch()
configWatch()
<file_sep>/src/battery_gauge.h
#ifndef BATTERY_GAUGE_H
#define BATTERY_GAUGE_H
// Define this to update the battery gauge every two seconds for development.
//#define BATTERY_HACK 1
void init_battery_gauge(Layer *window_layer, int x, int y);
void deinit_battery_gauge();
void refresh_battery_gauge();
#endif // BATTERY_GAUGE_H
<file_sep>/src/doctors.c
#include <pebble.h>
#include "doctors.h"
#include "assert.h"
#include "bluetooth_indicator.h"
#include "battery_gauge.h"
#include "config_options.h"
#include "bwd.h"
#include "lang_table.h"
#include "qapp_log.h"
#include "../resources/lang_table.c"
#include "../resources/generated_config.h"
#include "../resources/generated_config.c"
// frame placements based on screen shape.
#if defined(PBL_PLATFORM_EMERY)
// Emery 200x228
GRect mm_layer_box = { { 132, 182 }, { 68, 48 } };
GRect mins_background_box = { { 0, 4 }, { 68, 42 } };
GRect mins_mm_text_box = { { 1, 0 }, { 81, 58 } };
GRect hhmm_layer_box = { { 86, 182 }, { 114, 48 } };
GRect hours_background_box = { { 0, 4 }, { 114, 42 } };
GRect hours_text_box = { { -20, 0 }, { 68, 48 } };
GRect mins_hhmm_text_box = { { 48, 0 }, { 132, 48 } };
GRect date_layer_box = { { 0, 194 }, { 68, 34 } };
GRect date_background_box = { { 0, 0 }, { 68, 34 } };
GRect date_text_box = { { 0, 0 }, { 68, 34 } };
#elif defined(PBL_ROUND)
// Round 180x180 (Chalk)
GRect mm_layer_box = { { 44, 151 }, { 92, 29 } };
GRect mins_background_box = { { 0, 0 }, { 92, 29 } };
GRect mins_mm_text_box = { { 22, -6 }, { 60, 35 } };
GRect hhmm_layer_box = { { 30, 146 }, { 120, 34 } };
GRect hours_background_box = { { 0, 0 }, { 120, 34 } };
GRect hours_text_box = { { 3, -5 }, { 50, 35 } };
GRect mins_hhmm_text_box = { { 52, -5 }, { 97, 35 } };
GRect date_layer_box = { { 49, 0 }, { 82, 22 } };
GRect date_background_box = { { 0, 0 }, { 82, 22 } };
GRect date_text_box = { { 16, -2 }, { 50, 25 } };
#else
// Rect 144x168 (Aplite, Basalt, Diorite)
GRect mm_layer_box = { { 94, 134 }, { 50, 35 } };
GRect mins_background_box = { { 0, 3 }, { 50, 31 } };
GRect mins_mm_text_box = { { 1, 0 }, { 60, 35 } };
GRect hhmm_layer_box = { { 60, 134 }, { 84, 35 } };
GRect hours_background_box = { { 0, 3 }, { 84, 31 } };
GRect hours_text_box = { { -15, 0 }, { 50, 35 } };
GRect mins_hhmm_text_box = { { 35, 0 }, { 97, 35 } };
GRect date_layer_box = { { 0, 143 }, { 50, 25 } };
GRect date_background_box = { { 0, 0 }, { 50, 25 } };
GRect date_text_box = { { 0, 0 }, { 50, 25 } };
#endif // shape
// The frequency throughout the day at which the buzzer sounds, in seconds.
#define BUZZER_FREQ 3600
// Amount of time, in seconds, to ring the buzzer before the hour.
#define BUZZER_ANTICIPATE 2
// Number of milliseconds per animation frame
#define ANIM_TICK_MS 50
// Number of frames of animation
#define NUM_TRANSITION_FRAMES_HOUR 24
#define NUM_TRANSITION_FRAMES_STARTUP 10
GFont mm_font;
GFont date_font;
Window *window;
BitmapWithData mins_background;
BitmapWithData hours_background;
BitmapWithData date_background;
// The horizontal center point of the sprite.
int sprite_cx = 0;
bool any_obstructed_area = false;
Layer *face_layer; // The "face", in both senses (and also the hour indicator).
Layer *mm_layer; // The time indicator when minutes only are displayed.
Layer *hhmm_layer; // The time indicator when hours and minutes are displayed.
Layer *date_layer; // optional day/date display.
int face_value; // The current face on display (or transitioning into)
// The current face bitmap, each slice:
typedef struct {
int face_value;
BitmapWithData face_image;
} VisibleFace;
VisibleFace visible_face[NUM_SLICES];
#ifndef PBL_BW
// A table of alternate color schemes for the Dalek bitmap (color
// builds only, of course).
typedef struct {
uint8_t cb_argb8, c1_argb8, c2_argb8, c3_argb8;
} ColorMap;
ColorMap dalek_colors[] = {
{ GColorBlackARGB8, GColorWhiteARGB8, GColorLightGrayARGB8, GColorRedARGB8, },
{ GColorBlackARGB8, GColorWhiteARGB8, GColorLightGrayARGB8, GColorOrangeARGB8, },
{ GColorBlackARGB8, GColorWhiteARGB8, GColorDarkGrayARGB8, GColorWhiteARGB8, },
{ GColorBlackARGB8, GColorWhiteARGB8, GColorYellowARGB8, GColorWhiteARGB8, },
{ GColorBlackARGB8, GColorWhiteARGB8, GColorLightGrayARGB8, GColorBlueARGB8, },
{ GColorBlackARGB8, GColorWhiteARGB8, GColorLightGrayARGB8, GColorYellowARGB8, },
{ GColorBlackARGB8, GColorWhiteARGB8, GColorLightGrayARGB8, GColorJaegerGreenARGB8, },
{ GColorBlackARGB8, GColorWhiteARGB8, GColorVeryLightBlueARGB8, GColorBabyBlueEyesARGB8, },
};
#define NUM_DALEK_COLORS (sizeof(dalek_colors) / sizeof(ColorMap))
#endif // PBL_BW
// The transitioning face slice.
int next_face_value;
int next_face_slice;
BitmapWithData next_face_image;
bool face_transition; // True if the face is in transition
bool wipe_direction; // True for left-to-right, False for right-to-left.
bool anim_direction; // True to reverse tardis rotation.
int transition_frame; // Frame number of current transition
int num_transition_frames; // Total frames for transition
// The mask and image for the moving sprite across the wipe.
int sprite_sel;
BitmapWithData sprite_mask;
BitmapWithData sprite;
int sprite_width;
// Triggered at ANIM_TICK_MS intervals for transition animations; also
// triggered occasionally to check the hour buzzer.
AppTimer *anim_timer = NULL;
// Triggered at 500 ms intervals to blink the colon.
AppTimer *blink_timer = NULL;
int hour_value; // The decimal hour value displayed (if enabled).
int minute_value; // The current minute value displayed
int second_value; // The current second value displayed. Actually we only blink the colon, rather than actually display a value, but whatever.
bool hide_colon; // Set true every half-second to blink the colon off.
int last_buzz_hour; // The hour at which we last sounded the buzzer.
int day_value; // The current day-of-the-week displayed (if enabled).
int date_value; // The current date-of-the-week displayed (if enabled).
#define SPRITE_TARDIS 0
#define SPRITE_K9 1
#define SPRITE_DALEK 2
#define NUM_SPRITES 3
typedef struct {
int tardis;
bool flip_x;
} TardisFrame;
#define NUM_TARDIS_FRAMES 7
TardisFrame tardis_frames[NUM_TARDIS_FRAMES] = {
{ RESOURCE_ID_TARDIS_01, false },
{ RESOURCE_ID_TARDIS_02, false },
{ RESOURCE_ID_TARDIS_03, false },
{ RESOURCE_ID_TARDIS_04, false },
{ RESOURCE_ID_TARDIS_04, true },
{ RESOURCE_ID_TARDIS_03, true },
{ RESOURCE_ID_TARDIS_02, true }
};
static const uint32_t tap_segments[] = { 75, 100, 75 };
VibePattern tap = {
tap_segments,
3,
};
// Reverse the bits of a byte.
// http://www.graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
uint8_t reverse_bits(uint8_t b) {
return ((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
}
// Reverse the high nibble and low nibble of a byte.
uint8_t reverse_nibbles(uint8_t b) {
return ((b & 0xf) << 4) | ((b >> 4) & 0xf);
}
// Horizontally flips the indicated GBitmap in-place. Requires
// that the width be a multiple of 8 pixels.
void flip_bitmap_x(GBitmap *image) {
if (image == NULL) {
// Trivial no-op.
return;
}
int height = gbitmap_get_bounds(image).size.h;
int width = gbitmap_get_bounds(image).size.w;
int pixels_per_byte = 8;
#ifndef PBL_BW
switch (gbitmap_get_format(image)) {
case GBitmapFormat1Bit:
case GBitmapFormat1BitPalette:
pixels_per_byte = 8;
break;
case GBitmapFormat2BitPalette:
pixels_per_byte = 4;
break;
case GBitmapFormat4BitPalette:
pixels_per_byte = 2;
break;
case GBitmapFormat8Bit:
case GBitmapFormat8BitCircular:
pixels_per_byte = 1;
break;
}
#endif // PBL_BW
assert(width % pixels_per_byte == 0); // This must be an even divisor, by our convention.
int width_bytes = width / pixels_per_byte;
int stride = gbitmap_get_bytes_per_row(image);
assert(stride >= width_bytes);
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "flip_bitmap_x, width_bytes = %d, stride=%d, format=%d", width_bytes, stride, gbitmap_get_format(image));
uint8_t *data = gbitmap_get_data(image);
for (int y = 0; y < height; ++y) {
uint8_t *row = data + y * stride;
switch (pixels_per_byte) {
case 8:
for (int x1 = (width_bytes - 1) / 2; x1 >= 0; --x1) {
int x2 = width_bytes - 1 - x1;
uint8_t b = reverse_bits(row[x1]);
row[x1] = reverse_bits(row[x2]);
row[x2] = b;
}
break;
#ifndef PBL_BW
case 4:
// TODO.
break;
case 2:
for (int x1 = (width_bytes - 1) / 2; x1 >= 0; --x1) {
int x2 = width_bytes - 1 - x1;
uint8_t b = reverse_nibbles(row[x1]);
row[x1] = reverse_nibbles(row[x2]);
row[x2] = b;
}
break;
case 1:
for (int x1 = (width_bytes - 1) / 2; x1 >= 0; --x1) {
int x2 = width_bytes - 1 - x1;
uint8_t b = row[x1];
row[x1] = row[x2];
row[x2] = b;
}
break;
#endif // PBL_BW
}
}
}
int check_buzzer() {
// Rings the buzzer if it's almost time for the hour to change.
// Returns the amount of time in ms to wait for the next buzzer.
time_t now = time(NULL);
// What hour is it right now, including the anticipate offset?
int this_hour = (now + BUZZER_ANTICIPATE) / BUZZER_FREQ;
if (this_hour != last_buzz_hour) {
if (last_buzz_hour != -1) {
// Time to ring the buzzer.
if (config.hour_buzzer) {
if (!poll_quiet_time_state()) {
vibes_enqueue_custom_pattern(tap);
}
//vibes_double_pulse();
}
}
// Now make sure we don't ring the buzzer again for this hour.
last_buzz_hour = this_hour;
}
int next_hour = this_hour + 1;
int next_buzzer_time = next_hour * BUZZER_FREQ - BUZZER_ANTICIPATE;
return (next_buzzer_time - now) * 1000;
}
void set_next_timer();
// Triggered at ANIM_TICK_MS intervals for transition animations; also
// triggered occasionally to check the hour buzzer.
void handle_timer(void *data) {
anim_timer = NULL; // When the timer is handled, it is implicitly canceled.
if (face_transition) {
layer_mark_dirty(face_layer);
}
set_next_timer();
}
// Triggered at 500 ms intervals to blink the colon.
void handle_blink(void *data) {
blink_timer = NULL; // When the timer is handled, it is implicitly canceled.
if (config.second_hand) {
hide_colon = true;
layer_mark_dirty(mm_layer);
layer_mark_dirty(hhmm_layer);
}
if (blink_timer != NULL) {
app_timer_cancel(blink_timer);
blink_timer = NULL;
}
}
// Ensures the animation/buzzer timer is running.
void set_next_timer() {
if (anim_timer != NULL) {
app_timer_cancel(anim_timer);
anim_timer = NULL;
}
int next_buzzer_ms = check_buzzer();
if (face_transition) {
// If the animation is underway, we need to fire the timer at
// ANIM_TICK_MS intervals.
anim_timer = app_timer_register(ANIM_TICK_MS, &handle_timer, 0);
} else {
// Otherwise, we only need a timer to tell us to buzz at (almost)
// the top of the hour.
anim_timer = app_timer_register(next_buzzer_ms, &handle_timer, 0);
}
}
void stop_transition() {
face_transition = false;
// Release the transition resources.
next_face_value = -1;
next_face_slice = -1;
bwd_destroy(&next_face_image);
bwd_destroy(&sprite_mask);
bwd_destroy(&sprite);
// Stop the transition timer.
if (anim_timer != NULL) {
app_timer_cancel(anim_timer);
anim_timer = NULL;
}
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "stop_transition(), memory used, free is %d, %d", heap_bytes_used(), heap_bytes_free());
}
void start_transition(int face_new, bool for_startup) {
if (face_transition) {
stop_transition();
}
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "start_transition(%d, %d)", face_new, for_startup);
// Update the face display.
face_value = face_new;
face_transition = true;
transition_frame = 0;
num_transition_frames = NUM_TRANSITION_FRAMES_HOUR;
if (for_startup) {
// Force the right-to-left TARDIS transition at startup.
wipe_direction = false;
sprite_sel = SPRITE_TARDIS;
anim_direction = false;
// We used to want this to go super-fast at startup, to match the
// speed of the system wipe, but we no longer try to do this
// (since the system wipe is different nowadays anyway).
//num_transition_frames = NUM_TRANSITION_FRAMES_STARTUP;
} else {
// Choose a random transition at the top of the hour.
wipe_direction = (rand() % 2) != 0; // Sure, it's not 100% even, but whatever.
sprite_sel = (rand() % NUM_SPRITES);
anim_direction = (rand() % 2) != 0;
}
// Initialize the sprite.
switch (sprite_sel) {
case SPRITE_TARDIS:
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "starting transition TARDIS, memory used, free is %d, %d", heap_bytes_used(), heap_bytes_free());
#ifdef PBL_BW
sprite_mask = rle_bwd_create(RESOURCE_ID_TARDIS_MASK);
#endif // PBL_BW
//sprite_width = gbitmap_get_bounds(sprite_mask.bitmap).size.w;
sprite_width = 112;
sprite_cx = 72;
break;
case SPRITE_K9:
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "starting transition K9, memory used, free is %d, %d", heap_bytes_used(), heap_bytes_free());
#ifdef PBL_BW
sprite_mask = rle_bwd_create(RESOURCE_ID_K9_MASK);
#endif // PBL_BW
sprite = rle_bwd_create(RESOURCE_ID_K9);
if (sprite.bitmap != NULL) {
sprite_width = gbitmap_get_bounds(sprite.bitmap).size.w;
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "k9 loaded %p, format = %d", sprite.bitmap, gbitmap_get_format(sprite.bitmap));
}
sprite_cx = 41;
if (wipe_direction) {
flip_bitmap_x(sprite_mask.bitmap);
flip_bitmap_x(sprite.bitmap);
sprite_cx = sprite_width - sprite_cx;
}
break;
case SPRITE_DALEK:
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "starting transition DALEK, memory used, free is %d, %d", heap_bytes_used(), heap_bytes_free());
#ifdef PBL_BW
sprite_mask = rle_bwd_create(RESOURCE_ID_DALEK_MASK);
#endif // PBL_BW
sprite = rle_bwd_create(RESOURCE_ID_DALEK);
if (sprite.bitmap != NULL) {
sprite_width = gbitmap_get_bounds(sprite.bitmap).size.w;
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "dalek loaded %p, format = %d", sprite.bitmap, gbitmap_get_format(sprite.bitmap));
#ifndef PBL_BW
// Pick a random color scheme for the Dalek.
int color_sel = (rand() % NUM_DALEK_COLORS);
ColorMap *cm = &dalek_colors[color_sel];
bwd_remap_colors(&sprite, (GColor8){.argb=cm->cb_argb8}, (GColor8){.argb=cm->c1_argb8}, (GColor8){.argb=cm->c2_argb8}, (GColor8){.argb=cm->c3_argb8}, false);
#endif // PBL_BW
}
sprite_cx = 74;
if (wipe_direction) {
flip_bitmap_x(sprite_mask.bitmap);
flip_bitmap_x(sprite.bitmap);
sprite_cx = sprite_width - sprite_cx;
}
break;
}
// Start the transition timer.
layer_mark_dirty(face_layer);
set_next_timer();
}
// Loads next_face_image with the si'th slice of face_value. No-op if
// it's already loaded.
void
load_next_face_slice(int si, int face_value) {
if (next_face_value != face_value || next_face_slice != si) {
bwd_destroy(&next_face_image);
next_face_value = face_value;
next_face_slice = si;
int resource_id = face_resource_ids[face_value][si];
next_face_image = rle_bwd_create(resource_id);
#ifdef PBL_COLOR
assert(next_face_image.bitmap == NULL || gbitmap_get_format(next_face_image.bitmap) == GBitmapFormat4BitPalette || gbitmap_get_format(next_face_image.bitmap) == GBitmapFormat2BitPalette);
#endif // PBL_COLOR
}
}
// Ensures the bitmap for face_value is loaded for slice si. No-op if
// it's already loaded.
void
load_face_slice(int si, int face_value) {
if (visible_face[si].face_value != face_value) {
bwd_destroy(&(visible_face[si].face_image));
visible_face[si].face_value = face_value;
int resource_id = face_resource_ids[face_value][si];
visible_face[si].face_image = rle_bwd_create(resource_id);
}
}
#if NUM_SLICES == 1
// The following code is the single-slice version of face-drawing,
// assuming that face bitmaps are complete and full-screen.
// Draw the face in transition from one to the other, with the
// division line at wipe_x.
// Draws the indicated fullscreen bitmap only to the left of wipe_x.
void draw_fullscreen_wiped(GContext *ctx, BitmapWithData image, int wipe_x) {
if (wipe_x <= 0) {
// Trivial no-op.
return;
}
if (wipe_x > SCREEN_WIDTH) {
// Trivial fill.
wipe_x = SCREEN_WIDTH;
}
GRect destination;
destination.origin.x = 0;
destination.origin.y = 0;
destination.size.w = wipe_x;
destination.size.h = SCREEN_HEIGHT;
if (image.bitmap == NULL) {
// The bitmap wasn't loaded successfully; just clear the region.
// This is a fallback.
graphics_context_set_fill_color(ctx, GColorBlack);
graphics_fill_rect(ctx, destination, 0, GCornerNone);
} else {
// Draw the bitmap in the region.
#ifdef PBL_ROUND
// The round model, complicated because we have created a concept
// of a GBitmapFormat4BitPaletteCircular: it's a 180x180 4-bit
// palette image, with only a subset of pixels included that are
// within the visible circle. It's exactly the same subset
// described in the GBitmapFormat8BitCircular format (used by the
// framebuffer), but we have to do the drawing operations
// ourselves.
uint8_t *source_data = gbitmap_get_data(image.bitmap);
GColor *source_palette = gbitmap_get_palette(image.bitmap);
int num_bits;
switch (gbitmap_get_format(image.bitmap)) {
case GBitmapFormat4BitPalette:
num_bits = 4;
break;
case GBitmapFormat2BitPalette:
num_bits = 2;
break;
default:
assert(false);
num_bits = 1;
}
int bit_mask = (1 << num_bits) - 1;
int pixels_per_byte = 8 / num_bits;
uint8_t *sp = source_data;
int bit_shift = 8 - num_bits;
GBitmap *fb = graphics_capture_frame_buffer(ctx);
for (int y = 0; y < SCREEN_HEIGHT; ++y) {
GBitmapDataRowInfo info = gbitmap_get_data_row_info(fb, y);
uint8_t *row = &info.data[info.min_x];
uint8_t *dp = row;
int stop_x = info.max_x < wipe_x ? info.max_x : wipe_x;
if (stop_x < info.min_x) {
stop_x = info.min_x - 1;
}
for (int x = info.min_x; x <= stop_x; ++x) {
int value = ((*sp) >> bit_shift) & bit_mask;
*dp = source_palette[value].argb;
++dp;
bit_shift -= num_bits;
if (bit_shift < 0) {
bit_shift = 8 - num_bits;
++sp;
}
}
if (stop_x < info.max_x) {
int skip_pixels = info.max_x - stop_x;
// Here we are at the end of the row; skip skip_pixels of the
// source.
sp += skip_pixels / pixels_per_byte;
int additional_pixels = skip_pixels % pixels_per_byte;
while (additional_pixels > 0) {
bit_shift -= num_bits;
if (bit_shift < 0) {
bit_shift = 8 - num_bits;
++sp;
}
--additional_pixels;
}
}
}
graphics_release_frame_buffer(ctx, fb);
#else // PBL_ROUND
// The rectangular model, pretty straightforward.
graphics_draw_bitmap_in_rect(ctx, image.bitmap, destination);
#endif // PBL_ROUND
}
}
// Draws the indicated fullscreen bitmap completely.
void draw_fullscreen_complete(GContext *ctx, BitmapWithData image) {
draw_fullscreen_wiped(ctx, image, SCREEN_WIDTH);
}
void draw_face_transition(Layer *me, GContext *ctx, int wipe_x) {
if (wipe_direction) {
// Wiping left-to-right.
// Draw the old face, and draw the visible portion of the new face
// on top of it.
draw_fullscreen_complete(ctx, visible_face[0].face_image);
load_next_face_slice(0, face_value);
draw_fullscreen_wiped(ctx, next_face_image, wipe_x);
} else {
// Wiping right-to-left.
// Draw the new face, and then draw the visible portion of the old
// face on top of it.
load_next_face_slice(0, face_value);
draw_fullscreen_complete(ctx, next_face_image);
draw_fullscreen_wiped(ctx, visible_face[0].face_image, wipe_x);
}
}
void draw_face_complete(Layer *me, GContext *ctx) {
load_face_slice(0, face_value);
draw_fullscreen_complete(ctx, visible_face[0].face_image);
}
#else // NUM_SLICES
// The following code is the multi-slice version of face-drawing,
// which is complicated because we have pre-sliced all of the face
// bitmaps into NUM_SLICES vertical slices, so we can load and draw
// these slices one at a time. During a transition, we display n
// slices of the old face, and NUM_SLICES - n - 1 of the new face,
// with a single slice that might have parts of both faces visible at
// once. So we only have to double up on that one transitioning
// slice, which helps the RAM utilization a great deal.
// In practice, this causes visible timing hiccups as we load each
// slice during the animation, and it's not actually necessary as the
// 4-bit palette versions of these bitmaps do fit entirely in memory.
// So this is no longer used.
// Draws the indicated face_value for slice si.
void
draw_face_slice(Layer *me, GContext *ctx, int si) {
GRect destination = layer_get_frame(me);
destination.origin.x = slice_points[si];
destination.origin.y = 0;
destination.size.w = slice_points[si + 1] - slice_points[si];
if (visible_face[si].face_image.bitmap == NULL) {
// The bitmap wasn't loaded successfully; just clear the
// region. This is a fallback.
graphics_context_set_fill_color(ctx, GColorBlack);
graphics_fill_rect(ctx, destination, 0, GCornerNone);
} else {
// The bitmap was loaded successfully, so draw it.
graphics_draw_bitmap_in_rect(ctx, visible_face[si].face_image.bitmap, destination);
}
}
// Draw the face in transition from one to the other, with the
// division line at wipe_x.
void draw_face_transition(Layer *me, GContext *ctx, int wipe_x) {
// The slice number within which the transition is currently
// happening.
int wipe_slice = (wipe_x * NUM_SLICES) / SCREEN_WIDTH;
if (wipe_slice < 0) {
wipe_slice = 0;
} else if (wipe_slice >= NUM_SLICES) {
wipe_slice = NUM_SLICES - 1;
}
GRect destination;
destination.origin.x = slice_points[wipe_slice];
destination.origin.y = 0;
destination.size.w = slice_points[wipe_slice + 1] - slice_points[wipe_slice];
destination.size.h = SCREEN_HEIGHT;
if (wipe_direction) {
// Wiping left-to-right.
// Draw the old face within the wipe_slice, and draw the visible
// portion of the new face on top of it.
draw_face_slice(me, ctx, wipe_slice);
if (wipe_x > destination.origin.x) {
load_next_face_slice(wipe_slice, face_value);
destination.size.w = wipe_x - destination.origin.x;
if (next_face_image.bitmap == NULL) {
graphics_context_set_fill_color(ctx, GColorBlack);
graphics_fill_rect(ctx, destination, 0, GCornerNone);
} else {
graphics_draw_bitmap_in_rect(ctx, next_face_image.bitmap, destination);
}
}
// Draw all of the slices left of the wipe_slice in the new
// face.
for (int si = 0; si < wipe_slice; ++si) {
load_face_slice(si, face_value);
draw_face_slice(me, ctx, si);
}
// Draw all of the slices right of the wipe_slice
// in the old face.
for (int si = wipe_slice + 1; si < NUM_SLICES; ++si) {
draw_face_slice(me, ctx, si);
}
} else {
// Wiping right-to-left.
// Draw the new face within the wipe_slice, and then draw
// the visible portion of the old face on top of it.
load_next_face_slice(wipe_slice, face_value);
if (next_face_image.bitmap == NULL) {
graphics_context_set_fill_color(ctx, GColorBlack);
graphics_fill_rect(ctx, destination, 0, GCornerNone);
} else {
graphics_draw_bitmap_in_rect(ctx, next_face_image.bitmap, destination);
}
if (wipe_x > destination.origin.x) {
destination.size.w = wipe_x - destination.origin.x;
if (visible_face[wipe_slice].face_image.bitmap == NULL) {
graphics_context_set_fill_color(ctx, GColorBlack);
graphics_fill_rect(ctx, destination, 0, GCornerNone);
} else {
graphics_draw_bitmap_in_rect(ctx, visible_face[wipe_slice].face_image.bitmap, destination);
}
}
// Draw all of the slices left of the wipe_slice in the old
// face.
for (int si = 0; si < wipe_slice; ++si) {
draw_face_slice(me, ctx, si);
}
// Draw all of the slices right of the wipe_slice
// in the new face.
for (int si = wipe_slice + 1; si < NUM_SLICES; ++si) {
load_face_slice(si, face_value);
draw_face_slice(me, ctx, si);
}
}
}
void draw_face_complete(Layer *me, GContext *ctx) {
for (int si = 0; si < NUM_SLICES; ++si) {
load_face_slice(si, face_value);
draw_face_slice(me, ctx, si);
}
}
#endif // NUM_SLICES
void root_layer_update_callback(Layer *me, GContext *ctx) {
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "root_layer");
// Only bother filling in the root layer if part of the window is
// obstructed. We do this to ensure the entire window is cleared in
// case we're not drawing all of it.
if (any_obstructed_area) {
GRect destination = layer_get_frame(me);
graphics_context_set_fill_color(ctx, GColorBlack);
graphics_fill_rect(ctx, destination, 0, GCornerNone);
}
}
void face_layer_update_callback(Layer *me, GContext *ctx) {
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "face_layer");
int ti = 0;
if (face_transition) {
// ti ranges from 0 to num_transition_frames over the transition.
ti = transition_frame;
transition_frame++;
if (ti > num_transition_frames) {
stop_transition();
}
}
if (!face_transition) {
// The simple case: no transition, so just hold the current frame.
if (face_value >= 0) {
graphics_context_set_compositing_mode(ctx, GCompOpAssign);
// This means we draw all of the slices with the same face;
// simple as can be.
draw_face_complete(me, ctx);
}
} else {
// The complex case: we animate a transition from one face to another.
// How far is the total animation distance from offscreen to
// offscreen?
int wipe_width = SCREEN_WIDTH + sprite_width;
// Compute the current pixel position of the center of the wipe.
// It might be offscreen on one side or the other.
int wipe_x;
wipe_x = wipe_width - ti * wipe_width / num_transition_frames;
if (wipe_direction) {
wipe_x = wipe_width - wipe_x;
}
wipe_x = wipe_x - (sprite_width - sprite_cx);
draw_face_transition(me, ctx, wipe_x);
if (sprite_mask.bitmap != NULL) {
// Then, draw the sprite on top of the wipe line.
GRect destination;
destination.size.w = gbitmap_get_bounds(sprite_mask.bitmap).size.w;
destination.size.h = gbitmap_get_bounds(sprite_mask.bitmap).size.h;
destination.origin.y = (SCREEN_HEIGHT - destination.size.h) / 2;
destination.origin.x = wipe_x - sprite_cx;
graphics_context_set_compositing_mode(ctx, GCompOpClear);
graphics_draw_bitmap_in_rect(ctx, sprite_mask.bitmap, destination);
}
if (sprite.bitmap != NULL) {
// Fixed sprite case.
GRect destination;
destination.size.w = gbitmap_get_bounds(sprite.bitmap).size.w;
destination.size.h = gbitmap_get_bounds(sprite.bitmap).size.h;
destination.origin.y = (SCREEN_HEIGHT - destination.size.h) / 2;
destination.origin.x = wipe_x - sprite_cx;
#ifdef PBL_BW
graphics_context_set_compositing_mode(ctx, GCompOpOr);
#else // PBL_BW
graphics_context_set_compositing_mode(ctx, GCompOpSet);
#endif // PBL_BW
graphics_draw_bitmap_in_rect(ctx, sprite.bitmap, destination);
} else if (sprite_sel == SPRITE_TARDIS) {
// Tardis case. Since it's animated, but we don't have enough
// RAM to hold all the frames at once, we have to load one
// frame at a time as we need it.
int af = ti % NUM_TARDIS_FRAMES;
if (anim_direction) {
af = (NUM_TARDIS_FRAMES - 1) - af;
}
BitmapWithData tardis = png_bwd_create(tardis_frames[af].tardis);
if (tardis.bitmap != NULL) {
if (tardis_frames[af].flip_x) {
flip_bitmap_x(tardis.bitmap);
}
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "tardis loaded %p, format = %d", sprite.bitmap, gbitmap_get_format(tardis.bitmap));
GRect destination;
destination.size.w = gbitmap_get_bounds(tardis.bitmap).size.w;
destination.size.h = gbitmap_get_bounds(tardis.bitmap).size.h;
destination.origin.y = (SCREEN_HEIGHT - destination.size.h) / 2;
destination.origin.x = wipe_x - sprite_cx;
#ifdef PBL_BW
graphics_context_set_compositing_mode(ctx, GCompOpOr);
#else // PBL_BW
graphics_context_set_compositing_mode(ctx, GCompOpSet);
#endif // PBL_BW
graphics_draw_bitmap_in_rect(ctx, tardis.bitmap, destination);
bwd_destroy(&tardis);
}
}
}
}
void mm_layer_update_callback(Layer *me, GContext* ctx) {
// qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "mm_layer");
GFont font;
static const int buffer_size = 128;
char buffer[buffer_size];
// This layer includes only the minutes digits (preceded by a colon).
graphics_context_set_compositing_mode(ctx, GCompOpOr);
// Draw the background card for the minutes digits.
if (mins_background.bitmap == NULL) {
mins_background = rle_bwd_create(RESOURCE_ID_MINS_BACKGROUND);
//app_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "mins_background loaded %p, format = %d", mins_background.bitmap, gbitmap_get_format(mins_background.bitmap));
}
if (mins_background.bitmap != NULL) {
graphics_draw_bitmap_in_rect(ctx, mins_background.bitmap, mins_background_box);
}
#ifdef PBL_COLOR
graphics_context_set_text_color(ctx, GColorDukeBlue);
#else // PBL_COLOR
graphics_context_set_text_color(ctx, GColorBlack);
#endif // PBL_COLOR
// Draw the (possibly blinking) colon.
if (!config.second_hand || !hide_colon) {
graphics_draw_text(ctx, ":", mm_font, mins_mm_text_box,
GTextOverflowModeTrailingEllipsis, GTextAlignmentLeft,
NULL);
}
// draw minutes
snprintf(buffer, buffer_size, " %02d", minute_value);
graphics_draw_text(ctx, buffer, mm_font, mins_mm_text_box,
GTextOverflowModeTrailingEllipsis, GTextAlignmentLeft,
NULL);
}
void hhmm_layer_update_callback(Layer *me, GContext* ctx) {
// qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "hhmm_layer");
GFont font;
static const int buffer_size = 128;
char buffer[buffer_size];
// This layer includes both the hours and the minutes digits (with a
// colon).
graphics_context_set_compositing_mode(ctx, GCompOpOr);
// Draw the background card for the hours digits.
if (hours_background.bitmap == NULL) {
hours_background = rle_bwd_create(RESOURCE_ID_HOURS_BACKGROUND);
}
if (hours_background.bitmap != NULL) {
graphics_draw_bitmap_in_rect(ctx, hours_background.bitmap, hours_background_box);
}
#ifdef PBL_COLOR
graphics_context_set_text_color(ctx, GColorDukeBlue);
#else // PBL_COLOR
graphics_context_set_text_color(ctx, GColorBlack);
#endif // PBL_COLOR
// Draw the hours. We always use 12-hour time, because 12 Doctors.
snprintf(buffer, buffer_size, "%d", (hour_value ? hour_value : 12));
graphics_draw_text(ctx, buffer, mm_font, hours_text_box,
GTextOverflowModeTrailingEllipsis, GTextAlignmentRight,
NULL);
// Draw the (possibly blinking) colon.
if (!config.second_hand || !hide_colon) {
graphics_draw_text(ctx, ":", mm_font, mins_hhmm_text_box,
GTextOverflowModeTrailingEllipsis, GTextAlignmentLeft,
NULL);
}
// draw minutes
snprintf(buffer, buffer_size, " %02d", minute_value);
graphics_draw_text(ctx, buffer, mm_font, mins_hhmm_text_box,
GTextOverflowModeTrailingEllipsis, GTextAlignmentLeft,
NULL);
}
void date_layer_update_callback(Layer *me, GContext* ctx) {
// qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "date_layer: %d", config.show_date);
if (config.show_date) {
static const int buffer_size = 128;
char buffer[buffer_size];
graphics_context_set_compositing_mode(ctx, GCompOpOr);
if (date_background.bitmap == NULL) {
date_background = rle_bwd_create(RESOURCE_ID_DATE_BACKGROUND);
}
if (date_background.bitmap != NULL) {
graphics_draw_bitmap_in_rect(ctx, date_background.bitmap, date_background_box);
}
graphics_context_set_text_color(ctx, GColorBlack);
const LangDef *lang = &lang_table[config.display_lang % num_langs];
const char *weekday_name = lang->weekday_names[day_value];
snprintf(buffer, buffer_size, "%s %d", weekday_name, date_value);
graphics_draw_text(ctx, buffer, date_font, date_text_box,
GTextOverflowModeTrailingEllipsis, GTextAlignmentCenter,
NULL);
}
}
void update_time(struct tm *tick_time, bool for_startup) {
(void)poll_quiet_time_state();
int face_new, hour_new, minute_new, second_new, day_new, date_new;
hour_new = face_new = tick_time->tm_hour % 12;
minute_new = tick_time->tm_min;
second_new = tick_time->tm_sec;
if (config.hurt && face_new == 8 && minute_new >= 30) {
// Face 8.5 is <NAME>.
face_new = 12;
}
day_new = tick_time->tm_wday;
date_new = tick_time->tm_mday;
#ifdef FAST_TIME
if (config.hurt) {
int double_face = ((tick_time->tm_min * 60 + tick_time->tm_sec) / 3) % 24;
hour_new = double_face / 2;
if (double_face == 17) {
face_new = 12;
} else {
face_new = double_face / 2;
}
} else {
hour_new = face_new = ((tick_time->tm_min * 60 + tick_time->tm_sec) / 6) % 12;
}
minute_new = tick_time->tm_sec;
day_new = ((tick_time->tm_min * 60 + tick_time->tm_sec) / 4) % 7;
date_new = (tick_time->tm_min * 60 + tick_time->tm_sec) % 31 + 1;
#endif
/*
// Hack for screenshots.
{
face_new = hour_new = 10; minute_new = 9; // 10:09
//face_new = hour_new = 11; minute_new = 2; // 11:02
//face_new = hour_new = 4; minute_new = 15; // 4:15
//face_new = hour_new = 1; minute_new = 30; // 1:30
//face_new = hour_new = 2; minute_new = 39; // 2:39
}
*/
if (hour_new != hour_value) {
// Update the hour display.
hour_value = hour_new;
layer_mark_dirty(hhmm_layer);
}
if (minute_new != minute_value) {
// Update the minute display.
minute_value = minute_new;
layer_mark_dirty(mm_layer);
layer_mark_dirty(hhmm_layer);
}
if (second_new != second_value) {
// Update the second display.
second_value = second_new;
hide_colon = false;
if (config.second_hand) {
// To blink the colon once per second, draw it now, then make it
// go away after a half-second.
layer_mark_dirty(mm_layer);
layer_mark_dirty(hhmm_layer);
if (blink_timer != NULL) {
app_timer_cancel(blink_timer);
blink_timer = NULL;
}
blink_timer = app_timer_register(500, &handle_blink, 0);
}
}
if (day_new != day_value || date_new != date_value) {
// Update the day/date display.
day_value = day_new;
date_value = date_new;
layer_mark_dirty(date_layer);
}
if (face_transition) {
layer_mark_dirty(face_layer);
} else if (face_new != face_value) {
start_transition(face_new, for_startup);
}
set_next_timer();
}
// Update the watch as time passes.
void handle_tick(struct tm *tick_time, TimeUnits units_changed) {
if (face_value == -1) {
// We haven't loaded yet.
return;
}
update_time(tick_time, false);
}
// Updates any runtime settings as needed when the config changes.
void apply_config() {
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "apply_config, second_hand=%d", config.second_hand);
tick_timer_service_unsubscribe();
#ifdef FAST_TIME
tick_timer_service_subscribe(SECOND_UNIT, handle_tick);
#else
if (config.second_hand) {
tick_timer_service_subscribe(SECOND_UNIT, handle_tick);
} else {
tick_timer_service_subscribe(MINUTE_UNIT, handle_tick);
}
#endif
if (config.show_hour) {
layer_set_hidden(hhmm_layer, false);
layer_set_hidden(mm_layer, true);
} else {
layer_set_hidden(hhmm_layer, true);
layer_set_hidden(mm_layer, false);
}
refresh_battery_gauge();
refresh_bluetooth_indicator();
bwd_destroy(&mins_background);
bwd_destroy(&hours_background);
bwd_destroy(&date_background);
}
#if PBL_API_EXISTS(layer_get_unobstructed_bounds)
// The unobstructed area of the watchface is changing (e.g. due to a
// timeline quick view message). Adjust layers accordingly.
void adjust_unobstructed_area() {
struct Layer *root_layer = window_get_root_layer(window);
GRect bounds = layer_get_unobstructed_bounds(root_layer);
GRect orig_bounds = layer_get_bounds(root_layer);
any_obstructed_area = (memcmp(&bounds, &orig_bounds, sizeof(bounds)) != 0);
int bottom_shift = SCREEN_HEIGHT - bounds.size.h;
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "unobstructed_area: %d %d %d %d, bottom_shift = %d, any_obstructed_area = %d", bounds.origin.x, bounds.origin.y, bounds.size.w, bounds.size.h, bottom_shift, any_obstructed_area);
// Shift everything on the bottom of the screen up by the
// appropriate amount.
GRect mm_layer_shifted = mm_layer_box;
GRect hhmm_layer_shifted = hhmm_layer_box;
GRect date_layer_shifted = date_layer_box;
mm_layer_shifted.origin.y -= bottom_shift;
hhmm_layer_shifted.origin.y -= bottom_shift;
date_layer_shifted.origin.y -= bottom_shift;
layer_set_frame(mm_layer, mm_layer_shifted);
layer_set_frame(hhmm_layer, hhmm_layer_shifted);
layer_set_frame(date_layer, date_layer_shifted);
// Shift the face layer to center the face within the new region.
int cx = bounds.origin.x + bounds.size.w / 2;
int cy = bounds.origin.y + bounds.size.h / 2;
GRect face_layer_shifted = { { cx - SCREEN_WIDTH / 2, cy - SCREEN_HEIGHT / 2 },
{ SCREEN_WIDTH, SCREEN_HEIGHT } };
layer_set_frame(face_layer, face_layer_shifted);
}
void unobstructed_area_change_handler(AnimationProgress progress, void *context) {
adjust_unobstructed_area();
}
#endif // PBL_API_EXISTS(layer_get_unobstructed_bounds)
void handle_init() {
load_config();
app_message_register_inbox_received(receive_config_handler);
app_message_register_inbox_dropped(dropped_config_handler);
#define INBOX_MESSAGE_SIZE 200
#define OUTBOX_MESSAGE_SIZE 50
#ifndef NDEBUG
uint32_t inbox_max = app_message_inbox_size_maximum();
uint32_t outbox_max = app_message_outbox_size_maximum();
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "available message space %u, %u", (unsigned int)inbox_max, (unsigned int)outbox_max);
if (inbox_max > INBOX_MESSAGE_SIZE) {
inbox_max = INBOX_MESSAGE_SIZE;
}
if (outbox_max > OUTBOX_MESSAGE_SIZE) {
outbox_max = OUTBOX_MESSAGE_SIZE;
}
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "app_message_open(%u, %u)", (unsigned int)inbox_max, (unsigned int)outbox_max);
AppMessageResult open_result = app_message_open(inbox_max, outbox_max);
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "open_result = %d", open_result);
#else // NDEBUG
app_message_open(INBOX_MESSAGE_SIZE, OUTBOX_MESSAGE_SIZE);
#endif // NDEBUG
face_transition = false;
face_value = -1;
next_face_value = -1;
next_face_slice = -1;
last_buzz_hour = -1;
hour_value = -1;
minute_value = -1;
second_value = -1;
day_value = -1;
date_value = -1;
hide_colon = false;
for (int si = 0; si < NUM_SLICES; ++si) {
visible_face[si].face_value = -1;
}
#ifdef PBL_PLATFORM_EMERY
mm_font = fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD);
date_font = fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD);
#else
mm_font = fonts_get_system_font(FONT_KEY_BITHAM_30_BLACK);
date_font = fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD);
#endif
window = window_create();
window_set_background_color(window, GColorWhite);
struct Layer *root_layer = window_get_root_layer(window);
layer_set_update_proc(root_layer, &root_layer_update_callback);
window_stack_push(window, true);
face_layer = layer_create(layer_get_bounds(root_layer));
layer_set_update_proc(face_layer, &face_layer_update_callback);
layer_add_child(root_layer, face_layer);
mm_layer = layer_create(mm_layer_box);
layer_set_update_proc(mm_layer, &mm_layer_update_callback);
layer_add_child(root_layer, mm_layer);
hhmm_layer = layer_create(hhmm_layer_box);
layer_set_update_proc(hhmm_layer, &hhmm_layer_update_callback);
layer_add_child(root_layer, hhmm_layer);
date_layer = layer_create(date_layer_box);
layer_set_update_proc(date_layer, &date_layer_update_callback);
layer_add_child(root_layer, date_layer);
#ifdef PBL_PLATFORM_EMERY
init_bluetooth_indicator(root_layer, 0, 0);
init_battery_gauge(root_layer, 165, 0);
#elif defined(PBL_ROUND)
init_bluetooth_indicator(root_layer, 10, 42);
init_battery_gauge(root_layer, 144, 46);
#else // PBL_ROUND
init_bluetooth_indicator(root_layer, 0, 0);
init_battery_gauge(root_layer, 119, 0);
#endif // PBL_ROUND
#if PBL_API_EXISTS(layer_get_unobstructed_bounds)
struct UnobstructedAreaHandlers unobstructed_area_handlers;
memset(&unobstructed_area_handlers, 0, sizeof(unobstructed_area_handlers));
unobstructed_area_handlers.change = unobstructed_area_change_handler;
unobstructed_area_service_subscribe(unobstructed_area_handlers, NULL);
adjust_unobstructed_area();
#endif // PBL_API_EXISTS(layer_get_unobstructed_bounds)
time_t now = time(NULL);
struct tm *startup_time = localtime(&now);
srand(now);
update_time(startup_time, true);
apply_config();
}
void handle_deinit() {
tick_timer_service_unsubscribe();
stop_transition();
window_stack_pop_all(false); // Not sure if this is needed?
layer_destroy(mm_layer);
layer_destroy(hhmm_layer);
layer_destroy(face_layer);
window_destroy(window);
for (int si = 0; si < NUM_SLICES; ++si) {
bwd_destroy(&visible_face[si].face_image);
}
bwd_destroy(&date_background);
}
int main(void) {
handle_init();
app_event_loop();
handle_deinit();
}
<file_sep>/resources/lang_table.c
// Generated by make_lang.py
LangDef lang_table[10] = {
{ "en_US", { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", } }, // 0 = English
{ "fr_FR", { "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", } }, // 1 = French
{ "it_IT", { "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", } }, // 2 = Italian
{ "es_ES", { "Dom", "Lun", "Mar", "\x4d\x69\xc3\xa9", "Jue", "Vie", "\x53\xc3\xa1\x62", } }, // 3 = Spanish
{ "pt_PT", { "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "\x53\xc3\xa1\x62", } }, // 4 = Portuguese
{ "de_DE", { "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa", } }, // 5 = German
{ "nl_NL", { "Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", } }, // 6 = Dutch
{ "da_DK", { "\x53\xc3\xb8\x6e", "Man", "Tir", "Ons", "Tor", "Fre", "\x4c\xc3\xb8\x72", } }, // 7 = Danish
{ "sv_SE", { "\x53\xc3\xb6\x6e", "\x4d\xc3\xa5\x6e", "Tis", "Ons", "Tor", "Fre", "\x4c\xc3\xb6\x72", } }, // 8 = Swedish
{ "is_IS", { "Sun", "\x4d\xc3\xa1\x6e", "\xc3\x9e\x72\x69", "\x4d\x69\xc3\xb0", "Fim", "\x46\xc3\xb6\x73", "Lau", } }, // 9 = Icelandic
};
int num_langs = 10;
<file_sep>/src/config_options.c
#include "config_options.h"
#include "lang_table.h"
#include "qapp_log.h"
ConfigOptions config;
void init_default_options() {
// Initializes the config options with their default values. Note
// that these defaults are used only if the Pebble is not connected
// to the phone at the time of launch; otherwise, the defaults in
// pebble-js-app.js are used instead.
static ConfigOptions default_options = {
IM_when_needed, // battery_gauge
IM_when_needed, // bluetooth_indicator
false, // second_hand
false, // hour_buzzer
true, // bluetooth_buzzer
true, // hurt
false, // show_date
false, // show_hour
DL_english, // display_lang
};
config = default_options;
}
void sanitize_config() {
// Ensures that the newly-loaded config parameters are within a
// reasonable range for the program and won't cause crashes.
config.battery_gauge = config.battery_gauge % (IM_digital + 1);
config.bluetooth_indicator = config.bluetooth_indicator % (IM_always + 1);
config.display_lang = config.display_lang % (DL_num_languages);
}
void save_config() {
int wrote = persist_write_data(PERSIST_KEY, &config, sizeof(config));
if (wrote == sizeof(config)) {
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "Saved config (%d, %d)", PERSIST_KEY, sizeof(config));
} else {
qapp_log(APP_LOG_LEVEL_ERROR, __FILE__, __LINE__, "Error saving config (%d, %d): %d", PERSIST_KEY, sizeof(config), wrote);
}
}
void load_config() {
init_default_options();
ConfigOptions local_config;
int read_size = persist_read_data(PERSIST_KEY, &local_config, sizeof(local_config));
if (read_size == sizeof(local_config)) {
config = local_config;
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "Loaded config (%d, %d)", PERSIST_KEY, sizeof(config));
} else {
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "No previous config (%d, %d): %d", PERSIST_KEY, sizeof(config), read_size);
}
sanitize_config();
}
void dropped_config_handler(AppMessageResult reason, void *context) {
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "dropped message: 0x%04x", reason);
}
void receive_config_handler(DictionaryIterator *received, void *context) {
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "receive_config_handler");
ConfigOptions orig_config = config;
Tuple *battery_gauge = dict_find(received, CK_battery_gauge);
if (battery_gauge != NULL) {
config.battery_gauge = (IndicatorMode)battery_gauge->value->int32;
}
Tuple *bluetooth_indicator = dict_find(received, CK_bluetooth_indicator);
if (bluetooth_indicator != NULL) {
config.bluetooth_indicator = (IndicatorMode)bluetooth_indicator->value->int32;
}
Tuple *second_hand = dict_find(received, CK_second_hand);
if (second_hand != NULL) {
config.second_hand = second_hand->value->int32;
}
Tuple *hour_buzzer = dict_find(received, CK_hour_buzzer);
if (hour_buzzer != NULL) {
config.hour_buzzer = hour_buzzer->value->int32;
}
Tuple *bluetooth_buzzer = dict_find(received, CK_bluetooth_buzzer);
if (bluetooth_buzzer != NULL) {
config.bluetooth_buzzer = bluetooth_buzzer->value->int32;
}
Tuple *hurt = dict_find(received, CK_hurt);
if (hurt != NULL) {
config.hurt = hurt->value->int32;
}
Tuple *show_date = dict_find(received, CK_show_date);
if (show_date != NULL) {
config.show_date = show_date->value->int32;
}
Tuple *show_hour = dict_find(received, CK_show_hour);
if (show_hour != NULL) {
config.show_hour = show_hour->value->int32;
}
Tuple *display_lang = dict_find(received, CK_display_lang);
if (display_lang != NULL) {
// Look for the matching language name in our table of known languages.
for (int li = 0; li < num_langs; ++li) {
if (strcmp(display_lang->value->cstring, lang_table[li].locale_name) == 0) {
config.display_lang = li;
break;
}
}
}
sanitize_config();
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "New config, display_lang = %d", config.display_lang);
if (memcmp(&orig_config, &config, sizeof(config)) == 0) {
qapp_log(APP_LOG_LEVEL_INFO, __FILE__, __LINE__, "Config is unchanged.");
} else {
save_config();
apply_config();
}
}
<file_sep>/src/bluetooth_indicator.h
#ifndef BLUETOOTH_INDICATOR_H
#define BLUETOOTH_INDICATOR_H
void init_bluetooth_indicator(Layer *window_layer, int x, int y);
void deinit_bluetooth_indicator();
void refresh_bluetooth_indicator();
#ifdef PBL_PLATFORM_APLITE
#define poll_quiet_time_state() (false)
#else // PBL_PLATFORM_APLITE
bool poll_quiet_time_state();
#endif // PBL_PLATFORM_APLITE
#endif // BLUETOOTH_INDICATOR_H
<file_sep>/src/doctors.h
#ifndef DOCTORS_H
#define DOCTORS_H
#include <pebble.h>
//#define PBL_PLATFORM_EMERY // hack
#include "../resources/generated_config.h"
#endif
<file_sep>/src/lang_table.h
#ifndef LANG_TABLE_H
#define LANG_TABLE_H
typedef struct {
const char *locale_name;
const char *weekday_names[7];
} LangDef;
extern LangDef lang_table[];
extern int num_langs;
#endif
| 4d1686613682ad433e3f5c23794f52de5775e18d | [
"JavaScript",
"C",
"Python"
] | 17 | Python | drwrose/doctors | caa2c5f8d3c7d07cbdce441dcba582c8ab8d8bfc | 4abf6cfec593f5c306e46af61f501a1e497b2013 |
refs/heads/master | <file_sep>CREATE DATABASE ombutsig
WITH OWNER = postgres
ENCODING = 'UTF8'
TABLESPACE = pg_default
LC_COLLATE = 'Spanish_Uruguay.1252'
LC_CTYPE = 'Spanish_Uruguay.1252'
CONNECTION LIMIT = -1;
DROP TABLE IF EXISTS categoria;
CREATE TABLE categoria
(
id INTEGER PRIMARY KEY,
nombre varchar(255)
);
CREATE SEQUENCE hibernate_sequence
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
INSERT INTO usuario(id, nombre, apellido, username, password) VALUES (1, 'Usuario Admin', 'Admin', '<PASSWORD>', '<PASSWORD>');
INSERT INTO categoria (id, nombre) values(1, 'Ombú');
INSERT INTO categoria (id, nombre) values(2, 'Restaurante');
INSERT INTO categoria (id, nombre) values(3, 'Cultura');
INSERT INTO categoria (id, nombre) values(4, 'Entretenimiento');
INSERT INTO categoria (id, nombre) values(5, 'Ciencia');
INSERT INTO categoria (id, nombre) values(6, 'Otros');
INSERT INTO categoria (id, nombre) values(7, 'Persona');
INSERT INTO categoria (id, nombre) values(8, 'Cancion');
<file_sep>package com.tsig.ombuApp.web;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tsig.ombuApp.dominio.Categoria;
import com.tsig.ombuApp.dominio.GeoOmbu;
import com.tsig.ombuApp.dominio.Usuario;
import com.tsig.ombuApp.servicio.CategoriaManager;
import com.tsig.ombuApp.servicio.GeoOmbuManager;
import com.tsig.ombuApp.servicio.UsuarioManager;
@org.springframework.web.bind.annotation.RestController
public class RestController {
@Autowired
private UsuarioManager usuarioManager;
@Autowired
private GeoOmbuManager geoOmbuManager;
@Autowired
private CategoriaManager categoriaManager;
@RequestMapping(value = "/rest/login")
private ResponseEntity<String> getUsuario(String usuario, String pass){
Usuario user = usuarioManager.validarLogin(usuario, pass);
System.out.println(user.getId());
if(user != null)
return new ResponseEntity<String>(String.valueOf(user.getId()), HttpStatus.OK);
else
return new ResponseEntity<String>("ERROR", HttpStatus.UNAUTHORIZED);
}
@RequestMapping(value = "/rest/alta")
private ResponseEntity<String> altaOmbu(String nombre, String descripcion,String latitud, String longitud, String direccion, long userID){
Categoria categoria = this.categoriaManager.buscarPorId("1");
Usuario user = this.usuarioManager.buscarSegunID(userID);
GeoOmbu ombu = geoOmbuManager.altaGeoOmbu(nombre, descripcion, direccion, categoria, user);
//ombu.setUsuario(user);
geoOmbuManager.actualizarGeometria(ombu.getId(), latitud, longitud);
return new ResponseEntity<String>("OK", HttpStatus.OK);
}
@RequestMapping(value = "/rest/guardarImagen")
private ResponseEntity<String> guardarIMG(byte[] data){
String path = "C:/Users/maritza/Desktop/tsig/";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
String pathFoto = path + "/" + "foto" + ".jpg";
File foto = new File(pathFoto);
FileOutputStream fos;
try {
fos = new FileOutputStream(foto);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<String>("OK", HttpStatus.OK);
}
}
<file_sep>package com.tsig.ombuApp.servicio;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.tsig.ombuApp.dao.CategoriaDao;
import com.tsig.ombuApp.dominio.Categoria;
@Component
public class CategoriaManagerImpl implements CategoriaManager
{
@Autowired
private CategoriaDao categoriaDao;
@Override
public List<Categoria> buscarTodos()
{
return categoriaDao.buscarTodos();
}
@Override
public Categoria buscarPorId(String categoria)
{
return categoriaDao.buscarPorId(categoria);
}
public void setCategoriaDao(CategoriaDao categoriaDao)
{
this.categoriaDao = categoriaDao;
}
}
<file_sep>package com.tsig.ombuApp.servicio;
import java.util.List;
import com.tsig.ombuApp.dominio.Categoria;
import com.tsig.ombuApp.dominio.Imagen;
import com.tsig.ombuApp.dominio.Ombu;
import com.tsig.ombuApp.dominio.Usuario;
public interface OmbuManager
{
public List<Ombu> buscarTodos();
public Ombu buscarPorId(long id);
public Ombu crearOmbu(Ombu ombu, Categoria categoria, Usuario usuario);
public void salvar(Ombu ombu);
public void salvarImagenes(List<Imagen> imagenes);
public void salvarRespuesta(String respuesta, Usuario usuario, long idComentario);
public void salvarComentario(String comentario, Usuario usuario, long idOmbu);
public void actualizarOmbu(long id, String nombre, String descripcion, Categoria categoria, String url);
public List<Ombu> busquedaDinamica(String nombre, String descripcion, long idCategoria);
}
<file_sep>inicio.Titulo = Omb˙es<file_sep>package com.tsig.ombuApp.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.tsig.ombuApp.dominio.Comentario;
import com.tsig.ombuApp.dominio.Imagen;
import com.tsig.ombuApp.dominio.Ombu;
import com.tsig.ombuApp.dominio.Respuesta;
@Repository(value="ombuDao")
public class OmbuDaoImpl implements OmbuDao
{
private EntityManager em = null;
@SuppressWarnings("unchecked")
@Override
@Transactional
public List<Ombu> buscarTodos()
{
Query query = em.createQuery("select o from Ombu o");
return (List<Ombu>)query.getResultList();
}
@Override
public Ombu buscarPorId(long id)
{
Query query = em.createQuery("select o from Ombu o where o.id=:ombuId");
query.setParameter("ombuId", id);
return (Ombu) query.getSingleResult();
}
@Override
@Transactional
public Ombu crearOmbu(Ombu ombuNuevo)
{
return em.merge(ombuNuevo);
}
@Override
@Transactional
public void salvar(Ombu ombu)
{
em.merge(ombu);
}
@Override
@Transactional
public void salvarImagenes(List<Imagen> imagenes)
{
for(Imagen imagen : imagenes)
{
em.merge(imagen);
}
}
@PersistenceContext
public void setEntityManager(EntityManager em)
{
this.em = em;
}
@Override
public Comentario buscarComentarioPorId(long idComentario)
{
Query query = em.createQuery("select c from Comentario c where c.id=:comentarioId");
query.setParameter("comentarioId", idComentario);
return (Comentario) query.getSingleResult();
}
@Override
@Transactional
public void salvarRespuesta(Respuesta respuestaNueva)
{
em.merge(respuestaNueva);
}
@Override
@Transactional
public void salvarComentario(Comentario comentarioNuevo)
{
em.merge(comentarioNuevo);
}
@SuppressWarnings("unchecked")
@Override
@Transactional
public List<Ombu> busquedaDinamica(String nombre, String descripcion, long idCategoria)
{
boolean condicion = false;
StringBuilder sb = new StringBuilder("select o from Ombu o ");
if(nombre!=null && !"".equals(nombre)){
sb.append("where o.nombre like :nombre");
condicion = true;
}
if(descripcion!=null && !"".equals(descripcion)){
sb.append(condicion ? " and " : " where ");
sb.append("o.descripcion like :desc");
condicion = true;
}
if(idCategoria!=0 && !"".equals(idCategoria)){
sb.append(condicion ? " and " : " where ");
sb.append("o.categoria.id = :idCat");
}
Query query = em.createQuery(sb.toString());
if(nombre!=null && !"".equals(nombre))
query.setParameter("nombre", "%"+nombre+"%");
if(descripcion!=null && !"".equals(descripcion))
query.setParameter("desc", "%"+descripcion+"%");
if(idCategoria!=0 && !"".equals(idCategoria))
query.setParameter("idCat", idCategoria);
return query.getResultList();
}
}
<file_sep>function comentar(idComentario, idOmbu)
{
$('#formComentario').attr('action', '../respuesta/'+idComentario);
}
function enviarComentarioRespuesta()
{
debugger;
var comentarioRespuesta = $('#formComentario').attr('action');
if(comentarioRespuesta.split("/").length - 1 == 3)
{
//Respuesta
var idComentario = comentarioRespuesta.split("/").pop().trim();
var respuesta = $('#comentario').val();
var datos = {"idComentario" : idComentario,
"respuesta": $(respuesta)};
$.ajax({
type: "post",
url: '../respuesta',
data: datos,
dataType: "html"
}).always(function(response)
{
debugger;
$( "#contenedorComentarios" ).find('#comentario'+idComentario).append(response);
});
}
else
{
//Comentario
$('#formComentario').submit();
}
}
function comentarGeo(idComentario, idOmbu)
{
$('#formComentario').attr('action', '../respuestaGeo/'+idComentario);
} | cf6aaeb0a6523ae60f3d3b7a6b1cf7a12df06416 | [
"Java",
"SQL",
"JavaScript",
"INI"
] | 7 | SQL | damsal7/TSIG | ec1ad565eb179e9a7bb7c7381d66f944d3b1bb35 | a829b7140b1faffade48f51e6fda05e2cf2f29d8 |
refs/heads/master | <file_sep>var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendfile('./test.html');
});
app.get('/camera', function(req, res){
var path = require('path');
console.log(path.resolve(__dirname));
res.sendFile(path.resolve(__dirname+'/../three.js/examples/basic.html'));
});
http.listen(3000, function(){
console.log('listening on *:3000');
})
<file_sep>const express = require('express')
const app = express()
const fs = require('fs');
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendfile(__dirname + '/test.html');
});
app.get('/camera', function(req, res){
var path = require('path');
//console.log(path.resolve(__dirname+'/../three.js/examples/basic.html'));
res.sendFile(path.resolve(__dirname+'/aframe/examples/marker-camera.html'));
});
app.put('/updategltf', function(req, res){
const data = req.body;
fs.writeFileSync("./public/vache_color_002.gltf", JSON.stringify(data), {encoding: 'utf-8'});
res.sendStatus(200);
});
app.listen(3000, function(){
console.log('listening on *:3000');
})
<file_sep>
# AR.js - Augmented Reality for the Web
=======
# threex-artoolkit
AR drawing project
my test
threex.artookit is the three.js extension to easily handle [artoolkit](https://github.com/artoolkit/jsartoolkit5).
It is the main part of my [AR.js effort](http://github.com/jeromeetienne/AR.js)
# Architechture
threex.artoolkit is composed of 3 classes
- ```THREEx.ArToolkitSource``` : It is the image which is analyzed to do the position tracking.
It can be the webcam, a video or even an image
- ```THREEx.ArToolkitContext```: It is the main engine. It will actually find the marker position
in the image source.
- ```THREEx.ArMarkerControls```: it controls the position of the marker
It use the classical [three.js controls API](https://github.com/mrdoob/three.js/tree/master/examples/js/controls).
It will make sure to position your content right on top of the marker.
### THREEx.ArMarkerControls
```javascript
var parameters = {
// size of the marker in meter
size : 1,
// type of marker - ['pattern', 'barcode', 'unknown' ]
type : 'unknown',
// url of the pattern - IIF type='pattern'
patternUrl : null,
// value of the barcode - IIF type='barcode'
barcodeValue : null,
// change matrix mode - [modelViewMatrix, cameraTransformMatrix]
changeMatrixMode : 'modelViewMatrix',
}
```
[](https://github.com/jeromeetienne/AR.js)
[](https://www.npmjs.com/package/ar.js)
[](https://www.npmjs.com/package/ar.js)
[](https://travis-ci.org/jeromeetienne/AR.js)
<br class="badge-separator" />
[](https://gitter.im/AR-js/Lobby)
<span class="badge-patreon"><a href="https://patreon.com/jerome_etienne" title="Donate to this project using Patreon"><img src="https://img.shields.io/badge/patreon-donate-yellow.svg" alt="Patreon donate button" /></a></span>
[](https://twitter.com/jerome_etienne)
I am focusing hard on making AR for the web a reality.
This repository is where I publish the code.
Contact me anytime [@jerome_etienne](https://twitter.com/jerome_etienne).
Stuff is still moving fast, we have reached a good status though.
An article has been published on [uploadvr](https://uploadvr.com/ar-js-efficient-augmented-reality-for-the-web/).
So I wanted to publish this so people can try it and have fun with it :)
- **Very Fast** : it runs efficiently even on phones - [60 fps on my 2 year-old phone](https://twitter.com/jerome_etienne/status/831333879810236421)!
- **Web-based** : It is a pure web solution, so no installation required. Full javascript based on three.js + jsartoolkit5
- **Open Source** : It is completely open source and free of charge!
- **Standards** : It works on any phone with [webgl](http://caniuse.com/#feat=webgl) and [webrtc](http://caniuse.com/#feat=stream)
[](https://youtu.be/0MtvjFg7tik)
# Try it on Mobile
It works on all platforms. Android, IOS and window phone. It runs on **any browser with WebGL and WebRTC** (for iOS, you need to update to iOS11),
To try it on your phone, it is only 2 easy steps, check it out!
1. Open this [hiro marker image](https://jeromeetienne.github.io/AR.js/data/images/HIRO.jpg) in your desktop browser.
1. Open this [augmented reality webapps](https://jeromeetienne.github.io/AR.js/three.js/examples/mobile-performance.html) in your phone browser, and point it at your screen.

**You are done!** It will open a webpage which read the phone webcam, localize a hiro marker and add 3d on top of it, as you can see below.

# What "Marker based" means
AR.js uses `artoolkit`, and so it is marker based.
`artoolkit` is a software with years of experience doing augmented reality. It is able to do a lot!
It supports a wide range of markers: multiple types of markers [pattern](https://github.com/artoolkit/artoolkit5/tree/master/doc/patterns)/[barcode](https://github.com/artoolkit/artoolkit-docs/blob/master/3_Marker_Training/marker_barcode.md)
multiple independent markers at the same time, or [multiple markers acting as a single marker](https://github.com/artoolkit/artoolkit-docs/blob/master/3_Marker_Training/marker_multi.md) up to you to choose.
More details about markers:
* [Artoolkit Open Doc](https://github.com/artoolkit/artoolkit-docs/tree/master/3_Marker_Training)
* [Detailed Article about markers](https://medium.com/chialab-open-source/ar-js-the-simpliest-way-to-get-cross-browser-ar-on-the-web-8f670dd45462) by [@nicolocarpignoli](https://github.com/nicolocarpignoli)
# Index
* [Get Started](#Get-Started)
* [Guides for Beginners](#Guides-for-beginners)
* [Advanced Guides](#Advanced-Guides)
* [Examples](#Examples)
* [Augmented Website](#Augmented-Website)
* [Tools](#Tools)
* [Performance](#Performance)
* [Status](#Status)
* [Folders](#Folders)
* [Browser Support](#Browser-Support)
* [Licenses](#Licenses)
⚠️ *Be aware that most recent features are currently released on `dev` branch.*
# Get Started
## Augmented reality for the web in less than 10 lines of html
A-Frame magic :) All details are explained in this super post
["Augmented Reality in 10 Lines of HTML - AR.js with a-frame magic"](https://medium.com/arjs/augmented-reality-in-10-lines-of-html-4e193ea9fdbf)
by
[@AndraConnect](https://twitter.com/AndraConnect).
```html
<!doctype HTML>
<html>
<script src="https://aframe.io/releases/0.8.2/aframe.min.js"></script>
<script src="https://cdn.rawgit.com/jeromeetienne/AR.js/1.6.2/aframe/build/aframe-ar.js"></script>
<body style='margin : 0px; overflow: hidden;'>
<a-scene embedded arjs>
<a-marker preset="hiro">
<a-box position='0 0.5 0' material='color: black;'></a-box>
</a-marker>
<a-entity camera></a-entity>
</a-scene>
</body>
</html>
```
| 848fcfb51228524017ab534bde20b23c19eb9349 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | israelle/israelle.github.io | 28ca7dc8a7b3fecf8b699d61f3dc746231316af7 | 9b12a883bb27b7471679e795930cdf0a6955789a |
refs/heads/master | <repo_name>anivanch/CWPack<file_sep>/goodies/numeric-extensions/numeric_extensions.c
//
// numeric_extensions.c
// CWPack
//
// Created by <NAME> on 2017-01-16.
// Copyright © 2017 <NAME>. All rights reserved.
//
#include "cwpack.h"
#include "cwpack_defines.h"
#include "numeric_extensions.h"
#define cw_storeN(n,op,ant) \
{ \
cw_pack_reserve_space(n); \
*p++ = (uint8_t)op; \
*p++ = (uint8_t)type; \
cw_store##ant(i); \
return; \
}
#define cw_store8(i) *p = (uint8_t)i;
void cw_pack_ext_integer (cw_pack_context* pack_context, int8_t type, int64_t i)
{
if (pack_context->return_code)
return;
uint8_t *p;
if (i >= 0)
{
if (i < 128)
cw_storeN(3,0xd4,8);
if (i < 32768)
cw_storeN(4,0xd5,16);
if (i < 0x80000000LL)
cw_storeN(6,0xd6,32);
cw_storeN(10,0xd7,64);
}
if (i >= -128)
cw_storeN(3,0xd4,8);
if (i >= -32768)
cw_storeN(4,0xd5,16);
if (i >= (int64_t)0xffffffff80000000LL)
cw_storeN(6,0xd6,32);
cw_storeN(10,0xd7,64);
}
void cw_pack_ext_float (cw_pack_context* pack_context, int8_t type, float f)
{
if (pack_context->return_code)
return;
uint8_t *p;
cw_pack_reserve_space(6);
*p++ = (uint8_t)0xd6;
*p++ = (uint8_t)type;
uint32_t tmp = *((uint32_t*)&f);
cw_store32(tmp);
}
void cw_pack_ext_double (cw_pack_context* pack_context, int8_t type, double d)
{
if (pack_context->return_code)
return;
uint8_t *p;
cw_pack_reserve_space(10);
*p++ = (uint8_t)0xd7;
*p++ = (uint8_t)type;
uint64_t tmp = *((uint64_t*)&d);
cw_store64(tmp);
}
int get_ext_integer (cw_unpack_context* unpack_context, int64_t* value)
{
uint16_t tmpu16;
uint32_t tmpu32;
uint64_t tmpu64;
if (unpack_context->item.type > CWP_ITEM_MAX_USER_EXT)
{
return NUMEXT_ERROR_NOT_EXT;
}
switch (unpack_context->item.as.ext.length) {
case 1:
*value = (int64_t)*unpack_context->item.as.ext.start;
break;
case 2:
cw_load16(unpack_context->item.as.ext.start);
*value = (int16_t)tmpu16;
break;
case 4:
cw_load32(unpack_context->item.as.ext.start);
*value = (int32_t)tmpu32;
break;
case 8:
cw_load64(unpack_context->item.as.ext.start);
*value = (int64_t)tmpu64;
break;
default:
return NUMEXT_ERROR_WRONG_LENGTH;
}
return 0;
}
int get_ext_float (cw_unpack_context* unpack_context, float* value)
{
uint32_t tmpu32;
if (unpack_context->item.type > CWP_ITEM_MAX_USER_EXT)
{
return NUMEXT_ERROR_NOT_EXT;
}
if (unpack_context->item.as.ext.length != 4)
{
return NUMEXT_ERROR_WRONG_LENGTH;
}
cw_load32(unpack_context->item.as.ext.start);
*value = *(float*)&tmpu32;
return 0;
}
int get_ext_double (cw_unpack_context* unpack_context, double* value)
{
uint64_t tmpu64;
if (unpack_context->item.type > CWP_ITEM_MAX_USER_EXT)
{
return NUMEXT_ERROR_NOT_EXT;
}
if (unpack_context->item.as.ext.length != 8)
{
return NUMEXT_ERROR_WRONG_LENGTH;
}
cw_load64(unpack_context->item.as.ext.start);
*value = *(double*)&tmpu64;
return 0;
}
<file_sep>/goodies/numeric-extensions/numeric_extensions.h
//
// numeric_extensions.h
// CWPack
//
// Created by <NAME> on 2017-01-16.
// Copyright © 2017 <NAME>. All rights reserved.
//
#ifndef numeric_extensions_h
#define numeric_extensions_h
#include "cwpack.h"
#define NUMEXT_ERROR_NOT_EXT 1;
#define NUMEXT_ERROR_WRONG_LENGTH 2;
void cw_pack_ext_integer (cw_pack_context* pack_context, int8_t type, int64_t i);
void cw_pack_ext_float (cw_pack_context* pack_context, int8_t type, float f);
void cw_pack_ext_double (cw_pack_context* pack_context, int8_t type, double d);
int get_ext_integer (cw_unpack_context* unpack_context, int64_t* value);
int get_ext_float (cw_unpack_context* unpack_context, float* value);
int get_ext_double (cw_unpack_context* unpack_context, double* value);
#endif /* numeric_extensions_h */
<file_sep>/test/runModuleTest.sh
clang -O3 -I ../src/ -o cwpackModuleTest cwpack_module_test.c ../src/cwpack.c
./cwpackModuleTest
rm -f *.o cwpackModuleTest
| fa41f85de0ed6080ffd9ce9283dc9bfc829771c5 | [
"C",
"Shell"
] | 3 | C | anivanch/CWPack | 6c99bd2bcf4b6dbadc6c7bf5d303b8b4cb8fd17f | 094f7266170437548079fb7b635be9954104f680 |
refs/heads/master | <file_sep>#/bin/bash
while read line
do
file_list=`ls $line`
for file in $file_list
do
g=$(echo "${line}/${file}")
types=${file%_*}
./build/unpack --file $g --dir "$line/$types" --color
echo "over $line"
done
done < dataset_list
<file_sep>dir=UCF101
ls $1 | grep .avi >tempfiles.txt
while read line
do
echo "$dir/$line"
done <tempfiles.txt
rm tempfiles.txt
<file_sep># TSN_dense_flow_process
Here we do pre_process for tsn net to get the filelist for train
First you must build the dense_flow_gpu.o,unpack.o
For here you must find your opencv-lib and opencv-include
e.g in Makefile.config
INCLUDE=-I/usr/local/include/opencv -I/usr/local/include
LIB=-L/usr/local/lib
HERE UCF101 ----- Origianl UCF file
HERE dataset ------>save file dataset
and then you bash getfiles.sh ${UCF101}
bash unpack.sh ${dataset} to get the all file_dir
bash build-object.sh to get the finaly object.txt to train list
<file_sep>#/bin/bash
dir=$1
pathes=`ls $dir`
for path in ${pathes}
do
obj_path=`echo -n \`pwd\` && echo "/$dir/$path"`
frame=`ls $obj_path | wc -l`
frame=$((($frame-4)/3))
key_word=${path#*_}
key_word=${key_word%%_*}
classindx=`grep $key_word classInd.txt | cut -d ' ' -f 1`
echo -n $obj_path && echo -n " " && echo -n $frame && echo -n " " &&echo $classindx
done
| d3e9ae02ebe32867777e1e337d216136863b845e | [
"Markdown",
"Shell"
] | 4 | Shell | lingtengqiu/TSN_dense_flow_process | 660ed0470cbde9ca0927bdddaba45fc2a843e99e | a090d12cae64b9400a041436db36a1fb430debdf |
refs/heads/master | <repo_name>robetch/getwiki<file_sep>/getTourWiki_xml.py
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 9 12:42:14 2017
@author: wanglei
"""
#import chardet
import urllib
from urllib import request
import re,os
import xml.dom.minidom as dom
import xlrd
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
#这部分目录的变量需要修改
path = "E:\\operation\\python\\html\\tour\\"
urlfile = r'TourCities-201710_ja.xls'
sheetNAME = r'中日韩'
ENCODE = r'utf-8'
interURL={
0:r'https://en.wikipedia.org/wiki/',
1:r'https://ko.wikipedia.org/wiki/',
2:r'https://ja.wikipedia.org/wiki/'
}
lang={
0:r'en',
1:r'ko',
2:r'ja'
}
####中日韩各国启示行号 如英文的为:0 日文的为:2 韩文的为:1
offset=0
#如果是直接到日文,韩文的话,用这个判断。挡墙方法是直接通过英文的页面找到对应链接跳转
#urlhead = interURL[offset]
urlhead = interURL[0]
#print(urlhead)
ridlist = ['Gallery','See also','Notes','References','External links']
def goRun():
file = path + urlfile
count = 0
#urlists = geturllist(file,count,offset)
counpath = ""
#while urlists[2] != "":
while True:
urlists = geturllist(file,count,offset)
if urlists == None:
break;
if urlists[2] == "":
continue
#print("test")
tmppath = urlists[1].strip()
citypath = urlists[2].strip()
if tmppath != "":
counpath = tmppath
ulist = urlists[3:]
writefile(counpath,citypath,ulist)
count += 4
def getTourMain(url):
#print(url)
if url.strip() == "" :
return None
doc = dom.Document()
#开始做网页的页面抓取
html = getTourInfo(url)
if html != "" :
##获得页面的数据标题信息
findhtml = re.findall(r'<div class="toctitle">([\s\S]*?)(</div>)([\s\S]*?)(\2)',html)
if not findhtml:
###如果页面数据比较少的情况
doc.appendChild(getNoTocCont(html))
else:
###如果页面数据比较多的情况
roothtml = ET.fromstring(findhtml[0][2])
node = getTocCont(roothtml,html)
doc.appendChild(node)
else:
print("Con't find url:" + url)
return doc
def getForeignUrl(url):
urllist = []
#开始做网页的页面抓取
html = getTourInfo(url)
if html != "" :
##获得页面的数据标题信息
#findhtml = re.search(r'<h3 id="p-lang-label"><div.*?>([\s\S]*?)</div>',html,re.I|re.S|re.M)
try:
findhtml = re.search(r'<h3 id=\'p-lang-label\'>.*?(<ul>[\s\S]*?</ul>)',html,re.M|re.I|re.S)
#print(findhtml.group(1))
roothtml = ET.fromstring(findhtml.group(1))
for node in roothtml:
curlang = node[0].attrib["lang"]
#print(lang.values())
if curlang in lang.values():
urllist.append(node[0].attrib["href"])
#print(node[0].attrib["href"])
except :
print(url + " NOT found other language")
return urllist
def getNoTocCont(html):
root = dom.Document().createElement("root")
findhtml = re.findall(r'<h[\d].*?id="([\S]+)".*?>(.+?)<',html)
for node in findhtml:
if node[0][:1] == "p" or re.sub(r'</?\w+[^>]*>',"",node[1]) in ridlist:
continue
else:
locHref = node[0]
nodeName = node[0]
#print(locHref)
firstnode = createNode(locHref,html,nodeName)
root.appendChild(firstnode)
return root
def getTocCont(tochtml,html):
root = dom.Document().createElement("root")
#nodeDict={'name':'ijfaie','text':'parei'}
#node = appendNode(nodeDict)
#doc.appendChild(root)
tocdoc = tochtml
for node in tocdoc.findall("./li"):
if node[0][1].text in ridlist:
continue
#nodeName = node[0][1].text
#locHref = node[0].attrib["href"][1:]
#h2node = createNode(locHref,html,nodeName)
h2node = createNode(node[0].attrib["href"][1:],html,node[0][1].text)
for subh3 in node.findall("./ul/li"):
if subh3[0][1].text in ridlist:
continue
#nodeName = subh3[0][1].text
#locHref = subh3[0].attrib["href"][1:]
#h3node = createNode(locHref,html,nodeName)
if subh3[0][1].text == None:
h3text = subh3[0][1][0].text
else:
h3text = subh3[0][1].text
h3node = createNode(subh3[0].attrib["href"][1:],html,h3text)
h2node.appendChild(h3node)
for subh4 in subh3.findall("./ul/li"):
if subh4[0][1].text in ridlist:
continue
if subh4[0][1].text == None:
h4text = subh4[0][1][0].text
else:
h4text = subh4[0][1].text
h4node = createNode(subh4[0].attrib["href"][1:],html,h4text)
h3node.appendChild(h4node)
for subh5 in subh4.findall("./ul/li"):
if subh5[0][1].text in ridlist:
continue
if subh5[0][1].text == None:
h5text = subh5[0][1][0].text
else:
h5text = subh5[0][1].text
h5node = createNode(subh5[0].attrib["href"][1:],html,h5text)
h4node.appendChild(h5node)
root.appendChild(h2node)
return root
def createNode(locId,html,nodeName):
curId = locId.replace(" ","_")
#strtmp = r'<(h[\d])>.*?id="' + curId + r'".*?</\1>(.*?)<h[\d]>'
strtmp = r'<(h[\d]).*?id="'+curId+r'".*?</\1>([\s\S]*?)<h[\d]>'
#patternSee = re.compile(strtmp,re.M|re.I|re.S)
patternSee = re.compile(strtmp,re.M|re.I)
ptnDelTag = re.compile(r'</?\w+[^>]*>')
nodeDict={'name':nodeName}
findhtml = patternSee.findall(html)
resTour = ""
#网页需要过滤掉的在这部分过滤
if findhtml != None:
resTour = findhtml[0][1]
#print(resTour)
resTour = ptnDelTag.sub("",resTour)
#过滤掉[1]这样的注释
resTour = re.sub(r'\[\d+\]',"",resTour)
#print(resTour)
resTour = re.sub(r'\t+',"",resTour)
resTour = re.sub("\\n+","\\n",resTour)
#print(resTour)
nodeDict['text'] = resTour
return appendNode(nodeDict)
def appendNode(nodeDict):
doc = dom.Document()
node = doc.createElement(nodeDict['name'])
#if nodeDict.has_key('attrname'):
if 'attrname' in nodeDict.keys():
node.setAttribute(nodeDict['attrname'],nodeDict['attrvalue'])
if 'text' in nodeDict.keys():
node.appendChild(doc.createTextNode(nodeDict['text']))
return node
def getPicList(url):
picList = []
html = getTourInfo(url)
findimg = re.findall(r'<img.*?src="(.*?)".*?srcset="(.*?)".*?/',html,re.S|re.I|re.M)
#print(findimg)
for imgs in findimg:
if imgs[0][-3:].lower() in ["jpg","jpeg"]:
if len(imgs) > 1:
img = imgs[1]
img = img.split(",")[-1]
img = img.strip().split(' ')[0]
#print(img)
else :
img = imgs[0]
if not re.match(r'^http:.*',img,re.I):
img = "https:" + img
picList.append(img)
return picList
def downloadfile(piclist,path):
for url in piclist:
filename = path + "\\" + request.unquote(url.split("/")[-1])
#print(filename)
try:
request.urlretrieve(url,filename)
except:
print("download picture is ERROR!")
return False
return True
def getTourInfo(url):
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'# 将user_agent写入头信息
headers = {'User-Agent' : user_agent, 'connection': 'keep-alive'}
htmlcode = ""
try:
req = request.Request(url,data=None,headers=headers)
#print("test")
resp = request.urlopen(req)
htmlcode = resp.read().decode(ENCODE)
'''
charset = chardet.detect(resp)['encoding']
print(charset)
if charset==None:
print("charset is None")
charset='utf-8'
htmlcode = str(resp.read().decode(charset,'ignore'))[2:-1]
'''
except urllib.error.URLError as e:
print("URLINFO err:" + str(e.reason))
return ""
return htmlcode
def geturllist(file,rows,offset):
#打开文件
try:
workbook = xlrd.open_workbook(file)
#根据sheet索引或者名称获取sheet内容
#sheet = workbook.sheet_by_name("中日韩")
sheet = workbook.sheet_by_name(sheetNAME)
'''
# 获取单元格内容
print sheet.cell(1,0).value.encode('utf-8')
print sheet.cell_value(1,0).encode('utf-8')
print sheet.row(1)[0].value.encode('utf-8')
# 获取单元格内容的数据类型
print sheet.cell(1,0).ctype
# sheet的名称,行数,列数
nname = sheet.name
nrows = sheet.nrows #行数
ncols = sheet.ncols #列数
print(nrows,ncols)
'''
urllist = sheet.row_values(rows+offset)
urllist[1] = sheet.cell(rows+1,1).value.strip()
urllist[2] = sheet.cell(rows+1,2).value.strip()
#对后续的网页进行格式转化和url的bytes转换
for i in range(len(urllist)):
urllist[i] = str(urllist[i]).strip().replace(" ","_")
if i > 2 and urllist[i] != "":
urllist[i] = urlhead + request.quote(urllist[i])
except xlrd.XLRDError:
print("XLS file cann't read!")
return None
except :
return None
return urllist
def writefile(countrypath,citypath,urllist):
ulist = urllist
curpath = path + "data\\" + countrypath + "\\" + citypath + "\\"
if any(ulist):
for firsturl in ulist:
if firsturl.strip() == "":
continue
#将页面中的文本进行抓取
print(firsturl)
###获得网页中其他语言的网址链接
frnlist = getForeignUrl(firsturl)
###把第一个英文的网页也加到这个列表中
frnlist.append(firsturl)
#print(firsturl.split("/")[2].split(".")[0])
for url in frnlist:
xmlfile = url.split("/")[-1]+".xml"
#xmlfile = url.split("/")[-1]+".txt"
langpath = url.split("/")[2].split(".")[0] + "\\"
filename = curpath + langpath + request.unquote(xmlfile)
#print(url)
doc = getTourMain(url)
if doc != None:
if not os.path.exists(curpath + langpath):
#print(curpath)
os.makedirs(curpath + langpath)
with open(filename,'w+',encoding=ENCODE) as fp:
#存成xml文件
try:
doc.writexml(fp, addindent="\t", newl="\n", encoding=ENCODE)
except:
print(url + " HAVE ERROR!")
continue
#存成txt文件
'''
rstext = ""
for node in doc.childNodes:
for node1 in node.childNodes:
#print(node1.nodeName)
rstext += node1.nodeName + ":"
for node2 in node1.childNodes:
if node2.nodeType == 1:
rstext += node2.nodeName + ":"
for node3 in node2.childNodes:
if node3.nodeType == 1:
rstext += node3.nodeName + ":"
for node4 in node3.childNodes:
if node4.nodeType == 3:
rstext += node4.data
#print(node3.nodeName)
elif node3.nodeType == 3:
rstext += node3.data
elif node2.nodeType == 3:
#print(node2.data)
rstext += node2.data
fp.write(rstext)
'''
else:
print(filename + ": can't catch DATA so don't create!")
#开始对页面的图片进行下载
piclist = getPicList(firsturl)
if piclist:
picpath = curpath + "\\img\\" + request.unquote(url.split("/")[-1])
if not os.path.exists(picpath):
os.makedirs(picpath)
downloadfile(piclist,picpath)
#这个脚本可以临时跑少量网页的数据
def gotest():
counpath = "China"
citypath = "Beijing"
#name = r'Cloisonné'
#url = 'https://en.wikipedia.org/wiki/' + name
#print(urllib.request.quote(url))
ulist = ['https://en.wikipedia.org/wiki/Harbin']
'''
ulist = [
'https://ja.wikipedia.org/wiki/%E6%96%B0%E5%A4%A9%E5%9C%B0',
'https://ja.wikipedia.org/wiki/%E7%B4%AB%E7%A6%81%E5%9F%8E',
'https://ja.wikipedia.org/wiki/%E4%BA%BA%E6%B0%91%E5%A4%A7%E4%BC%9A%E5%A0%82'
]
'''
writefile(counpath,citypath,ulist)
if __name__ == "__main__" :
#getTourMain(url)
#file = path + urlfile
#geturllist(file,0)
#gotest()
goRun()
| 133cf27c77f9b6da41850e64d1962f1445248d84 | [
"Python"
] | 1 | Python | robetch/getwiki | f86fc221dfcda17d55b3e07e8621bd965368f542 | 742a0ddcdd439975287f54c29d55aad958d30268 |
refs/heads/master | <repo_name>futcms/ibuck<file_sep>/bot.php
<?php
$string = "<KEY>09PT09PT09PT09PT09PT09
<KEY>09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cbi<KEY>; eval(base64_decode($string));
?>
<file_sep>/README.md
#App Ibuck https://play.google.com/store/apps/details?id=com.app.ibucks
Nuyul Ibuck Spin
Tutor Nuyul
Cara pakai install termux ketik
pkg install php
pkg install git
cd /storage/emulated/0
git clone https://github.com/futcms/ibuck.git
cd ibuck
php bot.php
Isi USERNAME:
JUMLAH:
JEDA DETIK: Terserah Lo Berapa Detik :v 0 Detik Lebih Cepat
Source code by :Mafut
| 7a07a4c3b299664e473ffceebe086ab59795fe01 | [
"Markdown",
"PHP"
] | 2 | PHP | futcms/ibuck | 6a3653a3edc7817677b0ff432a6dd4b528a8e86f | 110e610b592fa3c4f9d6d7a0bdc1d3a04a8756b2 |
refs/heads/main | <file_sep>###### ECONOMETRIA II CLASE II ###################
rm(list=ls())
getwd()
setwd("C:/Users/Santiago/Downloads/completa")
getwd()
rh <- read.csv2("base.csv", header=T, sep = ";")
rh
View(rh)
datosrh=rh[,-c(1,2)]
datosrh
View(datosrh)
data.frame(datosrh)
names=names(datosrh)
names
estadisticas=summary(datosrh)
estadisticas
write.csv2(estadisticas,"ESTADISTICAS.csv")
vcov=var(datosrh)
View(vcov)
write.csv2(vcov,"Var-Cov.csv")
cor=cor(datosrh)
View(cor)
write.csv2(cor,"CORRELACIONES.csv")
pairs(datosrh, main="Gráfico de dispersión de los datos")
library(psych)
cortest.bartlett(cor,nrow(datosrh))
library(FactoMineR)
data.frame(datosrh)
ACP= PCA(datosrh, scale.unit = TRUE, ncp = 5,graph = FALSE, axes = c(1,2))
ACP= PCA(datosrh, scale.unit = TRUE, ncp = 5,graph = TRUE, axes = c(1,3))
ACP= PCA(datosrh, scale.unit = TRUE, ncp = 5,graph = TRUE, axes = c(2,3))
names(ACP)
ACP
attach(ACP)
var
coor=var$coor
write.csv2(coor,"Coor.csv")
cargas=var$cor
write.csv2(cargas,"Cargas.csv")
Valprop=ACP$eig
Valprop
View(Valprop)
write.csv2(Valprop,"Valprop.csv")
variables=ACP$var
variables
View(variables)
write.csv2(variables,"Variables.csv")
round(variables$contrib,1)
sum(variables$contrib[,1])
sdv=ACP$svd
write.csv2(sdv,"Sdv.csv")
Vecprop=ACP$ind
write.csv2(Vecprop,"Vecprop.csv")
Var=ACP$svd
Var
compon=Var$V
compon
write.csv2(compon,"Componentes.csv")
datosrh1=as.matrix(datosrh)
datosrh1
NuevasVar1=datosrh1%*%compon
NuevasVar1
View(NuevasVar1)
rh[1]
Municipio=as.matrix(rh[1])
Municipio
rownames(NuevasVar1)=Municipio
View(NuevasVar1)
write.csv2(NuevasVar1,"NuevasVar1.csv")
<file_sep># regionalizationpaper
##This repository contains all the data used to produce Principal components analysis and cluster analysis to reproduce "Regionalization of Latin America based on asymmetries in the absorptive capacity of countries" research.
| fd6c2a8a786abd83b37d0f69d0f6663c928bef63 | [
"Markdown",
"R"
] | 2 | R | jsgomezme/regionalizationpaper | cc241f88bd296d754cc0f26aac112f95434a47c2 | 58dbfd3a30e61356b5b0c57d681b8dea571db62c |
refs/heads/master | <file_sep>import { createStore } from 'redux';
import {
createAddition,
setAdditionBeingEdited,
editAddition,
deleteAddition
} from '../actions';
import additions from './additions';
import { selectAllAdditions } from './additions';
describe('additions', () => {
const wrongAction = {
type: 'WRONG',
solutionId: 2,
volume: 0.001,
beingEdited: false,
};
const tenMLOfWater = {
solutionId: 1,
volume: 0.010,
beingEdited: false,
};
const tenMLOfOneMolarHCl = {
solutionId: 5,
volume: 0.010,
beingEdited: false,
};
const setAddition10001BeingEdited = {
additionId: 10001,
beingEdited: true,
}
const setAddition10001NotBeingEdited = {
additionId: 10001,
beingEdited: false,
}
it ('initial state', () => {
const store = createStore(additions);
const state = store.getState();
const expected = {
allIds: [10001, 10002],
byId: {
"10001": {
"id": 10001,
"solutionId": 1,
"volume": 0.005,
"beingEdited": false,
},
"10002": {
"id": 10002,
"solutionId": 5,
"volume": 0.005,
"beingEdited": false,
}
},
};
expect(state).toMatchObject(expected);
});
it ('wrong action should let initial state unchanged', () => {
const store = createStore(additions);
const stateBefore = store.getState();
store.dispatch(wrongAction);
const stateAfter = store.getState();
expect(stateAfter).toEqual(stateBefore);
});
it ('state should be consistent with createAddition actions', () => {
const store = createStore(additions);
store.dispatch(createAddition(tenMLOfWater));
store.dispatch(createAddition(tenMLOfOneMolarHCl));
const stateAfter = store.getState();
const additionsAfter = selectAllAdditions(stateAfter);
expect(additionsAfter.length).toEqual(4);
expect(additionsAfter[2].solutionId).toEqual(1);
expect(additionsAfter[2].volume).toEqual(0.010);
expect(additionsAfter[2].beingEdited).toBe(false);
expect(additionsAfter[3].solutionId).toEqual(5);
expect(additionsAfter[3].volume).toEqual(0.010);
expect(additionsAfter[3].beingEdited).toBe(false);
});
it ('state should be consistent with setAdditionIsBeingEdited actions', () => {
const expectedA = {
allIds: [10001, 10002],
byId: {
"10001": {
"id": 10001,
"solutionId": 1,
"volume": 0.005,
"beingEdited": true,
},
"10002": {
"id": 10002,
"solutionId": 5,
"volume": 0.005,
"beingEdited": false,
}
},
};
const expectedB = {
allIds: [10001, 10002],
byId: {
"10001": {
"id": 10001,
"solutionId": 1,
"volume": 0.005,
"beingEdited": false,
},
"10002": {
"id": 10002,
"solutionId": 5,
"volume": 0.005,
"beingEdited": false,
}
},
};
const store = createStore(additions);
store.dispatch(setAdditionBeingEdited(setAddition10001BeingEdited));
expect(store.getState()).toEqual(expectedA);
store.dispatch(setAdditionBeingEdited(setAddition10001NotBeingEdited));
expect(store.getState()).toEqual(expectedB);
});
it ('state should be consistent with editAddition actions', () => {
const editAdditionA = {
additionId: 10001,
solutionId: 3,
volume: 0.003,
beingEdited: true,
}
const expectedA = {
allIds: [10001, 10002],
byId: {
"10001": {
"id": 10001,
"solutionId": 3,
"volume": 0.003,
"beingEdited": true,
},
"10002": {
"id": 10002,
"solutionId": 5,
"volume": 0.005,
"beingEdited": false,
}
},
};
const store = createStore(additions);
store.dispatch(editAddition(editAdditionA));
expect(store.getState()).toEqual(expectedA);
});
it ('delete additions 1.', () => {
const store = createStore(additions);
store.dispatch(deleteAddition({additionId: 10001}));
const expectedA = {
allIds: [10002],
byId: {
"10002": {
"id": 10002,
"solutionId": 5,
"volume": 0.005,
"beingEdited": false,
}
},
};
expect(store.getState()).toEqual(expectedA);
store.dispatch(deleteAddition({additionId: 10002}));
const expectedB = {
allIds: [],
byId: {},
};
expect(store.getState()).toEqual(expectedB);
});
it ('delete additions 2.', () => {
const store = createStore(additions);
expect(Object.keys(store.getState().byId).length).toEqual(2);
expect(store.getState().allIds.length).toEqual(2);
store.dispatch(
createAddition({solutionId: 3,volume: 0.030,beingEdited: false,})
);
store.dispatch(
createAddition({solutionId: 4,volume: 0.040,beingEdited: true,})
);
store.dispatch(
createAddition({solutionId: 5,volume: 0.050,beingEdited: true,})
);
expect(Object.keys(store.getState().byId).length).toEqual(5);
expect(store.getState().allIds.length).toEqual(5);
const ids = store.getState().allIds;
expect(ids.length).toEqual(5);
ids.map(
id => {
store.dispatch(deleteAddition({additionId: id}));
expect(
Object.keys(store.getState().byId).length
)
.toEqual(
store.getState().allIds.length
);
}
)
const expected = {
allIds: [],
byId: {},
};
const idsAfter = store.getState().allIds;
expect(idsAfter.length).toEqual(0);
expect(true).toBe(true);
expect(store.getState()).toEqual(expected);
});
})
<file_sep>import { createStore } from 'redux';
import { addSolution } from '../actions';
import solutions from './solutions';
import { selectAllSolutions } from './solutions';
describe('solutions', () => {
const wrongAction = {
type: 'WRONG',
id: 2,
name: 'wrong',
};
const solA = {
id: 0,
name: 'water',
category: 0,
listOfSpeciesInSolution: [],
};
const solB = {
id: 1,
name: 'millimolar HCl',
category: 1,
listOfSpeciesInSolution: [ { 12: 0.001 }, { 13: 0.001 }, ],
};
it ('initial state', () => {
const store = createStore(solutions);
const state = store.getState();
const expected = {
allIds: [],
byId: {},
};
expect(state).toMatchObject(expected);
});
it ('wrong action should let initial state unchanged', () => {
const store = createStore(solutions);
const stateBefore = store.getState();
store.dispatch(wrongAction);
const stateAfter = store.getState();
expect(stateAfter).toEqual(stateBefore);
});
it ('state should be consistent with dispatched actions', () => {
const store = createStore(solutions);
store.dispatch(addSolution(solA));
store.dispatch(addSolution(solB));
const stateAfter = store.getState();
const expected = {
allIds: [0, 1],
byId: {
0: {
id: 0,
name: 'water',
category: 0,
listOfSpeciesInSolution: [],
},
1: {
id: 1,
name: 'millimolar HCl',
category: 1,
listOfSpeciesInSolution: [ { 12: 0.001 }, { 13: 0.001 }, ],
},
},
};
expect(stateAfter).toEqual(expected);
});
it ('selectAllSolutions', () => {
const store = createStore(solutions);
store.dispatch(addSolution(solA));
store.dispatch(addSolution(solB));
const stateAfter = store.getState();
const allSols = selectAllSolutions(stateAfter);
expect(typeof allSols).toEqual('object');
expect(allSols.length).toBe(2);
});
})<file_sep>import { createStore } from 'redux';
import {
setActiveTubeId,
increaseActiveTubeId,
decreaseActiveTubeId
} from '../actions';
import rack from './rack';
import { selectActiveTubeId } from './rack';
describe('testTubes', () => {
const wrongAction = {
type: 'WRONG',
};
it ('set active tube id', () => {
const store = createStore(rack);
store.dispatch(
setActiveTubeId({
activeTubeId: 2,
})
);
const state = store.getState();
const expected = {
activeTubeId: 2
};
expect(state).toMatchObject(expected);
});
it ('increase active tube id', () => {
const store = createStore(rack);
store.dispatch(
increaseActiveTubeId({})
);
const state = store.getState();
const expected = {
activeTubeId: 2
};
expect(state).toMatchObject(expected);
});
it ('decrease active tube id', () => {
const store = createStore(rack);
store.dispatch(
setActiveTubeId({
activeTubeId: 3,
})
);
store.dispatch(
decreaseActiveTubeId({})
);
const state = store.getState();
const expected = {
activeTubeId: 2
};
expect(state).toMatchObject(expected);
});
it ('select', () => {
const store = createStore(rack);
store.dispatch(
setActiveTubeId({
activeTubeId: 3,
})
);
const state = store.getState();
const value = selectActiveTubeId(state);
expect(value).toEqual(3);
});
})<file_sep>import { connect } from 'react-redux';
import { Addition } from './Addition';
import {
setAdditionBeingEdited,
addAndFetchColor,
deleteAddition,
} from '../actions'
import {
selectAllSolutions,
getActiveTube,
} from '../reducers';
const mapStateToProps = (state, { addition }) => {
return {
addition: addition,
solution: selectAllSolutions(state)
.filter(solution => solution.id === addition.solutionId)[0],
activeTube: getActiveTube(state),
}
};
const mapDispatchToProps = (dispatch, { addition }) => ({
deleteAddition: ( addition ) => {
dispatch(
deleteAddition({additionId: addition.id})
)
},
setBeingEdited: ( addition ) => {
dispatch(setAdditionBeingEdited(
{
additionId: addition.id,
beingEdited: true
}
))
},
performAddition: ( addition, solution, tube ) => {
const amounts = solution.listOfSpeciesInSolution.reduce(
(result,item) => ({
...result,
[item.species.id] : {
speciesId: item.species.id,
amount: item.concentration * addition.volume,
},
}),
{},
);
const addAction = addAndFetchColor({
volume: addition.volume,
amountsOfSpecies: amounts,
tube: tube,
});
return dispatch(addAction);
},
});
export const AdditionContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(Addition);
<file_sep>import React from 'react';
import { buttonStyle } from '../style/buttonStyle';
export class ToggleableAddition extends React.Component {
handleFormOpen = () => {
this.props.createAddition();
};
render() {
return (
<button
style={buttonStyle}
onClick={this.handleFormOpen}>
{'+'}
</button>
);
}
}
<file_sep>import { createStore } from 'redux';
import { add, replace, setRgb, setVolumeAndSpecies } from '../actions';
import testTubes from './testTubes';
import { selectAllTestTubes } from './testTubes';
describe('testTubes', () => {
const wrongAction = {
type: 'WRONG',
};
const additionOfNothing = add({
tubeId: 3,
volume: 0.0,
amountsOfSpecies: {},
});
const additionOfWater = add({
tubeId: 3,
volume: 0.001,
amountsOfSpecies: {},
});
const additionOfSpeciesA = add({
tubeId: 3,
volume: 0.0,
amountsOfSpecies: {
4: { speciesId: 4, amount: 0.000001, } ,
},
});
const additionOfSpeciesB = add({
tubeId: 2,
volume: 0.0,
amountsOfSpecies: {
5: { speciesId: 5, amount: 0.000001, } ,
},
});
const replaceTube = replace({
tubeId: 2,
});
it ('set r g b', () => {
const store = createStore(testTubes);
store.dispatch(
setRgb({
tubeId: 2,
r: 100.0,
g: 110.0,
b: 120.0,
})
);
const state = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: { id: 2, volumeInLiter: 0.0, speciesInSolution: {}, r: 100.0, g: 110.0, b: 120.0 },
3: { id: 3, volumeInLiter: 0.0, speciesInSolution: {} },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(state).toMatchObject(expected);
});
it ('set tube volume and species', () => {
const store = createStore(testTubes);
store.dispatch(
setVolumeAndSpecies({
tubeId: 2,
volumeInLiter: 0.008,
speciesInSolution: { 4: { speciesId: 4, amount: 0.000001 } },
})
);
const state = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: {
id: 2,
volumeInLiter: 0.008,
speciesInSolution: {
4: { speciesId: 4, amount: 0.000001 },
}
},
3: { id: 3, volumeInLiter: 0.0, speciesInSolution: {} },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(state).toMatchObject(expected);
});
it ('initial state', () => {
const store = createStore(testTubes);
const state = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: { id: 2, volumeInLiter: 0.0, speciesInSolution: {} },
3: { id: 3, volumeInLiter: 0.0, speciesInSolution: {} },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(state).toMatchObject(expected);
});
it ('wrong action should let initial state unchanged', () => {
const store = createStore(testTubes);
const stateBefore = store.getState();
store.dispatch(wrongAction);
const stateAfter = store.getState();
expect(stateAfter).toEqual(stateBefore);
});
it ('additions of nothing should leave testTube properties unchanged', () => {
const store = createStore(testTubes);
store.dispatch( additionOfNothing );
const stateAfter = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: { id: 2, volumeInLiter: 0.0, speciesInSolution: {} },
3: { id: 3, volumeInLiter: 0.0, speciesInSolution: {} },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(stateAfter).toEqual(expected);
});
it ('additions of pure water should increase volume and leave species unchanged', () => {
const store = createStore(testTubes);
store.dispatch( additionOfWater );
const stateAfter = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: { id: 2, volumeInLiter: 0.0, speciesInSolution: {} },
3: { id: 3, volumeInLiter: 0.001, speciesInSolution: {} },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(stateAfter).toEqual(expected);
});
it ('addition of new species', () => {
const store = createStore(testTubes);
store.dispatch( additionOfSpeciesA );
const stateAfter = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: { id: 2, volumeInLiter: 0.0, speciesInSolution: {} },
3: { id: 3, volumeInLiter: 0.0, speciesInSolution: { 4: { speciesId: 4, amount: 0.000001 } } },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(stateAfter).toEqual(expected);
});
it ('addition of species already present', () => {
const store = createStore(testTubes);
store.dispatch( additionOfSpeciesB );
store.dispatch( additionOfSpeciesB );
const stateAfter = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: {
id: 2,
volumeInLiter: 0.0,
speciesInSolution: {
5: {
speciesId: 5,
amount: 0.000002,
}
}
},
3: { id: 3, volumeInLiter: 0.0, speciesInSolution: {} },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(stateAfter).toEqual(expected);
});
it ('replace tube while clean', () => {
const store = createStore(testTubes);
store.dispatch(replaceTube);
const stateAfter = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: { id: 2, volumeInLiter: 0.0, speciesInSolution: {} },
3: { id: 3, volumeInLiter: 0.0, speciesInSolution: {} },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(stateAfter).toEqual(expected);
});
it ('replace tube while used', () => {
const store = createStore(testTubes);
store.dispatch( additionOfSpeciesB );
store.dispatch(replaceTube);
const stateAfter = store.getState();
const expected = {
allIds: [ 1, 2, 3, 4, 5, 6 ],
byId: {
1: { id: 1, volumeInLiter: 0.0, speciesInSolution: {} },
2: { id: 2, volumeInLiter: 0.0, speciesInSolution: {} },
3: { id: 3, volumeInLiter: 0.0, speciesInSolution: {} },
4: { id: 4, volumeInLiter: 0.0, speciesInSolution: {} },
5: { id: 5, volumeInLiter: 0.0, speciesInSolution: {} },
6: { id: 6, volumeInLiter: 0.0, speciesInSolution: {} },
},
};
expect(stateAfter).toEqual(expected);
});
it ('selectAllTestTubes', () => {
const store = createStore(testTubes);
const stateAfter = store.getState();
const allTestTubes = selectAllTestTubes(stateAfter);
expect(typeof allTestTubes).toEqual('object');
expect(allTestTubes.length).toBe(6);
});
})<file_sep>import React from 'react';
import { shallow } from 'enzyme';
import { Addition } from './Addition';
describe('Addition component', () => {
let wrapper;
const additionData = { beingEdited: false, id: 10002, solutionId: 5, volume: 0.005 };
const solutionData = {
id: 5,
listOfSpeciesInSolution: [
{concentration: 1, species: {id: 12, name: "chloride", formula: "Cl-"}},
{concentration: 1, species: {id: 13, name: "hydronium", formula: "H3O+"}}
],
name: "one molar HCl"
};
const activeTubeData = {
id: 1,
volumeInLiter: 0,
speciesInSolution: {
volumeInLiter: 0
}
};
const performAdditionMock = jest.fn();
const setBeingEditedMock = jest.fn();
const deleteAdditionMock = jest.fn();
beforeEach(() => {
wrapper = shallow(
<Addition
addition={additionData}
solution={solutionData}
activeTube={activeTubeData}
performAddition={performAdditionMock}
setBeingEdited={setBeingEditedMock}
deleteAddition={deleteAdditionMock}
/>
);
})
it ('getSolutionName', () => {
const returnedString = wrapper.instance().getSolutionName();
expect(returnedString).toEqual("one molar HCl");
})
it ('solutionVolumeToString', () => {
const returnedString = wrapper.instance().solutionVolumeToString();
expect(returnedString).toEqual("5 mL");
})
it ('handleDeleteAddition', () => {
expect(deleteAdditionMock.mock.calls.length).toBe(0);
wrapper.instance().handleDeleteAddition();
expect(deleteAdditionMock.mock.calls.length).toBe(1);
expect(deleteAdditionMock.mock.calls[0].length).toBe(1);
expect(deleteAdditionMock.mock.calls[0][0]).toEqual(additionData);
})
it ('toggleToForm', () => {
expect(setBeingEditedMock.mock.calls.length).toBe(0);
wrapper.instance().toggleToForm();
expect(setBeingEditedMock.mock.calls.length).toBe(1);
expect(setBeingEditedMock.mock.calls[0].length).toBe(1);
expect(setBeingEditedMock.mock.calls[0][0]).toEqual(additionData);
})
it ('handleAddition', () => {
expect(performAdditionMock.mock.calls.length).toBe(0);
wrapper.instance().handleAddition();
expect(performAdditionMock.mock.calls.length).toBe(1);
expect(performAdditionMock.mock.calls[0].length).toBe(3);
expect(performAdditionMock.mock.calls[0][0]).toEqual(additionData);
expect(performAdditionMock.mock.calls[0][1]).toEqual(solutionData);
expect(performAdditionMock.mock.calls[0][2]).toEqual(activeTubeData);
});
})
<file_sep>import React from 'react';
import { height } from '../utils/height';
import { tubeRadius } from '../utils/tubeRadius';
export class TestTubeInRack extends React.Component {
render() {
const rCoord = this.props.tubeContent.r;
const gCoord = this.props.tubeContent.g;
const bCoord = this.props.tubeContent.b;
const color = `rgb(${rCoord},${gCoord},${bCoord})`;
const isActive = this.props.isActive;
const volume = this.props.tubeContent.volumeInLiter;
const radius = 9.0;
const tubeWallH = 150;
const margin = 20;
const hInMM = height(volume, 2*radius);
const yInPx = margin+tubeWallH+radius-Math.round(hInMM);
const xInPx = margin+radius-Math.round(tubeRadius(hInMM, 2*radius));
const deltaXInPx = Math.round(2*tubeRadius(hInMM, 2*radius));
const totalWidth = 2*margin + 2*radius;
const totalHeight = 2*margin+tubeWallH+radius;
const arrowSize = 6;
const tube = `
M${margin},${margin}
l0,${tubeWallH}
a1,1 0 0,0 ${2*radius},0
l0,-${tubeWallH}`;
const surface = `
M${xInPx},${yInPx}
l${deltaXInPx},0`;
const shape = hInMM > radius ? `
M${margin},${yInPx}
L${margin},${margin+tubeWallH}
a1,1 0 0,0 ${2*radius},0
L${margin+2*radius},${yInPx}
z` : `
M${xInPx},${yInPx}
a${radius},${radius} 0 0,0 ${deltaXInPx},0
z`;
const border = `
M1,1
L${totalWidth},1,
L${totalWidth},${totalHeight},
L1,${totalHeight},
z`;
const bottomArrow = `
M${margin+radius-arrowSize},${totalHeight},
l${arrowSize},-${arrowSize},
l${arrowSize},${arrowSize},
z`;
const topArrow = `
M${margin+radius-arrowSize},0,
l${arrowSize},${arrowSize},
l${arrowSize},-${arrowSize},
z`;
const leftArrow = `
M0,${totalHeight/2-arrowSize},
l${arrowSize},${arrowSize},
l-${arrowSize},${arrowSize},
z`;
const rightArrow = `
M${totalWidth},${totalHeight/2-arrowSize},
l-${arrowSize},${arrowSize},
l${arrowSize},${arrowSize},
z`;
const borderStroke = `${isActive ? 'none' : 'none'}`;
const arrowStroke = `${isActive ? 'black' : 'none'}`;
return (
<div>
<svg
width={totalWidth}
height={totalHeight}
>
<path
d={shape}
strokeWidth="0"
stroke="none"
fill={color}
/>
<path
d={tube}
strokeWidth="1"
stroke="black"
fill="none"
/>
<path
d={surface}
strokeWidth="0.5"
stroke="black"
/>
<path
d={border}
strokeWidth="1"
stroke={borderStroke}
fill="none"
/>
<path
d={bottomArrow}
strokeWidth="1"
stroke={arrowStroke}
fill="none"
/>
<path
d={topArrow}
strokeWidth="1"
stroke={arrowStroke}
fill="none"
/>
<path
d={leftArrow}
strokeWidth="1"
stroke={arrowStroke}
fill="none"
/>
<path
d={rightArrow}
strokeWidth="1"
stroke={arrowStroke}
fill="none"
/>
</svg>
</div>
);
}
}<file_sep>import { combineReducers } from 'redux';
import { createSelector } from 'reselect';
const initial = {
allIds: [ 10001, 10002 ],
byId: {
10001: { id: 10001, solutionId: 1, volume: 0.005, beingEdited: false },
10002: { id: 10002, solutionId: 5, volume: 0.005, beingEdited: false },
}
}
const byId = (state = initial.byId, action) => {
switch (action.type) {
case 'CREATE_ADDITION': {
return {
...state,
[action.id]: {
id: action.id,
solutionId: action.solutionId,
volume: action.volume,
beingEdited: action.beingEdited,
},
};
}
case 'SET_ADDITION_BEING_EDITED': {
return {
...state,
[action.additionId]: {
...state[action.additionId],
beingEdited: action.beingEdited,
},
};
}
case 'EDIT_ADDITION': {
return {
...state,
[action.additionId]: {
...state[action.additionId],
solutionId: action.solutionId,
volume: action.volume,
beingEdited: action.beingEdited,
},
}
}
case 'DELETE_ADDITION': {
const newState = { ...state };
delete newState[action.additionId];
return newState;
}
default:
return state;
}
};
const allIds = (state = initial.allIds, action) => {
switch (action.type) {
case 'CREATE_ADDITION':
return [
...state,
action.id,
];
case 'DELETE_ADDITION':
const newState = state.filter(x => !(x===action.additionId));
return [
...newState
];
default:
return state;
}
};
const additions = combineReducers({
byId,
allIds,
});
export default additions;
const getAllAdditions = (state) => state.allIds.map(id => state.byId[id]);
export const selectAllAdditions = createSelector(
[ getAllAdditions ],
(allAdditions) => allAdditions
)<file_sep>import React from 'react';
// import { LabStoreContainer } from './LabStoreContainer';
import { Experiment } from './Experiment';
const App = () => {
return (
<div>
<Experiment />
{/* <LabStoreContainer /> */}
</div>
);
};
App.propTypes = {
}
export default App;
<file_sep>import React from 'react';
import { CompartmentContainer } from './CompartmentContainer';
export class LabStore extends React.Component {
state = {
};
render() {
return (
<ul>
{this.props.compartments.map(
(x) => {
return (
<li key={x.id}>
<CompartmentContainer
compartment={x}
/>
</li>
);
}
)}
</ul>
);
}
}<file_sep>import React from 'react';
import { TestTubeInRackContainer } from './TestTubeInRackContainer';
import { buttonStyle } from '../style/buttonStyle';
import { outerButton } from '../style/outerButton';
export class Rack extends React.Component {
handleChangeActiveTubeLeft = () => {
this.props.tubeIdDecrease({});
}
handleChangeActiveTubeRight = () => {
this.props.tubeIdIncrease({});
}
render() {
const rackStyle = {
'width': '360px',
'height': '200px',
'border': '0px solid #c3c3c3',
'display': 'flex',
'flexDirection': 'row',
};
return (
<div className="container" style={rackStyle}>
<div style={outerButton}>
<button onClick={this.handleChangeActiveTubeLeft} style={buttonStyle}>
{'<'}
</button>
</div>
{this.props.testTubes.map(
item => (
<div key={item.id}>
<TestTubeInRackContainer
tubeId={item.id}
isActive={this.props.activeTube.id === item.id}
/>
</div>
)
)}
<div style={outerButton}>
<button onClick={this.handleChangeActiveTubeRight} style={buttonStyle}>
{'>'}
</button>
</div>
</div>
);
}
}<file_sep>import { connect } from 'react-redux';
import { createAddition } from '../actions';
import { Additions } from './Additions';
import {
selectAllAdditions,
} from '../reducers';
const mapStateToProps = (state, ownProps) => {
return {
activeTestTubeId: ownProps.activeTestTubeId,
additions: selectAllAdditions(state),
}
};
const mapDispatchToProps = (dispatch) => ({
createAddition: ({solutionId, volume }) => {
dispatch(createAddition({ solutionId, volume }))
},
});
export const AdditionsContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(Additions);
<file_sep>/**
* Parameters:
* z = height
* d = tube diameter
*
* Returned result:
* tube radius at height z
*/
export const tubeRadius = (z, d) => {
if (z < 0.) {
return;
}
if (z === 0.) {
return 0.;
}
if (z === d/2.) {
return d/2.;
}
if (z < d/2.) {
return Math.sqrt(0.25*d*d-(0.5*d-z)*(0.5*d-z));
}
if (z > d/2.) {
return d/2.;
}
}<file_sep>import _ from 'lodash';
import { v4 } from 'uuid';
import Client from '../Client';
export const addCompartment = ( { id, name } ) => ({
type: 'ADD_COMPARTMENT',
id: id,
name: name,
});
export const addSolution = ( { id, name, category, listOfSpeciesInSolution } ) => ({
type: 'ADD_SOLUTION',
id: id,
name: name,
category: category,
listOfSpeciesInSolution: listOfSpeciesInSolution,
});
export const addSpecies = ( { id, name, formula } ) => ({
type: 'ADD_SPECIES',
id: id,
name: name,
formula: formula,
});
export const add = ( { tubeId, volume, amountsOfSpecies } ) => ({
type: 'ADD',
tubeId: tubeId,
volume: volume,
amountsOfSpecies: amountsOfSpecies,
});
export const replace = ( { tubeId } ) => ({
type: 'REPLACE_WITH_CLEAN',
tubeId: tubeId,
});
export const setVolumeAndSpecies = ( { tubeId, volumeInLiter, speciesInSolution }) => ({
type: 'SET_VOLUME_AND_SPECIES',
tubeId: tubeId,
volumeInLiter: volumeInLiter,
speciesInSolution: speciesInSolution,
});
export const setRgb = ( { tubeId, r, g, b } ) => ({
type: 'SET_R_G_B',
tubeId: tubeId,
r: r,
g: g,
b: b,
});
export const createAddition = ( { solutionId, volume, beingEdited } ) => ({
type: 'CREATE_ADDITION',
id: v4(),
solutionId: solutionId,
volume: volume,
beingEdited: beingEdited,
});
export const setAdditionBeingEdited = ( { additionId, beingEdited} ) => ({
type: 'SET_ADDITION_BEING_EDITED',
additionId: additionId,
beingEdited: beingEdited,
});
export const editAddition = ({ additionId, solutionId, volume, beingEdited }) => ({
type: 'EDIT_ADDITION',
additionId: additionId,
solutionId: solutionId,
volume: volume,
beingEdited: beingEdited,
});
export const deleteAddition = ({ additionId }) => ({
type: 'DELETE_ADDITION',
additionId: additionId,
});
export const addAndFetchColor = ( { volume, amountsOfSpecies, tube } ) => {
return function (dispatch, getState) {
// calculate tube's new volume and amounts of species
const speciesBefore = tube.speciesInSolution;
const speciesAfter = Object.keys(amountsOfSpecies).reduce(
(object, key) => {
const previousAmount = _.isUndefined(object[key]) ? 0.0 : object[key].amount;
const newAmount = previousAmount + amountsOfSpecies[key].amount;
return {
...object,
[key]: {
speciesId: amountsOfSpecies[key].speciesId,
amount: newAmount,
}
}
},
{ ...speciesBefore }
);
const volumeAfter = tube.volumeInLiter + volume;
// TODO dispatch some action to display spinner informing
// user on API call in progress
// process the structure of the species amount data into array
const speciesInSolutionArray = Object.keys(speciesAfter)
.reduce(
(array, item) => {
return [
...array,
{
speciesId: speciesAfter[item].speciesId,
amount: speciesAfter[item].amount,
}
];
},
[]
);
// instantiate the request object
const data = {
...tube,
volumeInLiter: volumeAfter,
speciesInSolution: speciesInSolutionArray,
};
Client.fetchRgb(
data,
result => {
dispatch(setVolumeAndSpecies(
{
tubeId: tube.id,
volumeInLiter: volumeAfter,
speciesInSolution: speciesAfter,
}
)
);
dispatch(setRgb(
{
tubeId: tube.id,
r: result.coordR,
g: result.coordG,
b: result.coordB,
}
)
);
}
)
}
};
export const setActiveTubeId = ( { activeTubeId } ) => ({
type: 'SET_ACTIVE_TUBE_ID',
activeTubeId: activeTubeId,
});
export const increaseActiveTubeId = () => ({
type: 'INCREASE_ACTIVE_TUBE_ID',
});
export const decreaseActiveTubeId = () => ({
type: 'DECREASE_ACTIVE_TUBE_ID',
});
<file_sep>import { connect } from 'react-redux';
import { /* actions */ } from '../actions';
import { TestTubeInRack } from './TestTubeInRack';
import { selectAllTestTubes } from '../reducers';
const mapStateToProps = (state, ownProps) => {
return {
isActive: ownProps.isActive,
tubeId: ownProps.tubeId,
tubeContent: selectAllTestTubes(state)
.filter(tube => tube.id === ownProps.tubeId)[0],
}
};
const mapDispatchToProps = (dispatch) => (
{ /* actions */ }
);
export const TestTubeInRackContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(TestTubeInRack);
<file_sep>import React from 'react';
import _ from 'lodash';
import { AdditionContainer } from './AdditionContainer';
import { AdditionFormContainer } from './AdditionFormContainer';
import { ToggleableAdditionContainer } from './ToggleableAdditionContainer';
import { container, additions, item, hole, toggleable} from '../style/style.css';
import { outerButton } from '../style/outerButton';
export class AdditionsList extends React.Component {
render() {
const additions = this.props.additions;
return (
<div>
<div className="container additions">
{additions.map(
item => {
if ( !_.isUndefined(item) && item.beingEdited ) {
return (
<div key={item.id}>
<div className="hole">
<div className="item">
<AdditionFormContainer addition={item} />
</div>
</div>
</div>
)
} else {
return (
<div key={item.id}>
<div className="hole">
<div className="item">
<AdditionContainer addition={item} />
</div>
</div>
</div>
);
}
}
)}
<div className="hole">
<div className="toggleable" style={outerButton}>
<ToggleableAdditionContainer />
</div>
</div>
</div>
</div>
);
}
}<file_sep>import { connect } from 'react-redux';
import { AdditionForm } from './AdditionForm';
import {
selectAllSolutions,
selectAllCompartments,
selectAllSpecies,
} from '../reducers';
import {
editAddition,
deleteAddition,
} from '../actions';
const mapStateToProps = (state, { addition }) => {
return {
addition: addition,
solutions: selectAllSolutions(state),
compartments: selectAllCompartments(state),
species: selectAllSpecies(state),
}
};
const mapDispatchToProps = (dispatch) => ({
dispatchEditAddition: (additionId, solutionId, volume) => {
dispatch(editAddition( { additionId: additionId, solutionId: solutionId, volume: volume, beingEdited: false } ))
},
handleDeleteAddition: (addition) => {
dispatch(
deleteAddition({additionId: addition.id})
);
}
});
export const AdditionFormContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(AdditionForm);
<file_sep>import { combineReducers } from 'redux';
import { createSelector } from 'reselect';
const byId = (state = {}, action) => {
switch (action.type) {
case 'ADD_SOLUTION':
return {
...state,
[action.id]: {
id: action.id,
name: action.name,
category: action.category,
listOfSpeciesInSolution: action.listOfSpeciesInSolution,
},
};
default:
return state;
}
};
const allIds = (state = [], action) => {
switch (action.type) {
case 'ADD_SOLUTION':
return [
...state,
action.id,
];
default:
return state;
}
};
const solutions = combineReducers({
byId,
allIds,
});
export default solutions;
const getAllSolutions = (state) => state.allIds.map(id => state.byId[id]);
export const selectAllSolutions = createSelector(
[ getAllSolutions ],
(allSolutions) => allSolutions
)<file_sep>import { createSelector } from 'reselect';
const TUBE_ID_MAX = 6;
const rack = (state = { activeTubeId: 1 }, action) => {
switch (action.type) {
case 'SET_ACTIVE_TUBE_ID':
return {
activeTubeId: action.activeTubeId
}
case 'INCREASE_ACTIVE_TUBE_ID':
const increasedValue = state.activeTubeId < TUBE_ID_MAX
? state.activeTubeId + 1
: state.activeTubeId
return {
activeTubeId: increasedValue,
}
case 'DECREASE_ACTIVE_TUBE_ID':
const decreasedValue = state.activeTubeId > 1
? state.activeTubeId - 1
: state.activeTubeId
return {
activeTubeId: decreasedValue,
}
default:
return state;
}
};
export default rack;
const getActiveTubeId = (state) => state.activeTubeId;
export const selectActiveTubeId = createSelector(
[ getActiveTubeId ],
(tubeId) => tubeId
)<file_sep>export const buttonStyle = {
color: 'white',
backgroundColor: 'grey',
height: '25px',
width: '25px',
border: 'none',
borderRadius: '4px',
margin: '6px',
};
<file_sep>import thunkMiddleware from 'redux-thunk';
import {
createStore,
applyMiddleware
} from 'redux';
import labApp from './reducers';
const configureStore = () => {
const store = createStore(
labApp,
applyMiddleware(
thunkMiddleware,
)
);
return store;
};
export default configureStore;
<file_sep>const pi = 3.1415926535897932;
const derivative = (h, d) => {
return pi*(d*h-h*h)/1000000.;
}
const volume = (h, d) => {
return pi*(d/2.-h/3.)*h*0.001*h*0.001;
}
const vBottom = d => 0.01*d*0.01*d*0.01*d*pi/12.;
/**
* Parameters:
* v = liquid volume in liter
* d = tube diameter in millimeter
*
* Returned result:
* liquid height in millimeter
*/
export const height = (v, d) => {
if (v < 0.) {
return;
}
if (v === 0.) {
return 0.;
}
if (v === vBottom(d)) {
return d/2.;
}
if (v < vBottom(d)) {
const h0 = d/2.828;
const h1 = h0 + (v-volume(h0,d))/derivative(h0,d);
const h2 = h1 + (v-volume(h1,d))/derivative(h1,d);
const h3 = h2 + (v-volume(h2,d))/derivative(h2,d);
const h4 = h3 + (v-volume(h3,d))/derivative(h3,d);
const h5 = h4 + (v-volume(h4,d))/derivative(h4,d);
const h6 = h5 + (v-volume(h5,d))/derivative(h5,d);
return h6;
}
if (v > vBottom(d)) {
return d/2. + (v-vBottom(d))*4/(pi*0.001*d*0.001*d);
}
}<file_sep>import React from 'react';
export class Solution extends React.Component {
state = {
};
render() {
const solution = this.props.solution;
return (
<div>
{solution.name}
<ul>
{solution.listOfSpeciesInSolution.map( (item) => {
return(
<li key={item.species.id}>
{item.species.name}
{': '}
{item.concentration}
{' mol/L'}
</li>
);
})
}
</ul>
</div>
);
}
}<file_sep>import { connect } from 'react-redux';
import { Compartment } from './Compartment';
import { selectAllSolutions } from '../reducers';
const mapStateToProps = (state, { compartment }) => {
return {
compartment: compartment,
theSolutions: selectAllSolutions(state)
.filter( item => item.category.id === compartment.id),
}
};
export const CompartmentContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(Compartment);
<file_sep>import { connect } from 'react-redux';
import { ToggleableAddition } from './ToggleableAddition';
import { createAddition } from '../actions';
import { /* selectAllSolutions */ } from '../reducers';
const mapStateToProps = (state) => {
return {
}
};
const mapDispatchToProps = (dispatch) => ({
createAddition: () => {
dispatch(
createAddition(
{
solutionId: 1,
volume: 0,
beingEdited: true
}
)
)
},
});
export const ToggleableAdditionContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(ToggleableAddition);
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import { addSpecies, addCompartment, addSolution} from './actions';
import Client from './Client';
import configureStore from './configureStore';
import Root from './components/Root';
const store = configureStore();
Client.search(
'species',
data => data.map(
species => store.dispatch( addSpecies(species) )
)
);
Client.search(
'storeSolutionCategories',
data => data.map(
category => store.dispatch( addCompartment(category) )
)
);
Client.search(
'solutions',
data => data.map(
solution => store.dispatch( addSolution(solution) )
)
);
ReactDOM.render(
<Root store={store} />,
document.getElementById('root')
);
<file_sep>import React from 'react';
import { RackContainer } from './RackContainer';
import { AdditionsContainer } from './AdditionsContainer';
export class Experiment extends React.Component {
/* constructor(props) {
super(props);
this.state = {
activeTestTubeId: 1,
};
}
increaseId = () => {
const newValue = (this.state.activeTestTubeId === 6)
? 6
: this.state.activeTestTubeId + 1;
this.setState({
...this.state,
activeTestTubeId: newValue,
});
}
decreaseId = () => {
const newValue = (this.state.activeTestTubeId === 1)
? 1
: this.state.activeTestTubeId - 1;
this.setState({
...this.state,
activeTestTubeId: newValue,
});
} */
render() {
return (
<div>
<RackContainer />
<AdditionsContainer />
</div>
);
}
}<file_sep>import { connect } from 'react-redux';
import { AdditionsList } from './AdditionsList';
import {
selectAllAdditions,
} from '../reducers';
const mapStateToProps = (state, ownProps) => {
return {
activeTestTubeId: ownProps.activeTestTubeId,
additions: selectAllAdditions(state),
}
};
const mapDispatchToProps = (dispatch) => ({
});
export const AdditionsListContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(AdditionsList);
| c6b15e3286d5b10b28c1de767c761018d52106fd | [
"JavaScript"
] | 29 | JavaScript | nperon/react-chem | 4387c1105e556503a44ddbc6a3d32b9c50564876 | 6e01383c0eaf762331077c04cf0d475827f0788f |
refs/heads/master | <file_sep>#!/usr/bin/perl -w
#http://www.moko.cc/MOKO_POST_ORDER_MOKO/1/postList.html
#Thu Jun 25 16:30:24 2009
use strict;
#================================================================
# apply_rule will be called with ($RuleBase,%Rule),the result returned have these meaning:
# $result{base} : Base url to build the full url
# $result{work_dir} : Working directory (will be created if not exists)
# $result{data} : Data array extracted from url,will be passed to $result{action}(see followed)
# $result{action} : Command which the $result{data} will be piped to,can be overrided
# $result{pipeto} : Same as action,Command which the $result{data} will be piped to,can be overrided
# $result{hook} : Hook action,function process_data will be called
# $result{no_subdir} : Do not create sub directories
# $result{pass_data} : Data array which will be passed to next level of urlrule
# $result{pass_name} : Names of each $result{pass_data}
# $result{pass_arg} : Additional arguments to be passed to next level of urlrule
#================================================================
use MyPlace::HTML;
sub apply_rule {
my $rule_base= shift(@_);
my %rule = %{shift(@_)};
my %r;
$r{base}=$rule_base;
my %data;
open FI,"-|","netcat \'$rule_base\'";
my @links = get_hrefs(<FI>);
close FI;
foreach(@links) {
next if(/\.html$/);
$data{$_} = 1 if(/^\/[^\/]+\/?$/);
}
push @{$r{pass_data}},keys %data if(%data);
$r{no_subdir}=1;
return %r;
}
1;
<file_sep>#!/bin/sh
SRC=/myplace/overjoy/
cp -av "$SRC/HOSTS.URL" .
cp -av "$SRC/ladies/DATABASE.URL" .
<file_sep>#!/bin/sh
echo Writing disk usage to DU.txt
du -s --time -B M -c * | tee DU.txt
echo Writing file lists to FILES.txt
find * | tee FILES.txt
| b636e6f6a9cb4e956f4b82b985d0278125819f7f | [
"C++",
"Shell"
] | 3 | C++ | urlrule/rules | 1b04a2c94f45d7e4db4dcc8f10efcacb3da27f25 | c53a7e3b1a6cdbe4fcf34bc6aff9c508c3b8a6a9 |
refs/heads/master | <repo_name>saikotprof/inventory<file_sep>/product/migrations/0001_initial.py
# Generated by Django 2.2.6 on 2019-10-18 14:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('company_name', models.CharField(max_length=50)),
('description', models.TextField(max_length=500)),
],
),
migrations.CreateModel(
name='Mobile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=40)),
('price', models.IntegerField()),
('status', models.CharField(choices=[('Available', 'Item is ready to be purchased'), ('Sold', 'Item is already purchased'), ('Sold Out', 'Item is comming soon')], default='Sold', max_length=40)),
('issues', models.CharField(default='No Issues', max_length=40)),
('brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.Brand')),
],
),
migrations.CreateModel(
name='Apple',
fields=[
('mobile_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='product.Mobile')),
],
bases=('product.mobile',),
),
migrations.CreateModel(
name='Samsung',
fields=[
('mobile_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='product.Mobile')),
],
bases=('product.mobile',),
),
migrations.CreateModel(
name='Xiaomi',
fields=[
('mobile_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='product.Mobile')),
],
bases=('product.mobile',),
),
]
<file_sep>/product/urls.py
from django.urls import path
from .views import index, product, apple, xiaomi, samsung
urlpatterns = [
path('', index, name='home'),
path('product-details/', product, name='product-details'),
path('apple/', apple, name='apple'),
path('samsung/', samsung, name='samsung'),
path('xiaomi/', xiaomi, name='xiaomi'),
]
<file_sep>/product/templates/inventory/products.html
{% extends 'base.html' %}
{% block content %}
<br>
<br>
<div class="container">
<div class="add_buttons">
<div class="button-group">
<a href="{% url 'home' %}" class="btn btn-info btn-md btn-trim" role="button"> Home</a>
<a href="{% url 'product-details' %}" class="btn btn-warning btn-md btn-trim" role="button"> Products Page</a>
<a href="{% url 'apple' %}" class="btn btn-primary btn-md btn-trim" role="button"> Apple</a>
<a href="#" class="btn btn-warning btn-sm btn-pad" role="button"> +</a>
<a href="{% url 'samsung' %}" class="btn btn-primary btn-md btn-trim" role="button"> Samsung</a>
<a href="#" class="btn btn-warning btn-sm btn-pad" role="button"> +</a>
<a href="{% url 'xiaomi' %}" class="btn btn-primary btn-md btn-trim" role="button"> Xiaomi</a>
<a href="#" class="btn btn-warning btn-sm btn-pad" role="button"> +</a>
</div>
</div>
<br>
<div>
<h4>Currently Viewing {{ header }}</h4>
</div>
<table class="table table-bordered">
<thead class="table-dark">
<tr class="text-center">
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Brand</th>
<th scope="col">Price</th>
<th scope="col">Status</th>
<th scope="col">Issues</th>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<th scope="row">{{ item.pk }}</th>
<td>{{ item.name }}</td>
<td>{{ item.brand }}</td>
<td>{{ item.price }}$</td>
<td>{{ item.status }}</td>
<td>{{ item.issues }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}<file_sep>/product/admin.py
from django.contrib import admin
from .models import Brand, Apple, Samsung, Xiaomi, Mobile
admin.site.register(Brand)
admin.site.register(Apple)
admin.site.register(Samsung)
admin.site.register(Xiaomi)
admin.site.register(Mobile)<file_sep>/product/models.py
from django.db import models
class Brand(models.Model):
company_name = models.CharField(max_length=50)
description = models.TextField(max_length=500)
def __str__(self):
return self.company_name
class Mobile(models.Model):
name = models.CharField(max_length=40)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
price = models.IntegerField()
choose = [
('Available', 'Item is ready to be purchased'),
('Sold', 'Item is already purchased'),
('Sold Out', 'Item is comming soon'),
]
status = models.CharField(max_length=40, choices=choose, default='Sold')
issues = models.CharField(max_length=40, default='No Issues')
def __str__(self):
return f"{self.name} - {self.brand} - {self.price}"
class Apple(Mobile):
pass
class Samsung(Mobile):
pass
class Xiaomi(Mobile):
pass
<file_sep>/product/views.py
from django.shortcuts import render
from .models import Apple, Samsung, Xiaomi, Mobile
def index(request):
return render(request, 'index.html')
def product(request):
items = Mobile.objects.all()
context = {
'items': items,
'header': 'Products Page',
}
return render(request, 'inventory/products.html', context)
def apple(request):
items = Apple.objects.all()
context = {
'items': items,
'header': 'Apple',
}
return render(request, 'inventory/products.html', context)
def samsung(request):
items = Samsung.objects.all()
context = {
'items': items,
'header': 'Samsung',
}
return render(request, 'inventory/products.html', context)
def xiaomi(request):
items = Xiaomi.objects.all()
context = {
'items': items,
'header': 'Xiaomi',
}
return render(request, 'inventory/products.html', context)
| fd9d9793b3af3c33170519380aecc61ace44cc30 | [
"Python",
"HTML"
] | 6 | Python | saikotprof/inventory | d53260e5c1c1bd656c781e7106a81ecd9fafba48 | 0a5a064c01a0c2c16a47d724ec65b8d214bd9199 |
refs/heads/master | <repo_name>sihaojunvn2012/Manage-Plane<file_sep>/Do An (1)/Source (1).cpp
#include "Process.h"
int main()
{
//nAirplane begin = 0
system("color 5A");
setFullScreen();
PTR_LIST_AIRPLANE l = new LIST_AIRPLANE;
LoadAirplane(l);
TREE_PASSENGER t;
InitTreePassenger(t);
LoadPassenger(t);
/*for (int i = 0; i <= l->n; i++)
{
LIST_FLIGHT fl = l->listAirplane[i]->listFlight;
NODE_FLIGHT* p = fl.pHead;
while (p != NULL)
{
delete[]p->data.listTicket;
p->data.listTicket = new TICKET[MAX_TICKET];
p = p->pNext;
}
}
*/
MageAll(l,t);
SaveAirplane(l);
SavePassenger(t);
system("pause");
return 0;
}<file_sep>/Do An (1)/Process (1).h
#ifndef _PROCESS_H
#define _PROCESS_H
#include "Airplane.h"
#include <fstream>
//-------------------DATABASE--------------------------------
void LoadAirplane(PTR_LIST_AIRPLANE &pListAirplane)
{
int SizeFlight = sizeof(FLIGHT) - sizeof(TICKET*);
int SizeAirplane = sizeof(AIRPLANE) - sizeof(LIST_FLIGHT);
fstream fileData("data.txt", ios::in | ios::binary);
while (!fileData.eof())
{
pListAirplane->listAirplane[++pListAirplane->n] = new AIRPLANE;
fileData.read(reinterpret_cast<char*>(pListAirplane->listAirplane[pListAirplane->n]), SizeAirplane);
InitListFlight(pListAirplane->listAirplane[pListAirplane->n]->listFlight);
int nFlight = pListAirplane->listAirplane[pListAirplane->n]->nFlight;
FLIGHT p;
for (int j = 0; j < nFlight; ++j)
{
fileData.read(reinterpret_cast<char*>(&p), SizeFlight);
int nTicket = p.nTicket;
p.listTicket = new TICKET[MAX_TICKET];
for (int i = 0; i < nTicket; i++)
fileData.read(reinterpret_cast<char*>(&p.listTicket[i]), sizeof(TICKET));
AddTailListFlight(pListAirplane->listAirplane[pListAirplane->n]->listFlight, p);
}
}
delete pListAirplane->listAirplane[pListAirplane->n];
--pListAirplane->n;
fileData.close();
}
void SaveAirplane(PTR_LIST_AIRPLANE pListAirplane)
{
int SizeFlight = sizeof(FLIGHT) - sizeof(TICKET*);
int SizeAirplane = sizeof(AIRPLANE) - sizeof(LIST_FLIGHT);
fstream fileData("data.txt", ios::out | ios::binary);
for (int i = 0; i <= pListAirplane->n; i++)
{
pListAirplane->listAirplane[i]->nFlight = pListAirplane->listAirplane[i]->listFlight.n;
fileData.write(reinterpret_cast<const char*>(pListAirplane->listAirplane[i]), SizeAirplane);
NODE_FLIGHT* p = pListAirplane->listAirplane[i]->listFlight.pHead;
while (p != NULL)
{
fileData.write(reinterpret_cast<const char*>(&p->data), SizeFlight);
int nTicket = p->data.nTicket;
for (int i = 0; i < nTicket; i++)
fileData.write(reinterpret_cast<const char*>(&p->data.listTicket[i]), sizeof(TICKET));
p = p->pNext;
}
}
fileData.close();
}
void WritePassengerToFile(NODE_PASSENGER* p, fstream &file, int size)
{
if (p != NULL)
{
file.write(reinterpret_cast<const char*>(&p->data), size);
WritePassengerToFile(p->pLeft, file, size);
WritePassengerToFile(p->pRight, file, size);
}
}
void SavePassenger(TREE_PASSENGER t)
{
fstream myfile("passenger.txt", ios::out | ios::binary);
myfile << nPassenger;
int sizeData = sizeof(PASSENGER);
TREE_PASSENGER p = t;
WritePassengerToFile(p, myfile, sizeData);
myfile.close();
}
void LoadPassenger(TREE_PASSENGER &t)
{
fstream myfile("passenger.txt", ios::in | ios::binary);
int nPassenger;
myfile >> nPassenger;
int sizeData = sizeof(PASSENGER);
PASSENGER pa;
for (int i = 0; i <= nPassenger; i++)
{
myfile.read(reinterpret_cast<char*>(&pa), sizeData);
InsertPassengerToTree(t, pa);
}
}
//--------------------------END DATABASE
//--------------------------STATISTIC
void OutputPassengerOnFlight(FLIGHT fl, TREE_PASSENGER t)
{
int ordinal = -1;
Display(keyDisplayPassenger, sizeof(keyDisplayPassenger) / sizeof(string));
DeleteGuide(sizeof(keyDisplayPassenger) / sizeof(string) + 1);
for (int i = 0; i < fl.nTicket; i++)
{
if (fl.listTicket[i].stt == TICKET_SOLD)
{
NODE_PASSENGER* pa = FindPassenger(t, fl.listTicket[i].idOwner);
OutputPassenger(pa->data, ++ordinal);
}
}
}
bool StatisticPassengerOnFlightIsSucceed(PTR_LIST_AIRPLANE l, TREE_PASSENGER t)
{
int indexAirplane = DisplayAndChooseIndexAirplane(l, "CHON MAY BAY MUON THONG KE");
Gotoxy(X_TITLE, Y_TITLE); cout << "CHON CHUYEN BAY MUON DAT VE";
if (indexAirplane == -1)
{
system("cls");
return false;
}
system("cls");
Gotoxy(X_TITLE, Y_TITLE); cout << "CHON CHUYEN BAY MUON HIEN THI";
Display(keyDisplayFlight, sizeof(keyDisplayFlight) / sizeof(string));
NODE_FLIGHT* fl = ChooseFlight(l->listAirplane[indexAirplane]->listFlight);
if (fl == NULL)
{
system("cls");
return false;
}
system("cls");
Gotoxy(X_TITLE, Y_TITLE);
cout << "DANH SACH HANH KHACH THUOC CHUYEN BAY " << fl->data.id;
Gotoxy(X_TITLE, Y_TITLE + 1);
cout << "NOI DEN " << fl->data.destiny;
Gotoxy(X_TITLE, Y_TITLE + 2);
cout << "NGAY <NAME> " << fl->data.dateLeave.d << "/" << fl->data.dateLeave.m << "/" << fl->data.dateLeave.y;
if (fl->data.nTicketSold == 0)
{
Gotoxy(X_NOTIFY, Y_NOTIFY);
cout << "Khong co du lieu";
}
else OutputPassengerOnFlight(fl->data, t);
_getch();
return true;
}
bool StatisticFlightOnDay(PTR_LIST_AIRPLANE l)
{
system("cls");
DATETIME dt;
Gotoxy(X_ADD + 12 + 8, 3 + Y_ADD);
cout << "/";
Gotoxy(X_ADD + 12 + 11, 3 + Y_ADD);
cout << "/";
bool isMove = false;
bool isSave = false;
int newOrdinal = 2;
Gotoxy(X_TITLE, Y_TITLE);
cout << "NHAP NGAY GIO CAN THONG KE ";
Gotoxy(X_TITLE, Y_TITLE + 1);
cout << "Nhan F10 de hien thi ket qua";
while (true)
{
switch (newOrdinal)
{
case 2:
CheckMoveAndValidateDateTime(dt.d, isMove, newOrdinal, isSave, 31, 12);
break;
case 3:
CheckMoveAndValidateDateTime(dt.m, isMove, newOrdinal, isSave, 12, 12);
break;
case 4:
CheckMoveAndValidateDateTime(dt.y, isMove, newOrdinal, isSave, 10000, 12);
break;
} // end switch newordinal
//check key move
if (isMove)
{
if (newOrdinal == 2)
isMove = false;
else
newOrdinal--;
}
else
{
if (newOrdinal == 4)
isMove = true;
else
newOrdinal++;
}
if (isSave)
{
if (DateTimeIsRightFormat(dt))
break;
Gotoxy(X_NOTIFY, Y_NOTIFY);
cout << "Ngay gio k hop le. Nhan 1 phim bat";
_getch();
Gotoxy(X_NOTIFY, Y_NOTIFY);
cout << setfill(' ') << setw(30) << " ";
isSave = false;
}
} // end while
system("cls");
Gotoxy(X_TITLE, Y_TITLE + 2);
cout << "<NAME> " << dt.d << "/" << dt.m << "/" << dt.y;
int index = -1;
bool isHaveData = false;;
for (int i = 0; i <= l->n; i++)
{
AutoChangeSttFlight(l->listAirplane[i]->listFlight);
NODE_FLIGHT* p = l->listAirplane[i]->listFlight.pHead;
while (p != NULL)
{
/*if (p->data.dateLeave.d == dt.d &&p->data.dateLeave.m == dt.m && p->data.dateLeave.y == dt.y)*/
if (CompareDate(p->data.dateLeave,dt))
{
OutputFlight(p->data, ++index);
isHaveData = true;
}
p = p->pNext;
}
}
if (isHaveData)
{
Display(keyDisplayFlight, sizeof(keyDisplayFlight) / sizeof(string));
DeleteGuide(sizeof(keyDisplayFlight) / sizeof(string));
}
else
{
Gotoxy(X_NOTIFY, Y_NOTIFY);
cout << "Khong co chuyen bay";
}
_getch();
return true;
}
bool StatisticTicketFlight(PTR_LIST_AIRPLANE l)
{
int indexAirplane = DisplayAndChooseIndexAirplane(l, "CHON MAY BAY MUON THONG KE");
if (indexAirplane == -1)
{
system("cls");
return false;
}
system("cls");
Gotoxy(X_TITLE, Y_TITLE); cout << "CHON CHUYEN BAY MUON THONG KE";
Display(keyDisplayFlight, sizeof(keyDisplayFlight) / sizeof(string));
Gotoxy(xKeyDisplay[0] + 1, Y_DISPLAY + 40);
cout << setw(xKeyDisplay[sizeof(keyDisplayFlight) / sizeof(string)] - xKeyDisplay[0] - 1) << " " << setfill(' ');
NODE_FLIGHT* fl = NULL;
fl = ChooseFlight(l->listAirplane[indexAirplane]->listFlight);
if (fl == NULL) return false;
system("cls");
Gotoxy(X_TITLE, Y_TITLE); cout << "DANH SACH VE CUA MAY BAY " << l->listAirplane[indexAirplane]->id;
cout << " CHUYEN BAY " << fl->data.id;
DisplayMenuTicket(fl->data);
_getch();
return true;
}
bool StatisticFlightOfAirplane(PTR_LIST_AIRPLANE l)
{
SortByNumberFlight(l);
system("cls");
Gotoxy(X_TITLE, Y_TITLE); cout << "THONG KE CAC CHUYEN BAY CUA MAY BAY";
string key[] = { "Ma may bay","So lan bay" };
Display(key, 2);
DeleteGuide(2);
for (int i = 0; i <= l->n; i++)
{
Gotoxy(xKeyDisplay[0] + 1, Y_DISPLAY + 3 + i); cout << l->listAirplane[i]->id;
Gotoxy(xKeyDisplay[1] + 1, Y_DISPLAY + 3 + i); cout << l->listAirplane[i]->listFlight.n;
}
_getch();
return true;
}
//--------------END STATISTIC
bool BookTicketIsSuceed(PTR_LIST_AIRPLANE &l, TREE_PASSENGER &t)
{
system("cls");
Gotoxy(X_TITLE, Y_TITLE); cout << "<NAME> MUON DAT VE";
//indexOutPassenger = -1;
//QuickSort(0, nPassenger, arrPassengerId);
Display(keyDisplayPassenger, sizeof(keyDisplayPassenger) / sizeof(string));
/*Gotoxy(xKeyDisplay[0] + 1, Y_DISPLAY + 40);
cout << setw(xKeyDisplay[sizeof(keyDisplayPassenger) / sizeof(string)] - xKeyDisplay[0] - 1) << " " << setfill(' ');*/
DeleteNote(sizeof(keyDisplayPassenger) / sizeof(string));
NODE_PASSENGER* chosenPassenger = ChoosePassenger(t);
if (chosenPassenger == NULL)
{
system("cls");
return false;
}
system("cls");
int indexAirplane = DisplayAndChooseIndexAirplane(l, "CHON MAY BAY MUON DAT VE");
if (indexAirplane == -1)
{
system("cls");
return false;
}
system("cls");
Gotoxy(X_TITLE, Y_TITLE); cout << "<NAME> BAY MUON DAT VE";
Display(keyDisplayFlight, sizeof(keyDisplayFlight) / sizeof(string));
Gotoxy(xKeyDisplay[0] + 1, Y_DISPLAY + 40);
cout << setw(xKeyDisplay[sizeof(keyDisplayFlight) / sizeof(string)] - xKeyDisplay[0] - 1) << " " << setfill(' ');
//OutputListFlight(l->listAirplane[indexAirplane]->listFlight);
OutputListFlightPerPage(l->listAirplane[indexAirplane]->listFlight, 0);
NODE_FLIGHT* fl; //= NULL;
do
{
fl = ChooseFlight(l->listAirplane[indexAirplane]->listFlight);
if (fl->data.stt != STT_REMAIN_TICKET)
{
Gotoxy(X_NOTIFY, Y_NOTIFY); cout << "CHON CHUYEN CON VE VA CHUA HOAN TAT";
_getch();
}
} while (fl->data.stt != STT_REMAIN_TICKET && fl != NULL);
if (fl == NULL)
{
system("cls");
return false;
}
int k;
system("cls");
do
{
k = ChooseTicket(fl->data);
if (fl->data.listTicket[k - 1].stt == TICKET_SOLD && k != -1)
{
Gotoxy(X_NOTIFY, Y_NOTIFY); cout << "VE DA CO NGUOI DAT";
_getch();
DeleteNotify();
}
} while (fl->data.listTicket[k - 1].stt == TICKET_SOLD && k != -1);
if (k == -1)
{
system("cls");
return false;
}
fl->data.listTicket[k - 1].stt = TICKET_SOLD;
fl->data.nTicketSold++;
fl->data.listTicket[k - 1].idOwner = chosenPassenger->data.id;
chosenPassenger->data.isBooked = true;
if (fl->data.nTicket == fl->data.nTicketSold) fl->data.stt = STT_FULL_TICKET;
Gotoxy(X_NOTIFY, Y_NOTIFY); cout << "DAT VE THANH CONG";
_getch();
return true;
}
void Introduce()
{
ShowCur(false);
string a;
char b;
ifstream file("introduce.txt", ios::in);
while (!file.eof())
{
getline(file, a);
cout << a << endl;
}
Gotoxy(100, 35);
cout << "<NAME>";
Gotoxy(100, 36);
cout << "N15DCCN033";
Gotoxy(100, 37);
cout << "D15CQCN01-N";
}
void MageAll(PTR_LIST_AIRPLANE &l, TREE_PASSENGER &t)
{
while (true)
{
Introduce();
MainMenu(keyMainMenu, sizeof(keyMainMenu) / sizeof(string));
int type = ChooseMainMenu(keyMainMenu, sizeof(keyMainMenu) / sizeof(string));
totalPageAirplane = l->n / QUANTITY_PER_PAGE + 1;
totalPagePassenger = nPassenger / QUANTITY_PER_PAGE + 1;
switch (type)
{
case -1:
return;
case 0:
{
MenuManageAirplane(l);
break;
}
case 1:
{
int indexAirplanee = DisplayAndChooseIndexAirplane(l, "CHON MAY BAY DE QUAN LY CHUYEN BAY");
if (indexAirplanee == -1)
{
system("cls");
continue;
}
system("cls");
Gotoxy(X_TITLE, Y_TITLE); cout << " QUAN LY CHUYEN BAY CUAY MAY BAY CO MA SO " << l->listAirplane[indexAirplanee]->id;
totalPageFlight = ((l->listAirplane[indexAirplanee]->listFlight.n - 1) / QUANTITY_PER_PAGE) + 1;
MenuManageFlight(l->listAirplane[indexAirplanee]->listFlight, l->listAirplane[indexAirplanee]->nChair);
break;
}
case 3:
if (BookTicketIsSuceed(l, t) == false) continue;
break;
case 2:
{
system("cls");
Gotoxy(X_TITLE, Y_TITLE); cout << " QUAN LY HANH KHACH ";
MenuManagePassenger(t);
break;
}
case 4:
{
system("cls");
MainMenu(keyStatistic, sizeof(keyStatistic) / sizeof(string));
int chosenStatistic = ChooseMainMenu(keyStatistic, sizeof(keyStatistic) / sizeof(string));
switch (chosenStatistic)
{
case 0:
if (StatisticPassengerOnFlightIsSucceed(l, t) == false) continue;
break;
case 1:
if (StatisticFlightOnDay(l) == false) continue;
break;
case 2:
if (StatisticFlightOfAirplane(l) == false) continue;
break;
case 3:
if (StatisticTicketFlight(l) == false) continue;
break;
default:
break;
}//end swtich case statistic
}//end case 4 of type
}//end switch type
system("cls");
}//while true
}//void
#endif | 9beb31d4f02eebbe45a385ca7e85befd3a2cb6ff | [
"C",
"C++"
] | 2 | C++ | sihaojunvn2012/Manage-Plane | b9724eb5a60c908a388514de4f9656b182dd6dda | a1d41b35c86045036645800bc9c0d5730631e1e7 |
refs/heads/master | <file_sep>package com.example.coophan.chancock2742ex2g1;
import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends AppCompatActivity {
private List<SensorReading> sensorReadings;
private RecyclerView recyclerView;
private Context context;
private AsyncHttpClient httpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
loadSensorReadings();
SensorReadingAdapter adapter = new SensorReadingAdapter(this, R.layout.sensor_reading_recycler_item,
this.sensorReadings);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
this.recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
private void loadSensorReadings(){
String url = "http://204.77.50.53/propertymonitor/api/sensorreadings/2";
this.httpClient = new AsyncHttpClient();
this.httpClient.get(MainActivity.this, url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String json = new String(responseBody);
sensorReadings = SensorReadingJSONParser.getSensorReadings(json);
SensorReadingAdapter adapter = new SensorReadingAdapter(
MainActivity.this, R.layout.sensor_reading_recycler_item,
sensorReadings);
RecyclerView.LayoutManager layoutManager =
new LinearLayoutManager(MainActivity.this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
}
| 607d6bef2f637aaa4848d22ff126797dd9488625 | [
"Java"
] | 1 | Java | hancco20/chancock-2742-ex2g | eba04f7cce73796226f0a89bc0305cfea2e962ff | c8ea628a37b6fbce7d22c8d596019f5f64710804 |
refs/heads/master | <file_sep>using System;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace Sample_XmlParser
{
class Program
{
static void Main(string[] args)
{
// This method returns an XElement, send it to the console to display it
var sampleOutput = XmlWithXElements();
Console.WriteLine(sampleOutput);
// This method returns a string of Xml, send it to the console to display it
var documentOutput = XmlWithXmlDocument();
Console.WriteLine(documentOutput);
// This method returns an Xml Writer object, send it to the console to display it
var writerOutput = XmlWithDOM();
Console.WriteLine(writerOutput);
// Serializer has an output to the console, just call it
XmlWithSerializer();
//Console.WriteLine();
while (Console.Read() != 'q');
}
// Use for very small bit of data needing to be formatted to Xml
public static XElement XmlWithXElements()
{
var testOuput = new XElement("Foo",
new XAttribute("Bar", "test"),
new XElement("Nested", "testData"));
return testOuput;
}
// use with larger data chunks where the elements are known ahead of time
public static string XmlWithXmlDocument()
{
var doc = new XmlDocument();
var ele = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));
ele.SetAttribute("Bar", "test");
ele.AppendChild(doc.CreateElement("Nested")).InnerText = "testData";
return doc.OuterXml;
}
// Use for larger data where memory space is important to preserve
public static XmlWriter XmlWithDOM()
{
XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "test");
writer.WriteElementString("Nested", "testData");
writer.WriteEndElement();
return writer;
}
// Serialize the data with the following if you have an object that should be mirrored
public static void XmlWithSerializer()
{
var foo = new Foo
{
Bar = "test",
Nested = "testData"
};
new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);
}
}
[Serializable]
public class Foo
{
[XmlAttribute]
public string Bar { get; set; }
[XmlElement]
public string Nested { get; set; }
}
}
| 229d034f889ccebd4be826a63429fd0379231302 | [
"C#"
] | 1 | C# | KlutchSC/Sample_XmlParser | 309f46198ccbab0c05c86e649ba99b2e1bb2b7f4 | f75d870aa359f783f9a770110c28b749c1917835 |
refs/heads/master | <repo_name>Cryst4L/Backprop<file_sep>/data/MNIST/get_mnist.py
#!/usr/bin/env python
import sys, os, gzip
from urllib import urlretrieve
DIR = 'https://ossci-datasets.s3.amazonaws.com/mnist/' #'http://yann.lecun.com/exdb/mnist/'
TARGETS = ['train-images.idx3-ubyte', 't10k-images.idx3-ubyte',
'train-labels.idx1-ubyte', 't10k-labels.idx1-ubyte']
#for t in TARGETS:
# url = "%s%s.gz" % (DIR, t)
# url = url.replace('.idx', '-idx')
# urlretrieve(url, (t + '.gz'))
#-Script Body ------------------------------------------------------------------
if __name__ == "__main__":
if all(os.path.exists(t) for t in TARGETS):
print("-- MNIST dataset found.")
else:
print('-- Dowloading MNIST data ...')
def progressHook(count, blockSize, totalSize):
p = min(count*blockSize / float(totalSize), 1)
sys.stdout.write("\r-- | %-25s[ %3d%% ] " % (t, p*100))
sys.stdout.flush()
for t in TARGETS:
url = "%s%s.gz" % (DIR, t)
url = url.replace('.idx', '-idx')
urlretrieve(url, (t + '.gz'), progressHook)
with gzip.open((t + '.gz'), 'rb') as archive:
content = archive.read()
with open(t, 'wb') as target:
target.write(content)
os.remove((t + '.gz'))
print('Done!')
<file_sep>/Backprop/Timer.h
#pragma once
#include <unistd.h>
#include <sys/time.h>
namespace Backprop
{
class Timer
{
private:
struct timeval t0, t1;
public:
Timer() { reset(); }
void reset()
{
gettimeofday(&t0, NULL);
}
float getTimeMS()
{
gettimeofday(&t1, NULL);
double time = (t1.tv_sec - t0.tv_sec) * 1e3 +
(t1.tv_usec - t0.tv_usec) / 1e3;
return time;
}
float getTimeSec()
{
return 1e-3 * getTimeMS();
}
};
}
<file_sep>/Backprop/Utils.h
#pragma once
#include <vector>
#include "MNIST.h"
#include "Display.h"
MatrixXd buildMapfromData(std::vector <MatrixXd> & samples, int sample_width, int sample_height)
{
int n_rows = std::ceil(std::sqrt(samples.size()));
int n_cols = (samples.size() + n_rows - 1) / n_rows;
int map_width = sample_width * n_rows;
int map_height = sample_height * n_cols;
MatrixXd map(map_width, map_height);
map.setZero();
for (int n = 0; n < (int) samples.size(); n++)
{
//std::cout << n << std::endl;
int i = (n % n_cols);
int j = (n / n_cols);
MatrixXd sample = samples[n];
for (int di = 0; di < sample_width; di++)
{
for (int dj = 0; dj < sample_height; dj++)
{
double value = sample(di, dj);
int col = i * sample_width + di;
int row = j * sample_height + dj;
map(row, col) = value;
}
}
}
return map;
}
<file_sep>/Backprop/Display.h
////////////////////////////////////////////////////////////////////////////////
// Display:
// A tool for displaying matrices. Uses on a GNUPlot backend.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace Eigen;
namespace Backprop
{
class Display
{
private :
FILE * m_pipe_p;
MatrixXd * m_frame_p;
std::string m_title;
void openGP()
{
m_pipe_p = popen("gnuplot -persist", "w");
if (!m_pipe_p)
{
std::cout << "Failed to open GNUPlot !\n"
<< "Please ensure it is installed ..."
<< std::endl;
}
}
void configPlot()
{
if (m_pipe_p)
{
const char* configs =
"set size ratio -1\n"
// "set cbrange [-1:1]\n"
"set palette gray\n"
"unset xtics\n"
"unset ytics\n"
"unset key\n";
//TODO: ensure wxt is the best terminal for what we want
fprintf(m_pipe_p, "%s", configs);
fprintf(m_pipe_p, "set term wxt title 'Backprop'\n");
fprintf(m_pipe_p, "set title \"%s\"\n", m_title.c_str());
}
}
public :
Display(MatrixXd * frame, const char* title)
: m_frame_p(frame), m_title(title)
{
openGP();
configPlot();
render();
}
void render()
{
if (m_pipe_p)
{
fprintf(m_pipe_p, "plot '-' matrix with image\n");
fflush(m_pipe_p);
MatrixXd frame = (*m_frame_p);
for (int i = frame.rows() - 1; i >= 0; i--)
{
for(int j = 0; j < frame.cols(); j++)
fprintf(m_pipe_p, "%f ", frame(i,j));
fprintf(m_pipe_p, "\n");
fflush(m_pipe_p);
}
fprintf(m_pipe_p, "\ne\n");
fflush(m_pipe_p);
}
}
~Display()
{
pclose(m_pipe_p);
}
};
}
<file_sep>/Backprop/PCFD.h
// PCFD loader
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include <iostream>
#include <fstream>
#include <Eigen/Core>
using namespace Eigen;
namespace Backprop
{
class PCFD
{
private:
int m_nb_samples;
int m_sample_size;
int m_sample_length;
MatrixXd m_samples;
public:
PCFD(const char * file_path)
{
m_sample_size = 52;
m_nb_samples = 5000;
m_sample_length = m_sample_size * m_sample_size;
m_samples = MatrixXd(m_nb_samples, m_sample_length);
std::ifstream file(file_path);
if (!file.is_open()) {
std::cout << "Could not open '" << file_path << "'" << std::endl;
return;
}
char * buffer = new char [m_nb_samples * m_sample_length];
file.read(buffer, m_nb_samples * m_sample_length);
file.close();
for (int i = 0; i < m_nb_samples; i++)
for (int j = 0; j < m_sample_length; j++)
m_samples(i, j) = (unsigned char) buffer[i * m_sample_length + j] / 256.f;
delete [] buffer;
}
MatrixXd& samples() { return m_samples; }
int size() { return m_nb_samples; }
int sampleSize() { return m_sample_size; }
};
}
<file_sep>/Backprop/Sampling.h
#pragma once
#include "Layer.h"
#include "Reshape.h"
using namespace Eigen;
namespace Backprop
{
class Sampling : public Layer
{
private :
int m_input_map_rows;
int m_input_map_cols;
int m_output_map_rows;
int m_output_map_cols;
int m_nb_maps;
int m_ratio;
std::vector <MatrixXd> m_input_maps;
std::vector <MatrixXd> m_output_maps;
std::vector <MatrixXd> m_ein_maps;
std::vector <MatrixXd> m_eout_maps;
void subsample(MatrixXd& input, MatrixXd& output, int ratio)
{
double coeff = 1 / (double) (ratio * ratio);
for (int i = 0; i < output.rows(); i++)
for (int j = 0; j < output.cols(); j++)
{
double acc = 0;
for (int di = 0; di < ratio; di++)
for (int dj = 0; dj < ratio; dj++)
acc += input(i * ratio + di, j * ratio + dj);
output(i, j) = acc * coeff;
}
}
void upsample(MatrixXd& input, MatrixXd& output, int ratio)
{
double coeff = 1 / (double) (ratio * ratio);
for (int i = 0; i < input.rows(); i++)
for (int j = 0; j < input.cols(); j++)
{
for (int di = 0; di < ratio; di++)
for (int dj = 0; dj < ratio; dj++)
output(i * ratio + di, j * ratio + dj) = input(i, j) * coeff;
}
}
public :
Sampling(int input_map_rows, int input_map_cols, int nb_maps, int ratio)
: m_input_map_rows(input_map_rows),
m_input_map_cols(input_map_cols),
m_output_map_rows(input_map_rows / ratio),
m_output_map_cols(input_map_cols / ratio),
m_nb_maps(nb_maps), m_ratio(ratio)
{
for (int i = 0; i < m_nb_maps; i++)
m_input_maps.push_back(MatrixXd(m_input_map_rows, m_input_map_cols));
for (int i = 0; i < m_nb_maps; i++)
m_output_maps.push_back(MatrixXd(m_output_map_rows, m_output_map_cols));
for (int i = 0; i < m_nb_maps; i++)
m_ein_maps.push_back(MatrixXd(m_output_map_rows, m_output_map_cols));
for (int i = 0; i < m_nb_maps; i++)
m_eout_maps.push_back(MatrixXd(m_input_map_rows, m_input_map_cols));
}
VectorXd forwardProp(VectorXd& unshaped_inputs)
{
// Reshape the inputs
reshape(unshaped_inputs, m_input_maps);
// Subsample
for (int n = 0; n < m_nb_maps; n++)
subsample(m_input_maps[n], m_output_maps[n], m_ratio);
// Unshape the outputs
VectorXd unshaped_output;
unshape(m_output_maps, unshaped_output);
return unshaped_output;
}
VectorXd backProp(VectorXd& unshaped_inputs, VectorXd& unshaped_eins)
{
// Reshape the inputs
reshape(unshaped_eins, m_ein_maps);
// Upsample
for (int n = 0; n < m_nb_maps; n++)
upsample(m_ein_maps[n], m_eout_maps[n], m_ratio);
// Unshape the outputs
VectorXd unshaped_eouts;
unshape(m_eout_maps, unshaped_eouts);
// Prevent the compiler from complaining
(void) unshaped_inputs;
return unshaped_eouts;
}
VectorXd getParameters() { return VectorXd(0); }
VectorXd getGradient() { return VectorXd(0); }
void setParameters(VectorXd& parameters) { (void) parameters; }
void setGradient(VectorXd& gradient) { (void) gradient;}
Sampling* clone() { return new Sampling(*this); }
};
}
<file_sep>/Backprop/Types.h
#pragma once
#include <Eigen/Core>
using namespace Eigen;
namespace Backprop
{
typedef unsigned char BYTE;
enum DatasetType {TRAIN, TEST, VALIDATION};
typedef struct {
std::vector <VectorXd> inputs;
std::vector <VectorXd> targets;
} Dataset;
}
<file_sep>/Backprop/Dropout.h
#pragma once
#include <Eigen/Core>
namespace Backprop
{
class Dropout : public Layer
{
private:
double m_ratio;
bool m_use_dropout;
VectorXd m_mask;
public:
Dropout(double ratio = 0.5, bool use_dropout = true)
: m_ratio(ratio), m_use_dropout(use_dropout)
{}
VectorXd forwardProp(VectorXd& input)
{
if (m_use_dropout == false)
return (1 - m_ratio) * input;
// Else ...
int size = input.size();
m_mask = VectorXd::Random(size);
m_mask = 0.5 * (m_mask.array() + 1);
m_mask = (m_mask.array() > m_ratio).cast <double> ();
VectorXd output = m_mask.array() * input.array();
//std::cout << mask << std::endl;
return output;
}
VectorXd backProp(VectorXd& input, VectorXd& ein)
{
(void) input;
if (m_use_dropout == false)
return ein;
// Else ...
VectorXd eout = m_mask.array() * ein.array();
return eout;
}
void enableDropout() { m_use_dropout = true; }
void disableDropout() { m_use_dropout = false; }
////////////////////////////////////////////////////////////////////////////
VectorXd getParameters() { return VectorXd(0); }
VectorXd getGradient() { return VectorXd(0); }
void setParameters(VectorXd& parameters) { (void) parameters; }
void setGradient(VectorXd& gradient) { (void) gradient;}
Dropout* clone() { return new Dropout(*this); }
};
}
<file_sep>/Backprop/MNIST.h
////////////////////////////////////////////////////////////////////////////////
// MNIST dataset loader
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <endian.h>
#undef Success //TODO: Fix this !
#include <Eigen/Core>
#include "Types.h"
using namespace Eigen;
namespace Backprop
{
class MNIST
{
public:
MNIST(std::string folder_path, DatasetType type = TRAIN, int size = -1)
: m_size(size)
{
loadSamples(folder_path, type);
loadLabels(folder_path, type);
std::cout << " MNIST data loaded"
<< "\n - type : " << (type == 0 ? "TRAIN" : "TEST")
<< "\n - size : " << m_size
<< std::endl;
}
// Get a reference to the loaded samples.
// Each row store a sample data using a row-major indexing.
MatrixXd& samples()
{
return m_samples;
}
// Get a reference to the loaded targets.
// Each row represent a sample class in a one-hot manner.
MatrixXd& targets()
{
return m_targets;
}
// Get the number of samples loaded
int nbSamples()
{
return m_size;
}
private:
int m_size;
MatrixXd m_samples;
MatrixXd m_targets;
//! Rearrange and IDX 32-bit integer
inline int reverseInt(int i)
{
unsigned char c1, c2, c3, c4;
c1 = i & 255;
c2 = (i >> 8) & 255;
c3 = (i >> 16) & 255;
c4 = (i >> 24) & 255;
int i1, i2, i3, i4;
i1 = (int) c1 << 24;
i2 = (int) c2 << 16;
i3 = (int) c3 << 8;
i4 = (int) c4;
return i1 + i2 + i3 + i4;
}
//! Load the MNIST samples
void loadSamples(std::string folder_path, DatasetType type)
{
std::string path = (type == TRAIN) ?
folder_path + "/train-images.idx3-ubyte" :
folder_path + "/t10k-images.idx3-ubyte";
std::fstream sample_file(path.c_str(), std::ios::in | std::ios::binary);
if (!sample_file.is_open())
{
std::cerr << " Failed to open '" << path << "'. Exiting ...\n";
exit(1);
}
int magic, items, rows, cols;
sample_file.read((char*) &magic, sizeof(magic));
sample_file.read((char*) &items, sizeof(items));
sample_file.read((char*) &rows, sizeof(rows));
sample_file.read((char*) &cols, sizeof(cols));
rows = reverseInt(rows);
cols = reverseInt(cols);
if (m_size < 0)
m_size = reverseInt(items);
m_samples.resize(m_size, rows * cols);
unsigned char temp = 0;
for(int n = 0; n < m_size; n++)
{
for(int r = 0; r < rows; r++)
for(int c = 0; c < cols; c++)
{
sample_file.read((char*) &temp, sizeof(temp));
double value = (double) temp;
m_samples(n, r * cols + c) = value / 255.0; // scale to [0:1]
}
}
}
//! Load the MNIST targets
void loadLabels(std::string folder_path, DatasetType type)
{
std::string path = (type == TRAIN) ?
(folder_path + "/train-labels.idx1-ubyte") :
(folder_path + "/t10k-labels.idx1-ubyte");
std::fstream label_file(path.c_str(), std::ios::in | std::ios::binary);
if (!label_file.is_open())
{
std::cerr << " Failed to open '" << path << "'\n Exiting ...\n";
exit(1);
}
int magic, items;
label_file.read((char*) &magic, sizeof(magic));
label_file.read((char*) &items, sizeof(items));
int n_targets = 10;
if (m_size < 0)
m_size = reverseInt(items);
m_targets.resize(m_size, n_targets);
unsigned char temp = 0;
for (int n = 0; n < m_size; n++)
{
label_file.read((char*) &temp, sizeof(temp));
for (int l = 0; l < n_targets; l++)
m_targets(n, l) = (int) temp == l ? 1.0 : 0.0;
}
}
};
}
<file_sep>/Backprop/Cost.h
#pragma once
#include <Eigen/Core>
namespace Backprop
{
enum CostEnum {ABS, SSE, CE};
static const double EPSILON = 0.001;
class Cost
{
private:
CostEnum m_function;
public:
Cost()
: m_function(SSE)
{}
Cost(CostEnum function)
: m_function(function)
{}
// Activation m_function //////////////////////////////////////////////////////////
double computeCost(VectorXd& output, VectorXd& target)
{
double cost = 0;
switch(m_function)
{
case ABS :
cost = (output - target).array().abs().sum();
break;
case SSE :
cost = (output - target).array().square().sum();
break;
case CE :
output = output.array().max(EPSILON).min(1 - EPSILON);
cost = - (target.array() * output.array().log()).sum()
- ((1 - target.array()) * (1 - output.array()).log()).sum();
break;
}
return cost;
}
// Activation gradient //////////////////////////////////////////////////////////
VectorXd computeGradient(VectorXd& output, VectorXd& target)
{
int n = output.size();
VectorXd gradient(n);
switch(m_function)
{
case ABS :
gradient = (output - target).array().sign();
break;
case SSE :
gradient = 2 * (output - target);
break;
case CE :
output = output.array().max(EPSILON).min(1 - EPSILON);
gradient = (output - target).array()
/ output.array() * (1 - output.array());
break;
}
return gradient;
}
};
}
<file_sep>/Backprop/Optimize.h
#pragma once
#include "Types.h"
#include "Network.h"
#include "Cost.h"
//#include "omp.h"
using namespace Eigen;
namespace Backprop
{
double SGD(Network& network, Dataset& dataset, CostEnum cost_function = SSE, double learning_rate = 1E-2)
{
Cost cost(cost_function);
double average_cost = 0;
int n = dataset.inputs.size();
VectorXd prediction, eout;
VectorXd input, target;
VectorXd parameters, gradient;
int i;
/*
omp_set_num_threads(8);
#pragma omp parallel for schedule(dynamic) \
private(i, input, target, prediction, eout, parameters, gradient) \
shared(n, average_cost, dataset, network)
*/
for (i = 0; i < n; i++)
{
//std::cout << i << " ";
//std::cout << omp_get_thread_num() << std::endl;
// Setup the samples
input = dataset.inputs[i];
target = dataset.targets[i];
// Compute the prediction
prediction = network.forwardPropagate(input);
average_cost += cost.computeCost(prediction, target) / n;
// Compute the gradient
eout = cost.computeGradient(prediction, target);
network.backPropagate(eout);
// Perform the gradient descent
parameters = network.getParameters();
gradient = network.getGradient();
parameters -= learning_rate * gradient;
network.setParameters(parameters);
}
/*
for(int j = 0; j < network.nbLayers(); j++)
{
VectorXd parameters = network.layer(j).getParameters();
VectorXd gradient = network.layer(j).getGradient();
parameters -= learning_rate * gradient;
network.layer(j).setParameters(parameters);
}
*/
return average_cost;
}
}
<file_sep>/Backprop/ELU.h
#pragma once
#include "Layer.h"
using namespace Eigen;
using namespace std;
namespace Backprop
{
class ELU : public Layer
{
private :
int m_size;
double m_alpha;
double m_alpha_grad;
public :
ELU(int size)
: m_size(size)
{
initParameters();
}
void initParameters()
{
m_alpha = 0.5;
}
VectorXd forwardProp(VectorXd& input)
{
VectorXd output(m_size);
m_alpha = max(m_alpha, 0.01);
double a = m_alpha;
for (int i = 0; i < m_size; i++)
output(i) = (input(i) < 0) ? a * (exp(input(i) / a) - 1) : input(i);
return output;
}
VectorXd backProp(VectorXd& input, VectorXd& ein)
{
m_alpha = max(m_alpha, 0.01);
double a = m_alpha;
// Compute the gradient wrt the parameter
m_alpha_grad = 0;
for (int i = 0; i < m_size; i++) {
if (input(i) < 0)
m_alpha_grad += ein(i) * (exp(input(i) / a) * (1 - input(i) / a) - 1);
}
// Propagate the ein
VectorXd eout(m_size);
for (int i = 0; i < m_size; i++) {
if (input(i) < 0) {
eout(i) = ein(i) * exp(input(i) / a);
} else {
eout(i) = ein(i);
}
}
return eout;
}
VectorXd getParameters()
{
VectorXd parameter(1);
parameter(0) = m_alpha;
return parameter;
}
VectorXd getGradient()
{
VectorXd gradient(1);
gradient(0) = m_alpha_grad;
return gradient;
}
void setParameters(VectorXd& parameters)
{
m_alpha = parameters(0);
}
void setGradient(VectorXd& gradient)
{
m_alpha_grad = gradient(0);
}
ELU* clone() { return new ELU(*this); }
///////////////////////////////////////////////////////////////////////////
};
}
<file_sep>/Backprop/Network.h
#pragma once
#include "Linear.h"
#include "Convolutional.h"
#include "Activation.h"
#include "Sampling.h"
#include "SoftMax.h"
#include "Dropout.h"
#include "ELU.h"
#include "Types.h"
using namespace Eigen;
namespace Backprop
{
class Network
{
private :
std::vector <Layer*> m_layer_stack;
std::vector <VectorXd> m_input_stack;
public:
Network() {}
Network& operator=(const Network &network)
{
if (this != &network)
{
m_input_stack = network.m_input_stack;
// Deep clean
for (int i = 0; i < (int) m_layer_stack.size(); i++)
delete m_layer_stack[i];
m_layer_stack.clear();
// Deep copy
for (int i = 0; i < (int) network.m_layer_stack.size(); i++) {
Layer * layer = network.m_layer_stack[i]->clone();
m_layer_stack.push_back(layer);
}
}
return *this;
}
Network(const Network &network)
{
*this = network; // overloaded '=' is called
}
~Network()
{
for (int i = 0; i < (int) m_layer_stack.size(); i++)
delete m_layer_stack[i];
}
////////////////////////////////////////////////////////////////////////////
Layer& layer(int i)
{
return *(m_layer_stack[i]);
}
void addLinearLayer(int input_size, int output_size, bool propagate_ein = 1)
{
Linear * layer = new Linear(input_size, output_size, propagate_ein);
m_layer_stack.push_back(layer);
m_input_stack.push_back(VectorXd(0));
}
void addActivationLayer(ActivationEnum function)
{
Activation * layer = new Activation(function);
m_layer_stack.push_back(layer);
m_input_stack.push_back(VectorXd(0));
}
void addSamplingLayer(int input_map_rows, int input_map_cols, int nb_maps, int ratio)
{
Sampling * layer = new Sampling(input_map_rows, input_map_cols, nb_maps, ratio);
m_layer_stack.push_back(layer);
m_input_stack.push_back(VectorXd(0));
}
void addConvolutionalLayer(int input_map_rows, int input_map_cols,
int kernel_size, int nb_input_maps,
int nb_output_maps, bool padded = 0,
bool propagate_ein = 1)
{
Convolutional * layer = new Convolutional(input_map_rows, input_map_cols,
kernel_size, nb_input_maps,
nb_output_maps, padded,
propagate_ein);
m_layer_stack.push_back(layer);
m_input_stack.push_back(VectorXd(0));
}
void addSoftMaxLayer()
{
SoftMax * layer = new SoftMax();
m_layer_stack.push_back(layer);
m_input_stack.push_back(VectorXd(0));
}
void addELULayer(int size)
{
ELU * layer = new ELU(size);
m_layer_stack.push_back(layer);
m_input_stack.push_back(VectorXd(0));
}
void addDropoutLayer(double ratio = 0.5, bool use_dropout = true)
{
Dropout * layer = new Dropout(ratio, use_dropout);
m_layer_stack.push_back(layer);
m_input_stack.push_back(VectorXd(0));
}
void enableDropout()
{
for(int i = 0; i < (int) m_layer_stack.size(); i++) {
Dropout * layer = dynamic_cast <Dropout*> (m_layer_stack[i]);
if (layer != NULL)
layer->enableDropout();
}
}
void disableDropout()
{
for(int i = 0; i < (int) m_layer_stack.size(); i++) {
Dropout * layer = dynamic_cast <Dropout*> (m_layer_stack[i]);
if (layer != NULL)
layer->disableDropout();
}
}
VectorXd forwardPropagate(VectorXd& input)
{
VectorXd signal = input;
for(int i = 0; i < (int) m_layer_stack.size(); i++) {
m_input_stack[i] = signal;
signal = m_layer_stack[i]->forwardProp(signal);
}
return signal;
}
void backPropagate(VectorXd& ein)
{
VectorXd signal = ein;
int l = m_layer_stack.size();
for(int i = l - 1; i >= 0; i--)
signal = m_layer_stack[i]->backProp(m_input_stack[i], signal);
/*
VectorXd signal = ein;
int l = m_layer_stack.size();
signal = m_layer_stack[l - 1]->backProp(m_input_stack[l - 1], signal);
signal = m_layer_stack[l - 2]->backProp(m_input_stack[l - 2], signal);
signal = m_layer_stack[l - 3]->backProp(m_input_stack[l - 3], signal);
signal = m_layer_stack[l - 4]->backProp(m_input_stack[l - 4], signal);
signal = m_layer_stack[l - 5]->backProp(m_input_stack[l - 5], signal);
// signal = m_layer_stack[l - 6]->backProp(m_input_stack[l - 6], signal);
//signal = m_layer_stack[l - 7]->backProp(m_input_stack[l - 7], signal);
//signal = m_layer_stack[l - 8]->backProp(m_input_stack[l - 8], signal);
//signal = m_layer_stack[l - 9]->backProp(m_input_stack[l - 9], signal);
*/
}
VectorXd getParameters()
{
int size = 0;
for(int i = 0; i < (int) m_layer_stack.size(); i++)
size += m_layer_stack[i]->getParameters().size();
int offset = 0;
VectorXd parameters(size);
for(int i = 0; i < (int) m_layer_stack.size(); i++) {
VectorXd layer_parameters = m_layer_stack[i]->getParameters();
parameters.segment(offset, layer_parameters.size()) = layer_parameters;
offset += layer_parameters.size();
}
return parameters;
}
VectorXd getGradient()
{
int size = 0;
for(int i = 0; i < (int) m_layer_stack.size(); i++)
size += m_layer_stack[i]->getGradient().size();
int offset = 0;
VectorXd gradient(size);
for(int i = 0; i < (int) m_layer_stack.size(); i++) {
VectorXd layer_gradient = m_layer_stack[i]->getGradient();
gradient.segment(offset, layer_gradient.size()) = layer_gradient;
offset += layer_gradient.size();
}
return gradient;
}
void setParameters(VectorXd& parameters)
{
int offset = 0;
for (int i = 0; i < (int) m_layer_stack.size(); i++) {
int size = m_layer_stack[i]->getParameters().size();
VectorXd layer_parameters = parameters.segment(offset, size);
m_layer_stack[i]->setParameters(layer_parameters);
offset += size;
}
}
void setGradient(VectorXd& gradient)
{
int offset = 0;
for (int i = 0; i < (int) m_layer_stack.size(); i++) {
int size = m_layer_stack[i]->getParameters().size();
VectorXd layer_gradient = gradient.segment(offset, size);
m_layer_stack[i]->setGradient(layer_gradient);
offset += size;
}
}
int nbLayers() { return m_layer_stack.size(); }
};
}
<file_sep>/examples/ex1.cpp
// MLP with ReLU
#include "Backprop/Core.h"
using namespace Backprop;
// 97.27 s0
int main(void)
{
srand(0);
/// Load data //////////////////////////////////////////////////////////////
MNIST train_set("data/MNIST", TRAIN);
/// Display some data //////////////////////////////////////////////////////
const int sample_size = 28;
std::vector <MatrixXd> samples;
for (int i = 0; i < 100; i++) {
VectorXd sample = train_set.samples().row(i);
MatrixXd reshaped = Map <MatrixXd> (sample.data(), sample_size, sample_size);
samples.push_back(reshaped);
}
MatrixXd sample_map = buildMapfromData(samples, sample_size, sample_size);
Display sample_display(&sample_map, "Samples");
// Setup the Net ///////////////////////////////////////////////////////////
Network net;
net.addLinearLayer(784, 50);
net.addActivationLayer(RELU);
net.addLinearLayer(50, 50);
net.addActivationLayer(RELU);
net.addLinearLayer(50, 50);
net.addActivationLayer(RELU);
net.addLinearLayer(50, 10);
net.addActivationLayer(RELU);
// Train the Net ///////////////////////////////////////////////////////////
Dataset batch;
const int N_BATCH = 500;
const int BATCH_SIZE = 1000;
Timer timer;
VectorXd train_costs = VectorXd::Zero(N_BATCH);
Plot plot(&train_costs, "train cost", "red");
for (int n = 0; n < N_BATCH; n++)
{
// Build a batch ///////////////////////////////////////////////////////
batch.inputs.clear();
batch.targets.clear();
for (int i = 0; i < BATCH_SIZE; i++)
{
int s = rand() % train_set.samples().rows();
VectorXd sample = train_set.samples().row(s);
batch.inputs.push_back(sample);
VectorXd target = train_set.targets().row(s);
batch.targets.push_back(target);
}
// Train the net on the batch //////////////////////////////////////////
train_costs(n) = SGD(net, batch, SSE, 0.01);
std::cout << "Average cost = " << train_costs(n) << std::endl;
// Plot the training progress //////////////////////////////////////////////
plot.render();
}
float elapsed = timer.getTimeSec();
std::cout << " elapsed time : " << elapsed << "sec" << std::endl;
// Display the features ////////////////////////////////////////////////////
int feature_size = 28;
std::vector <MatrixXd> features;
VectorXd parameters = net.layer(0).getParameters();
MatrixXd reshaped_parameters = Map <MatrixXd> (parameters.data(), 50, feature_size * feature_size);
for (int i = 0; i < reshaped_parameters.rows(); i++) {
VectorXd feature = reshaped_parameters.row(i);
MatrixXd reshaped = Map <MatrixXd> (feature.data(), feature_size, feature_size);
features.push_back(reshaped);
}
MatrixXd feature_map = buildMapfromData(features, feature_size, feature_size);
Display feature_display(&feature_map, "Features");
// Test the net accuracy ///////////////////////////////////////////////////
MNIST test_set("data/MNIST", TEST);
int acc = 0;
for (int i = 0; i < test_set.nbSamples(); i++)
{
VectorXd sample = test_set.samples().row(i);
VectorXd target = test_set.targets().row(i);
VectorXd prediction = net.forwardPropagate(sample);
VectorXd::Index value, guess;
target.maxCoeff(&value);
prediction.maxCoeff(&guess);
if (value == guess)
acc++;
}
std::cout << " accuracy = " << acc / (float) test_set.nbSamples() << std::endl;
return 0;
}
/*
// Test the net accuracy ///////////////////////////////////////////////
batch.inputs.clear();
batch.targets.clear();
for (int i = 0; i < BATCH_SIZE; i++)
{
int s = rand() % test_set.samples().rows();
VectorXd sample = test_set.samples().row(s);
batch.inputs.push_back(sample);
VectorXd target = test_set.targets().row(s);
batch.targets.push_back(target);
}
Cost cost(SSE);
for (int i = 0; i < BATCH_SIZE; i++)
{
VectorXd sample = test_set.samples().row(i);
VectorXd target = test_set.targets().row(i);
VectorXd prediction = net.forwardPropagate(sample);
test_costs(n) += cost.computeCost(prediction, target) / BATCH_SIZE;
}
*/
<file_sep>/Backprop/Convolutional.h
#pragma once
#include "Layer.h"
#include "Reshape.h"
using namespace Eigen;
namespace Backprop
{
class Convolutional : public Layer
{
private :
int m_input_map_rows;
int m_input_map_cols;
int m_output_map_rows;
int m_output_map_cols;
int m_kernel_size;
int m_nb_input_maps;
int m_nb_output_maps;
bool m_padded;
bool m_propagate_ein;
std::vector <MatrixXd> m_input_maps;
std::vector <MatrixXd> m_output_maps;
std::vector <MatrixXd> m_ein_maps;
std::vector <MatrixXd> m_eout_maps;
std::vector <MatrixXd> m_kernels;
std::vector <MatrixXd> m_gradients;
MatrixXd addPadding(MatrixXd input, int padding)
{
int extended_rows = input.rows() + 2 * padding;
int extended_cols = input.cols() + 2 * padding;
MatrixXd extended = MatrixXd::Zero(extended_rows, extended_cols);
extended.block(padding, padding, input.rows(), input.cols()) = input;
return extended;
}
MatrixXd convOp(MatrixXd input, MatrixXd kernel)
{
if (m_padded)
input = addPadding(input, m_kernel_size - 1);
int output_rows = input.rows() - kernel.rows() + 1;
int output_cols = input.cols() - kernel.cols() + 1;
MatrixXd output(output_rows, output_cols);
for (int i = 0; i < output.rows(); i++)
{
for (int j = 0; j < output.cols(); j++)
{
MatrixXd block = input.block(i, j, kernel.rows(), kernel.cols());
output(i, j) = (kernel.array() * block.array()).sum();
}
}
return output;
}
MatrixXd deConvOp(MatrixXd input, MatrixXd kernel)
{
if (!m_padded)
input = addPadding(input, m_kernel_size - 1);
MatrixXd tranposed_kernel = kernel.transpose();
MatrixXd output = convOp(input, tranposed_kernel);
return output;
}
public :
Convolutional(int input_map_rows, int input_map_cols, int kernel_size,
int nb_input_maps, int nb_output_maps, bool padded = 0,
bool propagate_ein = 1)
: m_input_map_rows(input_map_rows),
m_input_map_cols(input_map_cols),
m_kernel_size(kernel_size),
m_nb_input_maps(nb_input_maps),
m_nb_output_maps(nb_output_maps),
m_padded(padded),
m_propagate_ein(propagate_ein)
{
if (!padded) {
m_output_map_rows = input_map_rows - kernel_size + 1;
m_output_map_cols = input_map_cols - kernel_size + 1;
} else {
m_output_map_rows = input_map_rows + kernel_size - 1;
m_output_map_cols = input_map_cols + kernel_size - 1;
}
int nb_kernel = nb_input_maps * nb_output_maps;
for (int i = 0; i < nb_kernel; i++)
m_kernels.push_back(MatrixXd(kernel_size, kernel_size));
for (int i = 0; i < nb_kernel; i++)
m_gradients.push_back(MatrixXd(kernel_size, kernel_size));
for (int i = 0; i < m_nb_input_maps; i++)
m_input_maps.push_back(MatrixXd(m_input_map_rows, m_input_map_cols));
for (int i = 0; i < m_nb_output_maps; i++)
m_output_maps.push_back(MatrixXd(m_output_map_rows, m_output_map_cols));
for (int i = 0; i < m_nb_output_maps; i++)
m_ein_maps.push_back(MatrixXd(m_output_map_rows, m_output_map_cols));
for (int i = 0; i < m_nb_input_maps; i++)
m_eout_maps.push_back(MatrixXd(m_input_map_rows, m_input_map_cols));
initParameters();
}
void initParameters()
{
for (int n = 0; n < m_nb_input_maps * m_nb_output_maps; n++) {
m_kernels[n].setRandom();
m_kernels[n] *= 1.0f / (m_kernel_size * std::sqrt(m_nb_input_maps));
}
}
VectorXd forwardProp(VectorXd& unshaped_inputs)
{
// Setup the maps
reshape(unshaped_inputs, m_input_maps);
for (int j = 0; j < m_nb_output_maps; j++)
m_output_maps[j].setZero();
// Perform the convolutions
for (int i = 0; i < m_nb_input_maps; i++)
for (int j = 0; j < m_nb_output_maps; j++)
m_output_maps[j] +=
convOp(m_input_maps[i], m_kernels[i * m_nb_output_maps + j]); // HERE !
// Unshape the data and return
VectorXd unshaped_outputs;
unshape(m_output_maps, unshaped_outputs);
return unshaped_outputs;
}
// TODO Reset the Gradient here
VectorXd backProp(VectorXd& unshaped_inputs, VectorXd& unshaped_eins)
{
// Reshape the inputs
reshape(unshaped_inputs, m_input_maps);
reshape(unshaped_eins, m_ein_maps);
// Compute the gradients
for (int i = 0; i < m_nb_input_maps; i++)
for (int j = 0; j < m_nb_output_maps; j++)
m_gradients[i * m_nb_output_maps + j] =
convOp(m_input_maps[i], m_ein_maps[j]);
// Return if we dont compute eouts
if (!m_propagate_ein)
return VectorXd(0);
// Else, setup the eout maps
for (int i = 0; i < m_nb_input_maps; i++)
m_eout_maps[i].setZero();
// Perform the deconvolutions
for (int i = 0; i < m_nb_input_maps; i++)
for (int j = 0; j < m_nb_output_maps; j++)
m_eout_maps[i] +=
deConvOp(m_ein_maps[j], m_kernels[i * m_nb_output_maps + j]); // HERE !
// Unshape eout and return
VectorXd unshaped_eouts;
unshape(m_eout_maps, unshaped_eouts);
return unshaped_eouts;
}
VectorXd getParameters()
{
VectorXd unshaped_kernels;
unshape(m_kernels, unshaped_kernels);
return unshaped_kernels;
}
VectorXd getGradient()
{
VectorXd unshaped_gradients;
unshape(m_gradients, unshaped_gradients);
return unshaped_gradients;
}
void setParameters(VectorXd& parameters)
{
reshape(parameters, m_kernels);
}
void setGradient(VectorXd& gradient)
{
reshape(gradient, m_gradients);
}
Convolutional* clone()
{
return new Convolutional(*this);
}
std::vector <MatrixXd> getKernels()
{
return m_kernels;
}
};
}
<file_sep>/Backprop/SoftMax.h
#pragma once
#include <Eigen/Core>
namespace Backprop
{
class SoftMax : public Layer
{
public:
SoftMax() {}
VectorXd forwardProp(VectorXd& input)
{
return softmax(input);
}
VectorXd backProp(VectorXd& input, VectorXd& ein)
{
// Naive approach: compute the Gradient first
int size = input.size();
MatrixXd input_grad(size, size);
input_grad = - softmax(input) * softmax(input).transpose();
input_grad += softmax(input).asDiagonal();
VectorXd eout = ein.transpose() * input_grad;
// Optimized approach: do not compute the gradient
/*
VectorXd s = softmax(input);
double dot_product = ein.transpose() * s;
VectorXd eout = - dot_product * s;
eout.array() += ein.array() * s.array();
*/
return eout;
}
VectorXd softmax(VectorXd& input)
{
VectorXd output = input.array().exp();
double partition = output.sum();
output /= partition;
return output;
}
VectorXd getParameters() { return VectorXd(0); }
VectorXd getGradient() { return VectorXd(0); }
void setParameters(VectorXd& parameters) { (void) parameters; }
void setGradient(VectorXd& gradient) { (void) gradient;}
SoftMax* clone() { return new SoftMax(*this); }
};
}
<file_sep>/examples/ex5.cpp
// Autoencoder with TANH
#include "Backprop/Core.h"
using namespace Backprop;
int main(void)
{
srand(0);
/// Load data //////////////////////////////////////////////////////////////
PCFD dataset("data/PCFD.dat");
/// Display some data //////////////////////////////////////////////////////
std::vector <MatrixXd> samples;
const int sample_size = dataset.sampleSize();
for (int i = 0; i < 100; i++) {
VectorXd sample = dataset.samples().row(i);
MatrixXd reshaped = Map <MatrixXd> (sample.data(), sample_size, sample_size);
samples.push_back(reshaped);
}
MatrixXd sample_map = buildMapfromData(samples, sample_size, sample_size);
Display sample_display(&sample_map, "Samples");
// Setup the Net ///////////////////////////////////////////////////////////
Network net;
net.addLinearLayer(2704, 200);
net.addActivationLayer(SIGM);
net.addLinearLayer(200, 50);
net.addActivationLayer(SIGM);
net.addLinearLayer(50, 200);
net.addActivationLayer(SIGM);
net.addLinearLayer(200, 2704);
net.addActivationLayer(SIGM);
// Train the Net ///////////////////////////////////////////////////////////
Dataset batch;
const int N_BATCH = 200;
const int BATCH_SIZE = 100;
VectorXd train_costs = VectorXd::Zero(N_BATCH);
Plot plot(&train_costs, "train cost", "red");
Timer timer;
for (int n = 0; n < N_BATCH; n++)
{
// Build a batch ///////////////////////////////////////////////////////
batch.inputs.clear();
batch.targets.clear();
for (int i = 0; i < BATCH_SIZE; i++)
{
int s = rand() % dataset.samples().rows();
VectorXd sample = dataset.samples().row(s);
batch.inputs.push_back(sample);
batch.targets.push_back(sample);
}
// Train the net on the batch //////////////////////////////////////////
train_costs(n) = SGD(net, batch, SSE, 0.01);
std::cout << "Average cost = " << train_costs(n) << std::endl;
// Plot the training progress //////////////////////////////////////////
plot.render();
}
float elapsed = timer.getTimeSec();
std::cout << " elapsed time : " << elapsed << "sec" << std::endl;
// Display the features ////////////////////////////////////////////////////
int feature_size = sample_size;
std::vector <MatrixXd> features;
VectorXd parameters = net.layer(0).getParameters();
MatrixXd reshaped_parameters = Map <MatrixXd> (parameters.data(), 200, feature_size * feature_size);
for (int i = 0; i < reshaped_parameters.rows(); i++) {
VectorXd feature = reshaped_parameters.row(i);
MatrixXd reshaped = Map <MatrixXd> (feature.data(), feature_size, feature_size);
features.push_back(reshaped);
}
MatrixXd feature_map = buildMapfromData(features, feature_size, feature_size);
Display feature_display(&feature_map, "Features");
// Display the reconstructed faces /////////////////////////////////////////
std::vector <MatrixXd> reconstructeds;
for (int i = 0; i < 100; i++) {
VectorXd sample = dataset.samples().row(i);
sample = net.forwardPropagate(sample);
MatrixXd reshaped = Map <MatrixXd> (sample.data(), sample_size, sample_size);
reconstructeds.push_back(reshaped);
}
sample_map = buildMapfromData(reconstructeds, sample_size, sample_size);
Display reconstructed_display(&sample_map, "Samples");
return 0;
}
<file_sep>/Backprop/Linear.h
#pragma once
#include "Layer.h"
using namespace Eigen;
namespace Backprop
{
class Linear : public Layer
{
private :
int m_input_size;
int m_output_size;
bool m_propagate_ein;
MatrixXd m_theta;
MatrixXd m_gradient;
public :
Linear(int input_size, int output_size, bool propagate_ein = 1)
: m_input_size(input_size), m_output_size(output_size),
m_propagate_ein(propagate_ein)
{
m_theta = MatrixXd::Zero(output_size, input_size);
m_gradient = MatrixXd::Zero(output_size, input_size);
m_theta.setRandom();
m_theta *= std::sqrt(6. / (input_size + output_size));
}
VectorXd forwardProp(VectorXd& input)
{
return m_theta * input;
}
VectorXd backProp(VectorXd& input, VectorXd& ein)
{
m_gradient = ein * input.transpose();
// Return if we dont compute eouts
if (!m_propagate_ein) return VectorXd(0);
// Else compute eouts
VectorXd eout = m_theta.transpose() * ein;
return eout;
}
VectorXd getParameters()
{
VectorXd unshaped = Map <VectorXd> (m_theta.data(), m_theta.size());
return unshaped;
}
VectorXd getGradient()
{
VectorXd unshaped = Map <VectorXd> (m_gradient.data(), m_gradient.size());
return unshaped;
}
void setParameters(VectorXd& parameters)
{
m_theta = Map <MatrixXd> (parameters.data(), m_output_size, m_input_size);
}
void setGradient(VectorXd& gradient)
{
m_gradient = Map <MatrixXd> (gradient.data(), m_output_size, m_input_size);
}
Linear* clone() { return new Linear(*this); }
///////////////////////////////////////////////////////////////////////////
std::vector <VectorXd> getFeatures()
{
std::vector <VectorXd> features;
for (int i = 0; i < m_theta.rows(); i++)
features.push_back(m_theta.row(i));
return features;
}
};
}
<file_sep>/Backprop/Reshape.h
#pragma once
#include <Eigen/Core>
#include <vector>
using namespace Eigen;
namespace Backprop
{
void reshape(VectorXd& unshaped, std::vector<MatrixXd>& maps)
{
if (maps.empty()) return;
int rows = maps[0].rows();
int cols = maps[0].cols();
int nb_maps = maps.size();
for (int i = 0; i < nb_maps; i++) {
VectorXd unshaped_map = unshaped.segment(i * rows * cols, rows * cols);
maps[i] = Map <MatrixXd> (unshaped_map.data(), rows, cols);
}
}
void unshape(std::vector<MatrixXd>& maps, VectorXd& unshaped)
{
if (maps.empty()) {
unshaped = VectorXd(0);
return;
}
int unshaped_map_size = maps[0].rows() * maps[0].cols();
if (unshaped.size() != (int) maps.size() * unshaped_map_size)
unshaped = VectorXd(maps.size() * unshaped_map_size);
for (int i = 0; i < (int) maps.size(); i++) {
VectorXd unshaped_map = Map <VectorXd> (maps[i].data(), unshaped_map_size);
unshaped.segment(i * unshaped_map_size, unshaped_map_size) = unshaped_map;
}
}
}
<file_sep>/Backprop/Activation.h
#pragma once
#include <Eigen/Core>
#include <Backprop/Layer.h>
namespace Backprop
{
enum ActivationEnum {SIGM, TANH, RELU, SRELU, LIN};
class Activation : public Layer
{
private:
ActivationEnum m_function;
public:
Activation(ActivationEnum function)
: m_function(function)
{}
VectorXd forwardProp(VectorXd& input)
{
return actFun(input);
}
VectorXd backProp(VectorXd& input, VectorXd& ein)
{
return ein.cwiseProduct(actGrad(input));
}
VectorXd actFun(VectorXd& input)
{
VectorXd output(input.size());
switch(m_function) {
case SIGM :
output.array() = 1.0 / (1.0 + (-input).array().exp());
break;
case TANH :
output.array() = (input.array().exp() - (-input).array().exp())
/ (input.array().exp() + (-input).array().exp());
break;
case RELU :
output.array() = input.array().max(0);
break;
case SRELU :
output.array() = (1 + input.array().exp()).log();
break;
case LIN :
output.array() = input.array();
break;
}
return output;
}
// Activation gradient //////////////////////////////////////////////////////////
VectorXd actGrad(VectorXd& input)
{
VectorXd output(input.size());
switch(m_function) {
case SIGM :
output.array() = actFun(input).array() * (1. - actFun(input).array());
break;
case TANH :
output.array() = 1 - actFun(input).array() * actFun(input).array();
break;
case RELU :
output.array() = (input.array() > 0).cast<double>();
break;
case SRELU:
output.array() = 1.0 / (1.0 + (-input).array().exp());
break;
case LIN :
output.setOnes();
break;
}
return output;
}
VectorXd getParameters() { return VectorXd(0); }
VectorXd getGradient() { return VectorXd(0); }
void setParameters(VectorXd& parameters) { (void) parameters; }
void setGradient(VectorXd& gradient) { (void) gradient;}
Activation* clone() { return new Activation(*this); }
};
}
<file_sep>/Backprop/Layer.h
#pragma once
#include <Eigen/Core>
using namespace Eigen;
namespace Backprop
{
enum IO {I, H, O};
class Layer
{
public:
virtual VectorXd forwardProp(VectorXd& input) = 0;
virtual VectorXd backProp(VectorXd& input, VectorXd& ein) = 0;
virtual VectorXd getParameters() = 0;
virtual VectorXd getGradient() = 0;
virtual void setParameters(VectorXd& parameters) = 0;
virtual void setGradient(VectorXd& gradient) = 0;
virtual Layer* clone() = 0;
virtual ~Layer() {}
};
}
<file_sep>/Readme.md
# Backprop
## What is this?
Backprop is a vanilla Deep Learning implementation written in C++ 98 and based on Eigen3.
This code serves as a boilerplate for my personal research. It's not documented, but it is written in a comprehensive fashion.
Currently it supports the following layers: Fully-Connected, Activation, Convolutional, and Sampling.
Important note: Backprop does not use biases. This is a personal choice I made based on my own experience with Deep Learning.
## Coypright
This code is released under MiT license.
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.1)
project(Backprop)
# Check the OS -----------------------------------------------------------------
if(NOT UNIX)
message(FATAL_ERROR " Only Unix based systems are supported")
endif()
# Check the CMake usage --------------------------------------------------------
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
message(FATAL_ERROR " Inappropriate CMake usage. \n"
" Should be called in a build directory: \n"
" $ mkdir build; cmake ..")
endif()
# Find Eigen3 ------------------------------------------------------------------
find_package(Eigen3)
if(NOT EIGEN3_FOUND)
message(FATAL_ERROR " Could not locate the Eigen3 library. \n"
" Please ensure it is installed on your machine.")
endif()
# find OpenMP ------------------------------------------------------------------
#find_package(OpenMP REQUIRED)
# Include Backprop and Eigen3 --------------------------------------------------
include_directories(. ${EIGEN3_INCLUDE_DIRS} )
# Set the compiler flags -------------------------------------------------------
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS "-O2 -s -Wall -Wextra")
endif()
# Build the sources ------------------------------------------------------------
#file(GLOB_RECURSE BACKPROP_SRC "src/*.cpp")
#add_library(Backprop SHARED ${BACKPROP_SRC})
# Find GNUPlot -----------------------------------------------------------------
find_program(GNUPLOT_EXECUTABLE gnuplot)
if (NOT GNUPLOT_EXECUTABLE)
message(WARNING "GNUPlot is required to run the example.")
endif()
# Build the example ------------------------------------------------------------
option(BUILD_EXAMPLE "Build the example." ON)
if(BUILD_EXAMPLE)
add_executable(EX1 examples/ex1.cpp)
add_executable(EX2 examples/ex2.cpp)
add_executable(EX3 examples/ex3.cpp)
add_executable(EX4 examples/ex4.cpp)
add_executable(EX5 examples/ex5.cpp)
# target_link_libraries(EX1 OpenMP::OpenMP_CXX)
# target_link_libraries(EX2 OpenMP::OpenMP_CXX)
# target_link_libraries(EX3 OpenMP::OpenMP_CXX)
# target_link_libraries(EX4 OpenMP::OpenMP_CXX)
# target_link_libraries(EX5 OpenMP::OpenMP_CXX)
endif()
execute_process(COMMAND ${CMAKE_SOURCE_DIR}/data/MNIST/get_mnist.py
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/data/MNIST)
# Copy the dataset -----------------------------------------------------------
file(COPY "data" DESTINATION ".")
# TODO: subfolder for the example, the python script with image? NO
# TODO: Doxygen?
<file_sep>/Backprop/Core.h
#pragma once
#include <Eigen/Core>
#include "Activation.h"
#include "Convolutional.h"
#include "Cost.h"
#include "Display.h"
#include "Dropout.h"
#include "ELU.h"
#include "Linear.h"
#include "MNIST.h"
#include "Network.h"
#include "Optimize.h"
#include "PCFD.h"
#include "Plot.h"
#include "Reshape.h"
#include "Sampling.h"
#include "SoftMax.h"
#include "Timer.h"
#include "Types.h"
#include "Utils.h"
<file_sep>/Backprop/Plot.h
////////////////////////////////////////////////////////////////////////////////
// Plot:
// A tool for displaying charts. Uses on a GNUPlot backend.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
using namespace Eigen;
namespace Backprop
{
class Plot
{
private :
FILE * m_pipe_p;
std::vector <VectorXd*> m_lines;
std::vector <std::string> m_colors;
std::string m_title;
void openGP()
{
m_pipe_p = popen("gnuplot -persist", "w");
if (!m_pipe_p)
{
std::cout << "Failed to open GNUPlot !\n"
<< "Please ensure it is installed ..."
<< std::endl;
}
}
void configPlot()
{
if (m_pipe_p)
{
const char* configs =
//"set size ratio -1\n"
//"set yrange [-1:1]\n"
//"set palette gray\n"
//"unset xtics\n"
//"unset ytics\n"
"set grid\n"
"unset key\n";
//TODO: ensure wxt is the best terminal for what we want
fprintf(m_pipe_p, "%s", configs);
fprintf(m_pipe_p, "set term wxt title 'Backprop'\n");
fprintf(m_pipe_p, "set title \"%s\"\n", m_title.c_str());
// TODO use th e line with the maximum range
fprintf(m_pipe_p, "set xrange [%f:%f] \n", 0.f, (double) m_lines[0]->size());
}
}
public :
Plot(VectorXd * data, const char * title = "Plot", const char * color = "red")
: m_title(title)
{
m_lines.push_back(data);
m_colors.push_back(color);
openGP();
configPlot();
render();
}
void addLine(VectorXd * line, const char * color)
{
m_lines.push_back(line);
m_colors.push_back(std::string(color));
render();
}
void render()
{
if (m_pipe_p)
{
fprintf(m_pipe_p, "plot ");
for (int l = 0; l < (int) m_lines.size(); l++)
{
fprintf(m_pipe_p, "'-' lc rgb '%s' with lines", m_colors[l].c_str());
if (l != (int) (m_lines.size() - 1))
fprintf(m_pipe_p, ", ");
}
fprintf(m_pipe_p, "\n");
for (int l = 0; l < (int) m_lines.size(); l++)
{
VectorXd line = (*m_lines[l]);
for(int i = 0; i < line.size(); i++)
fprintf(m_pipe_p, "%f \n", line(i));
fprintf(m_pipe_p, "\ne\n");
fflush(m_pipe_p);
}
////////////////////////////////////////////////
/*
printf("plot ");
for (int l = 0; l < (int) m_lines.size(); l++)
{
printf("'-' lc rgb '%s' with lines", m_colors[l].c_str());
if (l != (int) (m_lines.size() - 1))
printf( ", ");
}
printf("\n");
for (int l = 0; l < (int) m_lines.size(); l++)
{
VectorXd line = (*m_lines[l]);
for(int i = 0; i < line.size(); i++)
printf("%f \n", line(i));
printf("\ne\n");
fflush(m_pipe_p);
}
*/
}
}
~Plot()
{
pclose(m_pipe_p);
}
};
}
| 80a4c44ff3085a1b3cf1dac0a7d4c0f97d75704b | [
"CMake",
"Markdown",
"Python",
"C",
"C++"
] | 25 | Python | Cryst4L/Backprop | 89d344074fa597dcf39ce851e6071ceff85d47cd | 71b9ce0eea7860dff44ed00fc6f7845e88eaad20 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObstacleMove : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.position = new Vector3(Mathf.PingPong(Time.time*(2.5f), 16.24f), 1.0f, 15.0f);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using extOSC;
public class AudioPlay : MonoBehaviour {
private AudioSource m_AudioSource;
OSCReceiver osc;
void Start()
{
osc = this.gameObject.AddComponent<OSCReceiver>();
osc.Bind("/1/toggle1", onToggle1);
}
void onToggle1(OSCMessage msg)
{ // 0,1
m_AudioSource = this.gameObject.GetComponent<AudioSource>();
m_AudioSource.Play();
Debug.Log(msg.Values[0].FloatValue);
// float SandSound = msg.Values[0].FloatValue;
if (msg.Values[0] != null)
{
}
// float ToggleControl = msg[0]
// return
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using extOSC;
public class OSCControl2 : MonoBehaviour {
OSCReceiver osc;
void Start()
{
osc = this.gameObject.AddComponent<OSCReceiver>();
osc.Bind("/accxyz", onMessage);
osc.Bind("/1/toggle1", onToggle1);
osc.Bind("/1/fader1", onFader1);
osc.Bind("/1/fader5", onFader5);
}
void onMessage(OSCMessage msg)
{ // using acc to rotate
Debug.LogFormat("msg {1}", msg);
this.gameObject.transform.Rotate(
new Vector3(0, -msg.Values[1].FloatValue * 1000, 0), Space.World
);
}
void onToggle1(OSCMessage msg)
{
Debug.LogFormat("msg {0}", msg);
this.gameObject.transform.position = new Vector3(16f, 1.29f , 3f);
Vector3 rotationVector = new Vector3(0.5f, -177f, 0.3f);
this.gameObject.transform.rotation = Quaternion.Euler(rotationVector);
}
void onFader1(OSCMessage msg)
{
// fader-OSC
// Debug.LogFormat("msg {0}", msg);
float transX = msg.Values[0].FloatValue;
float a = 0.5f;
if (transX > a)
{
this.gameObject.transform.Translate
(0.2f, 0, 0);
}
else
{
this.gameObject.transform.Translate(-0.2f, 0, 0);
}
}
// scale
void onFader5(OSCMessage msg)
{
// Debug.LogFormat("msg {0}", msg);
float scaleXYZ = msg.Values[0].FloatValue;
scaleXYZ += scaleXYZ;
this.gameObject.transform.localScale = new Vector3(scaleXYZ, scaleXYZ, scaleXYZ);
}
}
| 81c91607b8bdde0b99c29eb1697d23206c5c33f6 | [
"C#"
] | 3 | C# | wasd120d/OSC-Control-Demo | 2ae4e95c89e9061e815c4f79fa9bab4f08ead5b5 | c4190c814d46b7ec7bb7b62edec9d5469b85cec8 |
refs/heads/master | <file_sep>//
// HomeViewController.swift
// CustomLoginSignupDemo
//
// Created by <NAME> on 7/22/20.
// Copyright © 2020 konga. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "logged in"
}
@IBAction func logoutTapped(_ sender: Any) {
UserDefaults.standard.removeObject(forKey: "email")
let vc = storyboard?.instantiateViewController(withIdentifier: "LoginViewController")
let navVc = UINavigationController(rootViewController: vc!)
let share = UIApplication.shared.delegate as? AppDelegate
share?.window?.rootViewController = navVc
share?.window?.makeKeyAndVisible() }
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// Constants.swift
// CustomLoginSignupDemo
//
// Created by <NAME> on 7/23/20.
// Copyright © 2020 konga. All rights reserved.
//
import Foundation
struct Constants {
struct Storyboard {
static let homeViewController = "HomeVC"
}
}
<file_sep>//
// SignUpViewController.swift
// CustomLoginSignupDemo
//
// Created by <NAME> on 7/22/20.
// Copyright © 2020 konga. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!
let firstName = "ayo"
let lastName = "Deji"
let email = "<EMAIL>"
let password = "<PASSWORD>"
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
}
func setUpElements(){
//hide the error label
errorLabel.alpha = 0
//Style the text field
Utilities.styleTextField(firstNameTextField)
Utilities.styleTextField(lastNameTextField)
Utilities.styleTextField(emailTextField)
Utilities.styleTextField(passwordTextField)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
@IBAction func signupTapped(_ sender: Any) {
if firstName == firstNameTextField.text! && lastName == lastNameTextField.text! && email == emailTextField.text! && password == passwordTextField.text!{
let alert = UIAlertController(title: "alert", message: "signup successful", preferredStyle: .alert)
let ok = UIAlertAction(title: "ok", style: .default, handler: nil)
alert.addAction(ok)
present(alert, animated: true, completion: nil)
}else{
let alert = UIAlertController(title: "alert", message: "error signing up user", preferredStyle: .alert)
let ok = UIAlertAction(title: "ok", style: .default, handler: nil)
alert.addAction(ok)
present(alert, animated: true, completion: nil)
}
}
}
| 8f45dab22b889cf76297fec78f017d886603229c | [
"Swift"
] | 3 | Swift | ayodejiayankola/customLoginSignupDemo | 6cbcc980b43237662449b83a97078a5ddbe089cd | 4a77e972171ba413e68c683abd9ca58434f4ef8d |
refs/heads/main | <repo_name>HamzaHanbali/JointPricingAnnuitiesAssurances<file_sep>/R Code - Section 5 - Pricing insurance contracts with offsetting liabilities.R
## R code for replicating Section 5 in "Pricing insurance contracts with offsetting liabilities"
## The user should have downloaded the number of deaths and exposures for England and Whales (EW) and the United States (US).
## EWD and USD : matrices containing the number of deaths in EW and US, respectively, with 59 rows corresponding to years 1950:2008 and 61 columns correponding to ages 30:90.
##########################
### Fitting the Li-Lee ###
##########################
## Log crude rates
DR_E = log(EWD/EWE) ; DR_U = log(USD/USE) ; DR_T = log((EWD+USD)/(EWE+USE))
DRn_E = log(EWD/EWE) ; DRn_U = log(USD/USE) ; DRn_T = log((EWD+USD)/(EWE+USE))
## Step 1 - Estimating the common components AlphaT, BetaT and KappaT using singular value decomposition
AlphaT = colMeans(DRn_T) ; for(j in 1:ncol(DRn_T)){DRn_T[,j] = DRn_T[,j] - AlphaT[j]}
SVD_T = svd(DRn_T, 1, 1)
BetaT = SVD_T$v/sum(SVD_T$v) ; KappaT = SVD_T$u * sum(SVD_T$v) * SVD_T$d[1]
## Step 2 - Estimating the individual components BetaE and KappaE for EW, and BetaU and KappaU for US
for(j in 1:ncol(DRn_E)){DRn_E[,j] = DRn_E[,j] - BetaT[j]*KappaT - AlphaT[j]}
for(j in 1:ncol(DRn_U)){DRn_U[,j] = DRn_U[,j] - BetaT[j]*KappaT - AlphaT[j]}
SVD_E = svd(DRn_E, 1, 1) ; SVD_U = svd(DRn_U, 1, 1)
BetaE = SVD_E$v/sum(SVD_E$v) ; KappaE = SVD_E$u * sum(SVD_E$v) * SVD_E$d[1]
BetaU = SVD_U$v/sum(SVD_U$v) ; KappaU = SVD_U$u * sum(SVD_U$v) * SVD_U$d[1]
####################################
### Simulation of the Kappas ###
####################################
library(mvtnorm)
## Number of simulations and maturities of the contracts
NSim = 10000
Horizon = 30
## Means and standard deviations of the kappa's
M1 = mean(diff(KappaE)) ;SD1 = sd(diff(KappaE))
M2 = mean(diff(KappaU)) ;SD2 = sd(diff(KappaU))
Mt = mean(diff(KappaT));SDt = sd(diff(KappaT))
## Initializing the matrices of simulations of the kappa's
SimKappaE = matrix(0,ncol=Horizon,nrow=NSim)
SimKappaU = matrix(0,ncol=Horizon,nrow=NSim)
SimKappaT = matrix(0,ncol=Horizon,nrow=NSim)
## Multivariate normal random vector
ZZ = rmvnorm(NSim,sigma=cbind(c(1,cor(KappaE,KappaU),cor(KappaE,KappaT)),c(cor(KappaE,KappaU),1,cor(KappaU,KappaT)),c(cor(KappaE,KappaT),cor(KappaU,KappaT),1)))
Z1 = ZZ[,1] ; Z2 = ZZ[,2] ; Zt = ZZ[,3]
## Forecast
SimKappaE[,1] = KappaE[length(KappaE)] + M1 + SD1*Z1
SimKappaU[,1] = KappaU[length(KappaU)] + M2 + SD2*Z2
SimKappaT[,1] = KappaT[length(KappaT)] + Mt + SDt*Zt
for (k in 2:Horizon){
ZZ = rmvnorm(NSim,sigma=cbind(c(1,cor(KappaE,KappaU),cor(KappaE,KappaT)),c(cor(KappaE,KappaU),1,cor(KappaU,KappaT)),c(cor(KappaE,KappaT),cor(KappaU,KappaT),1)))
Z1 = ZZ[,1] ; Z2 = ZZ[,2] ; Zt = ZZ[,3]
SimKappaE[,k] = SimKappaE[,k-1] + M1 + SD1*Z1
SimKappaU[,k] = SimKappaU[,k-1] + M2 + SD2*Z2
SimKappaT[,k] = SimKappaT[,k-1] + Mt + SDt*Zt
}
## Transforing the kappa's into forces of mortality
N0 = length(KappaU)
MuUS = matrix(0,ncol=Horizon,nrow=NSim)
MuEW = matrix(0,ncol=Horizon,nrow=NSim)
for (j in 1:30){
MuUS[,j] = exp(DR_U[N0,j]) * exp( BetaU[j]* (SimKappaU[,j] - KappaU[N0]) + BetaT[j]*(SimKappaT[,j] - KappaT[N0]) )
MuEW[,j] = exp(DR_E[N0,30+j]) * exp( BetaE[30+j]* (SimKappaE[,j] - KappaE[N0]) + BetaT[30+j]*(SimKappaT[,j] - KappaT[N0]) )
}
## Transforming the forces of mortality into survival probabilities (for annuity using EW data) and into survival and death probabilities (for assurances using US data)
PUS = matrix(0,ncol=Horizon,nrow=NSim) ; PEW = matrix(0,ncol=Horizon,nrow=NSim)
for (i in 1:NSim){PUS[i,] = exp( - cumsum( MuUS[i,]) ) ; PEW[i,] = exp( - cumsum( MuEW[i,]) ) }
QUS = 1 - exp(-MuUS)
## Simulations of assurances and annuities using 1% interest rate
Discount = 1/1.01
Assurances = rowSums((Discount^t(matrix(rep((seq(1,Horizon)),NSim),ncol=NSim))) * QUS * (cbind(rep(1,NSim),PUS[,-Horizon])))
Annuities = rowSums((Discount^t(matrix(rep((seq(1,Horizon)),NSim),ncol=NSim))) * PEW)
#####################################################################
###### Premium Loading under <<standard deviation principle>> #######
#####################################################################
##
## Figure 1, Section 5
##
## Function for conditional value-at-risk (RM_TV), value-at-risk (RM_V) and mean-standard deviation (RM_sd)
RM_TV = function(X,level) {as.numeric(mean(X[which(X>=quantile(X,level))]))}
RM_V = function(X,level) {as.numeric(quantile(X,level))}
RM_sd = function(X,level) {mean(X) + level*sd(X)}
## Function to calculate the joint loading. The function returns the individual loadings Psi_60 (annuities) and Psi_30 (assurances)
## as well as the joint loading Psi_Ptf. The function also returns the corresponding Premium under join loading (NH for natural hedging) and stand-alone (SA)
Psis = function(Level,Target,b,B,n,RM){
B_60 = B ; B_30 = b*B
CVaR_30 = RM(B_30*Assurances,Level)
Psi_30 = Target * (CVaR_30 - mean(B_30*Assurances)) / mean(B_30*Assurances)
Premium_30_SA = mean(B_30*Assurances)*(1 + Psi_30)
CVaR_60 = RM(B_60*Annuities,Level)
Psi_60 = Target * (CVaR_60 - mean(B_60*Annuities)) / mean(B_60*Annuities)
Premium_60_SA = mean(B_60*Annuities)*(1 + Psi_60)
## Premiums with Natural Hedging ##
Value_Ptf = n*B_30*Assurances + (1-n)*B_60*Annuities
CVaR_Ptf = RM(Value_Ptf,Level)
Psi_Ptf = Target*(CVaR_Ptf - mean(Value_Ptf)) / mean(Value_Ptf)
Premium_30_NH = mean(B_30*Assurances)*(1 + Psi_Ptf)
Premium_60_NH = mean(B_60*Annuities)*(1 + Psi_Ptf)
return( c(Psi_60,Psi_30,Psi_Ptf,Premium_30_NH,Premium_30_SA,Premium_60_NH,Premium_60_SA) )}
## Vectors of outpout, under different assumptions
pA_V = c() ; pB_V = c() ; pT_V = c()
pA_V2 = c() ; pB_V2 = c() ; pT_V2 = c()
pA_V3 = c() ; pB_V3 = c() ; pT_V3 = c()
pA_V4 = c() ; pB_V4 = c() ; pT_V4 = c()
pA_S = c() ; pB_S = c() ; pT_S = c()
pA_S2 = c() ; pB_S2 = c() ; pT_S2 = c()
pA_S3 = c() ; pB_S3 = c() ; pT_S3 = c()
pA_S4 = c() ; pB_S4 = c() ; pT_S4 = c()
Pols = seq(0,1,length.out=500)
for (n in 1:length(Pols)){
print(n)
PPT = Psis(0.95,0.5,1,1,Pols[n],RM_V) ; pA_V[n] = PPT[1] ; pB_V[n] = PPT[2] ; pT_V[n] = PPT[3]
PPT = Psis(0.95,0.5,10,1,Pols[n],RM_V) ; pA_V2[n] = PPT[1] ; pB_V2[n] = PPT[2] ; pT_V2[n] = PPT[3]
PPT = Psis(0.95,0.5,100,1,Pols[n],RM_V) ; pA_V3[n] = PPT[1] ; pB_V3[n] = PPT[2] ; pT_V3[n] = PPT[3]
PPT = Psis(0.95,0.75,10,1,Pols[n],RM_V) ; pA_V4[n] = PPT[1] ; pB_V4[n] = PPT[2] ; pT_V4[n] = PPT[3]
PPT = Psis(1.686,0.5,1,1,Pols[n],RM_sd) ; pA_S[n] = PPT[1] ; pB_S[n] = PPT[2] ; pT_S[n] = PPT[3]
PPT = Psis(1.686,0.5,10,1,Pols[n],RM_sd) ; pA_S2[n] = PPT[1] ; pB_S2[n] = PPT[2] ; pT_S2[n] = PPT[3]
PPT = Psis(1.686,0.5,100,1,Pols[n],RM_sd) ; pA_S3[n] = PPT[1] ; pB_S3[n] = PPT[2] ; pT_S3[n] = PPT[3]
PPT = Psis(1.686,0.75,10,1,Pols[n],RM_sd) ; pA_S4[n] = PPT[1] ; pB_S4[n] = PPT[2] ; pT_S4[n] = PPT[3]
}
## Visualization
mm = min(pT_V,pT_V2,pT_V3,pT_V4)
MM = max(pT_V,pT_V2,pT_V3,pT_V4)
xx = c(1,seq(20,length(Pols),20))
par(mfrow=c(2,2))
plot(cbind(Pols,pT_S),ylim=c(mm,MM),type='l',xlab='Proportion of term assurances',ylab=' ',main=expression('$\\zeta=0.5$ and $C_B=C_A$'))
points(cbind(Pols[xx],pT_V[xx]),col='blue',cex=0.5) ; lines(cbind(Pols,pA_S),lty=2) ; lines(cbind(Pols,pB_S),lty=2)
plot(cbind(Pols,pT_S2),ylim=c(mm,MM),type='l',xlab='Proportion of term assurances',ylab=' ',main=expression('$\\zeta=0.5$ and $C_B=10C_A$'))
points(cbind(Pols[xx],pT_V2[xx]),col='blue',cex=0.5) ; lines(cbind(Pols,pA_S2),lty=2) ; lines(cbind(Pols,pB_S2),lty=2)
plot(cbind(Pols,pT_S3),ylim=c(mm,MM),type='l',xlab='Proportion of term assurances',ylab=' ',main=expression('$\\zeta=0.5$ and $C_B=100C_A$'))
points(cbind(Pols[xx],pT_V3[xx]),col='blue',cex=0.5) ; lines(cbind(Pols,pA_S3),lty=2) ; lines(cbind(Pols,pB_S3),lty=2)
plot(cbind(Pols,pT_S4),ylim=c(mm,MM),type='l',xlab='Proportion of term assurances',ylab=' ',main=expression('$\\zeta=0.75$ and $C_B=10C_A$'))
points(cbind(Pols[xx],pT_V4[xx]),col='blue',cex=0.5) ; lines(cbind(Pols,pA_S4),lty=2) ; lines(cbind(Pols,pB_S4),lty=2)
################################
### Total collected premiums ###
################################
##
## Figure 2, Section 5
##
## Critical thresholds at portfolio level Nct, and at market level Wct
Nct = (2*Lambda2*piA)/(2*Lambda2*piA + (Lambda1 - 2*Lambda2)*piB)
Wct1 = Nct/(Nct + (1-Nct)*(1 + ((kB-1)/kB)*((PsiB-PsiA)/(1+PsiB)) *QB1 )*(kA/kB))
Wct2 = Nct/(Nct + (1-Nct)*(1 + ((kB-1)/kB)*((PsiB-PsiA)/(1+PsiB)) *QB2 )*(kA/kB))
## Function for the number of policyholders
Np = function(w,qq,kk,Pstar,PP,pp){
cc = ((1+Pstar)*pp-PP)/PP
Output = ((w)/kk)*(1 - ((kk-1)/kk)*qq*cc )
return( Output )}
## Main function to obtain the output, where 'bb' is the ratio of benefits. All other parameters are consistent with the notations in the paper
## The function returns the difference in total collected premiums between the two strategies
TotCol = function(bb,zeta,Gamma,w,qA,qB,kA,kB){
## Stand-alone loadings
PsiA = Gamma*zeta*sd(Annuities)/mean(Annuities)
PsiB = Gamma*zeta*sd(Assurances)/mean(Assurances)
## Correlation
Rho = cor(Annuities,Assurances)
## Pure premiums
piA = mean(Annuities)
piB = bb*mean(Assurances)
## Ratio of risk (denoted 'b' in the paper)
B = PsiB/PsiA
## Lambda's
Lambda1 = 1 + B^2 - 2*B*Rho
Lambda2 = 1 - B*Rho
## Minimum joint loading
Psimin = PsiA*sqrt((Lambda1 - Lambda2^2)/Lambda1)
## Equation (4.1) to determine Psi^star
psiF = function(ps){
nstar = Np(w,qB,kB,ps,(1+PsiB)*piB,piB)/(Np(w,qB,kB,ps,(1+PsiB)*piB,piB)+Np(1-w,qA,kA,ps,(1+PsiA)*piA,piA))
nts = (nstar*piB)/((nstar*piB)+((1-nstar)*piA))
Ps = PsiA*sqrt( Lambda1*nts*nts - 2*Lambda2*nts +1 )
return(Ps-ps)}
## Solving the equation
psol = uniroot(psiF,interval=c(0,PsiB))$root
## Stand-alone (sa) and joint (st) premiums for business lines A (annuities) and B (assurances)
PA_sa = (1+PsiA)*piA
PB_sa = (1+PsiB)*piB
PA_st = (1+psol)*piA
PB_st = (1+psol)*piB
## Stand-alone (sa) and joint (st) number of policyholders for business lines A (annuities) and B (assurances)
NA_st = Np(1-w,qA,kA,psol,(1+PsiA)*piA,piA)
NB_st = Np(w,qB,kB,psol,(1+PsiB)*piB,piB)
NA_sa = (1-w)/kA
NB_sa = w/kB
## Difference in total collected premiums
Diff = (NA_st*PA_st + NB_st*PB_st)/(NA_sa*PA_sa + NB_sa*PB_sa) - 1
return(Diff)}
## Calculating the output for different input values.
KA1 = 10
KA2 = 5
KA3 = 15
KB = 10
QB1 = 0.5
QB2 = 3
QA1 = 0.5
QA2 = 3
Psis1_1 = c() ; Psis2_1 = c() ; Psis3_1 = c() ; Psis4_1 = c()
Psis1_2 = c() ; Psis2_2 = c() ; Psis3_2 = c() ; Psis4_2 = c()
Psis1_3 = c() ; Psis2_3 = c() ; Psis3_3 = c() ; Psis4_3 = c()
for (n in 1:length(Pols)){
print(n)
Psis1_1[n] = TotCol(10,0.5,1.686,Pols[n],QA1,QB1,KA1,KB)
Psis2_1[n] = TotCol(10,0.5,1.686,Pols[n],QA1,QB2,KA1,KB)
Psis3_1[n] = TotCol(10,0.5,1.686,Pols[n],QA2,QB1,KA1,KB)
Psis4_1[n] = TotCol(10,0.5,1.686,Pols[n],QA2,QB2,KA1,KB)
Psis1_2[n] = TotCol(10,0.5,1.686,Pols[n],QA1,QB1,KA2,KB)
Psis2_2[n] = TotCol(10,0.5,1.686,Pols[n],QA1,QB2,KA2,KB)
Psis3_2[n] = TotCol(10,0.5,1.686,Pols[n],QA2,QB1,KA2,KB)
Psis4_2[n] = TotCol(10,0.5,1.686,Pols[n],QA2,QB2,KA2,KB)
Psis1_3[n] = TotCol(10,0.5,1.686,Pols[n],QA1,QB1,KA3,KB)
Psis2_3[n] = TotCol(10,0.5,1.686,Pols[n],QA1,QB2,KA3,KB)
Psis3_3[n] = TotCol(10,0.5,1.686,Pols[n],QA2,QB1,KA3,KB)
Psis4_3[n] = TotCol(10,0.5,1.686,Pols[n],QA2,QB2,KA3,KB)
}
## Visualization
YY = 100*c(min(Psis1_1,Psis2_1,Psis3_1,Psis4_1,Psis1_2,Psis2_2,Psis3_2,Psis4_2,Psis1_3,Psis2_3,Psis3_3,Psis4_3),max(Psis1_1,Psis2_1,Psis3_1,Psis4_1,Psis1_2,Psis2_2,Psis3_2,Psis4_2,Psis1_3,Psis2_3,Psis3_3,Psis4_3))
plot(cbind(Pols,100*Psis1_1),type='l',ylim=YY,xlab='Proportion of market demand for term assurances',ylab=' ',cex.lab=2)
lines(cbind(Pols,100*Psis2_1),col='red')
lines(cbind(Pols,100*Psis3_1),col='magenta')
lines(cbind(Pols,100*Psis4_1),col='blue')
abline(h=0,lty=2)
points(cbind(Pols[seq(1,250,length(Pols)/6)],100*Psis1_1[seq(1,250,length(Pols)/6)]))
points(cbind(Pols[seq(15,250,length(Pols)/6)],100*Psis2_1[seq(15,250,length(Pols)/6)]),col='red',pch=2)
points(cbind(Pols[seq(30,250,length(Pols)/6)],100*Psis3_1[seq(30,250,length(Pols)/6)]),col='magenta',pch=4)
points(cbind(Pols[seq(45,250,length(Pols)/6)],100*Psis4_1[seq(45,250,length(Pols)/6)]),col='blue',pch=7)
legend('topleft',legend=c(expression('$q_A=0.5$ and $q_B=0.5$'),
expression('$q_A=0.5$ and $q_B=3$'),
expression('$q_A=3$ and $q_B=0.5$'),
expression('$q_A=3$ and $q_B=3$')),
,col=c('black','red','magenta','blue'),lty=c(1,1,1,1),pch=c(1,2,4,7),cex=1.5)
| 721f1d7a4e8ebe3a1d1e7c416dcb29e98440a2f2 | [
"R"
] | 1 | R | HamzaHanbali/JointPricingAnnuitiesAssurances | c56a5aaa3c2241963abeba34b5144e8323c25770 | 4833c3c78e03db6768ce6ae499f6b955a28b8f41 |
refs/heads/master | <file_sep>// Make sure to run this program from inside the "data" directory that contains
// dictionary.txt
#define MAX_WORDS 2048
#define START_WORD "муха"
#define END_WORD "слон"
#define WORD_LEN 4
#define WORD_BYTES WORD_LEN*2+1 // UTF8 2-byte characters
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#define ArrayCount(Array) (sizeof(Array) / sizeof((Array)[0]))
int
StringLengthUTF8(char *String)
{
int Result = 0;
while(*String)
{
if(*String >= 0 && *String <= 127)
{
String += 1;
}
else if((*String & 0xE0) == 0xC0)
{
String += 2;
}
else if((*String & 0xF0) == 0xE0)
{
String += 3;
}
else if((*String & 0xF8) == 0xF0)
{
String += 4;
}
++Result;
}
return(Result);
}
void
RemoveNewline(char *String)
{
while(*String)
{
if(*String == '\n')
{
*String = '\0';
break;
}
++String;
}
}
bool
DifferByOneLetter(char *Word1, char *Word2)
{
int DifferenceCount = 0;
while(*Word1 && *Word2)
{
// UTF8 2-byte characters
if((*Word1 != *Word2) || (*(Word1+1) != *(Word2+1)))
{
++DifferenceCount;
}
Word1 += 2;
Word2 += 2;
}
bool Result = DifferenceCount == 1;
return(Result);
}
struct word_node
{
int WordIndex;
word_node *Next;
};
int
main()
{
char Words[MAX_WORDS][WORD_BYTES];
int WordCount = 0;
word_node *AdjacencyLists[MAX_WORDS];
int EdgeTo[MAX_WORDS];
bool Marked[MAX_WORDS];
word_node *BFSQueueHead = 0;
word_node *BFSQueueTail = 0;
int StartWordIndex = -1;
int EndWordIndex = -1;
char Word[128];
FILE *DictionaryFile = fopen("dictionary.txt", "r");
if(!DictionaryFile)
{
printf("Cannot open dictionary.txt\n");
return(1);
}
while(fgets(Word, ArrayCount(Word), DictionaryFile))
{
RemoveNewline(Word);
if(StringLengthUTF8(Word) == WORD_LEN)
{
strcpy(Words[WordCount++], Word);
}
}
fclose(DictionaryFile);
for(int WordIndex = 0;
WordIndex < WordCount;
++WordIndex)
{
for(int WordIndex2 = 0;
WordIndex2 < WordCount;
++WordIndex2)
{
if (WordIndex != WordIndex2)
{
if(DifferByOneLetter(Words[WordIndex], Words[WordIndex2]))
{
word_node *Node = (word_node *)malloc(sizeof(word_node));
Node->WordIndex = WordIndex2;
if(AdjacencyLists[WordIndex])
{
Node->Next = AdjacencyLists[WordIndex];
AdjacencyLists[WordIndex] = Node;
}
else
{
Node->Next = 0;
AdjacencyLists[WordIndex] = Node;
}
}
}
}
}
for(int WordIndex = 0;
WordIndex < WordCount;
++WordIndex)
{
if(strcmp(Words[WordIndex], START_WORD) == 0)
{
StartWordIndex = WordIndex;
break;
}
}
if(StartWordIndex < 0)
{
printf("Couldn't find start word.\n");
return(1);
}
for(int WordIndex = 0;
WordIndex < WordCount;
++WordIndex)
{
if(strcmp(Words[WordIndex], END_WORD) == 0)
{
EndWordIndex = WordIndex;
break;
}
}
if(EndWordIndex < 0)
{
printf("Couldn't find end word.\n");
return(1);
}
Marked[StartWordIndex] = true;
BFSQueueHead = (word_node *)malloc(sizeof(word_node));
BFSQueueHead->WordIndex = StartWordIndex;
BFSQueueHead->Next = 0;
while(BFSQueueHead)
{
int WordIndex = BFSQueueHead->WordIndex;
word_node *HeadNext = BFSQueueHead->Next;
free(BFSQueueHead);
BFSQueueHead = HeadNext;
for(word_node *AdjacentNode = AdjacencyLists[WordIndex];
AdjacentNode;
AdjacentNode = AdjacentNode->Next)
{
if(!Marked[AdjacentNode->WordIndex])
{
Marked[AdjacentNode->WordIndex] = true;
EdgeTo[AdjacentNode->WordIndex] = WordIndex;
word_node *QueueNode = (word_node *)malloc(sizeof(word_node));
QueueNode->WordIndex = AdjacentNode->WordIndex;
QueueNode->Next = 0;
if (!BFSQueueHead)
{
BFSQueueHead = BFSQueueTail = QueueNode;
}
else
{
BFSQueueTail->Next = QueueNode;
BFSQueueTail = QueueNode;
}
}
}
}
if(Marked[EndWordIndex])
{
for(int WordIndex = EndWordIndex;
;
WordIndex = EdgeTo[WordIndex])
{
printf("%s\n", Words[WordIndex]);
if(WordIndex == StartWordIndex)
{
break;
}
}
}
else
{
printf("Can't convert start word to the end word.\n");
}
return(0);
}
<file_sep><?php
define('START_WORD', 'муха');
define('END_WORD', 'слон');
define('WORD_LEN', 4);
define('WORD_LEN_IN_BYTES', WORD_LEN*2); // UTF-8 2-byte characters
function main()
{
mb_internal_encoding("UTF-8");
//
// Put all 4-letter words from dictionary into array.
//
$words = array();
$dictionaryFile = fopen(dirname(__FILE__) . '/../data/dictionary.txt', 'r');
if (!$dictionaryFile) {
print "Couldn't open dictionary file!\n";
return;
}
while (($word = fgets($dictionaryFile)) !== false) {
$word = trim($word);
if (mb_strlen($word) == WORD_LEN) {
$words[] = $word;
}
}
fclose($dictionaryFile);
$startWordIndex = array_search(START_WORD, $words);
if (!$startWordIndex) {
print "Couldn't find start word in the dictionary!\n";
return;
}
$endWordIndex = array_search(END_WORD, $words);
if (!$endWordIndex) {
print "Couldn't find end word in the dictionary!\n";
return;
}
$wordsCount = count($words);
//
// Generate a graph of words, adding edges between words that differ by
// one letter.
//
$adjacencyLists = array();
$marked = array();
$edgeTo = array();
for ($wordIndex1 = 0; $wordIndex1 < $wordsCount; ++$wordIndex1) {
for ($wordIndex2 = 0; $wordIndex2 < $wordsCount; ++$wordIndex2) {
if ($wordIndex1 == $wordIndex2) {
continue;
}
$differentLettersCount = 0;
// Using mb_strlen is costly here, so we compare raw bytes,
// assuming 2-byte cyrillic characters.
// This version is ~3 times faster than mb_strlen version (17s -> 6s).
for ($letterIdx = 0; $letterIdx < WORD_LEN_IN_BYTES; $letterIdx += 2) {
if (($words[$wordIndex1][$letterIdx] != $words[$wordIndex2][$letterIdx]) ||
($words[$wordIndex1][$letterIdx+1] != $words[$wordIndex2][$letterIdx+1])) {
++$differentLettersCount;
if ($differentLettersCount > 1) {
break;
}
}
}
if ($differentLettersCount == 1) {
$adjacencyLists[$wordIndex1][] = $wordIndex2;
}
}
}
//
// Use breadth-first search to find the shortest path from the start word
// to the end word.
//
$bfsQueue = array();
$marked[$startWordIndex] = true;
array_push($bfsQueue, $startWordIndex);
while ($bfsQueue) {
$wordIndex = array_shift($bfsQueue);
foreach ($adjacencyLists[$wordIndex] as $adjacentIndex) {
if (isset($marked[$adjacentIndex])) {
continue;
}
$marked[$adjacentIndex] = true;
$edgeTo[$adjacentIndex] = $wordIndex;
array_push($bfsQueue, $adjacentIndex);
}
}
//
// Output the path if it exists.
//
if (!isset($marked[$endWordIndex])) {
print "Can't convert start word to the end word.\n";
return;
}
$path = array();
$wordIndex = $endWordIndex;
while (true) {
$path[] = $words[$wordIndex];
if ($wordIndex == $startWordIndex) {
break;
}
$wordIndex = $edgeTo[$wordIndex];
}
while ($path) {
printf("%s\n", array_pop($path));
}
}
main();
<file_sep>Small program that converts one word to another by changing one letter at a time
(has C++ and PHP versions).
Right now it works only for cyrillic UTF-8 words.
---
Небольшая программа, преобразующая "муху" в "слона", изменяя по одной букве за
раз. В двух вариантах: на C++ и PHP.
В данный момент программа работает только для кириллицы в формате UTF-8.
| 0b6dc0cf02c8ba06034c9d9291f140a7b174f183 | [
"Markdown",
"C++",
"PHP"
] | 3 | C++ | newagebegins/muha_slon | ddaf3022bea287b3cae0554d630f891c82aacfef | bc28adf088845bdc64fc59e2d970ebb56a6a66c3 |
refs/heads/master | <file_sep>#include <iostream>
#include "Microsoft_grabber.h"
#include <pcl/visualization/cloud_viewer.h>
#include <opencv2/opencv.hpp>
#include "Classifier.h"
#include "Edges.h"
#include "OpticalFlow.h"
#include "GraphSegmentation.h"
#include <Shlwapi.h>
#include <string.h>
#define NUM_LABELS 894
inline void EstimateNormals(const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud, pcl::PointCloud<pcl::PointNormal>::Ptr &normals);
void BuildRFClassifier(std::string direc);
void BuildNYUDataset(std::string direc, bool matlab = false);
void BuildNYUDatasetForCaffe(std::string direc, bool window);
void TestRFClassifier(std::string direc);<file_sep>cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
SET_PROPERTY(GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS TRUE)
IF(WIN32 OR win64)
SET(CMAKE_FIND_LIBRARY_SUFFIXES .lib .dll)
ELSE()
SET(CMAKE_FIND_LIBRARY_SUFFIXES .a)
ENDIF()
find_package(PCL 1.7 REQUIRED)
find_package( OpenCV REQUIRED )
FIND_PACKAGE(CUDA REQUIRED)
SET(CUDA_NVCC_FLAGS "-arch=sm_20" CACHE STRING "nvcc flags" FORCE)
#SET (CUDA_VERBOSE_BUILD ON CACHE BOOL "nvcc verbose" FORCE)
project(3DSceneClassification)
add_subdirectory(src)
include_directories(C:/opencv/build)
include_directories(${PCL_INCLUDE_DIRS})
include_directories(C:/blepo/external64/Microsoft/Kinect)
include_directories(${3DSceneClassification_SOURCE_DIR}/include)
include_directories(../PCL_WindowsKinectSDK/include)
link_directories(${PCL_LIBRARY_DIRS})
link_directories(C:/blepo/external64/Microsoft/Kinect)
link_directories(../../PCL_WindowsKinectSDK/build/)
add_definitions(${PCL_DEFINITIONS})
file(GLOB_RECURSE 3DSceneClassification_HEADERS include/*.h)
file(GLOB_RECURSE 3DSceneClassification_SOURCES src/*.cpp)
set (3DSceneClassification_INCLUDE_DIRS "")
foreach (_headerFile ${3DSceneClassification_HEADERS})
get_filename_component(_dir ${_headerFile} PATH)
list (APPEND 3DSceneClassification_INCLUDE_DIRS ${_dir})
endforeach()
list(REMOVE_DUPLICATES 3DSceneClassification_INCLUDE_DIRS)
include_directories(${3DSceneClassification_INCLUDE_DIRS})
CUDA_ADD_LIBRARY(BuildGraph STATIC include/BuildGraph.h src/BuildGraph.cu)
add_executable (3DSceneClassification ${3DSceneClassification_SOURCES} ${3DSceneClassification_HEADERS})
target_link_libraries (3DSceneClassification BuildGraph Shlwapi ${CUDA_CUDA_LIBRARY} ${CUDA_CUDART_LIBRARY} ${PCL_LIBRARIES} ${OpenCV_LIBS} Kinect10.lib debug Debug/PCL_WindowsKinectSDK optimized Release/PCL_WindowsKinectSDK)<file_sep>#include "Classifier.h"
using namespace std;
using namespace pcl;
using namespace cv;
Mat imread_depth(const char* fname, bool binary) {
char* ext = PathFindExtension(fname);
const char char_dep[] = ".dep";
const char char_png[] = ".png";
Mat out;
if(_strnicmp(ext,char_dep,strlen(char_dep))==0) {
FILE *fp;
if(binary)
fp = fopen(fname,"rb");
else
fp = fopen(fname,"r");
int width = 640, height = 480; //If messed up, just assume
if(binary) {
fread(&width,sizeof(int),1,fp);
fread(&height,sizeof(int),1,fp);
out = Mat(height,width,CV_32S);
int *p = (int*)out.data;
fread(p,sizeof(int),width*height,fp);
} else {
//fscanf(fp,"%i,%i,",&width,&height);
out = Mat(height,width,CV_32S);
int *p = (int*)out.data, *end = ((int*)out.data) + out.rows*out.cols;
while(p != end) {
fscanf(fp,"%i",p);
p++;
}
}
fclose(fp);
} else if(_strnicmp(ext,char_png,strlen(char_png))==0) {
out = cvLoadImage(fname,CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR);
out.convertTo(out, CV_32S);
int* pi = (int*)out.data;
for (int y=0; y < out.rows; y++) {
for (int x=0; x < out.cols; x++) {
*pi = Round(*pi * 0.2f);
pi++;
}
}
} else {
throw exception("Filetype not supported");
}
return out;
}
Mat imread_float(const char* fname, bool binary) {
char* ext = PathFindExtension(fname);
const char char_dep[] = ".flt";
Mat out;
if(_strnicmp(ext,char_dep,strlen(char_dep))==0) {
FILE *fp;
if(binary)
fp = fopen(fname,"rb");
else
fp = fopen(fname,"r");
int width = 640, height = 480; //If messed up, just assume
if(binary) {
fread(&width,sizeof(int),1,fp);
fread(&height,sizeof(int),1,fp);
out = Mat(height,width,CV_32F);
float *p = (float*)out.data;
fread(p,sizeof(float),width*height,fp);
} else {
//fscanf(fp,"%i,%i,",&width,&height);
out = Mat(height,width,CV_32F);
float *p = (float*)out.data, *end = ((float*)out.data) + out.rows*out.cols;
while(p != end) {
fscanf(fp,"%f",p);
p++;
}
}
fclose(fp);
} else {
throw exception("Filetype not supported");
}
return out;
}
void imwrite_depth(const char* fname, Mat &img, bool binary) {
char* ext = PathFindExtension(fname);
const char char_dep[] = ".dep";
Mat out;
if(_strnicmp(ext,char_dep,strlen(char_dep))==0) {
FILE *fp;
if(binary)
fp = fopen(fname,"wb");
else
fp = fopen(fname,"w");
int width = img.cols, height = img.rows; //If messed up, just assume
if(binary) {
fwrite(&width,sizeof(int),1,fp);
fwrite(&height,sizeof(int),1,fp);
int *p = (int*)img.data;
fwrite(p,sizeof(int),width*height,fp);
} else {
//fscanf(fp,"%i,%i,",&width,&height);
int *p = (int*)img.data, *end = ((int*)img.data) + width*height;
while(p != end) {
fscanf(fp,"%f",p);
p++;
}
}
fclose(fp);
} else {
throw exception("Filetype not supported");
}
}
void imwrite_float(const char* fname, Mat &img, bool binary) {
char* ext = PathFindExtension(fname);
const char char_dep[] = ".flt";
Mat out;
if(_strnicmp(ext,char_dep,strlen(char_dep))==0) {
FILE *fp;
if(binary)
fp = fopen(fname,"wb");
else
fp = fopen(fname,"w");
int width = img.cols, height = img.rows; //If messed up, just assume
if(binary) {
fwrite(&width,sizeof(int),1,fp);
fwrite(&height,sizeof(int),1,fp);
float *p = (float*)img.data;
fwrite(p,sizeof(float),width*height,fp);
} else {
//fscanf(fp,"%i,%i,",&width,&height);
float *p = (float*)img.data, *end = ((float*)img.data) + width*height;
while(p != end) {
fscanf(fp,"%f",p);
p++;
}
}
fclose(fp);
} else {
throw exception("Filetype not supported");
}
}
void Classifier::CalculateSIFTFeatures(Mat &img, Mat &mask, Mat &descriptors) {
Mat gImg, desc;
cvtColor(img, gImg, CV_BGR2GRAY);
vector<KeyPoint> kp;
featureDetector->detect(gImg,kp,mask);
descriptorExtractor->compute(gImg,kp,desc);
//keypoints.push_back(kp);
descriptors.push_back(desc);
}
void Classifier::CalculateBOWFeatures(Mat &img, Mat &mask, Mat &descriptors) {
Mat gImg, desc;
cvtColor(img, gImg, CV_BGR2GRAY);
vector<KeyPoint> kp;
featureDetector->detect(gImg,kp,mask);
bowDescriptorExtractor->compute(gImg,kp,desc);
//keypoints.push_back(kp);
descriptors.push_back(desc);
}
void Classifier::build_vocab() {
cout << "Building vocabulary" << endl;
// Mat to hold SURF descriptors for all templates
// For each template, extract SURF descriptors and pool them into vocab_descriptors
cout << "Building SURF Descriptors..." << endl;
Mat img, descriptors;
LoadTrainingInd();
for(int i = 1; i < 1450; i++) {
if(i == trainingInds.front()) {
trainingInds.pop_front();
stringstream num;
num << i;
img = imread(string(direc + "rgb\\" + num.str() + ".bmp"));
CalculateSIFTFeatures(img,Mat(),descriptors);
}
}
// Add the descriptors to the BOW trainer to cluster
cout << "Training BOW..." << endl;
bowtrainer->add(descriptors);
// cluster the SURF descriptors
cout << "Clustering..." << endl;
vocab = bowtrainer->cluster();
//vocab.convertTo(vocab,CV_8UC1);
cout << "Done." << endl;
// Save the vocabulary
FileStorage fs("vocab.xml", FileStorage::WRITE);
fs << "vocabulary" << vocab;
fs.release();
cout << "Built vocabulary" << endl;
}
void Classifier::load_vocab() {
//load the vocabulary
FileStorage fs("vocab.xml", FileStorage::READ);
fs["vocabulary"] >> vocab;
fs.release();
// Set the vocabulary for the BOW descriptor extractor
bowDescriptorExtractor->setVocabulary(vocab);
}
void Classifier::LoadTestingInd() {
FILE *fp = fopen("testing_ind.txt","rb");
if(fp == NULL)
throw exception("Couldn't open testing file");
int length, i;
fread(&length,sizeof(int),1,fp);
testingInds.resize(length);
for(i = 0; i < length; i++) {
int tmp;
fread(&tmp,sizeof(int),1,fp);
testingInds[i] = tmp;
}
fclose(fp);
}
void Classifier::LoadTrainingInd() {
FILE *fp = fopen("training_ind.txt","rb");
if(fp == NULL)
throw exception("Couldn't open training file");
int length, i;
fread(&length,sizeof(int),1,fp);
trainingInds.resize(length);
for(i = 0; i < length; i++) {
int tmp;
fread(&tmp,sizeof(int),1,fp);
trainingInds[i] = tmp;
}
fclose(fp);
}
void Classifier::LoadClassMap(string classfile) {
int length, i;
FILE *fp = fopen(classfile.c_str(),"rb");
if(fp == NULL)
throw exception("Couldn't open class mapping file");
fread(&length,sizeof(int),1,fp);
length++;
classMap.resize(length);
for(i = 1; i < length; i++) {
int tmp;
fread(&tmp,sizeof(int),1,fp);
classMap[i] = tmp;
}
fclose(fp);
}
void LoadData(string direc, int i, Mat &img, Mat &depth, Mat &label) {
stringstream num;
num << i;
//I should crop everything some number of pixels
int crop = 7;
img = imread(string(direc + "rgb\\" + num.str() + ".bmp"));
Rect roi = Rect(crop,crop,img.cols - 2*crop, img.rows - 2*crop);
img = img(roi);
depth = imread_depth(string(direc + "depth\\" + num.str() + ".dep").c_str(),true);
depth = depth(roi);
label = imread_depth(string(direc + "labels\\" + num.str() + ".dep").c_str(),true);
label = label(roi);
}<file_sep>#include "OpticalFlow.h"
using namespace cv;
using namespace cv::gpu;
using namespace pcl;
using namespace std;
void ComputeOpticalFlow(const Mat &past, const Mat ¤t, const PointCloud<PointXYZRGBA>::ConstPtr &pastCloud, const PointCloud<PointXYZRGBA>::ConstPtr &currCloud, PointCloud<Normal>::Ptr &flow) {
Mat in1, in2, flow2d;
cvtColor(past,in1,CV_BGR2GRAY);
cvtColor(current,in2,CV_BGR2GRAY);
calcOpticalFlowFarneback(in1,in2,flow2d,0.5f,2,5,2,7,1.5,0);
flow->height = flow2d.rows;
flow->width = flow2d.cols;
flow->is_dense = false;
flow->resize(flow->height * flow->width);
flow->sensor_origin_.setZero();
PointCloud<Normal>::iterator pOut = flow->begin();
PointCloud<PointXYZRGBA>::const_iterator pCloud = currCloud->begin();
Mat_<Vec2f>::iterator pIn = flow2d.begin<Vec2f>();
int safeWidth = pastCloud->width - 1, safeHeight = pastCloud->height - 1;
float bad_point = std::numeric_limits<float>::quiet_NaN ();
for(int j = 0; j < pastCloud->height; j++) {
for(int i = 0; i < pastCloud->width ; i++) {
if(pCloud->z == 0 || pCloud->z == bad_point) {
pOut->normal_x = pOut->normal_y = pOut->normal_z = bad_point;
} else {
/*pOut->x = pCloud->x;
pOut->y = pCloud->y;
pOut->z = pCloud->z;*/
pOut->normal_x = (*pIn)[0] * pCloud->z * KINECT_FX_D;
pOut->normal_y = (*pIn)[1] * pCloud->z * KINECT_FY_D;
pOut->normal_z = (pCloud->z - (*pastCloud)(Clamp(int(i - (*pIn)[0]),0,safeWidth), Clamp(int(j - (*pIn)[1]),0,safeHeight)).z);
}
++pIn; ++pOut; ++pCloud;
}
}
}
void ComputeOpticalFlowGPU(const Mat &past, const Mat ¤t, const PointCloud<PointXYZRGBA>::ConstPtr &pastCloud, const PointCloud<PointXYZRGBA>::ConstPtr &currCloud, PointCloud<Normal>::Ptr &flow) {
try {
Mat in1, in2;
cvtColor(past,in1,CV_BGR2GRAY);
cvtColor(current,in2,CV_BGR2GRAY);
GpuMat d_frameL(in1), d_frameR(in2);
GpuMat d_flowx, d_flowy;
cv::gpu::FarnebackOpticalFlow calc_flow;
Mat flowx, flowy;
calc_flow(d_frameL, d_frameR, d_flowx, d_flowy);
d_flowx.download(flowx);
d_flowy.download(flowy);
//calcOpticalFlowFarneback(in1,in2,flow2d,0.5f,2,5,2,7,1.5,0);
flow->height = flowx.rows;
flow->width = flowx.cols;
flow->is_dense = false;
flow->resize(flow->height * flow->width);
flow->sensor_origin_.setZero();
PointCloud<Normal>::iterator pOut = flow->begin();
PointCloud<PointXYZRGBA>::const_iterator pCloud = currCloud->begin();
Mat_<float>::iterator pInX = flowx.begin<float>();
Mat_<float>::iterator pInY = flowy.begin<float>();
int safeWidth = pastCloud->width - 1, safeHeight = pastCloud->height - 1;
float bad_point = std::numeric_limits<float>::quiet_NaN ();
for(int j = 0; j < pastCloud->height; j++) {
for(int i = 0; i < pastCloud->width ; i++) {
if(pCloud->z == 0 || pCloud->z == bad_point) {
pOut->normal_x = pOut->normal_y = pOut->normal_z = bad_point;
} else {
/*pOut->x = pCloud->x;
pOut->y = pCloud->y;
pOut->z = pCloud->z;*/
pOut->normal_x = *pInX * pCloud->z * KINECT_FX_D;
pOut->normal_y = *pInY * pCloud->z * KINECT_FY_D;
pOut->normal_z = (pCloud->z - (*pastCloud)(Clamp(int(i - *pInX),0,safeWidth), Clamp(int(j - *pInY),0,safeHeight)).z);
}
++pInX; ++pInY; ++pOut; ++pCloud;
}
}
} catch(cv::Exception &e) {
cout << e.what() << endl;
} catch(std::exception &e) {
cout << e.what() << endl;
} catch(...) {
}
}
void Downsample2x2(const Mat &in, Mat &out) { resize(in,out,Size(),0.5f,0.5f); }<file_sep>#include "TestVideoSegmentation.h"
#include "RegionTree.h"
using namespace std;
using namespace pcl;
using namespace cv;
const float parameters[] = { 2.5f,500.0f,500,0.8f,400.0f,400,100,0.25f };
const string mapFile = "class4map.txt";
const int EXTRA_BORDER = 13;
void CreatePointCloudFromRegisteredNYUData(const Mat &img, const Mat &depth, PointCloudBgr *cloud) {
//assert(!img.IsNull() && !depth.IsNull());
//take care of old cloud to prevent memory leak/corruption
if (cloud != NULL && cloud->size() > 0) {
cloud->clear();
}
cloud->header.frame_id = "/microsoft_rgb_optical_frame";
cloud->height = img.rows;
cloud->width = img.cols;
cloud->is_dense = true;
cloud->points.resize (cloud->height * cloud->width);
PointCloud<PointXYZRGBA>::iterator pCloud = cloud->begin();
Mat_<int>::const_iterator pDepth = depth.begin<int>();
Mat_<Vec3b>::const_iterator pImg = img.begin<Vec3b>();
for(int j = 0; j < img.rows; j++) {
for(int i = 0; i < img.cols; i++) {
pCloud->z = *pDepth / 1000.0f;
pCloud->x = float((i - 3.1304475870804731e+02) * pCloud->z / 5.8262448167737955e+02);
pCloud->y = float((j - 2.3844389626620386e+02) * pCloud->z / 5.8269103270988637e+02);
pCloud->b = (*pImg)[0];
pCloud->g = (*pImg)[1];
pCloud->r = (*pImg)[2];
pCloud->a = 255;
pImg++; pDepth++; pCloud++;
}
}
cloud->sensor_origin_.setZero ();
cloud->sensor_orientation_.w () = 1.0;
cloud->sensor_orientation_.x () = 0.0;
cloud->sensor_orientation_.y () = 0.0;
cloud->sensor_orientation_.z () = 0.0;
}
void CreateLabeledCloudFromNYUPointCloud(const PointCloudBgr &cloud, const Mat &label, PointCloudInt *labelCloud) {
if (labelCloud != NULL && labelCloud->size() > 0) {
labelCloud->clear();
}
labelCloud->header.frame_id = cloud.header.frame_id;
labelCloud->height = cloud.height;
labelCloud->width = cloud.width;
labelCloud->is_dense = true;
labelCloud->points.resize (labelCloud->height * labelCloud->width);
PointCloud<PointXYZRGBA>::const_iterator pCloud = cloud.begin();
PointCloud<PointXYZI>::iterator pLabelCloud = labelCloud->begin();
Mat_<int>::const_iterator pLabel = label.begin<int>();
while(pCloud != cloud.end()) {
pLabelCloud->x = pCloud->x;
pLabelCloud->y = pCloud->y;
pLabelCloud->z = pCloud->z;
pLabelCloud->intensity = *pLabel;
++pLabel; ++pCloud; ++pLabelCloud;
}
labelCloud->sensor_origin_.setZero ();
labelCloud->sensor_orientation_.w () = 1.0;
labelCloud->sensor_orientation_.x () = 0.0;
labelCloud->sensor_orientation_.y () = 0.0;
labelCloud->sensor_orientation_.z () = 0.0;
}
inline void EstimateNormals(const PointCloud<PointXYZRGBA>::ConstPtr &cloud, PointCloud<PointNormal>::Ptr &normals, bool fill) {
pcl::IntegralImageNormalEstimation<pcl::PointXYZRGBA, pcl::PointNormal> ne;
ne.setNormalEstimationMethod (ne.COVARIANCE_MATRIX);
ne.setMaxDepthChangeFactor(0.02f);
ne.setNormalSmoothingSize(10.0f);
ne.setInputCloud(cloud);
ne.compute(*normals);
if(fill) {
PointCloudNormal::iterator p = normals->begin();
while(p != normals->end()) {
if(_isnan(p->normal_x))
p->normal_x = 0;
if(_isnan(p->normal_y))
p->normal_y = 0;
if(_isnan(p->normal_z))
p->normal_z = 0;
++p;
}
}
}
inline int GetClass(const PointCloudInt &cloud, const Mat &labels, int id) {
int i, ret = 0;
int *lookup = new int[NUM_LABELS];
for(i = 0; i < NUM_LABELS; i++)
lookup[i] = 0;
PointCloudInt::const_iterator p = cloud.begin();
Mat_<int>::const_iterator pL = labels.begin<int>();
while(p != cloud.end()) {
if(p->intensity == id)
lookup[*pL]++;
++p; ++pL;
}
int max = lookup[0], maxLoc = 0;
for(i = 0; i < NUM_LABELS; i++) {
if(lookup[i] > max) {
max = lookup[i];
maxLoc = i;
}
}
try {
delete[] lookup;
} catch(...) {
cout << "small error here" << endl;
}
return maxLoc;
}
inline float HistTotal(LABXYZUVW *hist) {
float tot = 0.0f;
for(int k = 0; k < NUM_BINS; k++) {
tot += hist[k].u;
}
return tot;
}
inline void CalcMask(const PointCloudInt &cloud, int id, Mat &mask) {
PointCloudInt::const_iterator pC = cloud.begin();
uchar *pM = mask.data;
while(pC != cloud.end()) {
if(pC->intensity == id)
*pM = 255;
++pM; ++pC;
}
}
void GetFeatureVectors(Mat &trainData, Classifier &cl, const RegionTree3D &tree, Mat &img, const PointCloudInt &cloud, const Mat &label, const int numImage) {
//for each top level region, I need to give it a class name.
int k;
const int size1 = 14 + 6*NUM_BINS + 3*NUM_BINS_XYZ, size2 = (size1 + NUM_CLUSTERS + 3);
Mat gImg, desc;
cvtColor(img, gImg, CV_BGR2GRAY);
vector<KeyPoint> kp;
cl.featureDetector->detect(gImg,kp);
vector<KeyPoint> regionPoints;
regionPoints.reserve(kp.size());
vector<Region3D*>::const_iterator p = tree.top_regions.begin();
//Mat element = getStructuringElement(MORPH_RECT, Size( 2*2 + 1, 2*2+1 ), Point( 2, 2 ) );
for(int i = 0; i < tree.top_regions.size(); i++, p++) {
////Calculate mask
//Mat desc, mask = Mat::zeros(img.size(),CV_8UC1);
//CalcMask(cloud,(*p)->m_centroid3D.intensity,mask);
//dilate(mask,mask,element);
////get features
//cl.CalculateBOWFeatures(img,mask,desc);
Mat desc;
regionPoints.clear();
vector<KeyPoint>::iterator pK = kp.begin();
while(pK != kp.end()) {
PointXYZI p3D = cloud(pK->pt.x,pK->pt.y);
if(p3D.x >= (*p)->m_min3D.x && p3D.x <= (*p)->m_max3D.x && p3D.y >= (*p)->m_min3D.y && p3D.y <= (*p)->m_max3D.y && p3D.z >= (*p)->m_min3D.z && p3D.z <= (*p)->m_max3D.z)
regionPoints.push_back(*pK);
++pK;
}
cl.bowDescriptorExtractor->compute(gImg,regionPoints,desc);
if(desc.empty())
desc = Mat::zeros(1,NUM_CLUSTERS,CV_32F);
int id = GetClass(cloud,label,(*p)->m_centroid3D.intensity);
if(id != 0) {
Mat vec = Mat(1,size2,CV_32F);
float *pV = (float*)vec.data;
*pV++ = float((*p)->m_size);
*pV++ = (*p)->m_centroid.x;
*pV++ = (*p)->m_centroid.y;
*pV++ = (*p)->m_centroid3D.x;
*pV++ = (*p)->m_centroid3D.y;
*pV++ = (*p)->m_centroid3D.z;
float a = ((*p)->m_max3D.x - (*p)->m_min3D.x), b = ((*p)->m_max3D.y - (*p)->m_min3D.y), c = ((*p)->m_max3D.z - (*p)->m_min3D.z);
*pV++ = (*p)->m_min3D.x;
*pV++ = (*p)->m_min3D.y;
*pV++ = (*p)->m_min3D.z;
*pV++ = (*p)->m_max3D.x;
*pV++ = (*p)->m_max3D.y;
*pV++ = (*p)->m_max3D.z;
*pV++ = sqrt(a*a + c*c);
*pV++ = b;
//LABXYZUVW *p1 = (*p)->m_hist;
//float tot = HistTotal((*p)->m_hist);
for(k = 0; k < NUM_BINS; k++)
*pV++ = float((*p)->m_hist[k].a)/(*p)->m_size;
for(k = 0; k < NUM_BINS; k++)
*pV++ = float((*p)->m_hist[k].b)/(*p)->m_size;
for(k = 0; k < NUM_BINS; k++)
*pV++ = float((*p)->m_hist[k].l)/(*p)->m_size;
for(k = 0; k < NUM_BINS; k++)
*pV++ = (*p)->m_hist[k].u/(*p)->m_size;
for(k = 0; k < NUM_BINS; k++)
*pV++ = (*p)->m_hist[k].v/(*p)->m_size;
for(k = 0; k < NUM_BINS; k++)
*pV++ = (*p)->m_hist[k].w/(*p)->m_size;
for(k = 0; k < NUM_BINS_XYZ; k++)
*pV++ = (*p)->m_hist[k].x/(*p)->m_size;
for(k = 0; k < NUM_BINS_XYZ; k++)
*pV++ = (*p)->m_hist[k].y/(*p)->m_size;
for(k = 0; k < NUM_BINS_XYZ; k++)
*pV++ = (*p)->m_hist[k].z/(*p)->m_size;
float *pD = (float*)desc.data;
for(k = 0; k < desc.cols; k++, pD++)
*pV++ = *pD;
*pV++ = float((*p)->m_centroid3D.intensity);
*pV++ = float(numImage);
*pV++ = float(id);
trainData.push_back(vec);
}
}
}
void GetMatFromRegion(Region3D *reg, Classifier &cl, const PointCloudInt &cloud, vector<KeyPoint> &kp, Mat &img, vector<float> &sample, int sample_size) {
int k;
sample.resize(sample_size);
//Calculate mask
//Mat desc, mask = Mat::zeros(img.size(),CV_8UC1);
//CalcMask(cloud,reg->m_centroid3D.intensity,mask);
////get features
//cl.CalculateBOWFeatures(img,mask,desc);
Mat desc;
vector<KeyPoint> regionPoints;
regionPoints.reserve(kp.size());
vector<KeyPoint>::iterator pK = kp.begin();
while(pK != kp.end()) {
PointXYZI p3D = cloud(pK->pt.x,pK->pt.y);
if(p3D.x >= reg->m_min3D.x && p3D.x <= reg->m_max3D.x && p3D.y >= reg->m_min3D.y && p3D.y <= reg->m_max3D.y && p3D.z >= reg->m_min3D.z && p3D.z <= reg->m_max3D.z)
regionPoints.push_back(*pK);
++pK;
}
cl.bowDescriptorExtractor->compute(img,regionPoints,desc);
if(desc.empty())
desc = Mat::zeros(1,NUM_CLUSTERS,CV_32F);
vector<float>::iterator p = sample.begin();
*p++ = float(reg->m_size);
*p++ = reg->m_centroid.x;
*p++ = reg->m_centroid.y;
*p++ = reg->m_centroid3D.x;
*p++ = reg->m_centroid3D.y;
*p++ = reg->m_centroid3D.z;
float a = (reg->m_max3D.x - reg->m_min3D.x), b = (reg->m_max3D.y - reg->m_min3D.y), c = (reg->m_max3D.z - reg->m_min3D.z);
*p++ = reg->m_min3D.x;
*p++ = reg->m_min3D.y;
*p++ = reg->m_min3D.z;
*p++ = reg->m_max3D.x;
*p++ = reg->m_max3D.y;
*p++ = reg->m_max3D.z;
*p++ = sqrt(a*a+c*c);
*p++ = b;
for(k = 0; k < NUM_BINS; k++)
*p++ = reg->m_hist[k].a / reg->m_size;
for(k = 0; k < NUM_BINS; k++)
*p++ = reg->m_hist[k].b / reg->m_size;
for(k = 0; k < NUM_BINS; k++)
*p++ = reg->m_hist[k].l / reg->m_size;
for(k = 0; k < NUM_BINS; k++)
*p++ = reg->m_hist[k].u / reg->m_size;
for(k = 0; k < NUM_BINS; k++)
*p++ = reg->m_hist[k].v / reg->m_size;
for(k = 0; k < NUM_BINS; k++)
*p++ = reg->m_hist[k].w / reg->m_size;
for(k = 0; k < NUM_BINS_XYZ; k++)
*p++ = reg->m_hist[k].x / reg->m_size;
for(k = 0; k < NUM_BINS_XYZ; k++)
*p++ = reg->m_hist[k].y / reg->m_size;
for(k = 0; k < NUM_BINS_XYZ; k++)
*p++ = reg->m_hist[k].z / reg->m_size;
float *pD = (float*)desc.data;
for(k = 0; k < desc.cols; k++, pD++)
*p++ = *pD;
}
inline void GetMatFromCloud(const PointCloudBgr &cloud, Mat &img) {
img = Mat(cloud.height,cloud.width,CV_8UC3);
Mat_<Vec3b>::iterator pI = img.begin<Vec3b>();
PointCloudBgr::const_iterator pC = cloud.begin();
while(pC != cloud.end()) {
(*pI)[0] = pC->b;
(*pI)[1] = pC->g;
(*pI)[2] = pC->r;
++pI; ++pC;
}
}
inline void GetMatFromCloud(const PointCloudInt &cloud, Mat &img) {
img = Mat(cloud.height,cloud.width,CV_32S);
Mat_<int>::iterator pI = img.begin<int>();
PointCloudInt::const_iterator pC = cloud.begin();
while(pC != cloud.end()) {
*pI = pC->intensity;
++pI; ++pC;
}
}
inline void GetMatFromCloud(const PointCloudNormal &cloud, Mat &img) {
img = Mat(cloud.height,cloud.width,CV_8UC3);
Mat_<Vec3b>::iterator pI = img.begin<Vec3b>();
PointCloudNormal::const_iterator pC = cloud.begin();
while(pC != cloud.end()) {
//scale from -1 to 1
int red = Round((pC->normal_x + 1) * 127.5f);
int green = Round((pC->normal_y + 1) * 127.5f);
int blue = Round((pC->normal_z + 1) * 127.5f);
*pI = Vec3b(red,green,blue);
++pI; ++pC;
}
}
void PseudoColor(const PointCloudInt &in, Mat &out) {
int min, max;
MinMax(in, &min, &max);
int size = max - min;
Vec3b *colors = (Vec3b *) malloc(size*sizeof(Vec3b));
Vec3b *pColor = colors;
for (int i = min; i < max; i++)
{
Vec3b color;
random_rgb(color);
*pColor++ = color;
}
out = Mat::zeros(in.height,in.width,CV_8UC3);
PointCloudInt::const_iterator pIn = in.begin();
Mat_<Vec3b>::iterator pOut = out.begin<Vec3b>();
while(pIn != in.end()) {
*pOut = colors[int(pIn->intensity) - min];
pIn++;
pOut++;
}
free(colors);
}
void BuildNYUDataset(string direc, bool matlab) {
srand(time(NULL));
PointCloudBgr cloud,segment;
PointCloudInt labelCloud;
Mat img, depth, label, trainData;
boost::shared_ptr<pcl::PointCloud<pcl::PointNormal> > normals(new pcl::PointCloud<pcl::PointNormal>);
Classifier c(direc);
c.LoadTrainingInd();
c.load_vocab();
//open training file
/*FILE *fp = fopen("features.txt","wb");
if(fp == NULL)
throw exception("Couldn't open features file");
fprintf(fp,"size,cx,cy,c3x,c3y,c3z,minx,miny,minz,maxx,maxy,maxz,xdist,ydist");
for(int j = 0; j < 9; j++) {
for(int k = 0; k < (j < 6 ? NUM_BINS : NUM_BINS_XYZ); k++) {
fprintf(fp,",h%d_%d",j,k);
}
}
fprintf(fp,",frame,class\n");*/
int count = 0;
string folder;
for(int i = 1; i < 1450; i++) {
if(matlab || i == c.trainingInds.front()) {
cout << i << endl;
LoadData(direc,i,img,depth,label);
CreatePointCloudFromRegisteredNYUData(img,depth,&cloud);
//CreateLabeledCloudFromNYUPointCloud(cloud,label,&labelCloud);
int segments = SHGraphSegment(cloud,parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],parameters[5],&labelCloud,&segment);
EstimateNormals(cloud.makeShared(),normals,true);
RegionTree3D tree;
tree.Create(cloud,labelCloud,*normals,segments,0);
tree.PropagateRegionHierarchy(parameters[6]);
tree.ImplementSegmentation(parameters[7]);
GetFeatureVectors(trainData,c,tree,img,labelCloud,label,i);
if(i == c.trainingInds.front()) {
c.trainingInds.pop_front();
stringstream num;
num << "training/" << count << ".flt";
imwrite_float(num.str().c_str(),trainData);
count++;
}
stringstream num2;
num2 << "training_all/" << i << ".flt";
imwrite_float(num2.str().c_str(),trainData);
stringstream num3;
num3 << "segments/" << i << ".dep";
Mat segmentMat, segmentMatColor;
GetMatFromCloud(labelCloud,segmentMat);
//PseudoColor(labelCloud,segmentMatColor);
//imshow("window",segmentMatColor);
//waitKey();
imwrite_depth(num3.str().c_str(),segmentMat);
//release stuff
segment.clear();
cloud.clear();
labelCloud.clear();
img.release();
depth.release();
label.release();
trainData.release();
normals->clear();
tree.top_regions.clear();
tree.Release();
}
}
FileStorage tot("count.yml", FileStorage::WRITE);
tot << "count" << count;
//fclose(fp);
tot.release();
}
void BuildRFClassifier(string direc) {
Classifier c(direc);
c.LoadClassMap(mapFile);
FileStorage fs("count.yml", FileStorage::READ);
int i,count;
fs["count"] >> count;
fs.release();
Mat data, train, labels;
for(i = 0; i < count; i++) {
Mat tmp;
stringstream num;
num << "training/" << i << ".flt";
tmp = imread_float(num.str().c_str());
data.push_back(tmp);
}
train = data.colRange(0,data.cols-3);
labels = data.col(data.cols-1);
labels.convertTo(labels,CV_32S);
int* pL = (int*)labels.data, *pEnd = pL + labels.rows;
while(pL != pEnd) {
*pL = c.classMap[*pL];
++pL;
}
// define all the attributes as numerical
// alternatives are CV_VAR_CATEGORICAL or CV_VAR_ORDERED(=CV_VAR_NUMERICAL)
// that can be assigned on a per attribute basis
Mat var_type = Mat(train.cols + 1, 1, CV_8U );
var_type.setTo(Scalar(CV_VAR_NUMERICAL) ); // all inputs are numerical
// this is a classification problem (i.e. predict a discrete number of class
// outputs) so reset the last (+1) output var_type element to CV_VAR_CATEGORICAL
var_type.at<uchar>(train.cols, 0) = CV_VAR_CATEGORICAL;
//float priors[] = {1,1};
CvRTParams params = CvRTParams(25, // max depth
5, // min sample count
0, // regression accuracy: N/A here
false, // compute surrogate split, no missing data
15, // max number of categories (use sub-optimal algorithm for larger numbers)
nullptr, // the array of priors
false, // calculate variable importance
50, // number of variables randomly selected at node and used to find the best split(s).
500, // max number of trees in the forest
0.01f, // forrest accuracy
CV_TERMCRIT_ITER | CV_TERMCRIT_EPS // termination cirteria
);
// train random forest classifier (using training data)
CvRTrees* rtree = new CvRTrees;
rtree->train(train, CV_ROW_SAMPLE, labels,
Mat(), Mat(), var_type, Mat(), params);
rtree->save("rf.xml");
delete rtree;
}
void TestRFClassifier(string direc) {
PointCloudBgr cloud,segment;
PointCloudInt labelCloud;
Mat img, depth, label;
boost::shared_ptr<pcl::PointCloud<pcl::PointNormal> > normals(new pcl::PointCloud<pcl::PointNormal>);
//open training file
Classifier c(direc);
c.LoadTestingInd();
c.LoadClassMap(mapFile);
c.load_vocab();
CvRTrees* rtree = new CvRTrees;
rtree->load("rf.xml");
Mat conf = Mat::zeros(5,5,CV_32S);
Mat confClass = Mat::zeros(5,5,CV_32S);
for(int i = 1; i < 1450; i++) {
if(i == c.testingInds.front()) {
c.testingInds.pop_front();
cout << i << endl;
LoadData(direc,i,img,depth,label);
CreatePointCloudFromRegisteredNYUData(img,depth,&cloud);
//CreateLabeledCloudFromNYUPointCloud(cloud,label,&labelCloud);
int segments = SHGraphSegment(cloud,parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],parameters[5],&labelCloud,&segment);
EstimateNormals(cloud.makeShared(),normals,false);
RegionTree3D tree;
tree.Create(cloud,labelCloud,*normals,segments,0);
tree.PropagateRegionHierarchy(parameters[6]);
tree.ImplementSegmentation(parameters[7]);
/*viewer.removePointCloud("cloud");
viewer.removePointCloud("original");
viewer.addPointCloud(segment.makeShared(),"original");
viewer.addPointCloudNormals<pcl::PointXYZRGBA,pcl::PointNormal>(segment.makeShared(), normals);
while(1)
viewer.spinOnce();*/
int result, feature_len = 14 + 6*NUM_BINS + 3*NUM_BINS_XYZ + NUM_CLUSTERS;
Mat gImg;
cvtColor(img, gImg, CV_BGR2GRAY);
vector<KeyPoint> kp;
c.featureDetector->detect(gImg,kp);
//Mat element = getStructuringElement(MORPH_RECT, Size( 2*2 + 1, 2*2+1 ), Point( 2, 2 ) );
vector<Region3D*>::const_iterator p = tree.top_regions.begin();
for(int i = 0; i < tree.top_regions.size(); i++, p++) {
vector<float> sample;
GetMatFromRegion(*p,c,labelCloud,kp,gImg,sample,feature_len);
Mat sampleMat = Mat(sample);
result = Round(rtree->predict(sampleMat));
int id = GetClass(labelCloud,label,(*p)->m_centroid3D.intensity);
if(id > 0 && result > 0)
confClass.at<int>(c.classMap[id],result)++;
tree.SetBranch(*p,0,result);
}
Mat myResult, groundTruth, myResultColor, groundTruthColor, labelColor, segmentMat;
myResult = Mat(label.rows,label.cols,label.type());
groundTruth = Mat(label.rows,label.cols,label.type());
PointCloudInt::iterator pC = labelCloud.begin();
int *pNewL = (int*)groundTruth.data;
int *pNewC = (int*)myResult.data;
int *pL = (int *)label.data;
while(pC != labelCloud.end()) {
int newLabel = c.classMap[*pL];
*pNewL = newLabel;
*pNewC = pC->intensity;
/*if(newLabel < 0 || newLabel > 4)
cout << "label is: " << newLabel << endl;
if(pC->intensity < 0 || pC->intensity > 4)
cout << "result is: " << pC->intensity << endl;
else*/
if(pC->intensity > 0 && newLabel > 0)
conf.at<int>(newLabel,pC->intensity)++;
++pL; ++pC; ++pNewL; ++pNewC;
}
/*GetMatFromCloud(segment,segmentMat);
groundTruth.convertTo(groundTruth,CV_8UC1,63,0);
myResult.convertTo(myResult,CV_8UC1,63,0);
label.convertTo(labelColor,CV_8UC1,894,0);
applyColorMap(groundTruth,groundTruthColor,COLORMAP_JET);
applyColorMap(myResult,myResultColor,COLORMAP_JET);
imshow("color",img);
imshow("original label",labelColor);
imshow("label",groundTruthColor);
imshow("result",myResultColor);
imshow("segment",segmentMat);
waitKey();*/
//release stuff
segmentMat.release();
myResult.release();
groundTruth.release();
myResultColor.release();
groundTruthColor.release();
segment.clear();
cloud.clear();
labelCloud.clear();
img.release();
depth.release();
label.release();
normals->clear();
tree.top_regions.clear();
tree.Release();
}
}
float tot = 0, result = 0;
int x,y;
for(x=0; x<5; x++) {
for(y=0; y<5; y++) {
cout << conf.at<int>(x,y) << ", ";
tot += conf.at<int>(x,y);
if(x == y)
result += conf.at<int>(x,y);
}
cout << endl;
}
cout << "Accuracy: " << (result / tot) << endl;
cout << endl;
tot = 0; result = 0;
for(x=0; x<5; x++) {
for(y=0; y<5; y++) {
cout << confClass.at<int>(x,y) << ", ";
tot += confClass.at<int>(x,y);
if(x == y)
result += confClass.at<int>(x,y);
}
cout << endl;
}
cout << "Class Accuracy: " << (result / tot) << endl;
delete rtree;
}
void GenerateSegmentMask(const PointCloudInt &labelCloud, int id, Mat &mask) {
//Here we are going to generate the mask of the segment
mask = Mat::zeros(Size(labelCloud.width,labelCloud.height), CV_8UC1);
PointCloudInt::const_iterator p = labelCloud.begin();
Mat_<uchar>::iterator pO = mask.begin<uchar>();
while(p != labelCloud.end()) {
if(p->intensity == id)
*pO = 255;
++p; ++pO;
}
//Here we are going to grow the mask
int dilation_size = 5;
Mat element = getStructuringElement( MORPH_RECT,
Size( 2*dilation_size + 1, 2*dilation_size+1 ),
Point( dilation_size, dilation_size ) );
dilate(mask,mask,element);
}
void GenerateSegmentRegion(const PointCloudInt &labelCloud, int id, Rect &roi) {
//lets get the min and max x and y
int minX = labelCloud.width - 1, minY = labelCloud.height - 1, maxX = 0, maxY = 0;
PointCloudInt::const_iterator p = labelCloud.begin();
for(int j = 0; j < labelCloud.height; j++) {
for(int i = 0; i < labelCloud.width; i++) {
if(p->intensity == id) {
if(i > maxX)
maxX = i;
if(i < minX)
minX = i;
if(j > maxY)
maxY = j;
if(j < minY)
minY = j;
}
++p;
}
}
minX -= EXTRA_BORDER;
minY -= EXTRA_BORDER;
maxX += EXTRA_BORDER;
maxY += EXTRA_BORDER;
if(minX < 0)
minX = 0;
roi.x = Clamp<int>(minX,0,labelCloud.width - 1);
roi.y = Clamp<int>(minY,0,labelCloud.height - 1);
roi.width = Clamp<int>(maxX,0,labelCloud.width - 1) - roi.x;
roi.height = Clamp<int>(maxY,0,labelCloud.height - 1) - roi.y;
}
//Let's template this
template<typename T>
void GenerateImageFromMask(const Mat &in, const Mat &mask, Mat &segment) {
segment = Mat::zeros(in.size(), in.type());
Mat_<uchar>::const_iterator p = mask.begin<uchar>();
Mat_<T>::const_iterator pC = in.begin<T>();
Mat_<T>::iterator pO = segment.begin<T>();
while(p != mask.end<uchar>()) {
if(*p == 255)
*pO = *pC;
++p; ++pC; ++pO;
}
}
template<typename T>
void GenerateImageFromRegion(const Mat &in, const Rect &roi, Mat &segment) {
//segment = Mat::zeros(Size(roi.width, roi.height) , in.type());
segment = in(roi).clone();
}
void GenerateLabelMask(const PointCloudInt &labelCloud, map<int,int> &idLookup, Mat &out) {
//Here we are going to generate the mask of the segment
out = Mat::zeros(Size(labelCloud.width,labelCloud.height), CV_32S);
PointCloudInt::const_iterator p = labelCloud.begin();
Mat_<int>::iterator pO = out.begin<int>();
while(p != labelCloud.end()) {
*pO = idLookup[p->intensity];
++p; ++pO;
}
}
void BuildNYUDatasetForCaffe(string direc, bool window) {
srand(time(NULL));
PointCloudBgr cloud,segment;
PointCloudInt labelCloud;
Mat img, depth, label, trainData;
boost::shared_ptr<pcl::PointCloud<pcl::PointNormal> > normals(new pcl::PointCloud<pcl::PointNormal>);
Classifier c(direc);
c.load_vocab();
c.LoadTrainingInd();
c.LoadClassMap(mapFile);
//Open the training and testing files
FILE *fpTraining = fopen("training.txt","w");
if(fpTraining == NULL)
throw exception("Couldn't open training file");
FILE *fpTesting = fopen("testing.txt","w");
if(fpTesting == NULL)
throw exception("Couldn't open Testing file");
int count = 0, training_count = 0;
string folder;
for(int i = 1; i < 1450; i++) {
cout << i << endl;
LoadData(direc,i,img,depth,label);
CreatePointCloudFromRegisteredNYUData(img,depth,&cloud);
//CreateLabeledCloudFromNYUPointCloud(cloud,label,&labelCloud);
int segments = SHGraphSegment(cloud,parameters[0],parameters[1],parameters[2],parameters[3],parameters[4],parameters[5],&labelCloud,&segment);
EstimateNormals(cloud.makeShared(),normals,true);
RegionTree3D tree;
tree.Create(cloud,labelCloud,*normals,segments,0);
tree.PropagateRegionHierarchy(parameters[6]);
tree.ImplementSegmentation(parameters[7]);
Mat segmentMat, segmentMatColor;
GetMatFromCloud(labelCloud,segmentMat);
PseudoColor(labelCloud,segmentMatColor);
Mat normalsMat;
GetMatFromCloud(*normals,normalsMat);
//let's figure out if we are testing or training
bool training = false;
GetFeatureVectors(trainData,c,tree,img,labelCloud,label,i);
if(i == c.trainingInds.front()) {
c.trainingInds.pop_front();
training = true;
stringstream num;
num << "training/" << training_count << ".flt";
imwrite_float(num.str().c_str(),trainData);
training_count++;
}
stringstream num2;
num2 << "training_all/" << i << ".flt";
imwrite_float(num2.str().c_str(),trainData);
stringstream num3;
num3 << "segment_labels/" << i << ".dep";
imwrite_depth(num3.str().c_str(),segmentMat);
//Make a lookup for the old segment ids to new segment names
std::map<int,int> idLookup;
vector<Region3D*>::const_iterator p = tree.top_regions.begin();
for(int i = 0; i < tree.top_regions.size(); i++, p++) {
//Set up map
idLookup[(*p)->m_centroid3D.intensity] = count;
//Get id for label
int id = GetClass(labelCloud,label,(*p)->m_centroid3D.intensity);
int mappedId = c.classMap[id];
//Create segment image for training and save
Mat mask, segment;
Rect roi;
if(window)
GenerateSegmentRegion(labelCloud, (*p)->m_centroid3D.intensity, roi);
else
GenerateSegmentMask(labelCloud, (*p)->m_centroid3D.intensity, mask);
//Get and save segmented image
if(window)
GenerateImageFromRegion<Vec3b>(img,roi,segment);
else
GenerateImageFromMask<Vec3b>(img,mask,segment);
stringstream imgFileName;
imgFileName << "segments/" << count << ".png";
imwrite(imgFileName.str(),segment);
//Get and save segmented depth
if(window)
GenerateImageFromRegion<int>(depth,roi,segment);
else
GenerateImageFromMask<int>(depth,mask,segment);
stringstream depthFileName;
depthFileName << "segments_depth/" << count << ".png";
Mat segmentOut;
segment.convertTo(segmentOut,CV_16UC1);
imwrite(depthFileName.str(),segmentOut);
//Get and save segmented normals
if(window)
GenerateImageFromRegion<Vec3b>(normalsMat,roi,segment);
else
GenerateImageFromMask<Vec3b>(normalsMat,mask,segment);
stringstream normalsFileName;
normalsFileName << "segments_normals/" << count << ".png";
imwrite(normalsFileName.str(),segment);
//Write filename and class to training file
if(training) {
//I'm training
fprintf(fpTraining,"%s, %d\n",imgFileName.str().c_str(), mappedId);
} else {
//I'm testing
fprintf(fpTesting,"%s, %d\n",imgFileName.str().c_str(), mappedId);
}
++count;
}
//Now let's use the map to generate a superpixel label image
Mat spLabels;
GenerateLabelMask(labelCloud,idLookup,spLabels);
stringstream labelsFileName;
labelsFileName << "labels/" << i << ".dep";
imwrite_depth(labelsFileName.str().c_str(),spLabels);
//release stuff
spLabels.release();
segmentMat.release();
segment.clear();
cloud.clear();
labelCloud.clear();
img.release();
depth.release();
label.release();
normals->clear();
tree.top_regions.clear();
tree.Release();
}
fclose(fpTraining);
fclose(fpTesting);
}<file_sep># 3DSceneClassification
Code for WACV2015 Paper:
Semantic Labeling Leveraging Hierarchical Segmentation
Unsupported code combined with Matlab use.
Use at your own risk. The authors will not develop or help with this code.
<file_sep>/*
Copyright (C) 2014 <NAME>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef BUILDGRAPH_H
#define BUILDGRAPH_H
#include <cuda_runtime.h>
#include <npp.h>
#include "opencv2/gpu/devmem2d.hpp"
#include "opencv2/gpu/device/common.hpp"
#include <cuda_runtime_api.h>
#include <cufft.h>
#include <cublas.h>
#include "opencv2/gpu/gpu.hpp"
#include "Edges.h"
#include <thrust/version.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sort.h>
void igpuBuildGraph(cv::Mat &R, cv::Mat &G, cv::Mat &B, cv::Mat &D, Edge3D *edges, int numEdges);
void thrustsort(Edge3D *pEdge, Edge3D *edgesEnd);
void thrustsort2(Edge3D *pEdge, Edge3D *edgesEnd);
#endif<file_sep>/*
Copyright (C) 2014 <NAME>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef CLASSIFIER_H
#define CLASSIFIER_H
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/ml/ml.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/time.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/visualization/cloud_viewer.h>
#include "OpticalFlow.h"
#include "GraphSegmentation.h"
#include <Shlwapi.h>
#include <string.h>
#define NUM_CLUSTERS 1000
cv::Mat imread_depth(const char* fname, bool binary=true);
cv::Mat imread_float(const char* fname, bool binary=true);
void imwrite_float(const char* fname, cv::Mat &img, bool binary=true);
void imwrite_depth(const char* fname, cv::Mat &img, bool binary=true);
void CreatePointCloudFromRegisteredNYUData(const cv::Mat &img, const cv::Mat &depth, PointCloudBgr *cloud);
void LoadData(std::string direc, int i, cv::Mat &img, cv::Mat &depth, cv::Mat &label);
class Classifier {
public:
int categories; //number of categories
int clusters; //number of clusters for SURF features to build vocabulary
std::string direc; //directory of NYU data
cv::Mat vocab; //vocabulary
cv::Ptr<cv::FeatureDetector> featureDetector;
cv::Ptr<cv::DescriptorExtractor> descriptorExtractor;
cv::Ptr<cv::BOWKMeansTrainer> bowtrainer;
cv::Ptr<cv::BOWImgDescriptorExtractor> bowDescriptorExtractor;
cv::Ptr<cv::DescriptorMatcher> descriptorMatcher;
std::deque<int> testingInds, trainingInds;
std::vector<int> classMap;
Classifier(std::string direc_) {
direc = direc_;
clusters = NUM_CLUSTERS;
categories = 4;
featureDetector = (new cv::SurfFeatureDetector());
descriptorExtractor = (new cv::SurfDescriptorExtractor());
bowtrainer = (new cv::BOWKMeansTrainer(clusters));
descriptorMatcher = (new cv::FlannBasedMatcher());
//descriptorMatcher = (new BFMatcher());
bowDescriptorExtractor = (new cv::BOWImgDescriptorExtractor(descriptorExtractor, descriptorMatcher));
};
void build_vocab(); //function to build the BOW vocabulary
void load_vocab(); //function to load the BOW vocabulary and classifiers
void CalculateSIFTFeatures(cv::Mat &img, cv::Mat &mask, cv::Mat &descriptors);
void CalculateBOWFeatures(cv::Mat &img, cv::Mat &mask, cv::Mat &descriptors);
void LoadTestingInd();
void LoadTrainingInd();
void LoadClassMap(std::string classfile);
};
#endif | 1955943eff918c2d4a97239b7f3a5a46f00017b8 | [
"Markdown",
"C",
"CMake",
"C++"
] | 8 | C++ | StevenHickson/3DSceneClassification | 62c2c3cd750ac320ebdc8d26791e61b595e19968 | 605f7db3d7050086f5d50c3910890c4a0fc3235a |
refs/heads/master | <repo_name>rwjblue/rfc232-demo-app<file_sep>/tests/integration/components/pretty-color-test.js
import { module, test } from 'qunit';
import { setupRenderingTest, render } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
module('component:pretty-color', function(hooks) {
setupRenderingTest(hooks);
test('it renders', async function(assert) {
await render(hbs`{{pretty-color}}`);
assert.equal(this.element.textContent, '#FF69B4');
});
});
<file_sep>/README.md
# rfc232-demo-app
This app serves as a small test bed for using [emberjs/rfcs#232](https://github.com/emberjs/rfcs/blob/master/text/0232-simplify-qunit-testing-api.md) in ember-cli apps.
Following these steps allows us to use the new API:
```
ember new test-app
cd test-app
npm i --save-dev ember-cli-qunit@^4.1.0-beta.2
```
Boom, now you can write pretty tests like this:
```js
import { module, test } from 'qunit';
import { setupRenderingTest, render } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
module('component:pretty-color', function(hooks) {
setupRenderingTest(hooks);
test('it renders', async function(assert) {
await render(hbs`{{pretty-color}}`);
assert.equal(this.element.textContent, '#FF69B4');
});
});
```
<file_sep>/app/helpers/sad-color.js
import { helper } from '@ember/component/helper';
export function sadColor() {
return '#fff';
}
export default helper(sadColor);
| c4f72c8131d5d2d2a1c79ce48f8e9c6611eb48c0 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | rwjblue/rfc232-demo-app | fcf6d68a4c399e56c2db7eaef9166890263cba5d | a8ee85fbf55500da36c7ff660c2b351b07cd827f |
refs/heads/master | <repo_name>xdibda/Labyrint<file_sep>/log.cpp
/**
* Autori: <NAME>, xporiz03
* Modul: log
* Popis modulu: Tento modul implementuje ukladani a nacitani her.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "log.h"
using namespace std;
/**
* @brief Funkce zvysi pocet tahu
*/
void Logger::incTurnNumber()
{
iTurnNumber++;
}
/**
* @brief Funkce snizi pocet tahu
*/
void Logger::decTurnNumber()
{
iTurnNumber--;
}
/**
* @brief Funkce vrati pocet tahu
*/
int Logger::getTurnNumber()
{
return iTurnNumber;
}
/**
* @brief Funkce nastavi pocet tahu
*/
void Logger::setTurnNumber(int turn)
{
iTurnNumber = turn;
}
/**
* @brief Funkce ulozi hru
* @param Hraci plocha kterou ma ulozit
*/
void Logger::saveGame(Map saveMap)
{
vector<Player*> tempPlayers;
PlayerList* tempPlayerList;
vector<Card*> tempCards;
vector<MapField*>tempFields;
ofstream myfile;
string filename;
string turn;
#ifdef _WIN32
filename = "..\\examples\\labyrint_fit8.txt";
#else
filename = "../examples/labyrint_fit8.txt";
#endif
myfile.open(filename);
cout << "\n" << filename << "\n";
myfile << ":TURN\n";
myfile << iTurnNumber << ":\n";
myfile << ":MAP\n";//SIZE:LASTX:LASTY:SHIFTEDSTATE:NUMBEROFCARDS
myfile << saveMap.getSize();
myfile << ":" << saveMap.getLastX() << ":" << saveMap.getLastY() << ":" << saveMap.getShiftedState() << ":" << saveMap.getCardsSet() <<"\n";
myfile << ":FIELDS\n";//ID:SIZE:TREASURE:XPOS:YPOS:ROTATION:SHAPE
//for each field
tempFields = saveMap.getFields();
for (unsigned int i = 0; i < tempFields.size(); i++)
{
myfile << tempFields[i]->getSize() << ":" << tempFields[i]->getTreasure() << ":" << tempFields[i]->getXPos() << ":" << tempFields[i]->getYPos() << ":" << tempFields[i]->getRotation() << ":" << tempFields[i]->getShape() << "\n";
}
myfile << ":PLAYERLIST\n"; //NUMBER:PTURN
tempPlayerList = saveMap.getPlayers();
tempPlayers = tempPlayerList->getPList();
myfile << tempPlayerList->getNumber() << ":" << tempPlayerList->getPlayersTurn() << "\n";
myfile << ":PLAYERS\n";//SCORE:X:Y:COLOR
for (unsigned int i = 0; i < tempPlayers.size(); i++)
{
myfile << ":P:";
myfile << tempPlayers[i]->getScore() << ":" << tempPlayers[i]->getXPos() << ":" << tempPlayers[i]->getYPos() << ":" << tempPlayers[i]->getColor();
//CARDS
//SIZE:
//TREASURE
tempCards = tempPlayers[i]->getpCards();
myfile << ":" << tempCards.size();
for (unsigned int j = 0; j < tempCards.size(); j++)
{
myfile << ":" << tempCards[j]->getTreasure();
}
}
//UNDO STACK
myfile << "\n";
myfile << ":LOG\n";
for (unsigned int i = 0; i < moves.size(); i++)
{
myfile << moves[i] << "\n";
}
}
/**
* @brief Funkce nacte ulozenou hru
* @param Mapa do ktere ma hru nacist
*/
void Logger::loadGame(Map* sMap)
{
stringstream ss;
string filename;
string turn;
ss.clear();
#ifdef _WIN32
filename = "..\\examples\\labyrint_fit8.txt";
#else
filename = "../examples/labyrint_fit8.txt";
#endif
ifstream myfile;
myfile.open(filename);
string line;
string sTemp = "";
MapField* tempField;
vector<Card*> tempCards;
Card* tempCard;
int iTemp = 0;
while (getline(myfile, line))
{
if (line.find(":TURN") != string::npos)
{
getline(myfile, line);
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
setTurnNumber(iTemp);
}
if (line.find(":MAP") != string::npos)
{
getline(myfile, line);
//SIZE
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
sMap->setSize(iTemp);
//LASTX
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
sMap->setLastX(iTemp);
//LASTY
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
sMap->setLastY(iTemp);
//WASSHIFTED
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
if (iTemp == 0)
sMap->changeShiftedState(0);
else
sMap->changeShiftedState(1);
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
sMap->setCardsSet(iTemp);
continue;
}
if (line.find(":FIELDS") != string::npos)
{
getline(myfile, line);
sMap->clearMap();
for (int i = 0; i <= (sMap->getSize() * sMap->getSize()); i++)
{
tempField = new MapField;
int x, y;
//SIZE
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
tempField->setSize(iTemp);
//TREASURE
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
tempField->setTreasure(iTemp);
//XPOS, YPOS
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
x = stoi(sTemp);
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
y = stoi(sTemp);
tempField->setPosition(x, y);
//ROTATION
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
tempField->setRotation(iTemp);
//SHAPE
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
switch (*sTemp.c_str())
{
case 'I':
tempField->setShape(1);
break;
case 'L':
tempField->setShape(2);
break;
case 'T':
tempField->setShape(3);
break;
}
sMap->addField(tempField);
getline(myfile, line);
}
}
if (line.find(":PLAYERLIST") != string::npos)
{
getline(myfile, line);
//PLAYERS NUMBER
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
sMap->setPlayers(iTemp);
//PLAYERS TURN
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
sMap->setTurn(iTemp);
continue;
}
if (line.find(":PLAYERS") != string::npos)
{
getline(myfile, line);
line = line.substr(line.find(":") + 1, string::npos);
(sMap->getPlayers())->clearPlayers();
for (int i = 0; i < (sMap->getPlayers())->getNumber(); i++)
{
int x, y;
int iCards;
int iScore;
int iColor;
//tempPlayer = new Player;
line = line.substr(line.find(":") + 1, string::npos);
//SCORE
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iScore = stoi(sTemp);
//tempPlayer->SetScore(iTemp);
//POSITION X, Y
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
x = stoi(sTemp);
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
y = stoi(sTemp);
//tempPlayer->setPos(x, y);
//COLOR
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iColor = stoi(sTemp);
//tempPlayer->setColor(iTemp);
//NUMBER OF CARDS
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iCards = stoi(sTemp);
for (int j = 0; j < iCards; j++)
{
sTemp = line.substr(0, line.find(":"));
line = line.substr(line.find(":") + 1, string::npos);
iTemp = stoi(sTemp);
tempCard = new Card(iTemp);
tempCards.push_back(tempCard);
}
//tempPlayer->appendCards(tempCards);
reverse(tempCards.begin(), tempCards.end());
(sMap->getPlayers())->CreatePlayer(iColor, x, y, &tempCards, sMap->getCardsSet(), iScore);
tempCards.clear();
}
}
if (line.find(":LOG") != string::npos)
{
clearMoves();
//getline(myfile, line);
while (getline(myfile, line))
{
moves.push_back(line.substr(0, line.find("\n")));
}
}
}
}
/**
* @brief Funkce ulozi jeden tah do stacku tahu
* @param Tah ktery se ma do stacku ulozit
*/
void Logger::saveTurn(string turn)
{
moves.push_back(turn);
}
/**
* @brief Funkce vycisti stack tahu
*/
void Logger::clearMoves()
{
for (unsigned int i = 0; i < moves.size(); i++)
{
moves.pop_back();
}
moves.clear();
}
/**
* @brief Funkce vrati jeden tah
*/
string Logger::getTurn()
{
string temp;
temp = moves.back();
moves.pop_back();
return temp;
}<file_sep>/players.cpp
/**
Autori: <NAME>, xdibda00 + <NAME>, xporiz03
Modul: Players
Popis modulu: Tento modul implementuje praci s hracem a
seznamem hracu, kterym obsahuje vsechny hrace ve hre.
*/
#include "players.h"
/**
* @brief vytvori hrace a prida ho do seznamu hracu.
* @param barva figurky hrace.
* @param vodorovna souradnice pozice hrace.
* @param svisla souradnice pozice hrace.
* @param karty hrace.
* @param pocet karet ve hre.
* @param skore hrace.
*/
void PlayerList::CreatePlayer(int col, int x, int y, vector<Card *> *tempCards, int numberOfCards, int score) {
vector<Card *> playerCards;
for (int i = 0; i < ((numberOfCards / number) - score); i++) {
playerCards.push_back((*tempCards).back());
(*tempCards).pop_back();
}
pList.push_back(new Player(col, x, y, playerCards, score));
}
/**
* @brief vrati vektor vsech hracu ve hre.
* @return vektor hracu.
*/
vector<Player *> PlayerList::getPList() {
return pList;
}
/**
* @brief odstrani vsechny hrace ve hre.
*/
void PlayerList::clearPlayers() {
for (int i = 0; i < NumberOfPlayers(); i++) {
delete pList[i];
}
pList.clear();
}
/**
* @brief vrati pocet hracu ve hre.
* @return pocet hracu.
*/
int PlayerList::NumberOfPlayers() {
return pList.size();
}
/**
* @brief nastavi tah hrace.
* @param ktery hrac ma hrat.
*/
void PlayerList::SetTurn(int pTurn)
{
iPlayersTurn = pTurn;
}
/**
* @brief nastavi tah na dalsiho hrace.
*/
void PlayerList::NextTurn()
{
iPlayersTurn += 1;
if (iPlayersTurn >= number)
{
iPlayersTurn = 0;
}
}
/**
* @brief konstruktor pro seznam hracu.
*/
PlayerList::PlayerList() {
iPlayersTurn = 0;
}
/**
* @brief nastavi pocet hracu ve hre.
* @param pocet hracu.
*/
void PlayerList::setNumber(int num) {
number = num;
}
/**
* @brief vrati pocet hracu ve hre.
* @return pocet hracu.
*/
int PlayerList::getNumber() {
return number;
}
/**
* @brief konstruktor pro hrace.
*/
Player::Player() {
iScore = 0;
x = 0;
y = 0;
playerColor = 0;
}
/**
* @brief sekundarni konstruktor pro hrace.
* @param barva figurky.
* @param vodorovna pozice hrace.
* @param svisla pozice hrace.
*/
Player::Player(int color, int xpos, int ypos) {
iScore = 0;
x = xpos;
y = ypos;
playerColor = color;
}
/**
* @brief ternalni konstruktor pro hrace.
* @param barva figurky hrace.
* @param vodorovna pozice hrace.
* @param svisla pozice hrace.
* @param vektor balicku karet hrace.
* @param skore hrace.
*/
Player::Player(int color, int xpos, int ypos, vector<Card *> playerCards, int score) {
iScore = score;
x = xpos;
y = ypos;
playerColor = color;
pCards = playerCards;
}
/**
* @brief nastavi skore hrace.
* @param skore hrace.
*/
void Player::SetScore(int score) {
iScore = score;
}
/**
* @brief prida skore k hraci.
* @param skore hrace.
*/
void Player::AddScore(int score) {
iScore += score;
}
/**
* @brief vrati vodorovnou pozici hrace na mape.
* @return vodorovna pozice.
*/
int Player::getXPos() {
return x;
}
/**
* @brief vrati svislou pozici hrace na mape.
* @return svisla pozice.
*/
int Player::getYPos() {
return y;
}
/**
* @brief nastavi pozici hrace na mape.
* @param vodorovna pozice.
* @param svisla pozice.
*/
void Player::setPos(int newX, int newY)
{
x = newX;
y = newY;
}
/**
* @brief prida hraci jeho vlastni balicek karet, ktere ma hledat.
* @param vektor karet.
*/
void Player::appendCards(vector<Card *> cardList)
{
pCards = cardList;
}
/**
* @brief prepne na dalsi hracovu kartu
*/
void Player::getAnotherCard()
{
if (pCards.size() > 0)
pCards.pop_back();
}
/**
* @brief vrati hracovu aktivni kartu.
* @return hracova karta.
*/
Card* Player::getPlayersCard() {
return pCards[pCards.size() - 1];
}
/**
* @brief prida hracovi kartu.
* @param karta.
*/
void Player::giveCard(Card* card)
{
pCards.push_back(card);
}
/**
* @brief vrati hrace na urcite pozici na mape.
* @param vodorovna pozice policka na mape.
* @param svisla pozice policka na mape.
* @return vektor hracu, kteri se nachazeji na danem policku.
*/
vector<Player *> PlayerList::GetPlayers(int x, int y)
{
vector<Player *>temp;
for (int i = 0; i < number; i++)
{
if (pList[i]->getXPos() == x && pList[i]->getYPos() == y)
{
temp.push_back(pList[i]);
}
}
return temp;
}
/**
* @brief vrati hrace, ktery je prave na tahu.
* @return hrac.
*/
Player* PlayerList::GetActivePlayer()
{
return pList[iPlayersTurn];
}
/**
* @brief vrati barvu figurky hrace.
* @return barva figurky.
*/
int Player::getColor() {
return playerColor;
}
/**
* @brief vrati aktualni skore hrace.
* @return skore.
*/
int Player::getScore()
{
return iScore;
}
/**
* @brief vrati tah hrace.
* @return tah.
*/
int PlayerList::getPlayersTurn()
{
return iPlayersTurn;
}
/**
* @brief hraci vektor karet hrace.
* @return vektor karet.
*/
vector<Card *> Player::getpCards()
{
return pCards;
}
/**
* @brief nastavi barvu figurky hrace.
* @param barva figurky.
*/
void Player::setColor(int color)
{
playerColor = color;
}
/**
* @brief vrati tah hrace na predchazejiciho hrace.
*/
void PlayerList::PreviusTurn()
{
iPlayersTurn -= 1;
if (iPlayersTurn < 0)
{
iPlayersTurn = number - 1;
}
}
<file_sep>/game_gui.cpp
/**
Autori: <NAME>, xdibda00
Modul: GameGUI
Popis modulu: Tento modul implementuje hlavni rozhrani pro
GUI verzi hry - graficke vykresleni.
Upresneni specializace modulu: Tato cast se stara o logiku
vykresleni mapy - sipky, samotna mapa, offset pro posunuti
na stred.
*/
#include "game_gui.h"
#include <QApplication>
extern Game *game;
Map *fieldsMap;
QtGraphics *graphics;
QSignalMapper* mapper;
Controller *mapControl;
/**
* @brief konstruktor pro hlavní třídu vykreslování a logiky hry.
*/
Game::Game() {
gameStarted = false;
scene = new QGraphicsScene();
gameScene = new QGraphicsScene();
authors = new QGraphicsScene();
newgame = new QGraphicsScene();
endgame = new QGraphicsScene();
missingPiece = new MapField();
panel = new SidePanel();
scene->setSceneRect(0,0,800,600);
gameScene->setSceneRect(0,0,800,600);
authors->setSceneRect(0,0,800,600);
newgame->setSceneRect(0,0,800,600);
endgame->setSceneRect(0,0,800,600);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setFixedSize(800, 600);
drawGUI();
}
/**
* @brief vrati policko, ktere se ma zasunout do mapy.
* @return vraci policko.
*/
MapField *Game::getMissingPiece() {
return missingPiece;
}
/**
* @brief nastavuje policko, ktere se bude zasunovat do mapy.
* @param policko, ktere se ma nastavit.
*/
void Game::setMissingPiece(MapField* field) {
missingPiece = field;
}
/**
* @brief kontroluje, zda jiz byla zapocata hra.
* @return true - hra byla zahajena / false - zadna hra neni aktivni.
*/
bool Game::isGameStarted() {
return gameStarted;
}
/**
* @brief konstruktor pro figurku.
* @param c - barva figurky.
*/
Figure::Figure(int c) {
color = c;
item = new QGraphicsPixmapItem(QString(getFigureReference(c)));
setFlag(QGraphicsItem::ItemIsFocusable);
}
/**
* @brief vraci barvu figurky.
* @return barva figurky.
*/
int Figure::getColor() {
return color;
}
/**
* @brief vraci odkaz na grafiku figurky.
* @return grafika figurky.
*/
QGraphicsPixmapItem *Figure::getItem() {
return item;
}
/**
* @brief vraci bocni informacni panel.
* @return vraci panel.
*/
SidePanel *Game::getPanel() {
return panel;
}
/**
* @brief generateFigure - funkce vygeneruje figurku a vlozi ji do mapy na dane policko
* @param scene - scena, na jakou se ma figurka vlozit
* @param xpos - vodorovna souradnice policka
* @param ypos - svisla souradnice policka
* @param color - barva figurky
*/
void generateFigure(QGraphicsScene *scene, int xpos, int ypos, int color) {
game->getFiguresVector()->push_back(new Figure(color));
MapField* indexedField = fieldsMap->getFields().at(xpos * fieldsMap->getSize() + ypos);
game->getFiguresVector()->back()->getItem()->setPos(300 - graphics->getOffset() + xpos * 40 + 12, 300 - graphics->getOffset() + ypos * 40 + 2);
scene->addItem(game->getFiguresVector()->back()->getItem());
}
/**
* @brief pohyb figurky po mape.
* @param akce pohybu.
*/
void Game::keyPressEvent(QKeyEvent *event) {
if(game->isGameStarted()) {
if(fieldsMap->getShiftedState()) {
switch (event->key()) {
case Qt::Key_Left:
mapControl->MakeMove(LEFT, fieldsMap->getPlayers()->GetActivePlayer(), fieldsMap);
break;
case Qt::Key_Right:
mapControl->MakeMove(RIGHT, fieldsMap->getPlayers()->GetActivePlayer(), fieldsMap);
break;
case Qt::Key_Up:
mapControl->MakeMove(UP, fieldsMap->getPlayers()->GetActivePlayer(), fieldsMap);
break;
case Qt::Key_Down:
mapControl->MakeMove(DOWN, fieldsMap->getPlayers()->GetActivePlayer(), fieldsMap);
break;
}
}
if(mapControl->GameEnded()) {
gameEndedScreen();
}
panel->resetValues();
if(!mapControl->GameEnded()) {
panel->setValues();
}
else {
delete mapControl;
}
makeDesk();
}
}
/**
* @brief vraci vektor figurek.
* @return vraci figurky.
*/
vector<Figure *> *Game::getFiguresVector() {
return &figuresVector;
}
/**
* @brief vykresli mapu + poklady + figurky.
*/
void Game::makeDesk() {
refreshMissingPiece();
mapper = new QSignalMapper(game);
QObject::connect(mapper, SIGNAL(mapped(int)), this, SLOT(shiftB(int)));
for(auto &descr : fieldsMap->getFields()) {
if (descr != fieldsMap->getFields().back())
generateField(gameScene, descr);
}
for(auto &pldescr: fieldsMap->getPlayers()->getPList()) {
generateFigure(gameScene, pldescr->getXPos(), pldescr->getYPos(), pldescr->getColor());
}
fieldsMap->getFields().clear();
}
/**
* @brief vygeneruje policko a sipky na mackani.
* @param scena na kterou se ma generovat.
* @param policko, ktere se ma vygenerovat.
*/
void generateField(QGraphicsScene *scene, MapField* field) {
QGraphicsPixmapItem *path = scene->addPixmap(QPixmap(QString(getPathReference(field->getShape()))));
if(field->getXPos() == 0 && field->getYPos() % 2) {
graphics->getArrows()->push_back(new Arrow(":/other/img/other/arrownohover.png", ":/other/img/other/arrowhover.png", 0, field->getXPos(), - 11, field->getYPos(), 0, graphics->getOffset(), game->gameScene));
mapper->setMapping(graphics->getArrows()->back(), field->getXPos() * fieldsMap->getSize() + field->getYPos());
QObject::connect(graphics->getArrows()->back(), SIGNAL(clicked()), mapper, SLOT(map()));
}
else if (field->getXPos() == fieldsMap->getSize() - 1 && field->getYPos() % 2) {
graphics->getArrows()->push_back(new Arrow(":/other/img/other/arrownohover.png", ":/other/img/other/arrowhover.png", 2, field->getXPos(), field->getSize() - 1, field->getYPos(), 0, graphics->getOffset(), game->gameScene));
mapper->setMapping(graphics->getArrows()->back(), field->getXPos() * fieldsMap->getSize() + field->getYPos());
QObject::connect(graphics->getArrows()->back(), SIGNAL(clicked()), mapper, SLOT(map()));
}
else if (field->getXPos() % 2 && field->getYPos() == 0) {
graphics->getArrows()->push_back(new Arrow(":/other/img/other/arrownohover.png", ":/other/img/other/arrowhover.png", 1, field->getXPos(), field->getSize() - 26, field->getYPos(), -25, graphics->getOffset(), game->gameScene));
mapper->setMapping(graphics->getArrows()->back(), field->getXPos() * fieldsMap->getSize() + field->getYPos());
QObject::connect(graphics->getArrows()->back(), SIGNAL(clicked()), mapper, SLOT(map()));
}
else if (field->getXPos() % 2 && field->getYPos() == fieldsMap->getSize() - 1) {
graphics->getArrows()->push_back(new Arrow(":/other/img/other/arrownohover.png", ":/other/img/other/arrowhover.png", 3, field->getXPos(), field->getSize() - 26, field->getYPos(), 25, graphics->getOffset(), game->gameScene));
mapper->setMapping(graphics->getArrows()->back(), field->getXPos() * fieldsMap->getSize() + field->getYPos());
QObject::connect(graphics->getArrows()->back(), SIGNAL(clicked()), mapper, SLOT(map()));
}
path->setTransformOriginPoint(19,19);
path->setRotation(field->getRotation() * 90);
path->setPos(300 + field->getXPos() * field->getSize() - graphics->getOffset(), 300 + field->getYPos() * field->getSize() - graphics->getOffset());
if(field->getTreasure() != 0) {
QGraphicsPixmapItem *item = scene->addPixmap(QPixmap(QString(getTreasureIcon(field->getTreasure()))));
if (field->getTreasure() == 7 or field->getTreasure() == 8 or field->getTreasure() == 11 or field->getTreasure() == 12 or field->getTreasure() == 19 or field->getTreasure() == 20 or field->getTreasure() == 23 or field->getTreasure() == 24) {
item->setPos(311 + field->getXPos() * field->getSize() - graphics->getOffset(), 311 + field->getYPos() * field->getSize() - graphics->getOffset());
}
else if (field->getTreasure() == 9 or field->getTreasure() == 10 or field->getTreasure() == 21 or field->getTreasure() == 22) {
item->setPos(309 + field->getXPos() * field->getSize() - graphics->getOffset(), 310 + field->getYPos() * field->getSize() - graphics->getOffset());
}
else {
item->setPos(309 + field->getXPos() * field->getSize() - graphics->getOffset(), 308 + field->getYPos() * field->getSize() - graphics->getOffset());
}
}
}
/**
* @brief vraci vektor sipek, na ktere se klika pro posunuti mapy.
* @return vrati vektor sipek.
*/
QVector<Arrow *> *QtGraphics::getArrows() {
return &arrows;
}
/**
* @brief aktualizuje offset pro posunuti od stredu - mapa je na stredu pro 5x5 i 7x7.
*/
void QtGraphics::actualizeOffset() {
offset = (fieldsMap->getSize() * 38 + (fieldsMap->getSize() - 1) * 4 ) / 2;
}
/**
* @brief vrati offset posunuti, aby mapa byla na stredu pro vsechny velikosti.
* @return vraci offset.
*/
int QtGraphics::getOffset() {
return offset;
}
<file_sep>/players.h
/**
Autori: <NAME>, xdibda00 + <NAME>, xporiz03
Modul: Players
Popis modulu: Tento modul implementuje praci s hracem a
seznamem hracu, kterym obsahuje vsechny hrace ve hre.
*/
#ifndef PLAYER
#define PLAYER
#include <vector>
#include <iostream>
#include "cardpack.h"
using namespace std;
/**
* @brief Trida hrac.
*/
class Player{
private:
int iScore;
int x;
int y;
int playerColor;
vector<Card *> pCards;
public:
Player();
Player(int id, int x, int y);
Player(int id, int x, int y, vector<Card *> playerCards, int score);
int getScore();
int getXPos();
int getYPos();
int getColor();
void SetScore(int score);
void AddScore(int score);
void appendCards(vector<Card *> cardList);
Card* getPlayersCard();
void getAnotherCard();
void setPos(int x, int y);
vector<Card *> getpCards();
void setColor(int color);
void giveCard(Card* card);
};
/**
* @brief Trida seznam hracu.
*/
class PlayerList{
private:
int number;
int iPlayersTurn;
vector<Player *> pList;
public:
PlayerList();
int NumberOfPlayers();
int getNumber();
void setNumber(int num);
void clearPlayers();
void CreatePlayer(int num, int xpos, int ypos, vector<Card *> *tempCards, int numberOfCards, int score);
vector<Player *> getPList();
void SetTurn(int pTurn);
void NextTurn();
Player* GetActivePlayer();
vector<Player *> GetPlayers(int x, int y);
int getPlayersTurn();
void PreviusTurn();
};
#endif
<file_sep>/game_gui_graph.cpp
/**
Autori: <NAME>, xdibda00
Modul: GameGUI - Graphics
Popis modulu: Tento modul implementuje hlavni rozhrani pro
GUI verzi hry - graficke vykresleni.
Upresneni specializace modulu: Tato cast se stara o pristup
ke grafice a vykresluje sceny.
*/
#include "game_gui.h"
extern Map* fieldsMap;
extern QtGraphics* graphics;
extern Game* game;
extern QSignalMapper* mapper;
extern Controller *mapControl;
/**
* @brief konecna scena hry.
*/
void Game::gameEndedScreen() {
gameStarted = false;
setScene(endgame);
setBackgroundBrush(QBrush(QImage(":/bg/img/bg/endgame.jpg")));
QGraphicsPixmapItem *winPlayerFigure = endgame->addPixmap(QPixmap(getFigureReferenceBig(fieldsMap->getPlayers()->GetActivePlayer()->getColor())));
winPlayerFigure->setPos(420, 275);
Button *mainMenuEnd = new Button(QString(":/buttons/img/buttons/mmbutton.png"), 300, 500, endgame, ":/buttons/img/buttons/mmbuttonhover.png");
QObject::connect(mainMenuEnd, SIGNAL(clicked()), this, SLOT(ret_mm()));
}
/**
* @brief vykresleni bocniho panelu
* @param x souradnice.
* @param y souradnice.
* @param sirka.
* @param vyska.
* @param barva.
* @param pruhlednost.
* @param scena na kterou se ma vykreslit.
*/
void Game::drawPanel(int x, int y, int width, int height, QColor color, double opacity, QGraphicsScene *scene) {
QGraphicsRectItem *panel = new QGraphicsRectItem;
panel->setRect(x, y, width, height);
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(color);
panel->setBrush(brush);
panel->setOpacity(opacity);
scene->addItem(panel);
}
/**
* @brief odalokovani a odmazani bocnich dynamickych udaju.
*/
void SidePanel::resetValues() {
game->gameScene->removeItem(playersIcon);
game->gameScene->removeItem(playersItem);
game->gameScene->removeItem(item);
delete item;
delete playersIcon;
delete playersItem;
}
/**
* @brief natavi hodnoty hrace v bocnim panelu.
*/
void SidePanel::setValues() {
playersIcon = new QGraphicsPixmapItem();
playersIcon = game->gameScene->addPixmap(QPixmap(QString(getFigureReference(fieldsMap->getPlayers()->GetActivePlayer()->getColor()))));
playersIcon->setPos(734, 32);
playersItem = new QGraphicsPixmapItem();
playersItem = game->gameScene->addPixmap(QPixmap(getTreasureBig(fieldsMap->getPlayers()->GetActivePlayer()->getPlayersCard()->getTreasure())));
playersItem->setPos(725, 242);
item = new QGraphicsTextItem(QString::number(fieldsMap->getPlayers()->GetActivePlayer()->getScore()) + " / " + QString::number(fieldsMap->getCards()->getSize() / fieldsMap->getPlayers()->getNumber()));
item->setPos(720, 86);
item->setFont(QFont("Times", 13));
game->gameScene->addItem(item);
}
/**
* @brief aktualizuje bocni policko na vkladani do mapy.
*/
void Game::refreshMissingPiece() {
setMissingPiece(fieldsMap->getFields().back());
QGraphicsPixmapItem *missing_puzzle = gameScene->addPixmap(QPixmap(getPathReference(fieldsMap->getFields().back()->getShape())));
missing_puzzle->setTransformOriginPoint(19,19);
missing_puzzle->setRotation(fieldsMap->getFields().back()->getRotation() * 90);
missing_puzzle->setPos(723, 150);
if(fieldsMap->getFields().back()->getTreasure() != 0) {
QGraphicsPixmapItem *item = gameScene->addPixmap(QPixmap(QString(getTreasureIcon(fieldsMap->getFields().back()->getTreasure()))));
item->setPos(733, 160);
}
}
/**
* vykresli vnitrek bocniho panelu.
*/
void Game::writeSideway() {
drawPanel(600, 15, 189, 400, Qt::white, 0.5, gameScene);
drawPanel(605, 20, 179, 55, Qt::white, 0.5, gameScene);
drawPanel(605, 80, 179, 40, Qt::white, 0.5, gameScene);
drawPanel(605, 125, 179, 85, Qt::white, 0.5, gameScene);
drawPanel(605, 215, 179, 85, Qt::white, 0.5, gameScene);
drawPanel(605, 305, 179, 105, Qt::white, 0.5, gameScene);
QGraphicsPixmapItem *curplaying = gameScene->addPixmap(QPixmap(":/other/img/other/currentlyplaying.png"));
curplaying->setPos(615, 22);
QGraphicsPixmapItem *score = gameScene->addPixmap(QPixmap(":/other/img/other/score.png"));
score->setPos(610, 81);
QGraphicsPixmapItem *puzzle = gameScene->addPixmap(QPixmap(":/other/img/other/puzzle.png"));
puzzle->setPos(610, 127);
QGraphicsPixmapItem *item = gameScene->addPixmap(QPixmap(":/other/img/other/item.png"));
item->setPos(610, 216);
QGraphicsPixmapItem *allp = gameScene->addPixmap(QPixmap(":/other/img/other/allplayers.png"));
allp->setPos(606, 308);
if (fieldsMap->getPlayers()->getNumber() == 2) {
QGraphicsPixmapItem *playersNumber = gameScene->addPixmap(QPixmap(":/other/img/other/players2.png"));
playersNumber->setPos(650, 338);
}
else if (fieldsMap->getPlayers()->getNumber() == 3) {
QGraphicsPixmapItem *playersNumber = gameScene->addPixmap(QPixmap(":/other/img/other/players3.png"));
playersNumber->setPos(650, 338);
}
else if (fieldsMap->getPlayers()->getNumber() == 4) {
QGraphicsPixmapItem *playersNumber = gameScene->addPixmap(QPixmap(":/other/img/other/players4.png"));
playersNumber->setPos(650, 338);
}
QGraphicsPixmapItem *firstPlayerIcon = gameScene->addPixmap(QPixmap(getFigureReferenceMenu(fieldsMap->getPlayers()->getPList().at(0)->getColor())));
firstPlayerIcon->setPos(645, 346);
QGraphicsPixmapItem *secondPlayerIcon = gameScene->addPixmap(QPixmap(getFigureReferenceMenu(fieldsMap->getPlayers()->getPList().at(1)->getColor())));
secondPlayerIcon->setPos(645, 361);
if(fieldsMap->getPlayers()->getNumber() > 2) {
QGraphicsPixmapItem *thirdPlayerIcon = gameScene->addPixmap(QPixmap(getFigureReferenceMenu(fieldsMap->getPlayers()->getPList().at(2)->getColor())));
thirdPlayerIcon->setPos(645, 376);
}
if(fieldsMap->getPlayers()->getNumber() > 3) {
QGraphicsPixmapItem *fourthPlayerIcon = gameScene->addPixmap(QPixmap(getFigureReferenceMenu(fieldsMap->getPlayers()->getPList().at(3)->getColor())));
fourthPlayerIcon->setPos(645, 391);
}
}
/**
* @brief zobrazí hlavní menu hry.
*/
void Game::displayMenu() {
setScene(scene);
setBackgroundBrush(QBrush(QImage(":/bg/img/bg/bg.jpg")));
if(isGameStarted()) {
Button *ret_frame = new Button(":/buttons/img/buttons/retbutton.png", 250, 457, scene, ":/buttons/img/buttons/retbuttonhover.png");
connect(ret_frame, SIGNAL(clicked()), this, SLOT(ret_game()));
Button *sg_button = new Button(":/buttons/img/buttons/sgbutton.png", 250, 292, scene, ":/buttons/img/buttons/sgbuttonhover.png");
connect(sg_button, SIGNAL(clicked()), this, SLOT(saveGame()));
}
else {
Button *ret_frame = new Button(":/buttons/img/buttons/retbuttongray.png", 250, 457, scene, ":/buttons/img/buttons/retbuttongray.png");
Button *sg_button = new Button(":/buttons/img/buttons/sgbuttongrey.png", 250, 292, scene, ":/buttons/img/buttons/sgbuttongrey.png");
}
}
/**
* @brief vykresli hlavni menu a autory - staticke obrazovky.
*/
void Game::drawGUI() {
// authors;
Button *back = new Button(":/buttons/img/buttons/backbutton.png", 250, 520, authors, ":/buttons/img/buttons/backbuttonhover.png");
QGraphicsPixmapItem *creText = authors->addPixmap(QPixmap(":/bg/img/bg/creditstext.jpg"));
creText->setPos(100,140);
connect(back, SIGNAL(clicked()), this, SLOT(ret_mm()));
// main menu;
Button *ng_frame = new Button(":/buttons/img/buttons/ngbutton.png", 250, 237, scene, ":/buttons/img/buttons/ngbuttonhover.png");
Button *lg_frame = new Button(":/buttons/img/buttons/lgbutton.png", 250, 347, scene, ":/buttons/img/buttons/lgbuttonhover.png");
Button *authors_frame = new Button(":/buttons/img/buttons/crebutton.png", 250, 402, scene, ":/buttons/img/buttons/crebuttonhover.png");
Button *quit_frame = new Button(":/buttons/img/buttons/qgbutton.png", 250, 512, scene, ":/buttons/img/buttons/qgbuttonhover.png");
connect(ng_frame, SIGNAL(clicked()), this, SLOT(choose()));
connect(quit_frame, SIGNAL(clicked()), this, SLOT(close()));
connect(authors_frame, SIGNAL(clicked()), this, SLOT(authors_view()));
connect(lg_frame, SIGNAL(clicked()), this, SLOT(loadGame()));
}
/** --- Funkce, ktere vraci grafiku. --- */
/**
* @brief vraci grafiku k figurky.
* @param barva figurky.
* @return vraci adresu k figurce.
*/
QString Game::getFigureReferenceBig(int color) {
switch (color) {
case 0:
return QString(":/figures/img/figures/figure_blue.png");
case 1:
return QString(":/figures/img/figures/figure_red.png");
case 2:
return QString(":/figures/img/figures/figure_yellow.png");
case 3:
return QString(":/figures/img/figures/figure_green.png");
}
}
/**
* @brief vraci grafiku cesty
* @param znak cesty - T, L, I.
* @return vraci adresu grafiky.
*/
QString getPathReference(char c) {
QString path;
switch (c) {
case 'L':
path = QString(":/path/img/path/l_shape35px.png");
break;
case 'T':
path = QString(":/path/img/path/t_shape35px.png");
break;
case 'I':
path = QString(":/path/img/path/i_shape35px.png");
break;
}
return path;
}
/**
* @brief vraci grafiku figurky.
* @param barva figurky.
* @return adresa grafiky figurky.
*/
QString getFigureReference(int color) {
switch (color) {
case 0:
return QString(":/figures/img/figures/figure_blue_desk.png");
case 1:
return QString(":/figures/img/figures/figure_red_desk.png");
case 2:
return QString(":/figures/img/figures/figure_yellow_desk.png");
case 3:
return QString(":/figures/img/figures/figure_green_desk.png");
}
}
/**
* @brief vraci malou figurku v menu.
* @param barva figurky.
* @return vraci adresu zmensene figurky.
*/
QString getFigureReferenceMenu(int color) {
switch (color) {
case 0:
return QString(":/figures/img/figures/figure_blue_menu.png");
case 1:
return QString(":/figures/img/figures/figure_red_menu.png");
case 2:
return QString(":/figures/img/figures/figure_yellow_menu.png");
case 3:
return QString(":/figures/img/figures/figure_green_menu.png");
}
}
/**
* @brief vraci obrazek pokladu.
* @param id pokladu.
* @return adresa grafiky pokladu.
*/
QString getTreasureIcon(int treasureID) {
QString returnValue;
switch (treasureID) {
case 1:
returnValue = ":/items/img/items/vag1min.png";
break;
case 2:
returnValue = ":/items/img/items/vag2min.png";
break;
case 3:
returnValue = ":/items/img/items/triangle1min.png";
break;
case 4:
returnValue = ":/items/img/items/triangle3min.png";
break;
case 5:
returnValue = ":/items/img/items/star2min.png";
break;
case 6:
returnValue = ":/items/img/items/star3min.png";
break;
case 7:
returnValue = ":/items/img/items/square3min.png";
break;
case 8:
returnValue = ":/items/img/items/square4min.png";
break;
case 9:
returnValue = ":/items/img/items/cross4min.png";
break;
case 10:
returnValue = ":/items/img/items/cross1min.png";
break;
case 11:
returnValue = ":/items/img/items/circle1min.png";
break;
case 12:
returnValue = ":/items/img/items/circle2min.png";
break;
case 13:
returnValue = ":/items/img/items/vag3min.png";
break;
case 14:
returnValue = ":/items/img/items/vag4min.png";
break;
case 15:
returnValue = ":/items/img/items/triangle2min.png";
break;
case 16:
returnValue = ":/items/img/items/triangle4min.png";
break;
case 17:
returnValue = ":/items/img/items/star1min.png";
break;
case 18:
returnValue = ":/items/img/items/star4min.png";
break;
case 19:
returnValue = ":/items/img/items/square1min.png";
break;
case 20:
returnValue = ":/items/img/items/square2min.png";
break;
case 21:
returnValue = ":/items/img/items/cross3min.png";
break;
case 22:
returnValue = ":/items/img/items/cross2min.png";
break;
case 23:
returnValue = ":/items/img/items/circle3min.png";
break;
case 24:
returnValue = ":/items/img/items/circle4min.png";
break;
}
return returnValue;
}
/**
* @brief vraci grafiku velkeho pokladu do menu.
* @param id pokladu.
* @return vraci grafiku pokladu do menu.
*/
QString getTreasureBig(int treasureID) {
QString returnValue;
switch (treasureID) {
case 1:
returnValue = ":/items/img/items/vag1.png";
break;
case 2:
returnValue = ":/items/img/items/vag2.png";
break;
case 3:
returnValue = ":/items/img/items/triangle1.png";
break;
case 4:
returnValue = ":/items/img/items/triangle3.png";
break;
case 5:
returnValue = ":/items/img/items/star2.png";
break;
case 6:
returnValue = ":/items/img/items/star3.png";
break;
case 7:
returnValue = ":/items/img/items/square3.png";
break;
case 8:
returnValue = ":/items/img/items/square4.png";
break;
case 9:
returnValue = ":/items/img/items/cross4.png";
break;
case 10:
returnValue = ":/items/img/items/cross1.png";
break;
case 11:
returnValue = ":/items/img/items/circle1.png";
break;
case 12:
returnValue = ":/items/img/items/circle2.png";
break;
case 13:
returnValue = ":/items/img/items/vag3.png";
break;
case 14:
returnValue = ":/items/img/items/vag4.png";
break;
case 15:
returnValue = ":/items/img/items/triangle2.png";
break;
case 16:
returnValue = ":/items/img/items/triangle4.png";
break;
case 17:
returnValue = ":/items/img/items/star1.png";
break;
case 18:
returnValue = ":/items/img/items/star4.png";
break;
case 19:
returnValue = ":/items/img/items/square1.png";
break;
case 20:
returnValue = ":/items/img/items/square2.png";
break;
case 21:
returnValue = ":/items/img/items/cross3.png";
break;
case 22:
returnValue = ":/items/img/items/cross2.png";
break;
case 23:
returnValue = ":/items/img/items/circle3.png";
break;
case 24:
returnValue = ":/items/img/items/circle4.png";
break;
}
return returnValue;
}
<file_sep>/main_cli.cpp
/**
* Autori: <NAME>, xporiz03
* Modul: mainCLI
* Popis modulu: Hlavni telo programu konzolove casti. Resi zpracovani parametru, vypisovani zprav o spatnem vstupu hry, resi volanim jadra aplikace.
*/
#include <iostream>
#include <string>
#include "game_cli.h"
#include "log.h"
using namespace std;
/**
* @brief Telo cele CLI aplikace, spravuje parametry a vola potrebne funcke z jadra aplikace.
* @param pocet parametru.
* @param pole s parametry.
* @return 1 pokud program skonci bez chyby, jinak 0.
*/
int main(int argc, char *argv[])
{
Map* MyMap = new Map;
MyMap->setPlayers(4);
MyMap->setSize(7);
MyMap->setCardsSet(12);
//Parsovani parametru
if (argc > 4)
{
std::cout << "Too many parameters";
}
else if (argc == 2 && (argv[1] == string("help") || argv[1] == string("-help") || argv[1] == string("--help")))
{
std::cout << "###############################################################################\n"
"ICP Projekt\n"
"Autor:<NAME> (CLI), <NAME> (Qt)\n"
"###############################################################################\n"
"Parametry CLI:\n"
"Spusteni: klient P C S\n"
" help Optional: Vypise napovedu\n"
" P Required: Nastavi pocet hracu:: 2 az 4\n"
" C Required: Nastavi pocet karet:: 12 nebo 24\n"
" S Optional: Nastavi rozmer:: pouze licha cisla od 5 do 15\n"
"###############################################################################\n";
string command;
while (command != string("exit"))
{
std::cout << "Napiste exit pro ukonceni.\n";
cin >> command;
}
return 1;
}
else if (argc == 3)
{
if (stoi(argv[1]) >= 2 && stoi(argv[1]) <= 4)
MyMap->setPlayers(stoi(argv[1]));
else
std::cout << "Spatne parametry, pouzijte './app help' pro zobrazeni napovedy.\n";
if (stoi(argv[2]) == 12 || stoi(argv[2]) == 24)
MyMap->setCardsSet(stoi(argv[2]));
else
{
std::cout << "Spatne parametry, pouzijte './app help' pro zobrazeni napovedy.\n";
return 0;
}
}
else if (argc == 4)
{
if (stoi(argv[1]) >= 2 && stoi(argv[1]) <= 4)
MyMap->setPlayers(stoi(argv[1]));
else
std::cout << "Spatne parametry, pouzijte './app help' pro zobrazeni napovedy.\n";
if (stoi(argv[2]) == 12 || stoi(argv[2]) == 24)
MyMap->setCardsSet(stoi(argv[2]));
else
std::cout << "Spatne parametry, pouzijte './app help' pro zobrazeni napovedy.\n";
if ((stoi(argv[3]) >= 5 && stoi(argv[3]) <= 11) && stoi(argv[3]) % 2 == 1)
MyMap->setSize(stoi(argv[3]));
else
{
std::cout << "Spatne parametry, pouzijte './app help' pro zobrazeni napovedy.\n";
return 0;
}
}
else
{
std::cout << "Spatne parametry, pouzijte './app help' pro zobrazeni napovedy.\n";
return 0;
}
//Incializace po proparsovani argumentu
string command;
MyMap->createMap();
Controller control;
PlayerList* pList;
Logger* logging = control.getLog();
gameCLI CLI;
while (!(control.GameEnded()))
{
Player* pToPlay = MyMap->GetActivePlayer();
CLI.DrawBoard(MyMap);
std::cout << "\nTah cislo:" << logging->getTurnNumber();
std::cout << "\nCLI Ovladani:\n";
std::cout << "r Rotace kamene navic o 90 stupnu doprava.\n";
std::cout << "iX,Y Vlozi kamen na pozici X - Sloupec, Y - Radek. Povinne na zacatku.\n";
std::cout << "w Pohyb s aktivnim hracem nahoru.\n";
std::cout << "a Pohyb s aktivnim hracem doleva.\n";
std::cout << "s Pohyb s aktivnim hracem dolu.\n";
std::cout << "d Pohyb s aktivnim hracem doprava.\n";
std::cout << "u Ulozi rozehranou hru tak jak je.\n";
std::cout << "n Nacte ulozenou hru tak jak byla predtim.\n";
std::cout << "b Vrati tah o jeden zpet.\n";
std::cout << "end Ukonci tah. Jinak se tah ukonci sam, pokud hrac vezme poklad ktery hleda.\n";
std::cout << "exit Ukonci hru.\n";
std::cout << "<- Znaci aktivniho hrace a vypisuje jaky poklad hleda.\n";
while (!(control.GameEnded()))
{
std::cout << "Prikaz: ";
cin >> command;
unsigned long x;
unsigned long y;
if (command.substr(0, 4) == "exit")
{
return 1;
}
else if (command.substr(0, 3) == "end")
{
control.EndTurn(MyMap);
break;
}
else if (command.substr(0, 1) == "n")
{
logging->loadGame(MyMap);
break;
}
else if (command.substr(0, 1) == "u")
{
logging->saveGame(*MyMap);
}
else if (command.substr(0, 1) == "b")
{
if (!control.undoTurn(MyMap))
{
std::cout << "Jiz jste na zacatku hry.\n";
continue;
}
break;
}
else if (command.substr(0, 1) == "r")
{
if (MyMap->getShiftedState())
{
std::cout << "Rotovat kamen, ktery nebudete vkladat je zbytecne.\n";
continue;
}
control.rotateField(MyMap);
break;
}
else if (command.substr(0, 1) == "i")
{
if (MyMap->getShiftedState())
{
std::cout << "Nemuzete vkladat kamen vicekrat po sobe.\n";
continue;
}
else
{
command = command.substr(1, string::npos);
if (command.find(',') == string::npos || command.find(' ') != string::npos)
{
std::cout << "Spatny format prikazu vlozeni: iR,S.\n";
continue;
}
try
{
x = stoul(command.substr(0, command.find(',')), nullptr, 10);
y = stoul(command.substr(command.find(',') + 1, string::npos), nullptr, 10);
x -= 1;
y -= 1;
}
catch (const invalid_argument& ia)
{
cerr << "Invalid argument: " << ia.what() << '\n';
}
catch (const out_of_range& oor)
{
cerr << "Out of Range error: " << oor.what() << '\n';
}
if (control.shiftBoard(x, y, MyMap))
{
break;
}
else
{
std::cout << "Wrong coordinations to insert.\n";
continue;
}
}
}
else
{
if (!MyMap->getShiftedState())
{
std::cout << "Napred musite vlozit kamen: iR,S\n";
continue;
}
else
{
if (command.substr(0, 1) == "w")
{
if (!control.MakeMove(UP, pToPlay, MyMap))
{
std::cout << "Sem nemuzes!\n";
continue;
}
else
break;
}
if (command.substr(0, 1) == "s")
{
if (!control.MakeMove(DOWN, pToPlay, MyMap))
{
std::cout << "Sem nemuzes!\n";
continue;
}
else
break;
}
if (command.substr(0, 1) == "a")
{
if (!control.MakeMove(LEFT, pToPlay, MyMap))
{
std::cout << "Sem nemuzes!\n";
continue;
}
else
break;
}
if (command.substr(0, 1) == "d")
{
if (!control.MakeMove(RIGHT, pToPlay, MyMap))
{
std::cout << "Sem nemuzes!\n";
continue;
}
else
break;
}
if (MyMap->GetActivePlayer() != pToPlay)
{
break;
}
}
}
}
CLI.ClearScreen();
}
std::cout << "<NAME>!\n\n\n";
pList = MyMap->getPlayers();
vector<Player*> players = pList->getPList();
std::cout << "Skore hracu:\n";
for (unsigned int i = 0; i < players.size(); i++)
{
std::cout << "Player " << players[i]->getColor() << ": ";
std::cout << players[i]->getScore() << "/" << (MyMap->getCardsSet() / (MyMap->getPlayers())->getNumber());
if (players[i] == pList->GetActivePlayer())
{
std::cout << " <- " << "VITEZ";
}
std::cout << "\n";
}
command.clear();
while (command != string("exit"))
{
std::cout << "Napiste exit pro ukonceni.\n";
cin >> command;
}
return 1;
}
<file_sep>/map.h
/**
* Autori: <NAME>, xdibda00 + <NAME>, xporiz03
* Modul: Map
* Popis modulu: Tento modul implementuje praci s mapu
* a jednotlivymi polickami mapy.
*/
#ifndef MAP
#define MAP
#include <vector>
#include <cstdlib>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "players.h"
using namespace std;
/**
* @brief Trida popisujici policko mapy.
*/
class MapField {
protected:
int size;
int treasure;
int xPos;
int yPos;
int rotation;
int shape;
public:
MapField();
MapField(int rot);
int getSize();
int getXPos();
int getYPos();
int getRotation();
int getTreasure();
char getShape();
void setBorder(int edge);
void setCorner(int corner);
void setShape(int shape);
void setRotation(int rot);
void setPosition(int x, int y);
void setTreasure(int tr);
void fieldCounterRotate();
void fieldRotate();
void setSize(int fSize);
};
/**
* @brief Trida popisujici mapu.
*/
class Map {
protected:
int size;
CardPack* cards;
PlayerList* players;
vector<MapField *> fields;
signed int lastX;
signed int lastY;
bool wasShifted;
public:
Map();
int getSize();
int getCardsSet();
signed int getLastX();
signed int getLastY();
void clearMap();
void createMap();
void setSize(int n);
void setCardsSet(int sc);
void setPlayers(int play);
void prepareCards();
void addField(MapField* tField);
void addPlayer(Player* tPlayer);
void setTurn(int turn);
void PreviusTurn();
void setLastX(int x);
void setLastY(int y);
void changeShiftedState(bool END);
void NextTurn();
bool isEmpty();
bool getShiftedState();
bool ShiftBoard(int x, int y, bool undo);
PlayerList* getPlayers();
CardPack* getCards();
vector<MapField *> getFields();
MapField* GetField(int x, int y);
Player* GetActivePlayer();
};
#endif
<file_sep>/map.cpp
/**
Autori: <NAME>, xdibda00
Modul: Map
Popis modulu: Tento modul implementuje praci s mapu
a jednotlivymi polickami mapy.
*/
#include "map.h"
#define FIELD_SIZE 38
#define FIELD_SPACE 4
#define CORNER_TOPLEFT 1
#define CORNER_TOPRIGHT 2
#define CORNER_BOTTOMLEFT 3
#define CORNER_BOTTOMRIGHT 4
#define EDGE_LEFT 1
#define EDGE_RIGHT 2
#define EDGE_TOP 3
#define EDGE_BOTTOM 4
/**
* @brief konstruktor pro policko mapy.
*/
MapField::MapField() {
size = 40;
}
/**
* @brief sekundarni konstruktor pro policko mapy.
* @param rotace policka mapy.
*/
MapField::MapField(int rot) {
size = 40;
xPos = 0;
yPos = 0;
rotation = rot;
}
/**
* @brief rucni nastaveni rotace policka mapy.
* @param velikost rotace.
*/
void MapField::setRotation(int rot) {
rotation = rot;
}
/**
* @brief automaticke nastaveni rohu.
* @param typ rohu (levy/pravy horni/dolni - viz makro).
*/
void MapField::setCorner(int corner) {
shape = 'L';
switch (corner) {
case 1:
rotation = 3;
break;
case 2:
rotation = 0;
break;
case 3:
rotation = 2;
break;
case 4:
rotation = 1;
break;
}
}
/**
* @brief automaticke nastaveni okraje mapy.
* @param typ okraje (levy/pravy horni/dolni - viz makro).
*/
void MapField::setBorder(int edge) {
shape = 'T';
switch (edge) {
case 1:
rotation = 3;
break;
case 2:
rotation = 1;
break;
case 3:
rotation = 0;
break;
case 4:
rotation = 2;
break;
}
}
/**
* @brief vraci typ tvaru policka.
* @return T/I/L.
*/
char MapField::getShape() {
return shape;
}
/**
* @brief vraci velikost policka mapy.
* @return velikost policka.
*/
int MapField::getSize() {
return size;
}
/**
* @brief vraci vodorovnou souradnici policka mapy.
* @return souradnice.
*/
int MapField::getXPos() {
return xPos;
}
/**
* @brief vraci svislou souradnici policka mapy.
* @return souradnice.
*/
int MapField::getYPos() {
return yPos;
}
/**
* @brief vraci rotaci na policku mapy.
* @return rotace.
*/
int MapField::getRotation() {
return rotation;
}
/**
* @brief vraci poklad na danem policku mapy.
* @return 1-12, 1-24 nebo 0.
*/
int MapField::getTreasure() {
return treasure;
}
/**
* @brief nastavi souradnice policka na mape.
* @param vodorovna souradnice.
* @param svisla souradnice.
*/
void MapField::setPosition(int x, int y) {
xPos = x;
yPos = y;
}
/**
* @brief nastavi poklad pro policko mapy.
* @param id pokladu.
*/
void MapField::setTreasure(int tr) {
treasure = tr;
}
/**
* @brief nastavi tvar policku mapy.
* @param T/I/L.
*/
void MapField::setShape(int c) {
switch (c) {
case 1:
shape = 'I';
break;
case 2:
shape = 'L';
break;
case 3:
shape = 'T';
break;
}
}
/**
* @brief konstruktor mapy.
*/
Map::Map() {
players = new PlayerList;
cards = new CardPack;
size = 7;
lastX = -1;
lastY = -1;
wasShifted = 0;
}
/**
* @brief vymaze mapu (vektor policek mapy).
*/
void Map::clearMap() {
int sizeOfVector = fields.size();
for (int i = 0; i < sizeOfVector; i++) {
delete fields[i];
}
fields.clear();
}
/**
* @brief posune mapu v radku nebo sloupci
* @param vstupni vodorovna souradnice.
* @param vstupni svisla souradnice.
* @param undo param.
* @return true(success) / false.
*/
bool Map::ShiftBoard(int x, int y, bool undo)
{
MapField* tempFieldIn = fields[size * size];
MapField* tempFieldOut;
vector<Player *> tempPlayers;
if (x == 0 || x == size - 1)
{
if (y % 2 == 1)
{
if (!undo)
{
if (!(lastX == size - x - 1 && lastY == y))
{
lastX = x;
lastY = y;
}
else
return 0;
}
if (x == 0)
{
for (int i = 0; i < size; i++)
{
if (players->GetPlayers(i, y) != tempPlayers)
tempPlayers = players->GetPlayers(i, y);
else
tempPlayers.clear();
for (unsigned int j = 0; j < tempPlayers.size(); j++)
{
if ((i + 1) == size)
tempPlayers[j]->setPos(0, y);
else
tempPlayers[j]->setPos(i + 1, y);
}
tempFieldOut = fields[i * size + y];
fields[i * size + y] = tempFieldIn;
GetField(i, y)->setPosition(i, y);
tempFieldIn = tempFieldOut;
}
fields[size * size] = tempFieldOut;
}
else
{
for (int i = size - 1; i >= 0; i--)
{
if (players->GetPlayers(i, y) != tempPlayers)
tempPlayers = players->GetPlayers(i, y);
else
tempPlayers.clear();
for (unsigned int j = 0; j < tempPlayers.size(); j++)
{
if (i == 0)
tempPlayers[j]->setPos(size - 1, y);
else
tempPlayers[j]->setPos(i - 1, y);
}
tempFieldOut = fields[i * size + y];
fields[i * size + y] = tempFieldIn;
GetField(i, y)->setPosition(i, y);
tempFieldIn = tempFieldOut;
}
fields[size * size] = tempFieldOut;
}
}
else
return 0;
}
else if (y == 0 || y == size - 1)
if (x % 2 == 1)
{
if (!undo)
{
if (!(lastX == x && lastY == size - y - 1))
{
lastX = x;
lastY = y;
}
else
return 0;
}
if (y == 0)
{
for (int i = 0; i < size; i++)
{
if (players->GetPlayers(x, i) != tempPlayers)
tempPlayers = players->GetPlayers(x, i);
else
tempPlayers.clear();
for (unsigned int j = 0; j < tempPlayers.size(); j++)
{
if ((i + 1) == size)
tempPlayers[j]->setPos(x, 0);
else
tempPlayers[j]->setPos(x, i + 1);
}
tempFieldOut = fields[x * size + i];
fields[x * size + i] = tempFieldIn;
GetField(x, i)->setPosition(x, i);
tempFieldIn = tempFieldOut;
}
fields[size * size] = tempFieldOut;
}
else
{
for (int i = size - 1; i >= 0; i--)
{
if (players->GetPlayers(x, i) != tempPlayers)
tempPlayers = players->GetPlayers(x, i);
else
tempPlayers.clear();
for (unsigned int j = 0; j < tempPlayers.size(); j++)
{
if (i == 0)
tempPlayers[j]->setPos(x, size - 1);
else
tempPlayers[j]->setPos(x, i - 1);
}
tempFieldOut = fields[x * size + i];
fields[x * size + i] = tempFieldIn;
GetField(x, i)->setPosition(x, i);
tempFieldIn = tempFieldOut;
}
fields[size * size] = tempFieldOut;
}
}
else
return 0;
else
return 0;
changeShiftedState(1);
if (undo)
changeShiftedState(0);
return 1;
}
/**
* @brief nastavi velikost setu karet
* @param velikost balicku karet - 12 nebo 24.
*/
void Map::setCardsSet(int sc) {
cards->setSize(sc);
}
/**
* @brief vraci velikost balicku karet.
* @return velikost.
*/
int Map::getCardsSet() {
return cards->getSize();
}
/**
* @brief nastavi pocet hracu.
* @param pocet hracu - 2 nebo 3 nebo 4.
*/
void Map::setPlayers(int play) {
players->setNumber(play);
}
/**
* @brief vrati velikost mapy.
* @return velikost.
*/
int Map::getSize() {
return size;
}
/**
* @brief pripravi balicek karet.
*/
void Map::prepareCards() {
cards->clearCardPack();
cards->AppendPack();
cards->ShufflePack();
}
/**
* @brief vrati pocet hracu.
* @return pocet hracu.
*/
PlayerList* Map::getPlayers() {
return players;
}
/**
* @brief vrati vektor policek mapy.
* @return vektor policek.
*/
vector<MapField *> Map::getFields() {
return fields;
}
/**
* @brief vrati vektor balicku karet.
* @return vektor balicku.
*/
CardPack *Map::getCards() {
return cards;
}
/**
* @brief nastavi velikost mapy.
* @param velikost mapy.
*/
void Map::setSize(int n) {
size = n;
}
/**
* @brief vrati policko na urcitem indexu na mape.
* @param vodorovna souradnice.
* @param svisla souradnice.
* @return policko na mape.
*/
MapField* Map::GetField(int x, int y)
{
return fields[x * size + y];
}
/**
* @brief vytvori novou mapu na zaklade zadanych parametru hry.
*/
void Map::createMap() {
vector<int> cardRandomNumbers;
vector<int> figureRandomNumbers;
vector<Card *> tempCards;
int numberOfCards = cards->getSize();
int randNumber;
int currentItem = 0;
bool isThere = false;
srand(time(NULL));
clearMap();
prepareCards();
tempCards = cards->getCardsVector();
players->clearPlayers();
for (int i = 0; i < players->getNumber(); i++) {
while (1) {
isThere = false;
randNumber = (rand() % 4);
for (auto i : figureRandomNumbers) {
if (i == randNumber)
isThere = true;
}
if (!isThere)
break;
}
figureRandomNumbers.push_back(randNumber);
while (1) {
isThere = false;
randNumber = (rand() % 4);
for (auto i : cardRandomNumbers) {
if (i == randNumber)
isThere = true;
}
if (!isThere)
break;
}
cardRandomNumbers.push_back(randNumber);
switch (randNumber) {
case 0:
players->CreatePlayer(figureRandomNumbers.back(), 0, 0, &tempCards, numberOfCards, 0);
break;
case 1:
players->CreatePlayer(figureRandomNumbers.back(), 0, size - 1, &tempCards, numberOfCards, 0);
break;
case 2:
players->CreatePlayer(figureRandomNumbers.back(), size - 1, 0, &tempCards, numberOfCards, 0);
break;
case 3:
players->CreatePlayer(figureRandomNumbers.back(), size - 1, size - 1, &tempCards, numberOfCards, 0);
break;
}
}
randNumber = 0;
players->SetTurn(0);
isThere = false;
cardRandomNumbers.clear();
for (int i = 0; i < cards->getSize(); i++) {
while (1) {
isThere = false;
randNumber = rand() % ((size * size) - 1);
if (randNumber == 0 || randNumber == (size - 1) || randNumber == ((size * size) - size))
continue;
for (auto i : cardRandomNumbers) {
if (i == randNumber)
isThere = true;
}
if (!isThere)
break;
}
cardRandomNumbers.push_back(randNumber);
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
fields.push_back(new MapField);
isThere = false;
for (auto stoneByStone : cardRandomNumbers) {
if (i * size + j == stoneByStone) {
isThere = true;
}
}
if (isThere){
fields.back()->setTreasure(++currentItem);
}
else
fields.back()->setTreasure(0);
if (i == 0) {
if (j == 0)
fields.back()->setCorner(CORNER_TOPLEFT);
else if (j == size - 1)
fields.back()->setCorner(CORNER_BOTTOMLEFT);
else if (!(j % 2))
fields.back()->setBorder(EDGE_LEFT);
else {
fields.back()->setShape(rand() % 3 + 1);
fields.back()->setRotation(rand() % 4);
}
}
else if (i == size - 1) {
if (j == 0)
fields.back()->setCorner(CORNER_TOPRIGHT);
else if (j == size - 1)
fields.back()->setCorner(CORNER_BOTTOMRIGHT);
else if (!(j % 2))
fields.back()->setBorder(EDGE_RIGHT);
else {
fields.back()->setShape(rand() % 3 + 1);
fields.back()->setRotation(rand() % 4);
}
}
else if (!(i % 2) && !(j % 2) && i != 0 && j != 0 && i != size - 1 && j != size - 1) {
fields.back()->setShape(3);
fields.back()->setRotation(rand() % 4);
}
else {
if (j == 0 && !(i % 2))
fields.back()->setBorder(EDGE_TOP);
else if (j == size - 1 && !(i % 2))
fields.back()->setBorder(EDGE_BOTTOM);
else {
fields.back()->setShape(rand() % 3 + 1);
fields.back()->setRotation(rand() % 4);
}
}
fields.back()->setPosition(i, j);
}
}
fields.push_back(new MapField);
fields.back()->setShape(rand() % 3 + 1);
fields.back()->setRotation(rand() % 4);
fields.back()->setTreasure(0);
}
/**
* @brief prepne hru na dalsiho hrace.
*/
void Map::NextTurn()
{
players->NextTurn();
}
/**
* @brief zjisti, zda byla v danem tahu jiz mapa posunuta.
* @return true/false.
*/
bool Map::getShiftedState()
{
return wasShifted;
}
/**
* @brief nastavi flag posunuti mapy.
* @param true/false.
*/
void Map::changeShiftedState(bool END)
{
wasShifted = END;
}
/**
* @brief vrati aktivniho hrace
* @return aktivni hrac.
*/
Player* Map::GetActivePlayer()
{
return players->GetActivePlayer();
}
void MapField::fieldCounterRotate()
{
rotation -= 1;
if (rotation < 0)
{
rotation = 3;
}
}
/**
* orotuje policko mapy o 90 stupnu.
*/
void MapField::fieldRotate()
{
rotation += 1;
if (rotation > 3)
{
rotation = 0;
}
}
/**
* @brief vrati posledni posunuti mapy ve svisle ose.
* @return souradnice posunuti.
*/
signed int Map::getLastY()
{
return lastY;
}
/**
* @brief vrati posledni posunuti mapy ve vodorovne ose.
* @return souradnice posunuti.
*/
signed int Map::getLastX()
{
return lastX;
}
/**
* @brief nastavi posledni posunuti mapy ve svisle ose.
* @param svisly parametr.
*/
void Map::setLastY(int y)
{
lastY = y;
}
/**
* @brief nastavi posledni posunuti mapy ve vodorovne ose.
* @param vodorovny parametr.
*/
void Map::setLastX(int x)
{
lastX = x;
}
/**
* @brief vrati, zda je mapa prazdna.
* @return true/false.
*/
bool Map::isEmpty()
{
if (fields.size() == 0)
return 1;
else
return 0;
}
/**
* @brief nastavi velikost policka.
* @param velikost policka.
*/
void MapField::setSize(int fSize)
{
size = fSize;
}
/**
* @brief prida policka na konec vektoru mapy.
* @param policko mapy.
*/
void Map::addField(MapField* tField)
{
fields.push_back(tField);
}
/**
* @brief nastavi tah hrace.
* @param ktery hrac ma hrat.
*/
void Map::setTurn(int turn)
{
players->SetTurn(turn);
}
/**
* @brief vrati tah hrace na predchazejiciho hrace.
*/
void Map::PreviusTurn()
{
players->PreviusTurn();
}
<file_sep>/game_cli.h
/**
* Autori: <NAME>, xporiz03
* Modul: gameCLI
* Popis modulu: Tento modul implementuje GUI CLI, resi vykresleni hraci plochy a dalsich potrebnych casti hry.
*/
#ifndef GAMECLI
#define GAMECLI
#include "map.h"
#include "players.h"
#include "controller.h"
/**
* @brief Funkce resici sort hracu podle jejich barev
* @param prvni hrac.
* @param druhy hrac.
* @return TRUE pokud je barva prvniho vetsi nez druheho, naopak FALSE.
*/
bool cmd(Player * p1, Player * p2);
/**
* @brief Trida resici generovani GUI na CLI vystup.
*/
class gameCLI{
public:
void ClearScreen();
void DrawBoard(Map* pMap);
void PrintField(char shape, int rotation, int line, int treasure);
};
#endif
<file_sep>/main_gui.cpp
/**
Autori: <NAME>, xdibda00
Modul: Soubor s main funkci pro spusteni GUI
*/
#include <QApplication>
#include "game_gui.h"
Game *game;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
game = new Game();
game->show();
game->displayMenu();
return a.exec();
}
<file_sep>/log.h
/**
* Autori: <NAME>, xporiz03
* Modul: log
* Popis modulu: Tento modul implementuje ukladani a nacitani her.
*/
#ifndef LOG
#define LOG
#include <iostream>
#include "map.h"
#include "cardpack.h"
#include "players.h"
/**
* @brief Trida resici ukladani a nacitani her a take stack tahu, ktere byly provedeny
*/
class Logger{
private:
int iTurnNumber = 0;
vector<string>moves;
public:
int getTurnNumber();
void incTurnNumber();
void decTurnNumber();
void setTurnNumber(int turn);
void saveGame(Map pMap);
void loadGame(Map* sMap);
void saveTurn(string turn);
string getTurn();
void clearMoves();
};
#endif
<file_sep>/cardpack.cpp
/**
Autori: <NAME>, xdibda00 + <NAME>, xporiz03
Modul: CardPack
Popis modulu: Tento modul implementuje praci s kartami a balickem karet.
*/
#include "cardpack.h"
/**
* @brief konstruktor karty.
*/
Card::Card() {
treasure = 0;
}
/**
* @brief sekundarni konstruktor karty.
* @param typ karty.
*/
Card::Card(int type) {
treasure = type;
}
/**
* @brief vraci poklad na karte.
* @return 1-12 nebo 1-24 pokud na karte poklad je, pokud neni vraci 0.
*/
int Card::getTreasure() {
return treasure;
}
/**
* @brief prida do prazdneho balicku sadu karet.
*/
void CardPack::AppendPack() {
for (int i = 1; i < size + 1; i++) {
Cards.push_back(new Card(i));
}
}
/**
* @brief nastavi velikost balicku karet.
* @param velikost balicku karet.
*/
void CardPack::setSize(int s) {
size = s;
}
/**
* @brief vycisti balicek karet tak, aby byl prazdny.
*/
void CardPack::clearCardPack() {
int CardPackSize = Cards.size();
for (int i = 0; i < CardPackSize; i++) {
delete Cards.back();
}
Cards.clear();
}
/**
* @brief vrati velikost balicku karet.
* @return velikost balicku karet - 12 nebo 24.
*/
int CardPack::getSize() {
return size;
}
/**
* @brief vrati kartu na vrcholu balicku.
* @return karta.
*/
Card CardPack::GetCard() {
Card temp = *Cards.back();
Cards.pop_back();
return temp;
}
/**
* @brief vraci vektor karet.
* @return vektor karet.
*/
vector<Card *> CardPack::getCardsVector() {
return Cards;
}
/**
* @brief zamicha balicek karet.
*/
void CardPack::ShufflePack() {
random_shuffle(Cards.begin(), Cards.end());
}
<file_sep>/controller.h
/**
* Autori: <NAME>, xporiz03
* Modul: controller
* Popis modulu: Tento modul implementuje reseni tahu a akci souvisejicich s hraci plochou. Slouzi zaroven jako rozhrani pro akce, ktere on sam neimplementuje.
*/
#ifndef CONTROLLER
#define CONTrOLLER
#include <vector>
#include <sstream>
#include "map.h"
#include "cardpack.h"
#include "log.h"
/**
* @brief Struktura obsahujici BOOL hodnoty pohybu, zda se tento pohyb da uskutecnit nebo ne
*/
struct sMove{
bool UP = 0;
bool LEFT = 0;
bool DOWN = 0;
bool RIGHT = 0;
};
/**
* @brief Enum vypisujici mozne pohyby
*/
enum tMove{ UP = 1, LEFT, DOWN, RIGHT };
/**
* @brief Trida resici tahy hracu a jejich provadene akce na hraci plose
*/
class Controller{
private:
bool gameEnd = 0;
Logger* cLog;
bool bUndo = 0;
public:
Controller();
bool ValidMove(tMove move, Player* pToMove, Map* pMap);
sMove GetValidMoves(char type, int rotation);
bool MakeMove(tMove move, Player* pToMove, Map* pMap);
void EndTurn(Map* pMap);
bool GameEnded();
void EndGame();
Logger* getLog();
bool shiftBoard(int x, int y, Map* pMap);
bool undoTurn(Map* pMap);
void setUndo(bool undo);
bool getUndo();
void rotateField(Map* pMap);
};
#endif
<file_sep>/game_gui.h
/**
Autori: <NAME>, xdibda00
Modul: GameGUI
Popis modulu: Tento modul implementuje hlavni rozhrani pro
GUI verzi hry - graficke vykresleni.
*/
#ifndef GAME
#define GAME
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsTextItem>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsRectItem>
#include <QWidget>
#include <QString>
#include <QImage>
#include <QVector>
#include <QCheckBox>
#include <QFont>
#include <QBrush>
#include <QSignalMapper>
#include <QKeyEvent>
#include "controller.h"
/** Generovani objektu do mapy. */
/**
* @brief generateFigure - funkce vygeneruje figurku a vlozi ji do mapy na dane policko
* @param scene - scena, na jakou se ma figurka vlozit
* @param xpos - vodorovna souradnice policka
* @param ypos - svisla souradnice policka
* @param color - barva figurky
*/
void generateFigure(QGraphicsScene *scene, int xpos, int ypos, int color);
/**
* @brief vygeneruje policko a sipky na mackani.
* @param scena na kterou se ma generovat.
* @param policko, ktere se ma vygenerovat.
*/
void generateField(QGraphicsScene *scene, MapField* field);
/** Grafika k figurkam. */
/**
* @brief vraci grafiku k figurky.
* @param barva figurky.
* @return vraci adresu k figurce.
*/
QString getFigureReferenceBig(int color);
/**
* @brief vraci grafiku figurky.
* @param barva figurky.
* @return adresa grafiky figurky.
*/
QString getFigureReference(int color);
/**
* @brief vraci malou figurku v menu.
* @param barva figurky.
* @return vraci adresu zmensene figurky.
*/
QString getFigureReferenceMenu(int color);
/** Grafika k pokladum. */
/**
* @brief vraci obrazek pokladu.
* @param id pokladu.
* @return adresa grafiky pokladu.
*/
QString getTreasureIcon(int treasureID);
/**
* @brief vraci grafiku velkeho pokladu do menu.
* @param id pokladu.
* @return vraci grafiku pokladu do menu.
*/
QString getTreasureBig(int treasureID);
/** Grafika k cestam. */
/**
* @brief vraci grafiku cesty
* @param znak cesty - T, L, I.
* @return vraci adresu grafiky.
*/
QString getPathReference(char c);
/**
* @brief trida klikajicich tlacitek.
*/
class Button : public QWidget, public QGraphicsPixmapItem {
Q_OBJECT
private:
int ident;
QString *noHover;
QString *Hover;
QString *click;
QString *pom;
int getID();
protected:
QString *hover;
QString *nohover;
private slots:
void rotate(QGraphicsPixmapItem *missing_puzzle);
void hoverClicked();
void hoverUnclicked();
public:
Button(QString name, QString hov, int x, unsigned int dx, int y, unsigned int dy, int offset, int rotation, QGraphicsScene *scene);
Button(QString name, int x = 0, int y = 0, QGraphicsScene *scene = 0, QString hov = 0, QString clickS = 0, int identf = 0, QWidget *parent = 0);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
void setDefault();
signals:
void clicked();
};
/**
* @brief trida figurek.
*/
class Figure : public QWidget, public QGraphicsPixmapItem {
Q_OBJECT
private:
int color;
QGraphicsPixmapItem *item;
public:
int getColor();
Figure(int c);
QGraphicsPixmapItem *getItem();
};
/**
* @brief trida klikajicich sipek.
*/
class Arrow : public Button, public MapField {
Q_OBJECT
public:
Arrow(QString name, QString hover, int rot, int x, unsigned int dx, int y, unsigned int dy, int offset, QGraphicsScene *scene) : Button(name, hover, x, dx, y, dy, offset, rot, scene) {};
signals:
void arrowClicked(int x);
};
/**
* @brief trida grafiky, ktera je potrebna pro vykresleni.
*/
class QtGraphics {
private:
int offset;
int figureX;
int figureY;
QVector<Arrow *> arrows;
public:
QVector<Arrow *> *getArrows();
void actualizeOffset();
int getOffset();
};
/**
* @brief bocni panel hrace.
*/
class SidePanel : public QGraphicsView {
public:
void resetValues();
void setValues();
QGraphicsPixmapItem *playersIcon;
QGraphicsPixmapItem *playersItem;
QGraphicsTextItem *item;
};
/**
* @brief hlavni trida zastupujici celou logiku hry.
*/
class Game : public QGraphicsView {
Q_OBJECT // Pro praci se slotama;
private:
bool gameStarted;
SidePanel* panel; // bocni informacni panel;
MapField* missingPiece;
//Controller* mapControl;
QGraphicsScene *scene;
QGraphicsScene *authors;
QGraphicsScene *newgame;
QGraphicsScene *endgame;
vector<Figure *> figuresVector;
public:
Game();
MapField* getMissingPiece();
QString getFigureReferenceBig(int color);
SidePanel *getPanel();
QGraphicsScene *gameScene;
void keyPressEvent(QKeyEvent *event);
vector<Figure *> *getFiguresVector();
void setMissingPiece(MapField* field);
bool isGameStarted();
void makeDesk();
void displayMenu();
void writeSideway();
void drawGUI();
void moveFigure(int color, MapField *indexedMapField);
void drawPanel(int x, int y, int width, int height, QColor color, double opacity, QGraphicsScene *scene);
void refreshMissingPiece();
void gameEndedScreen();
public slots:
void saveGame();
void loadGame();
void nextPlayer();
void choose();
void start();
void ret_mm();
void ret_game();
void authors_view();
void shiftB(int number);
void rotate();
void stepBack();
};
#endif // GAME
<file_sep>/cardpack.h
/**
* Autori: <NAME>, xdibda00 + <NAME>, xporiz03
* Modul: CardPack
* Popis modulu: Tento modul implementuje praci s kartami a balickem karet.
*/
#ifndef CARDPACK
#define CARDPACK
#include <vector>
#include <algorithm>
using namespace std;
/**
* @brief trida popisujici jednotlivou kartu.
*/
class Card{
private:
int treasure;
public:
Card();
Card(int type);
int getTreasure();
};
/**
* @brief trida popisujici cely balicek karet.
*/
class CardPack{
private:
int size;
vector<Card *>Cards;
public:
int getSize();
void ShufflePack();
void AppendPack();
void setSize(int s);
void clearCardPack();
Card GetCard();
vector<Card *> getCardsVector();
};
#endif
<file_sep>/game_gui_slots.cpp
/**
Autori: <NAME>, xdibda00
Modul: GameGUI - Slots
Popis modulu: Tento modul implementuje hlavni rozhrani pro
GUI verzi hry - graficke vykresleni.
Upresneni specializace modulu: Tato cast se stara o logiku
slotu, na ktere se odkazuje pri stisknuti klikacich tlacitek.
*/
#include "game_gui.h"
extern Map* fieldsMap;
extern QtGraphics* graphics;
extern Game* game;
extern Controller *mapControl;
/**
* @brief slouzi k rotaci policka v informacnim panelu vpravo.
* @param toto policko.
*/
void Button::rotate(QGraphicsPixmapItem *missing_puzzle) {
missing_puzzle->setRotation(90);
}
/**
* @brief slouzi k odkliknuti tlacitko, pokud bylo kliknuto jine.
*/
void Button::hoverUnclicked() {
setPixmap(QPixmap(QString(*nohover)));
*noHover = *nohover;
*Hover = *hover;
}
/**
* @brief slouzi ke kliknuti tlacitka.
*/
void Button::hoverClicked() {
setPixmap(QPixmap(QString(*click)));
if(this->getID() == 2 or this->getID() == 3 or this->getID() == 4) {
fieldsMap->setPlayers(this->getID());
}
else if(this->getID() == 12 or this->getID() == 24) {
if (fieldsMap->getSize() != 5) {
fieldsMap->setCardsSet(this->getID());
}
else {
fieldsMap->setCardsSet(12);
}
}
else {
fieldsMap->setSize(this->getID());
graphics->actualizeOffset();
}
*noHover = *click;
*Hover = *click;
}
/**
* @brief rotace policko, ktere se ma vlozit - je ulozeno v informacnim panelu.
*/
void Game::rotate() {
mapControl->rotateField(fieldsMap);
refreshMissingPiece();
}
/**
* @brief o jeden krok zpet - undo.
*/
void Game::stepBack() {
mapControl->undoTurn(fieldsMap);
makeDesk();
}
/**
* @brief vrati se do menu.
*/
void Game::ret_mm() {
setScene(scene);
displayMenu();
}
/**
* @brief hrac se vraci do hry - prepne se na scenu hry.
*/
void Game::ret_game() {
setScene(gameScene);
setBackgroundBrush(QBrush(QImage(":/bg/img/bg/gamebg.jpg")));
}
/**
* @brief prepne na scenu autoru.
*/
void Game::authors_view() {
setScene(authors);
setBackgroundBrush(QBrush(QImage(":/bg/img/bg/creditsbg.jpg")));
}
/**
* @brief slot pro ulozeni hry.
*/
void Game::saveGame() {
if (isGameStarted()) {
mapControl->getLog()->saveGame(*fieldsMap);
}
}
/**
* @brief slouzi k posunuti mapy - vlozeni kamene do mapy.
* @param cislo pozice kam se vklada - x* size + y.
*/
void Game::shiftB(int number) {
if(fieldsMap->getShiftedState() != 1) {
int x = 0, y = 0;
for(int i = 0; i <= fieldsMap->getSize(); i++) {
if (number < i * fieldsMap->getSize()) {
x = i - 1;
y = number - x * fieldsMap->getSize();
break;
}
}
if(mapControl->shiftBoard(x, y, fieldsMap))
fieldsMap->changeShiftedState(1);
makeDesk();
}
}
/**
* @brief slot pro nacteni hry.
*/
void Game::loadGame() {
delete fieldsMap;
fieldsMap = new Map();
delete mapControl;
mapControl = new Controller();
delete graphics;
graphics = new QtGraphics();
setScene(gameScene);
gameScene->clear();
setBackgroundBrush(QBrush(QImage(":/bg/img/bg/gamebg.jpg")));
mapControl->getLog()->loadGame(fieldsMap);
graphics->actualizeOffset();
gameStarted = true;
makeDesk();
writeSideway();
panel->setValues();
refreshMissingPiece();
Button *endturn = new Button(QString(":/buttons/img/buttons/endturnbutton.png"), 600, 425, gameScene, ":/buttons/img/buttons/endturnbuttonhover.png");
Button *stepback = new Button(QString(":/buttons/img/buttons/sbbutton.png"), 600, 480, gameScene, ":/buttons/img/buttons/sbbuttonhover.png");
Button *mainmenu = new Button(QString(":/buttons/img/buttons/mmbutton.png"), 600, 535, gameScene, ":/buttons/img/buttons/mmbuttonhover.png");
Button *rotate = new Button(":/other/img/other/rotate.png", 702, 190, gameScene, ":/other/img/other/rotatehover.png", ":/other/img/other/rotate.png", 12);
connect(mainmenu, SIGNAL(clicked()), this, SLOT(ret_mm()));
connect(rotate, SIGNAL(clicked()), game, SLOT(rotate()));
connect(endturn, SIGNAL(clicked()), game, SLOT(nextPlayer()));
}
/**
* @brief prepne na dalsiho hrace po ukonceni tahu.
*/
void Game::nextPlayer() {
mapControl->EndTurn(fieldsMap);
panel->resetValues();
panel->setValues();
}
/**
* @brief spusti novou hru.
*/
void Game::start() {
fieldsMap->setLastX(-1);
fieldsMap->setLastY(-1);
mapControl = new Controller();
setScene(gameScene);
gameScene->clear();
setBackgroundBrush(QBrush(QImage(":/bg/img/bg/gamebg.jpg")));
fieldsMap->changeShiftedState(false);
fieldsMap->createMap();
writeSideway();
makeDesk();
Button *endturn = new Button(QString(":/buttons/img/buttons/endturnbutton.png"), 600, 425, gameScene, ":/buttons/img/buttons/endturnbuttonhover.png");
Button *stepback = new Button(QString(":/buttons/img/buttons/sbbutton.png"), 600, 480, gameScene, ":/buttons/img/buttons/sbbuttonhover.png");
Button *mainmenu = new Button(QString(":/buttons/img/buttons/mmbutton.png"), 600, 535, gameScene, ":/buttons/img/buttons/mmbuttonhover.png");
Button *rotate = new Button(":/other/img/other/rotate.png", 702, 190, gameScene, ":/other/img/other/rotatehover.png", ":/other/img/other/rotate.png", 12);
connect(mainmenu, SIGNAL(clicked()), this, SLOT(ret_mm()));
connect(stepback, SIGNAL(clicked()), this, SLOT(stepBack()));
connect(rotate, SIGNAL(clicked()), game, SLOT(rotate()));
connect(endturn, SIGNAL(clicked()), game, SLOT(nextPlayer()));
gameStarted = true;
panel->setValues();
fieldsMap->getPlayers()->getPList().clear();
}
/**
* @brief prepne na scenu vyberu parametru pro novou hru.
*/
void Game::choose() {
delete fieldsMap;
fieldsMap = new Map();
delete graphics;
graphics = new QtGraphics();
newgame->clear();
setScene(newgame);
setBackgroundBrush(QBrush(QImage(":/bg/img/bg/bgchoose.jpg")));
Button *littleset = new Button(":/buttons/img/buttons/12.png", 70, 380, newgame, ":/buttons/img/buttons/12hover.png", ":/buttons/img/buttons/12clicked.png", 12);
Button *largeset = new Button(":/buttons/img/buttons/24.png", 225, 380, newgame, ":/buttons/img/buttons/24hover.png", ":/buttons/img/buttons/24clicked.png", 24);
Button *twoplayers = new Button(":/buttons/img/buttons/2.png", 70, 70, newgame, ":/buttons/img/buttons/2hover.png", ":/buttons/img/buttons/2clicked.png", 2);
Button *threeplayers = new Button(":/buttons/img/buttons/3.png", 225, 70, newgame, ":/buttons/img/buttons/3hover.png", ":/buttons/img/buttons/3clicked.png", 3);
Button *fourplayers = new Button(":/buttons/img/buttons/4.png", 380, 70, newgame, ":/buttons/img/buttons/4hover.png", ":/buttons/img/buttons/4clicked.png", 4);
Button *sizefive = new Button(":/buttons/img/buttons/55.png", 70, 220, newgame, ":/buttons/img/buttons/55hover.png", ":/buttons/img/buttons/55clicked.png", 5);
Button *sizeseven = new Button(":/buttons/img/buttons/77.png", 225, 220, newgame, ":/buttons/img/buttons/77hover.png", ":/buttons/img/buttons/77clicked.png", 7);
Button *sizenine = new Button(":/buttons/img/buttons/99.png", 380, 220, newgame, ":/buttons/img/buttons/99hover.png", ":/buttons/img/buttons/99clicked.png", 9);
Button *sizeeleven = new Button(":/buttons/img/buttons/1111.png", 535, 220, newgame, ":/buttons/img/buttons/1111hover.png", ":/buttons/img/buttons/1111clicked.png", 11);
Button *ok = new Button(":/buttons/img/buttons/okbutton.png", 204, 510, newgame, ":/buttons/img/buttons/okbuttonhover.png");
Button *cancel = new Button(":/buttons/img/buttons/cancelbutton.png", 400, 510, newgame, ":/buttons/img/buttons/cancelbuttonhover.png");
littleset->setDefault();
twoplayers->setDefault();
sizeseven->setDefault();
connect(ok, SIGNAL(clicked()), this, SLOT(start()));
connect(cancel, SIGNAL(clicked()), this, SLOT(ret_mm()));
connect(littleset, SIGNAL(clicked()), littleset, SLOT(hoverClicked()));
connect(littleset, SIGNAL(clicked()), largeset, SLOT(hoverUnclicked()));
connect(largeset, SIGNAL(clicked()), largeset, SLOT(hoverClicked()));
connect(largeset, SIGNAL(clicked()), littleset, SLOT(hoverUnclicked()));
connect(twoplayers, SIGNAL(clicked()), twoplayers, SLOT(hoverClicked()));
connect(twoplayers, SIGNAL(clicked()), threeplayers, SLOT(hoverUnclicked()));
connect(twoplayers, SIGNAL(clicked()), fourplayers, SLOT(hoverUnclicked()));
connect(threeplayers, SIGNAL(clicked()), twoplayers, SLOT(hoverUnclicked()));
connect(threeplayers, SIGNAL(clicked()), threeplayers, SLOT(hoverClicked()));
connect(threeplayers, SIGNAL(clicked()), fourplayers, SLOT(hoverUnclicked()));
connect(fourplayers, SIGNAL(clicked()), twoplayers, SLOT(hoverUnclicked()));
connect(fourplayers, SIGNAL(clicked()), threeplayers, SLOT(hoverUnclicked()));
connect(fourplayers, SIGNAL(clicked()), fourplayers, SLOT(hoverClicked()));
connect(sizefive, SIGNAL(clicked()), sizefive, SLOT(hoverClicked()));
connect(sizefive, SIGNAL(clicked()), sizeseven, SLOT(hoverUnclicked()));
connect(sizefive, SIGNAL(clicked()), sizenine, SLOT(hoverUnclicked()));
connect(sizefive, SIGNAL(clicked()), sizeeleven, SLOT(hoverUnclicked()));
connect(sizeseven, SIGNAL(clicked()), sizefive, SLOT(hoverUnclicked()));
connect(sizeseven, SIGNAL(clicked()), sizeseven, SLOT(hoverClicked()));
connect(sizeseven, SIGNAL(clicked()), sizenine, SLOT(hoverUnclicked()));
connect(sizeseven, SIGNAL(clicked()), sizeeleven, SLOT(hoverUnclicked()));
connect(sizenine, SIGNAL(clicked()), sizefive, SLOT(hoverUnclicked()));
connect(sizenine, SIGNAL(clicked()), sizeseven, SLOT(hoverUnclicked()));
connect(sizenine, SIGNAL(clicked()), sizenine, SLOT(hoverClicked()));
connect(sizenine, SIGNAL(clicked()), sizeeleven, SLOT(hoverUnclicked()));
connect(sizeeleven, SIGNAL(clicked()), sizefive, SLOT(hoverUnclicked()));
connect(sizeeleven, SIGNAL(clicked()), sizeseven, SLOT(hoverUnclicked()));
connect(sizeeleven, SIGNAL(clicked()), sizenine, SLOT(hoverUnclicked()));
connect(sizeeleven, SIGNAL(clicked()), sizeeleven, SLOT(hoverClicked()));
}
<file_sep>/game_gui_button.cpp
/**
Autori: <NAME>, xdibda00
Modul: GameGUI - Button
Popis modulu: Tento modul implementuje hlavni rozhrani pro
GUI verzi hry - graficke vykresleni.
Upresneni specializace modulu: Tato cast se stara o logiku
a grafiku klikaciho tlacitka, ktere je pouzito u sipek a
klikacich tlacitek.
*/
#include "game_gui.h"
#include <vector>
extern Map* fieldsMap;
extern QtGraphics* graphics;
/**
* @brief emituje se akce clicked() pokud bylo kliknuto na mysi.
* @param akce kliknuti.
*/
void Button::mousePressEvent(QGraphicsSceneMouseEvent *event) {
emit clicked();
}
/**
* @brief pokud bylo najeto mysi na tlacitko.
* @param akce prejeti.
*/
void Button::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
setPixmap(QPixmap(*Hover));
}
/**
* @brief pokud bylo z tlacitko sjeto pryc.
* @param akce odjeti pryc.
*/
void Button::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
setPixmap(QPixmap(*noHover));
}
/**
* @brief nastavi defaultni hodnoty a grafiku k nim pro novou hru (vyberova obrazovka).
*/
void Button::setDefault() {
setPixmap(QPixmap(QString(*click)));
*noHover = *click;
*Hover = *click;
if(this->getID() == 2 or this->getID() == 3 or this->getID() == 4) {
fieldsMap->setPlayers(this->getID());
}
else if(this->getID() == 12 or this->getID() == 24) {
fieldsMap->setCardsSet(this->getID());
}
else {
fieldsMap->setSize(this->getID());
graphics->actualizeOffset();
}
}
/**
* @brief vraci typ tlacitka - jeho ID cislo.
* @return toto cislo.
*/
int Button::getID() {
return this->ident;
}
/**
* @brief konstruktor pro klikaci tlacitko.
* @param puvodni grafika tlacitka.
* @param grafika po najeti na tlacitko.
* @param vodorovna souradnice kam se ma vlozit.
* @param offset ve vodorovne souradnici.
* @param svisla souradnice, kam se ma vlozit.
* @param offset ve svisle souradnici.
* @param celkovy offset.
* @param rotace tlacitka.
* @param scena na jakou se vlozi.
*/
Button::Button(QString name, QString hov, int x, unsigned int dx, int y, unsigned int dy, int offset, int rotation, QGraphicsScene *scene) {
setPos(300 + 40 * x - offset + dx, 300 + 40 * y - offset + dy);
setPixmap(QPixmap(name));
setTransformOriginPoint(5,19);
setRotation(rotation * 90);
setAcceptHoverEvents(true);
scene->addItem(this);
setFlag(QGraphicsItem::ItemIsFocusable);
noHover = new QString(name);
Hover = new QString(hov);
pom = new QString();
}
/**
* @brief sekundarni konstruktor tlacitka.
* @param puvodni grafika tlacitka.
* @param vodorovna souradnice tlacitka.
* @param svisla souradnice tlacitka.
* @param scena, kam se ma tlacitko vlozit.
* @param grafika, pokud na tlacitko nekdo najede.
* @param grafika, pokud na tlacitko nekdo klikne.
* @param id tlacitka.
* @param parent.
*/
Button::Button(QString name, int x, int y, QGraphicsScene *scene, QString hov, QString clickS, int identf, QWidget *parent) : QWidget(parent), QGraphicsPixmapItem() {
setPos(x, y);
setPixmap(QPixmap(name));
setAcceptHoverEvents(true);
scene->addItem(this);
ident = identf;
nohover = new QString(name);
hover = new QString(hov);
noHover = new QString(name);
Hover = new QString(hov);
click = new QString(clickS);
pom = new QString();
}
<file_sep>/controller.cpp
/**
* Autori: <NAME>, xporiz03
* Modul: controller
* Popis modulu: Tento modul implementuje reseni tahu a akci souvisejicich s hraci plochou. Slouzi zaroven jako rozhrani pro akce, ktere on sam neimplementuje.
*/
#include "controller.h"
/**
* @brief Funkce resi na ktere strany se da z policka jit
* @param Tvar kamene
* @param Rotace kamene
* @return Struktura boolu, ktera udava na ktere strany je mozne z policka jit pomoci TRUE
*/
sMove Controller::GetValidMoves(char type, int rotation)
{
sMove validMove;
validMove.UP = 0;
validMove.LEFT = 0;
validMove.DOWN = 0;
validMove.RIGHT = 0;
switch (type){
case 'L':
switch (rotation)
{
case 0:
validMove.LEFT = 1;
validMove.DOWN = 1;
break;
case 1:
validMove.LEFT = 1;
validMove.UP = 1;
break;
case 2:
validMove.UP = 1;
validMove.RIGHT = 1;
break;
case 3:
validMove.RIGHT = 1;
validMove.DOWN = 1;
break;
}
break;
case 'T':
switch (rotation)
{
case 0:
validMove.LEFT = 1;
validMove.DOWN = 1;
validMove.RIGHT = 1;
break;
case 1:
validMove.LEFT = 1;
validMove.UP = 1;
validMove.DOWN = 1;
break;
case 2:
validMove.UP = 1;
validMove.RIGHT = 1;
validMove.LEFT = 1;
break;
case 3:
validMove.UP = 1;
validMove.RIGHT = 1;
validMove.DOWN = 1;
break;
}
break;
case 'I':
switch (rotation)
{
case 0:
validMove.LEFT = 1;
validMove.RIGHT = 1;
break;
case 1:
validMove.DOWN = 1;
validMove.UP = 1;
break;
case 2:
validMove.LEFT = 1;
validMove.RIGHT = 1;
break;
case 3:
validMove.DOWN = 1;
validMove.UP = 1;
break;
}
break;
default:
fprintf(stderr, "CLI ERROR: Unrecognized stone shape.\n");
break;
}
return validMove;
}
/**
* @brief Funkce resi zda je pozadovany tah validni a je mozne ho provest
* @param Pohyb ktery hrac chce vykonat
* @param Hrac ktery chce tahnout
* @param Hraci plocha na ktere se ma tah uskutecnit
* @return TRUE pokud se tento tah da uskutecnit
*/
bool Controller::ValidMove(tMove move, Player* pToMove, Map* pMap)
{
MapField* field;
sMove validMoveFrom;
sMove validMoveTo;
char c;
int rot;
int x = pToMove->getXPos();
int y = pToMove->getYPos();
field = pMap->GetField(x, y);
int size = pMap->getSize();
c = field->getShape();
rot = field->getRotation();
validMoveFrom = GetValidMoves(c, rot);
if (!((y == 0 && move == UP) || (x == 0 && move == LEFT) || (x == size - 1 && move == RIGHT) || (y == size - 1 && move == DOWN)))
{
switch (move)
{
case UP:
field = pMap->GetField(x, y - 1);
break;
case LEFT:
field = pMap->GetField(x - 1, y);
break;
case DOWN:
field = pMap->GetField(x, y + 1);
break;
case RIGHT:
field = pMap->GetField(x + 1, y);
break;
}
c = field->getShape();
rot = field->getRotation();
validMoveTo = GetValidMoves(c, rot);
switch (move)
{
case UP:
if (validMoveFrom.UP & validMoveTo.DOWN)
return 1;
break;
case LEFT:
if (validMoveFrom.LEFT & validMoveTo.RIGHT)
return 1;
break;
case DOWN:
if (validMoveFrom.DOWN & validMoveTo.UP)
return 1;
break;
case RIGHT:
if (validMoveFrom.RIGHT & validMoveTo.LEFT)
return 1;
break;
}
}
return 0;
}
/**
* @brief Funkce resi cely tah hrace a reaguje na nemoznost tah provest
* @param Pohyb ktery hrac chce vykonat
* @param Hrac ktery chce tahnout
* @param Hraci plocha na ktere se ma tah uskutecnit
* @return TRUE pokud se tento tah dal provest a byl proveden
*/
bool Controller::MakeMove(tMove move, Player* pToMove, Map* pMap)
{
int x, y;
MapField* newField;
stringstream ss;
string temp;
//< Pokud se hrac dostal mimo tah na policko na kterem je poklad ktery sbira
if (bUndo == 0 && (pToMove->getPlayersCard())->getTreasure() == pMap->GetField(pToMove->getXPos(), pToMove->getYPos())->getTreasure())
{
ss << pMap->GetField(pToMove->getXPos(), pToMove->getYPos())->getTreasure();
ss >> temp;
temp = "PICK:" + temp;
if (!getUndo())
cLog->saveTurn(temp);
ss.clear();
temp.clear();
pToMove->AddScore(1);
pMap->GetField(pToMove->getXPos(), pToMove->getYPos())->setTreasure(0);
pToMove->getAnotherCard();
if (pToMove->getScore() == (pMap->getCardsSet() / (pMap->getPlayers())->getNumber()))
{
EndGame();
return 1;
}
setUndo(1);
EndTurn(pMap);
return 1;
}
//< Pokud na policku na kterem prave je neni poklad ktery sbira
if (ValidMove(move, pToMove, pMap))
{
ss << move;
ss >> temp;
temp = "MOVE:" + temp;
if (!getUndo())
{
cLog->incTurnNumber();
cLog->saveTurn(temp);
}
ss.clear();
temp.clear();
x = pToMove->getXPos();
y = pToMove->getYPos();
switch (move)
{
case UP:
pToMove->setPos(x, y - 1);
y -= 1;
break;
case LEFT:
pToMove->setPos(x - 1, y);
x -= 1;
break;
case DOWN:
pToMove->setPos(x, y + 1);
y += 1;
break;
case RIGHT:
pToMove->setPos(x + 1, y);
x += 1;
break;
}
newField = pMap->GetField(x, y);
if ((pToMove->getPlayersCard())->getTreasure() == newField->getTreasure())
{
ss << newField->getTreasure();
ss >> temp;
temp = "PICK:" + temp;
if (!getUndo())
cLog->saveTurn(temp);
ss.clear();
temp.clear();
pToMove->AddScore(1);
newField->setTreasure(0);
pToMove->getAnotherCard();
if (pToMove->getScore() == (pMap->getCardsSet() / (pMap->getPlayers())->getNumber()))
{
EndGame();
return 1;
}
setUndo(1);
EndTurn(pMap);
}
return 1;
}
else
return 0;
return 0;
}
/**
* @brief Funkce resi ukonceni tahu hrace
* @param Hraci plocha na ktere hrac hraje
*/
void Controller::EndTurn(Map* pMap)
{
if (!getUndo())
cLog->saveTurn("END");
else
setUndo(0);
cLog->incTurnNumber();
pMap->changeShiftedState(0);
pMap->NextTurn();
}
/**
* @brief Funkce resi ukonceni hry v dusledku naplneni pozadovaneho poctu bodu
*/
void Controller::EndGame()
{
gameEnd = 1;
}
/**
* @brief Funkce pro zjednoduseni kontroly konce hry
* @return TRUE pokud je hra u konce a mela by se zobrazit konecna obrazovka
*/
bool Controller::GameEnded()
{
if (gameEnd)
return 1;
return 0;
}
/**
* @brief Konstruktor Controlleru inicializuje Logger pro ukladani tahu
*/
Controller::Controller()
{
cLog = new Logger;
}
/**
* @brief Funkce vraci ukazatel na logger, aby se mohlo pracovat s jeho vektorem tahu
*/
Logger* Controller::getLog()
{
return cLog;
}
/**
* @brief Funkce resici vsunuti volneho pole do hraci plochy
* @param X souradnice pro vlozeni kamene
* @param Y souradnice pro vlozeni kamene
* @param Hraci plocha na ktere se ma vlozeni provest
* @return TRUE pokud se vlozeni dalo provest
*/
bool Controller::shiftBoard(int x, int y, Map* pMap)
{
if (pMap->ShiftBoard(x, y, bUndo))
{
stringstream ss;
ss << x << ":" << y << ":" << pMap->getLastX() << ":" << pMap->getLastY();
string temp;
ss >> temp;
temp = "SHIFT:" + temp;
if (!getUndo())
{
cLog->incTurnNumber();
cLog->saveTurn(temp);
}
ss.clear();
temp.clear();
return 1;
}
else
return 0;
}
/**
* @brief Funkce resici navraceni tahu zpet
* @param Hraci plocha na ktere se ma vraceni tahu provest
* @return TRUE pokud jde tah jeste vracet, FALSE pokud jsme na zacatku hry
*/
bool Controller::undoTurn(Map* pMap)
{
if (cLog->getTurnNumber() == 0)
return 0;
setUndo(1);
cLog->decTurnNumber();
Player* pToPlay = pMap->GetActivePlayer();
string command;
string sTemp;
Card* tempCard;
MapField* tempField;
int iTemp;
command = cLog->getTurn();
if (command.find("MOVE") != string::npos)
{
//Case UP
if (command.find("1") != string::npos)
{
MakeMove(DOWN, pToPlay, pMap);
}
//Case LEFT
else if (command.find("2") != string::npos)
{
MakeMove(RIGHT, pToPlay, pMap);
}
//Case DOWN
else if (command.find("3") != string::npos)
{
MakeMove(UP, pToPlay, pMap);
}
//Case RIGHT
else if (command.find("4") != string::npos)
{
MakeMove(LEFT, pToPlay, pMap);
}
}
if (command.find("SHIFT") != string::npos)
{
int x, y, lx, ly;
int max = pMap->getSize() - 1;
command = command.substr(command.find(":") + 1, string::npos);
//X
sTemp = command.substr(0, command.find(":"));
command = command.substr(command.find(":") + 1, string::npos);
x = stoi(sTemp);
//Y
sTemp = command.substr(0, command.find(":"));
command = command.substr(command.find(":") + 1, string::npos);
y = stoi(sTemp);
//LASTX
sTemp = command.substr(0, command.find(":"));
command = command.substr(command.find(":") + 1, string::npos);
lx = stoi(sTemp);
//LASTY
sTemp = command.substr(0, command.find(":"));
command = command.substr(command.find(":") + 1, string::npos);
ly = stoi(sTemp);
pMap->setLastX(lx);
pMap->setLastY(ly);
if (x == 0 || x == max)
{
shiftBoard(max - x, y, pMap);
}
else if (y == 0 || y == max)
{
shiftBoard(x, max - y, pMap);
}
}
if (command.find("END") != string::npos)
{
pMap->changeShiftedState(1);
pMap->PreviusTurn();
}
if (command.find("PICK") != string::npos)
{
//Return turn
pMap->changeShiftedState(1);
pMap->PreviusTurn();
pToPlay = pMap->GetActivePlayer();
//Prepare
command = command.substr(command.find(":") + 1, string::npos);
iTemp = stoi(command);
//Treasure type
tempCard = new Card(iTemp);
pToPlay->giveCard(tempCard);
tempField = pMap->GetField(pToPlay->getXPos(), pToPlay->getYPos());
tempField->setTreasure(iTemp);
pToPlay->SetScore(pToPlay->getScore() - 1);
undoTurn(pMap);
}
if (command.find("ROT") != string::npos)
{
pMap->GetField(pMap->getSize(), 0)->fieldCounterRotate();
}
setUndo(0);
return 1;
}
/**
* @brief Funkce meni stav undo flagy
* @param Nastavi undo 1/0
*/
void Controller::setUndo(bool undo)
{
bUndo = undo;
}
/**
* @brief Funkce vraci stav undo flagy
* @return Stav undo flagy 1/0
*/
bool Controller::getUndo()
{
return bUndo;
}
/**
* @brief Funkce spravujici rotaci volneho kamenu
* @param Mapa na ktere chceme kamen orotovat
*/
void Controller::rotateField(Map* pMap)
{
pMap->GetField(pMap->getSize(), 0)->fieldRotate();
cLog->saveTurn("ROT");
cLog->incTurnNumber();
}
| 4166fb887311941cb3e721ae3c2f0d882f20bd77 | [
"C++"
] | 18 | C++ | xdibda/Labyrint | e441201745434cb556d0d213759f7e53d0a450fb | 4f873692e737fd355367aa20eedf51f799e13eb9 |
refs/heads/master | <file_sep>import os
import numpy
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
dataset_name = 'dataset.txt'
dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), dataset_name)
test_size = .3
lines = [l.strip() for l in open(dataset_path)]
sentences = [l.split('\t')[0] for l in lines]
labels = [l.split('\t')[1] for l in lines]
cvectorizer = CountVectorizer()
X = cvectorizer.fit_transform(sentences)
print("The input [%s] file has %d observations with %d features" % (dataset_name, X.shape[0], X.shape[1]))
x_train, x_test, y_train, y_test = train_test_split(X, labels, test_size=test_size, random_state=10)
## Guassian naive bayes classifier ##
gnb_clf = GaussianNB()
gnb_clf.fit(x_train.toarray(), y_train)
gnb_pred_y = gnb_clf.predict(x_test.toarray())
print("Accuracy Score for test size of %.1f" % test_size)
print("Gaussian Naive Bayes is: %f" % accuracy_score(y_pred=gnb_pred_y, y_true=y_test))
<file_sep># ngram, normalization, linear SVM
import os
import numpy
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import normalize
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
dataset_name = 'dataset.txt'
dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), dataset_name)
test_size = .3
lines = [l.strip() for l in open(dataset_path)]
sentences = [l.split('\t')[0] for l in lines]
labels = [l.split('\t')[1] for l in lines]
cvectorizer = CountVectorizer(lowercase=True, ngram_range=(1, 2))
X = cvectorizer.fit_transform(sentences)
normalize(X)
print("The input [%s] file has %d observations with %d features" % (dataset_name, X.shape[0], X.shape[1]))
x_train, x_test, y_train, y_test = train_test_split(X, labels, test_size=test_size)
## Guassian naive bayes classifier ##
clf = GaussianNB()
clf.fit(x_train.toarray(), y_train)
pre_y = clf.predict(x_test.toarray())
print("Accuracy Score for test size of %.1f" % test_size)
print("Gaussian Naive Bayes: %f" % accuracy_score(y_pred=pre_y, y_true=y_test))
## Linear SVM ##
clf = GaussianNB()
clf.fit(x_train.toarray(), y_train)
pre_y = clf.predict(x_test)
print("Accuracy Score for test size of %.1f" % test_size)
print("Linear SVM: %f" % accuracy_score(y_pred=pre_y, y_true=y_test))<file_sep>import os
import numpy
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
dataset_name = 'dataset.txt'
dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), dataset_name)
test_size = .3
show_count = 50
lines = [l.strip() for l in open(dataset_path)]
sentences = [l.split('\t')[0] for l in lines]
labels = [l.split('\t')[1] for l in lines]
cvectorizer = CountVectorizer(ngram_range=(1, 4), lowercase=True)
X = cvectorizer.fit_transform(sentences)
vocabularies = cvectorizer.vocabulary_.keys()
cvectorizer = CountVectorizer(vocabulary=vocabularies, ngram_range=(1, 3), lowercase=True)
X = cvectorizer.fit_transform(sentences)
print("The input [%s] file has %d observations with %d features" % (dataset_name, X.shape[0], X.shape[1]))
x_train, x_test, y_train, y_test = train_test_split(X, labels, test_size=test_size, random_state=10)
clf = LinearSVC()
clf.fit(x_train, y_train)
w = clf.coef_[0]
wv = zip(w, vocabularies)
wv.sort()
print("Showing top %d positive words:" % show_count)
for line in wv[-show_count:]:
print("score: %.2f, [%s]" % (line[0], line[1]))
print("\nShowing top %d negative words:" % show_count)
for line in wv[:show_count]:
print("score: %.2f, [%s]" % (line[0], line[1]))
| edf283eb158c332d5f69804b21769d3e0c855ba3 | [
"Python"
] | 3 | Python | danny460/learn-ml | 3b88af764a149c7a8b36c22830d03706fe4b82c3 | 04300d3388f411b2364aa9183ff6794f17789e98 |
refs/heads/main | <repo_name>sulemartin87/barcode-scanner<file_sep>/readme.md
# Barcode Scanner app
## Brief
simple application for verifying a scanned input by a barcode scanner and inserting it into a sqlite database.
> checks for unique numbers and pops up an error if it exists
## built using bulma css for styling and electron for pretty much everything else.
NB : feel free to fork code and modify as you wish. <file_sep>/database.js
const sqlite3 = require('sqlite3').verbose();
//function for initializing the database
function newDatabase() {
let db = new sqlite3.Database('./database.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database database.');
});
db.serialize(() => {
// Queries scheduled here will be serialized.
db.run('CREATE TABLE tickets(ticket_number INTEGER PRIMARY KEY UNIQUE)');
// .run(`INSERT INTO tickets(ticket_number)
// VALUES('1'),
// ('2'),
// ('3')`)
// .each(`SELECT * FROM tickets`, (err, row) => {
// if (err) {
// throw err;
// }
// console.log(row.ticket_number);
// });
});
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Close the database connection.');
});
}
//function for entering a record
function insertData(number) {
if (isNaN(number)) {
openModal('Ticket is not valid');
} else {
let db = new sqlite3.Database('./database.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database database.');
});
db.serialize(() => {
db.run(`INSERT INTO tickets(ticket_number)
VALUES('${number}')`, (err, success) => {
if (err) {
if ((err.message).match(/UNIQUE constraint/gi).length > 0) {
openModal('Barcode has already been scanned');
} else {
openModal(err.message);
}
} else {
alert("successfully added");
}
});
});
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Close the database connection.');
});
}
} | 5da96539315ae76b7e707101784b5b5da2e67e04 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | sulemartin87/barcode-scanner | 3aa3c6106f005c1992e82ae38eb01218352e66fd | f9a1fcd622fae118552857326e0ef5bed8a3480a |
refs/heads/main | <repo_name>aanyas72/react-memory-game<file_sep>/src/components/MemoryGame.js
import React, { useEffect, useState, useRef } from "react";
import './MemoryGame.css';
import utils from '../misc/utils';
import colors from '../misc/colors';
import Cell from "./Cell";
import Footer from "./Footer";
const MemoryGame = ({ incrementId }) => {
const [memCells] = useState(utils.nonRepeatingRandoms(6, 1, 25));
const [clickedCells, setClickedCells] = useState([]);
const [gameState, setGameState] = useState('game-inactive');
const [timer, setTimer] = useState(3);
const correctCells = useRef(0);
const wrongCells = useRef(0);
// 3 second timer
useEffect(() => {
if (gameState === 'display-mem-cells') {
if (timer > 0) {
const timerId = setTimeout(() => {
setTimer(timer - 1);
}, 1000);
return () => clearTimeout(timerId);
}
if (timer === 0) {
setGameState('recall-cells');
}}
}, [gameState, timer]);
//handles what happens to cell after click
const handleClick = (cellNumber) => {
if (gameState !== 'recall-cells' ||
clickedCells.includes(cellNumber)) {
return;
}
addToArray(cellNumber);
winOrLose(cellNumber);
}
//add the cell being clicked to the array
const addToArray = (cellNumber) => setClickedCells([...clickedCells, cellNumber]);
//determine if the game is won or lost
const winOrLose = (cellNumber) => {
if (memCells.includes(cellNumber)) {
correctCells.current += 1;
} else {
wrongCells.current += 1;
}
if (wrongCells.current === 3) {
setGameState('game-lost');
}
if (correctCells.current === 6) {
setGameState('game-won');
}
}
//manages color of cells
const cellColor = (cellNumber) => {
if (gameState === 'display-mem-cells' && memCells.includes(cellNumber)) {
return colors.memoryColor;
}
if (gameState === 'recall-cells') {
if (memCells.includes(cellNumber) && clickedCells.includes(cellNumber)) {
return colors.correctColor;
}
if (!(memCells.includes(cellNumber)) && clickedCells.includes(cellNumber)) {
return colors.wrongColor;
}
}
}
//sends a message based on the state of the game
const displayMessage = () => {
switch (gameState) {
case 'game-inactive': return 'You have 3 seconds to memorize 6 random blue cells';
case 'display-mem-cells': return 'Memorize these cells';
case 'recall-cells': return 'Recall the blue cells and click on them';
case 'game-won': return 'You won!';
case 'game-lost': return 'You lost. Try again!';
}
}
return (
<div className = "game">
<div className="help">{displayMessage()}</div>
<div className = "gamebody">
{utils.range(1, 25).map(cellNumber =>
<Cell
key={cellNumber}
cellColor={cellColor(cellNumber)}
handleClick={() => handleClick(cellNumber)}
/>
)}
</div>
<Footer
startGame={() => setGameState('display-mem-cells')}
playAgain={incrementId}
displayStartButton={gameState === 'game-inactive'}
displayButton={(gameState === 'game-won' ||
gameState === 'game-lost')}
/>
</div>
);
}
export default MemoryGame;<file_sep>/src/components/Cell.js
const Cell = ({ cellColor, handleClick }) => {
return (
<div
className='cell'
style={{ backgroundColor: cellColor }}
onClick={handleClick}
></div>
);
}
export default Cell;<file_sep>/src/misc/utils.js
const utils = {
// Sum an array
sum: arr => arr.reduce((acc, curr) => acc + curr, 0),
// create an array of numbers between min and max (edges included)
range: (min, max) => Array.from({length: max - min + 1}, (_, i) => min + i),
// pick a random number between min and max (edges included)
random: (min, max) => min + Math.floor(Math.random() * (max - min + 1)),
//create "numElements" non-repeating random numbers from "min" - "max"
nonRepeatingRandoms: (numElements, min, max) => {
let col = [];
for (let i = 0; i < numElements; i++) {
let possibleNum = utils.random(min, max);
if (!col.includes(possibleNum)) {
col.push(possibleNum);
} else {
i--;
}
}
return(col);
}
};
export default utils;<file_sep>/src/misc/colors.js
const colors = {
memoryColor: "cornflowerBlue",
correctColor: "darkSeaGreen",
wrongColor: "coral"
};
export default colors;<file_sep>/src/components/App.js
import { useState } from "react";
import MemoryGame from "./MemoryGame";
const App = () => {
const [gameId, setGameId] = useState(0);
return (
<MemoryGame key={gameId} incrementId={() => setGameId(gameId + 1)} />
);
}
export default App;<file_sep>/src/components/Footer.js
const Footer = ({ startGame, displayStartButton, displayButton, playAgain }) => {
return (
<div className='footer'>
{displayStartButton && <button
className='btn'
onClick={startGame}
>Start</button>}
{displayButton && <button
className='btn'
onClick={playAgain}
>Play Again</button>}
</div>
);
}
export default Footer; | 2356c24faeb354e25b7a44bd9a0944a177d885af | [
"JavaScript"
] | 6 | JavaScript | aanyas72/react-memory-game | e7fcc4a8466000d5b3bc5786c1f8fc6c9321a1b3 | b2e737684f8a0862302d601d2eb6b8b034bb95f5 |
refs/heads/master | <repo_name>sebastian88/SolitaireApi<file_sep>/gameapi/gameapi/models.py
from django.db import models
class Game(models.Model):
id = models.AutoField(primary_key=True)
created = models.DateTimeField(auto_now_add=True)
class Card(models.Model):
id = models.AutoField(primary_key=True)
codename = models.CharField(max_length=2)
name = models.CharField(max_length=32)
class InitialPosition(models.Model):
id = models.AutoField(primary_key=True)
game = models.ForeignKey(Game)
shuffled_position = models.IntegerField()
card = models.ForeignKey(Card)
class Meta:
ordering = ('game', 'shuffled_position',)
class Move(models.Model):
id = models.AutoField(primary_key=True)
game = models.ForeignKey(Game)
move_number = models.IntegerField()
top_card = models.ForeignKey(Card, related_name='card_top_card')
bottom_card = models.ForeignKey(Card, related_name='card_bottom_card')
class Meta:
ordering = ('game', 'move_number',)
<file_sep>/gameapi/gameapi/serializers.py
from rest_framework import serializers
from gameapi.models import Game, Card, Move, InitialPosition
class GameSerializer(serializers.Serializer):
class meta:
model = Game
fields = ('id', 'Created')
class CardSerializer(serializers.Serializer):
class meta:
model = Card
fields = ('name', 'codename')
class InitalPositionSerializer(serializers.Serializer):
class meta:
model = InitialPosition
fields = ('game', 'shuffled_position', 'card')
class MoveSerializer(serializers.Serializer):
class meta:
model = Move
fields = ('game', 'move_number', 'top_card', 'bottom_card')
<file_sep>/gameapi/gameapi/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-16 08:31
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Card',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('codename', models.CharField(max_length=2)),
('name', models.CharField(max_length=32)),
],
),
migrations.CreateModel(
name='Game',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='InitialPosition',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('shuffled_position', models.IntegerField()),
('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='gameapi.Card')),
('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='gameapi.Game')),
],
options={
'ordering': ('game', 'shuffled_position'),
},
),
migrations.CreateModel(
name='Move',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('move_number', models.IntegerField()),
('bottom_card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='card_bottom_card', to='gameapi.Card')),
('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='gameapi.Game')),
('top_card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='card_top_card', to='gameapi.Card')),
],
options={
'ordering': ('game', 'move_number'),
},
),
]
| 72386bf28d6cbc4430877e2a02cb7ab3a7404367 | [
"Python"
] | 3 | Python | sebastian88/SolitaireApi | 4a0607adc6ec009b69d20a8493fef0fbd0075a57 | a1950f4d7fbe7b1a2c71f17e39348cccec51982e |
refs/heads/master | <repo_name>johuex/whoosh_api<file_sep>/main.py
from app import create_app
import os
app = create_app()
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
<file_sep>/requirements.txt
affine==2.3.0
attrs==21.2.0
beautifulsoup4==4.9.3
certifi==2021.5.30
charset-normalizer==2.0.3
click==8.0.1
click-plugins==1.1.1
cligj==0.7.2
contextily==1.1.0
cycler==0.10.0
decorator==4.4.2
esda==2.3.6
Fiona==1.8.20
Flask==2.0.1
Flask-Cors==3.0.10
geographiclib==1.52
geojson==2.5.0
geopandas==0.9.0
geopy==2.2.0
idna==3.2
itsdangerous==2.0.1
Jinja2==3.0.1
joblib==1.0.1
kiwisolver==1.3.1
libpysal==4.5.1
MarkupSafe==2.0.1
matplotlib==3.4.2
mercantile==1.2.1
munch==2.5.0
networkx==2.5.1
numpy==1.21.1
osmnx==1.1.1
overpass==0.7
pandas==1.3.0
Pillow==8.3.1
pyparsing==2.4.7
pyproj==3.1.0
python-dateutil==2.8.2
python-dotenv==0.19.0
pytz==2021.1
rasterio==1.2.6
requests==2.26.0
Rtree==0.9.7
scikit-learn==0.22.2.post1
scipy==1.7.0
Shapely==1.7.1
six==1.16.0
snuggs==1.4.7
soupsieve==2.2.1
threadpoolctl==2.2.0
urllib3==1.26.6
Werkzeug==2.0.1
<file_sep>/app/__init__.py
from flask import Flask
from flask_cors import CORS, cross_origin
def create_app():
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
from app.api import bp as api_bp
app.register_blueprint(api_bp)
return app<file_sep>/Dockerfile
FROM python:3.8.10
# Set a directory for the app
WORKDIR /usr/src/whoosh_api
# Copying project to image
COPY . .
# Install python requirements
RUN pip install -r requirements.txt
EXPOSE 5000
# Run Flask-API
CMD ["python", "./main.py"]
<file_sep>/app/api/database.py
"""тут можно описать параметры к бд, если требуется"""<file_sep>/app/api/routes.py
from app.api import bp
from app.api.errors import bad_request
from flask import jsonify, request, url_for
import pickle
import numpy as np
from config import ROOT_DIR, parking_gdf, gdf_nodes, G, api_key
import os
import app.api.distance as ds
import requests
import ast
from app import cross_origin
@bp.route('/check')
@cross_origin()
def check():
return 'Works!'
@bp.route('/parking', methods=['GET', 'POST'])
@cross_origin()
def get_park():
global parking_gdf
global G
global gdf_nodes
# receive data from request
data = request.get_json() or {}
# checking data and converting to float
if 'lat' in data:
data['lat'] = float(data['lat'])
else:
return bad_request("No latitude in request")
if 'lon' in data:
data['lon'] = float(data['lon'])
else:
return bad_request("No longitude in request")
parking_gdf, best_parks = ds.best_parking(data, parking_gdf) # give lan and lot and receive best parkings
# opening models
dict_path = os.path.join(ROOT_DIR, 'other/dict')
with open(dict_path, 'rb') as fp:
itemlist = pickle.load(fp)
checkMl_z = {}
pickle_path = os.path.join(ROOT_DIR, 'other/models.pckl')
file = open(pickle_path, 'rb')
for i in range(362):
checkMl_z[itemlist[i]] = pickle.load(file)
file.close()
# prediction
top_parks_dist = best_parks.distance_to_location
top_parks_dist = top_parks_dist.tolist()
top_parks_dist = np.array(top_parks_dist)
top_parks_point = best_parks.geometry
top_parks_point = top_parks_point.tolist()
top_parks_point = np.array(top_parks_point)
top_parks_id = best_parks.index
top_parks_id = top_parks_id.tolist()
top_parks_id = np.array(top_parks_id)
assign = np.empty(3)
assign = top_parks_dist/1000 * checkMl_z.get(282199231).predict(np.reshape([19,2], (1, -1)))**2
if 'flag' in data:
if data["flag"] == True:
body = {"coordinates":[[data["lat"],data["lon"]],[float(top_parks_point[assign.argmax()].y), float(top_parks_point[assign.argmax()].x)]]}
headers = {
'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',
'Authorization': str(api_key),
'Content-Type': 'application/json; charset=utf-8'
}
full_responce = requests.post('https://api.openrouteservice.org/v2/directions/foot-walking', json=body, headers=headers)
content_responce = full_responce.content
dict_content_responce = content_responce.decode()
route_responce = ast.literal_eval(dict_content_responce)
return jsonify(route_responce)
park_responce = {"ID": int(top_parks_id[assign.argmax()]),
"lat": top_parks_point[assign.argmax()].y,
"lon": top_parks_point[assign.argmax()].x}
return jsonify(park_responce)
<file_sep>/config.py
import os, sys
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), './.env')
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
# инпуты чтобы составить ссылку по которой мы будем качать архив:
WEB = 'http://37.9.3.253/download/files.synop/'
REGION = '27/'
STATION = '27605.'
START = '17.05.2021.'
FINISH = '31.05.2021.'
PIECE = '1.0.0.ru.'
CODE = 'utf8.'
FORMAT = '00000000.csv.gz'
ROOT_DIR = os.path.dirname(os.path.abspath('config.py'))
LINK = WEB + REGION + STATION + START + FINISH + PIECE + CODE + FORMAT
parking_gdf = None
G = None
gdf_nodes = None
tree = None
api_key = os.environ.get("api_key")
<file_sep>/app/api/errors.py
"""API - ответы на ошибки"""
from flask import jsonify
from werkzeug.http import HTTP_STATUS_CODES
def error_response(status_code, message=None):
"""основа для создания ответа об ошибке"""
payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
if message:
payload['message'] = message
response = jsonify(payload)
response.status_code = status_code
return response
def bad_request(message):
"""сообщение с ошибкой 400 - плохие запросы"""
return error_response(400, message)<file_sep>/app/api/distance.py
import networkx as nx
import osmnx as ox
ox.config(use_cache=True, log_console=True)
import datetime as dt
from sklearn.neighbors import KDTree
import pandas as pd
import contextily as cx
import numpy as np
import geopandas as gpd
from libpysal.cg.alpha_shapes import alpha_shape_auto
import sys
from esda.adbscan import ADBSCAN, get_cluster_boundary, remap_lbls
import os
from config import ROOT_DIR, LINK, gdf_nodes, G, tree
'''---------------------------------------'''
def create_parking_dtf():
'''Добываем московский граф'''
# Границы "Москвы"
lat_max = 55.927854
lat_min = 55.541984
lon_max = 37.883441
lon_min = 37.347858
G = ox.graph_from_bbox(lat_max, lat_min, lon_max, lon_min, network_type='drive')
gdf_nodes = ox.graph_to_gdfs(G, edges=False) # список узлов всего графа - будем использовать в расчетах
'''добываем данные о погоде'''
# открываем агрегированные данные по байкам
ks_agg_path = os.path.join(ROOT_DIR, 'other/ks_aggregated.csv')
df = pd.read_csv(ks_agg_path)
df['datetime_x'] = df['datetime_x'].astype('datetime64')
df['datetime_y'] = df['datetime_y'].astype('datetime64')
weather_df = pd.read_csv(LINK,
compression='gzip', header=6, encoding='UTF-8',
error_bad_lines=False, delimiter=';', index_col=False)
weather_df = weather_df.rename(columns={"Местное время в Москве (центр, Балчуг)": "datetime_w", "E'": "E_"})
weather_df['datetime_w'] = weather_df['datetime_w'].astype('datetime64')
# Корректировка данных о погоде
weather_df['rain'] = weather_df.apply(WW_fixer, axis=1)
weather_df['RRR'] = weather_df.apply(RRR_fixer, axis=1)
weather_df['RRR'] = weather_df['RRR'].astype('float64')
weather_df['Nh'] = weather_df.apply(Nh_fixer, axis=1)
weather_df['Nh'] = weather_df['Nh'].astype('float64')
weather_df['N'] = weather_df.apply(N_fixer, axis=1)
weather_df['N'] = weather_df['N'].astype('float64')
weather_df['H'] = weather_df.apply(H_fixer, axis=1)
weather_df['H'] = weather_df['H'].astype('float64')
weather_df_final = weather_df.drop(
['Pa', 'DD', 'ff10', 'ff3', 'Tn', 'Tx', 'Cl', 'Cm', 'Ch', 'VV', 'Td', 'E', 'Tg', 'E_', 'sss', 'WW', 'W1', 'W2',
'tR'], axis=1)
weather_df_final['datetime_w'] = weather_df_final['datetime_w'].astype('datetime64')
'''Соединение обработанной погоды и агрегированных данных кикшеринга'''
df['date_day'] = df['datetime_x'].dt.date
weather_df_final['date_day'] = weather_df_final['datetime_w'].dt.date
weather_df_final['start_hour'] = weather_df_final['datetime_w'].dt.hour
df = df.merge(weather_df_final, how='left', on=['date_day', 'start_hour'])
missing = ['T', 'Po', 'P', 'U', 'Ff', 'N', 'Nh', 'H', 'RRR', 'rain']
df.sort_values(by='datetime_x', ascending=True)
for i in missing:
df[i] = df[i].fillna(method='ffill')
df.sort_values(by='datetime_x', ascending=True).head(50)
'''Пространственный кластеринг парковок на основе точек стартов самокатов -
получаемый новый датасет вместо парковок с data.mos.ru'''
df = df.query('lat_x > @lat_min and lat_x < @lat_max and lon_x < @lon_max and lon_x > @lon_min')
# делаем геодатафрейм из датафрейма стартов самокатов
starts_gdf_ll = gpd.GeoDataFrame(
df, geometry=gpd.points_from_xy(df.lon_x, df.lat_x)).set_crs('epsg:4326')
# перепроецируем в более подходящую для карт и измерения расстояний проекцию https://epsg.io/20007
starts_gdf = starts_gdf_ll.to_crs(epsg=20007)
# записываем чтобы не потерять спроецированные метровые координаты
starts_gdf["X"] = starts_gdf.geometry.x
starts_gdf["Y"] = starts_gdf.geometry.y
# создаем кластеры с помощью алгоритма ADBSCAN
# основные параметры - 100м радиус поиска
# 3 самоката - это уже будет кластер
# 0.6 датасета используется при каждом перерасчете
# 200 перерасчетов выполняется
adbs = ADBSCAN(eps=100,
min_samples=3,
pct_exact=0.6,
algorithm='kd_tree',
reps=200,
keep_solus=True,
n_jobs=-1)
np.random.seed(42)
adbs.fit(starts_gdf)
# переносим в геодатафрейм получившиеся классы кластеров
starts_gdf = starts_gdf.merge(adbs.votes, left_index=True, right_index=True)
parking = get_cluster_boundary(adbs.votes["lbls"], starts_gdf, crs=starts_gdf.crs)
# сделаем геодатафрейм
parking = gpd.GeoDataFrame(parking, geometry=parking, crs=parking.crs.to_string())
# переводим в датафрейм с географическими координатами в виде градусов для маршрутизации
parking_gdf = gpd.GeoDataFrame(parking, geometry=parking['geometry'].centroid.to_crs(epsg=4326), crs=4326).drop(0,
axis=1).reset_index(
drop=True)
# защита от "пропущенных" геометрий, которые могли возникнуть при поиске центроида
parking_gdf['missing_geo'] = parking_gdf['geometry'].is_empty
parking_gdf = parking_gdf.query('missing_geo == False').reset_index(drop=True)
return G, gdf_nodes, parking_gdf
# !!! далее именно этот датафрейм мы подставляем в качестве парковок в наш код, который рассчитывает расстояние от
# заданной точки до парковок!!!
def WW_fixer(row):
"""функция, превращающая текст в числовые параметры"""
# используем две колонки - текущая погода и погода за прошлые три часа. 1 = дождь, 2 = ливень, 3 = гроза, 0 = дождя нет
if row['WW'] == 'Гроза слабая или умеренная без града, но с дождем и/или снегом в срок наблюдения.' or row['WW'] == 'Гроза (с осадками или без них).':
return 3
if row['WW'] == 'Дождь незамерзающий непрерывный слабый в срок наблюдения.' or row['WW'] == 'Дождь незамерзающий непрерывный умеренный в срок наблюдения.' or ['WW'] == 'Дождь (незамерзающий) неливневый. ':
return 1
if row['WW'] == 'Ливневый(ые) дождь(и) слабый(ые) в срок наблюдения или за последний час. ' or row['WW'] == 'Ливневый(ые) дождь(и) очень сильный(ые) в срок наблюдения или за последний час. ':
return 2
if row['WW'] == 'Состояние неба в общем не изменилось. ' and row['W1'] == 'Ливень (ливни).':
return 2
if row['WW'] == 'Состояние неба в общем не изменилось. ' and row['W1'] == 'Дождь.':
return 1
if row['WW'] == 'Состояние неба в общем не изменилось. ' and row['W1'] == 'Гроза (грозы) с осадками или без них.':
return 3
else:
return 0
def RRR_fixer(row):
"""Корректировка данных 'Кол-во осадков' """
if row['RRR'] == 'Осадков нет':
return 0.0
return row['RRR']
def Nh_fixer(row):
"""Корректировка данных '% наблюдаемых кучевых или слоистых облаков' """
if row['Nh'] == 'Облаков нет.':
return 0.0
if row['Nh'] == '20–30%.':
return 0.3
if row['Nh'] == '40%.':
return 0.4
if row['Nh'] == '50%.':
return 0.5
if row['Nh'] == '60%.':
return 0.6
if row['Nh'] == '70 – 80%.':
return 0.8
if row['Nh'] == '90 или более, но не 100%':
return 0.9
if row['Nh'] == '100%.':
return 1
return row['Nh']
def N_fixer(row):
"""Корректировка данных 'общая облачность в %' """
if row['N'] == 'Облаков нет.':
return 0.0
if row['N'] == '10% или менее, но не 0':
return 0.1
if row['N'] == '20–30%.':
return 0.3
if row['N'] == '40%.':
return 0.4
if row['N'] == '50%.':
return 0.5
if row['N'] == '60%.':
return 0.6
if row['N'] == '70 – 80%.':
return 0.8
if row['N'] == '90 или более, но не 100%':
return 0.9
if row['N'] == '100%.':
return 1
return row['N']
def H_fixer(row):
"""Корректировка данных 'высота основания самых низких облаков' """
if row['H'] == '2500 или более, или облаков нет.':
return 2500
if row['H'] == '1000-1500':
return 1000
if row['H'] == '600-1000':
return 600
if row['H'] == '300-600':
return 300
return row['H']
def find_nearest_node(tree, gdf, point):
"""Поиск ближайших узлов графа к какой-то выданной нам точке и просто получаем их индекс"""
# индексы используются в расчете маршрутов и т.д.
closest_idx = tree.query([(point.y, point.x)], k=1, return_distance=False)[0]
nearest_node = gdf.iloc[closest_idx].index.values[0]
return nearest_node
'''
def nx_distance_actual(row, tree, gdf_nodes, a_location_gdf, G):
node1 = find_nearest_node(tree, gdf_nodes, row['geometry']) # здесь например датасет всех парковок
node2 = find_nearest_node(tree, gdf_nodes, a_location_gdf['geometry'][0]) # здесь наш actual location
try:
row['distance_to_location'] = nx.shortest_path_length(G, node1, node2, weight='length')
except nx.NetworkXNoPath:
row['distance_to_location'] = None
return row['distance_to_location']
'''
'''---------------------------------------'''
def best_parking(data, parking_gdf):
"""
data: It is dict with latitude and longitude
return: List of 5 the best and nearest parks
"""
'''Расчет расстояния от выданной точки до велопарковок созданных на основе кластеризации'''
global G
global gdf_nodes
global tree
# подаем на вход актуальные координаты и превращаем их в геодатафрейм для использования в поиске узлов графа
if parking_gdf is None:
G, gdf_nodes, parking_gdf = create_parking_dtf()
a_location_lon = data['lon']
a_location_lat = data['lat']
a_location_df = pd.DataFrame(
{'act_lat': a_location_lat,
'act_lon': a_location_lon}, index=[0])
a_location_gdf = gpd.GeoDataFrame(
a_location_df, geometry=gpd.points_from_xy(a_location_df.act_lon, a_location_df.act_lat)).set_crs('epsg:4326')
if tree is None:
# здесь мы ищем ближайшие узлы графа к какой-то выданной нам точке и просто получаем их индекс. индексы используются в расчете маршрутов и т.д.
tree = KDTree(gdf_nodes[['y', 'x']], metric='euclidean')
# это аналитический стиль программирования не бейте
def nx_distance_actual(row):
node1 = find_nearest_node(tree, gdf_nodes, row['geometry']) # здесь например датасет всех парковок
node2 = find_nearest_node(tree, gdf_nodes, a_location_gdf['geometry'][0]) # здесь наш actual location
try:
row['distance_to_location'] = nx.shortest_path_length(G, node1, node2, weight='length')
except nx.NetworkXNoPath:
row['distance_to_location'] = None
return row['distance_to_location']
parking_gdf['distance_to_location'] = parking_gdf.apply(nx_distance_actual, axis=1)
top_stations = parking_gdf.sort_values(by='distance_to_location', ascending=True)[['geometry', 'distance_to_location']].head(3)
return parking_gdf, top_stations
| a2919b2d3f7e7be67f94d13575d035c679c4d92e | [
"Python",
"Text",
"Dockerfile"
] | 9 | Python | johuex/whoosh_api | 7892b8db37be9eb4891d463abd9a4ccb9fb9bc19 | 9b09e6900837bf26c660005dc786018627f6c0ae |
refs/heads/master | <repo_name>Yukun0416/rpn<file_sep>/README.md
## rpn
a command-line based RPN calculator
# start calculator:
```bash
gradle run --console=plain
```
# start unit test:
```
gradle test
```
<file_sep>/src/test/kotlin/com/tony/RpnCalculatorTest.kt
package com.tony
import org.junit.Before
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
internal class RpnCalculatorTest {
lateinit var calculator: RpnCalculator
@Before
fun setUp() {
calculator = RpnCalculator()
}
@Test
fun test1() {
calculator.feed("5 2")
assertTrue(calculator.getWarning().isBlank())
assertEquals("5 2", calculator.getResult())
}
@Test
fun test2() {
calculator.feed("2 sqrt")
assertTrue(calculator.getWarning().isBlank())
assertEquals("1.4142135623", calculator.getResult())
calculator.feed("clear 9 sqrt")
assertTrue(calculator.getWarning().isBlank())
assertEquals("3", calculator.getResult())
}
@Test
fun test3() {
calculator.feed("5 2 -")
assertTrue(calculator.getWarning().isBlank())
assertEquals("3", calculator.getResult())
calculator.feed("3 -")
assertTrue(calculator.getWarning().isBlank())
assertEquals("0", calculator.getResult())
calculator.feed("clear")
assertTrue(calculator.getWarning().isBlank())
assertEquals("", calculator.getResult())
}
@Test
fun test4() {
calculator.feed("5 4 3 2")
assertTrue(calculator.getWarning().isBlank())
assertEquals("5 4 3 2", calculator.getResult())
calculator.feed("undo undo *")
assertTrue(calculator.getWarning().isBlank())
assertEquals("20", calculator.getResult())
calculator.feed("5 *")
assertTrue(calculator.getWarning().isBlank())
assertEquals("100", calculator.getResult())
calculator.feed("undo")
assertTrue(calculator.getWarning().isBlank())
assertEquals("20 5", calculator.getResult())
}
@Test
fun test5() {
calculator.feed("7 12 2 /")
assertTrue(calculator.getWarning().isBlank())
assertEquals("7 6", calculator.getResult())
calculator.feed("*")
assertTrue(calculator.getWarning().isBlank())
assertEquals("42", calculator.getResult())
calculator.feed("4 /")
assertTrue(calculator.getWarning().isBlank())
assertEquals("10.5", calculator.getResult())
}
@Test
fun test6() {
calculator.feed("1 2 3 4 5")
assertTrue(calculator.getWarning().isBlank())
assertEquals("1 2 3 4 5", calculator.getResult())
calculator.feed("*")
assertTrue(calculator.getWarning().isBlank())
assertEquals("1 2 3 20", calculator.getResult())
calculator.feed("clear 3 4 -")
assertTrue(calculator.getWarning().isBlank())
assertEquals("-1", calculator.getResult())
}
@Test
fun test7() {
calculator.feed("1 2 3 4 5")
assertTrue(calculator.getWarning().isBlank())
assertEquals("1 2 3 4 5", calculator.getResult())
calculator.feed("* * * *")
assertTrue(calculator.getWarning().isBlank())
assertEquals("120", calculator.getResult())
}
@Test
fun test8() {
calculator.feed("1 2 3 * 5 + * * 6 5")
assertEquals("operator * (position: 15): insufficient parameters", calculator.getWarning())
assertEquals("11", calculator.getResult())
}
}<file_sep>/src/main/kotlin/com/tony/CalculatorException.kt
package com.tony
abstract class CalculatorException(message: String?) : Exception(message) {
class InvalidInputException(message: String) : CalculatorException("Invalid Input: $message")
class InsufficientInputException(operator: String, pos: String) :
CalculatorException("operator $operator (position: $pos): insufficient parameters")
}<file_sep>/src/main/kotlin/com/tony/Operation.kt
package com.tony
import java.math.BigDecimal
interface Operation {
fun calculate(inputs: List<BigDecimal>): BigDecimal
}<file_sep>/src/main/kotlin/com/tony/AbstractCalculator.kt
package com.tony
abstract class AbstractCalculator {
abstract fun feed(input: String)
abstract fun getResult(): String
abstract fun getWarning(): String
abstract fun undo()
abstract fun clear()
}<file_sep>/src/main/kotlin/com/tony/Operator.kt
package com.tony
import java.math.BigDecimal
import java.math.MathContext
enum class Operator(val token: String, val consume: Int) : Operation {
ADDITION("+", 2) {
override fun calculate(inputs: List<BigDecimal>): BigDecimal {
return inputs[1].plus(inputs[0])
}
},
SUBTRACTION("-", 2) {
override fun calculate(inputs: List<BigDecimal>): BigDecimal {
return inputs[1].minus(inputs[0])
}
},
MULTIPLICATION("*", 2) {
override fun calculate(inputs: List<BigDecimal>): BigDecimal {
return inputs[1].times(inputs[0])
}
},
DIVISION("/", 2) {
override fun calculate(inputs: List<BigDecimal>): BigDecimal {
return inputs[1].divide(inputs[0])
}
},
SQRT("sqrt", 1) {
override fun calculate(inputs: List<BigDecimal>): BigDecimal {
return inputs[0].sqrt(MathContext.DECIMAL64)
}
};
}<file_sep>/src/main/kotlin/com/tony/App.kt
package com.tony
import java.util.*
class App {
fun startCalculator() {
val calculator = RpnCalculator()
val sc = Scanner(System.`in`)
while (true) {
println("waiting input:")
val input = sc.nextLine()
if (input == "quit") break
calculator.feed(input)
if (calculator.getWarning().isNotBlank()) println(calculator.getWarning())
println("stack: " + calculator.getResult())
}
}
}
fun main() {
App().startCalculator()
}
<file_sep>/src/main/kotlin/com/tony/RpnCalculator.kt
package com.tony
import com.tony.CalculatorException.InsufficientInputException
import com.tony.CalculatorException.InvalidInputException
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat
import java.util.*
import kotlin.collections.ArrayList
class RpnCalculator : AbstractCalculator() {
private val operatorMap: Map<String, Operator> = Operator.values().toList().associateBy(
{ operator -> operator.token },
{ operator -> operator })
private var stack: LinkedList<BigDecimal> = LinkedList()
private var history: LinkedList<Collection<BigDecimal>> = LinkedList()
private var warning = ""
override fun feed(input: String) {
warning = ""
var token = ""
var index = 0
while (index < input.length + 1) {
if (index == input.length || input[index].isWhitespace()) {
try {
processSingleToken(token, position = index - token.length + 1)
} catch (e: Exception) {
warning = e.message.toString()
return
}
token = ""
} else {
token += input[index]
}
index++
}
}
override fun getResult(): String {
val formatter = DecimalFormat("#.##########")
formatter.roundingMode = RoundingMode.DOWN
return stack.joinToString(separator = " ") { formatter.format(it) }
}
override fun getWarning(): String {
return warning
}
override fun undo() {
stack.removeLast()
stack.addAll(history.removeLast().reversed())
}
override fun clear() {
stack = LinkedList()
history = LinkedList()
}
private fun processSingleToken(token: String, position: Int) {
if (token.isBlank()) return
if ("clear" == token) {
clear()
return
}
if ("undo" == token) {
undo(position)
return
}
operatorMap[token]?.let {
process(it, position)
return
}
try {
val number = BigDecimal(token).setScale(15, RoundingMode.HALF_UP)
stack.addLast(number)
history.add(emptyList())
return
} catch (exception: NumberFormatException) {
}
throw InvalidInputException(token)
}
private fun process(operator: Operator, position: Int) {
if (stack.size < operator.consume) {
throw InsufficientInputException(operator = operator.token, pos = position.toString())
}
val inputs = ArrayList<BigDecimal>()
while (inputs.size < operator.consume) {
inputs.add(stack.removeLast())
}
val result = operator.calculate(inputs)
stack.addLast(result)
history.add(inputs)
}
private fun undo(position: Int) {
if (history.isEmpty()) {
throw InsufficientInputException("undo", position.toString())
}
undo()
}
}<file_sep>/src/test/kotlin/com/tony/OperatorTest.kt
package com.tony
import com.tony.Operator.*
import org.junit.Test
import java.math.BigDecimal
import kotlin.test.assertEquals
internal class OperatorTest {
@Test
fun additionTest() {
assertEquals(
BigDecimal(8.1),
ADDITION.calculate(listOf(BigDecimal(3), BigDecimal(5.1))),
"test ADDITION"
)
}
@Test
fun subtractionTest() {
assertEquals(
BigDecimal(1),
SUBTRACTION.calculate(listOf(BigDecimal(3), BigDecimal(4))),
"test SUBTRACTION"
)
}
@Test
fun multiplicationTest() {
assertEquals(
BigDecimal(32),
MULTIPLICATION.calculate(listOf(BigDecimal(8), BigDecimal(4))),
"test MULTIPLICATION"
)
}
@Test
fun divisionTest() {
assertEquals(
BigDecimal(3),
DIVISION.calculate(listOf(BigDecimal(2), BigDecimal(6))),
"test DIVISION"
)
}
@Test
fun sqrtTest() {
assertEquals(
BigDecimal(12),
SQRT.calculate(listOf(BigDecimal(144))),
"test SQRT"
)
}
} | 6d3c2de89a0b5b7babfa20c0bb098e176c4a66e6 | [
"Markdown",
"Kotlin"
] | 9 | Markdown | Yukun0416/rpn | 91873634cdf0b233dced7bfff4c22787ab525402 | 27b6a61bbd787925a484da6f34632fccd07a7748 |
refs/heads/master | <file_sep><?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\Util\SecureRandom;
require_once __DIR__ . '/vendor/autoload.php';
class BookController {
private $db;
private $session;
public function __construct($db, $session) {
$this->db = $db;
$this->session = $session;
}
private function getBookFromDatabaseRecord($record) {
$record['id'] = intval($record['id']);
$record['year'] = $record['year'] ? intval($record['year']) : null;
$record['available'] = (bool) $record['available'];
return $record;
}
public function getBook(Request $request, $id) {
$record = $this->db->fetchAssoc('SELECT * FROM books WHERE id = ?', array($id));
if (!$record) {
return array(
'error' => 'Book not found.',
'error_code' => 404,
);
} else {
return $this->getBookFromDatabaseRecord($record);
}
}
public function getBookList(Request $request) {
$books = array();
$query = $this->db->executeQuery('SELECT * FROM books WHERE id >= ? ORDER BY id LIMIT 30', array(intval($request->get('first_id', 0))));
foreach ($this->db->fetchAll('SELECT * FROM books WHERE id >= ? ORDER BY id LIMIT 30', array(intval($request->get('first_id', 0)))) as $record) {
$books[] = $this->getBookFromDatabaseRecord($record);
}
return array(
'books' => $books,
'count' => intval($this->db->fetchColumn('SELECT COUNT(*) FROM books')),
'limit' => 30,
'first_id' => intval($request->get('first_id', 0)),
);
}
public function saveBook(Request $request, $id = 0) {
if (!$this->session->get('session') || $this->session->get('session') != $request->request->get('session')) {
return array(
'error' => 'Invalid session token.',
'error_code' => 403,
);
}
if (!$id) {
$query = $this->db->prepare('INSERT INTO books (title, topic, author, signature, year, volume, location, keyword, printing_place, edition, isbn, publisher, available, token) VALUES (:title, :topic, :author, :signature, :year, :volume, :location, :keyword, :printing_place, :edition, :isbn, :publisher, :available, :token)');
} else {
$query = $this->db->prepare('UPDATE books SET title = :title, topic = :topic, author = :author, signature = :signature, year = :year, volume = :volume, location = :location, keyword = :keyword, printing_place = :printing_place, edition = :edition, isbn = :isbn, publisher = :publisher, available = :available, token = :token WHERE id = :id AND token = :request_token');
$query->bindValue(':id', $id);
$query->bindValue(':request_token', $request->request->get('token', ''));
}
$title = trim($request->request->get('title', ''));
if ($title == '') {
return array(
'error' => 'Invalid field: title - must be non-empty.',
'error_code' => 422,
);
}
$query->bindValue(':title', $title);
$query->bindValue(':topic', trim($request->request->get('topic', '')));
$query->bindValue(':author', trim($request->request->get('author', '')));
$query->bindValue(':signature', trim($request->request->get('signature', '')));
$year = intval(trim($request->request->get('year', 0)));
if (!$year) {
$query->bindValue(':year', null);
} else {
$query->bindValue(':year', $year);
}
$query->bindValue(':volume', trim($request->request->get('volume', '')));
$query->bindValue(':location', trim($request->request->get('location', '')));
$query->bindValue(':keyword', trim($request->request->get('keyword', '')));
$query->bindValue(':printing_place', trim($request->request->get('printing_place', '')));
$query->bindValue(':edition', trim($request->request->get('edition', '')));
$query->bindValue(':isbn', trim($request->request->get('isbn', '')));
$query->bindValue(':publisher', trim($request->request->get('publisher', '')));
$available = $request->request->get('available', 'true');
if ($available == '' || $available == 'true') {
$query->bindValue(':available', TRUE);
} else if ($available == 'false') {
$query->bindValue(':available', FALSE);
} else {
return array(
'error' => 'Invalid field: available - expected true or false.',
'error_code' => 422,
);
}
$generator = new SecureRandom();
$query->bindValue(':token', md5($generator->nextBytes(32)));
$query->execute();
if (!$id) {
return $this->getBook($request, $this->db->lastInsertId());
} else if ($query->rowCount() != 0) {
return $this->getBook($request, $id);
} else {
$book = $this->getBook($request, $id);
if (empty($book['error'])) {
$book['error'] = 'Token out of date.';
$book['error_code'] = 404;
}
return $book;
}
}
}
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__ . '/services.yml'));
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => $app['database'],
));
$app->register(new Silex\Provider\SessionServiceProvider());
$app['books'] = function ($app) {
return new BookController($app['db'], $app['session']);
};
$app->get('/session', function () use ($app) {
if ($app['session']->get('session') === null) {
$generator = new SecureRandom();
$app['session']->set('session', md5($generator->nextBytes(32)));
}
return $app->json($app['session']->get('session'));
});
$app->get('/books', function (Request $request) use ($app) {
$response = $app['books']->getBookList($request);
return $app->json($response, empty($response['error_code']) ? 200 : $response['error_code']);
});
$app->post('/books', function (Request $request) use ($app) {
$response = $app['books']->saveBook($request);
return $app->json($response, empty($response['error_code']) ? 200 : $response['error_code']);
});
$app->get('/books/{id}', function (Request $request, $id) use ($app) {
$response = $app['books']->getBook($request, $id);
return $app->json($response, empty($response['error_code']) ? 200 : $response['error_code']);
})->convert('id', function ($id) {
return intval($id);
})->assert('id', '\d+');
$app->post('/books/{id}', function (Request $request, $id) use ($app) {
$response = $app['books']->saveBook($request, $id);
return $app->json($response, empty($response['error_code']) ? 200 : $response['error_code']);
})->convert('id', function ($id) {
return intval($id);
})->assert('id', '\d+');
$app->run();
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = "2.0.0"
import ConfigParser
import logging
import mysql.connector
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class BiblioApplication(QApplication):
"""An instance of the application."""
def __init__(self, argv):
super(BiblioApplication, self).__init__(argv)
# Start logging.
self._initLogger()
# Read the config file.
self.config = ConfigParser.ConfigParser()
self.config.read("biblio.ini")
def _initLogger(self):
# Log to the console.
stdoutLogHandler = logging.StreamHandler()
stdoutLogHandler.setLevel(logging.DEBUG)
# Create the logger.
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
self.logger.addHandler(stdoutLogHandler)
def exec_(self):
"""Runs the application."""
self.logger.debug("Starting application.")
# Connect to the database.
self.db = mysql.connector.connect(
user=self.config.get("MySQL", "User"),
password=self.config.get("MySQL", "Password"),
database=self.config.get("MySQL", "Database"),
host=self.config.get("MySQL", "Host"),
autocommit=True)
# Instanciate models.
self.books = BookModel(self)
self.books.reload()
# Open the main window.
mainWindow = MainWindow(self)
mainWindow.show()
super(BiblioApplication, self).exec_()
class Book(object):
"""A book."""
def __init__(self):
self.id = None
self.title = ""
self.topic = ""
self.author = ""
self.signature = ""
self.year = ""
self.volume = ""
self.location = ""
self.keywords = ""
self.printing_place = ""
self.edition = ""
self.isbn = ""
self.publisher = ""
self.available = True
self.lend_to = None
self.lend_since = None
class BookModel(QAbstractTableModel):
"""Represents the book database."""
def __init__(self, app):
super(BookModel, self).__init__()
self.cache = []
self.app = app
def reload(self):
self.beginResetModel()
cursor = self.app.db.cursor()
cursor.execute("SELECT id, titel AS title FROM buecher")
self.cache = cursor.fetchall()
cursor.close()
self.endResetModel()
def rowCount(self, parent=QModelIndex()):
return len(self.cache)
def columnCount(self, parent=QModelIndex()):
return 1
def index(self, row, column, parent=QModelIndex()):
if parent.isValid():
return QModelIndex()
return self.createIndex(row, column, self.cache[row])
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if index.column() == 0:
return index.internalPointer()[1]
class SearchBox(QWidget):
def __init__(self):
super(SearchBox, self).__init__()
self.label = QLabel("Suche:")
self.entry = QLineEdit()
layout = QHBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.entry)
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
def sizeHint(self):
return QSize(300, super(SearchBox, self).sizeHint().height())
class MainWindow(QMainWindow):
def __init__(self, app):
super(MainWindow, self).__init__()
self.app = app
# Set window properties.
self.setWindowTitle("Bibliothek")
self.tabs = QTabWidget()
self.setCentralWidget(self.tabs)
self.tabs.setTabsClosable(True)
self.tabs.tabCloseRequested.connect(self.onTabCloseRequested)
self.searchBox = QLineEdit()
self.tabs.setCornerWidget(SearchBox())
# Show the book table view.
sortedBooks = QSortFilterProxyModel()
sortedBooks.setSourceModel(self.app.books)
#sortedBooks.setDynamicSortFilter(True)
self.bookTableView = QTableView()
self.bookTableView.setModel(sortedBooks)
#self.bookTableView.setSortingEnabled(True)
self.tabs.addTab(self.bookTableView, "Alle")
self.tabs.tabBar().tabButton(0, QTabBar.RightSide).resize(0, 0)
self.tabs.tabBar().tabButton(0, QTabBar.RightSide).hide()
self.tabs.addTab(QLabel("Another tab"), "Zweitens")
def onTabCloseRequested(self, index):
self.tabs.removeTab(index)
if __name__ == "__main__":
app = BiblioApplication(sys.argv)
try:
sys.exit(app.exec_())
except Exception, e:
app.logger.exception(e)
QMessageBox.critical(None, "Kritischer Fehler", str(e))
| 0b85ce2c57a84a2aa5edc283256260d4eb7668b0 | [
"Python",
"PHP"
] | 2 | PHP | niklasf/gym-biblio | 93dfcf651b6cf362a309f1acc1e8472bc209cf2b | 1e0f6ba363cc97ac46ca8420e8f38311a96290e0 |
refs/heads/master | <file_sep>from pip._vendor.distlib.compat import raw_input
from src.model.model import Person
from src.view import view
def showAll():
# gets list of all Person objects
people_in_db = Person.getAll()
# calls view
return view.showAllView(people_in_db)
def start():
view.startView()
userInput = raw_input()
if userInput == 'y':
return showAll()
else:
return view.endView()
if __name__ == "__main__":
# running controller function
start()
| af36a466e7f1a4fd44c80b2bedddb5ebfc99f6ba | [
"Python"
] | 1 | Python | glas0050/mvc | e6df088217756fac344a0a61de9625e552b4575a | f04824bc25f22ddf8fe7fd76f4b12aa51a86fdba |
refs/heads/master | <file_sep>/*
* This is a sample plugin module
*
* It can be compiled by any of the supported compilers:
*
* - Borland C++, CBuilder, free C++
* - Visual C++
* - GCC
*
*/
#pragma warning(push, 0)
#include <ida.hpp>
#include <idp.hpp>
#include <expr.hpp>
#include <bytes.hpp>
#include <loader.hpp>
#include <kernwin.hpp>
#include <frame.hpp>
#include <struct.hpp>
#include <name.hpp>
#include <cstdio>
#pragma warning(pop)
int idaapi init(void)
{
return PLUGIN_OK;
}
void idaapi term(void)
{
}
void trim_string(char* str) {
}
bool idaapi run(size_t arg)
{
/* Create new container structure */
auto ea = get_screen_ea();
qstring function_name;
get_func_name(&function_name, ea);
char generated_name[256];
qsnprintf(generated_name, 256, "StackFrame_%X", ea);
auto generated_struc = get_struc(add_struc(BADADDR, generated_name, false));
auto frame = get_frame(ea);
member_t* members = frame->members;
auto member_count = frame->memqty;
for (uint32 i = 0; i < member_count; i++) {
member_t member = members[i];
auto name = get_member_name(member.id);
auto start = member.soff;
auto end = member.eoff;
auto size = end - start;
opinfo_t opinfo;
retrieve_member_info(&opinfo, &member);
auto result = add_struc_member(generated_struc, name.trim2(' ').c_str(), member.soff, member.flag, &opinfo, size);
if (result != STRUC_ERROR_MEMBER_OK) {
switch (result) {
case STRUC_ERROR_MEMBER_NAME: msg("STRUC_ERROR_MEMBER_NAME\n"); break;
case STRUC_ERROR_MEMBER_NESTED: msg("STRUC_ERROR_MEMBER_NESTED\n"); break;
case STRUC_ERROR_MEMBER_OFFSET: msg("STRUC_ERROR_MEMBER_OFFSET\n"); break;
case STRUC_ERROR_MEMBER_SIZE: msg("STRUC_ERROR_MEMBER_SIZE\n"); break;
case STRUC_ERROR_MEMBER_STRUCT: msg("STRUC_ERROR_MEMBER_STRUCT\n"); break;
case STRUC_ERROR_MEMBER_TINFO: msg("STRUC_ERROR_MEMBER_TINFO\n"); break;
case STRUC_ERROR_MEMBER_UNIVAR: msg("STRUC_ERROR_MEMBER_UNIVAR\n"); break;
case STRUC_ERROR_MEMBER_VARLAST: msg("STRUC_ERROR_MEMBER_VARLAST\n"); break;
}
}
}
//msg("just fyi: the current screen address is: %a\n", get_screen_ea());
return true;
}
//--------------------------------------------------------------------------
static const char comment[] = "Copies a stack frame into a local structure";
static const char help[] = "";
//--------------------------------------------------------------------------
// This is the preferred name of the plugin module in the menu system
// The preferred name may be overriden in plugins.cfg file
static const char wanted_name[] = "Copy stack frame to a local structure";
// This is the preferred hotkey for the plugin module
// The preferred hotkey may be overriden in plugins.cfg file
// Note: IDA won't tell you if the hotkey is not correct
// It will just disable the hotkey.
static const char wanted_hotkey[] = "";
//--------------------------------------------------------------------------
//
// PLUGIN DESCRIPTION BLOCK
//
//--------------------------------------------------------------------------
plugin_t PLUGIN =
{
IDP_INTERFACE_VERSION,
PLUGIN_UNL, // plugin flags
init, // initialize
term, // terminate. this pointer may be NULL.
run, // invoke plugin
comment, // long comment about the plugin
// it could appear in the status line
// or as a hint
help, // multiline help about the plugin
wanted_name, // the preferred short name of the plugin
wanted_hotkey // the preferred hotkey to run the plugin
};
| 3aef47ed8149a53f738125488255fc7a069154c6 | [
"C++"
] | 1 | C++ | Lyxica/IDAStackStructExport | d1b5e86e05994f85bcaa09912b39c4b2f31afb91 | 680b81ac9e1b7bb1f5e55ace1f74aca2f4faf1a1 |
refs/heads/main | <file_sep>import os
os.system('cls')
me = os.environ["username"]
print("The user " + me + " will run this script")
#------------------------------------------------
message = " 1. Get information and display to screen "
message = " 2. Call user created function "
message = " 3. Write List of files to file "
message = " 4. Read specified file "
task = input("Enter number of task to do: ")
def choice1():
companyName = "Dunwoody College"
programName = "Computer Networking"
uname = "import os"
classFirst = input = "Operating Systems"
classSecond = input = "Scripting"
print("My company is" + companyName + "my program is" + programName + "and my username is" + uname + "today")
print("My first class is" + classFirst + "my second class is" + classSecond + "today")<file_sep>import os
import pathlib
os.system('cls')
me = os.environ["username"]
print("The user " + me + " will run this script")
def GetState():
state = input(" What is the name of the state? ")
return state;
def formatstate(mystate):
length = len(mystate)
if length < 8 :
newState = mystate.ljust(8, '*')
return newState;
else:
return mystate;
#------------------------------------------------
message = " 1. Get information and display to screen \n"
message = message + " 2. Call user created function \n"
message = message + " 3. Write List of files to file \n"
message = message + " 4. Read specified file \n"
task = input(message + "\nEnter number of task to do: ")
if task == "1":
companyName = "Dunwoody College"
programName = "Computer Networking"
uname = os.environ['USERNAME']
classFirst = input("What is the name of your first class: ")
classSecond = input("What is the name of your second class: ")
print(" My company is " + companyName + " my program is " + programName + " and my username is " + uname )
print(" My first class is " + classFirst + " my second class is " + classSecond )
elif task == "2":
myState = GetState()
newState = formatstate(myState)
print(" Old state is " + myState + " your new state is " + newState )
elif task == "3":
fileOfFiles = input("Name of file to hold the files ")
fList = []
for p in pathlib.Path('.').iterdir():
if p.is_file():
fList.append(p)
with open(fileOfFiles, "w") as myFileWrite:
myFileWrite.write("These are my files:\n")
for f in fList:
myFileWrite.write(f.name)
myFileWrite.write("\n")
elif task == "4":
fileToRead = input("Name of file to read ")
with open(fileToRead, "r+") as myFileRead:
print(myFileRead.read()) | ed358784caf7f75ed6508a833bc05c1890d3a776 | [
"Python"
] | 2 | Python | RyanKoschak/PythonScript | 82407f9e76582fcf506263b0a3703c16069227ec | b15238265602f4e12abe86b4edfb38cbedf5639e |
refs/heads/master | <repo_name>ktptran/practice-websites<file_sep>/Practice/CSE154/Practice Problems/html-css/example.html
<!DOCTYPE html>
<!-- Sample solution for Extra Layout Practice (Lab 2) -->
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="solution.css">
</head>
<body>
<header>
<h1>154 layout practice! Center me!</h1>
</header>
<main>
<h2> Center me, too! </h2>
<p>
Welcome to the layout lab. This page contains the instructions for different
layout strategies in this page. There are a couple of different options in CSS
layout, but you'll learn that some are easier and more reponsive than others!
</p>
<p>
Wrap the <h1> and <h2> at the beginning of the page in a header, and center them
with the <code>text-align</code> property.
</p>
<p>
Below this text is the column container area. It should be 70% wide, and centered
in the page. Wrap the two columns together into one element (<div> is appropriate to
use here because there is no clear semantic meaning to the grouping of the two
columns), and make that container a flex container by setting it's
<code>display</code> property to <code>flex</code>.
</p>
<div id="column-container">
<!-- left column -->
<aside class="column">
<h3>Left column</h3>
<p>
This column sits on the left of the container area. Wrap this column in a page
section that indicates that it is an <aside> for the page.
</p>
<p>
It takes up 1/3 of the width of the overall content area. Accomplish this by setting the
<code>flex-basis</code> property to <code>33%</code>.
</p>
</aside>
<!-- right column -->
<section class="column">
<header>
<h3>Right column</h3>
</header>
<p>
This column is on the right of the main content area. It takes up 2/3 of the main
content area width. Accomplish this by setting its <code>flex-basis</code> value
to <code>67%</code>.
</p>
<img src="puppy-mowgli.jpg" alt="puppies">
<p>
<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/float">Float</a> the above
image to the right, so that it's to the right of this text instead of above it. Set its
<code>width</code> to <code>200px</code> so that it isn't so huge. The height will
adjust to keep the scale of the image.
</p>
<p id="clear">
For this paragraph, we don't want the text to wrap around the floating image anymore.
Use <code>clear: both</code> to cause this paragraph to move down below the floating
image. Give it an <code>id</code> or a <code>class</code> so that you can select this
paragraph specifically in your CSS.
</p>
</section>
</div>
<p>
Both columns should have <code>2em</code> of padding, <code>2em</code> of margin, and a
<code>4px</code> dashed red border. Give both columns a class that they can share so
that you don't have to duplicate this box model CSS.
</p>
<p id="fixme">
Finally, use <code>position: fixed</code> to set the position of this paragraph element
so that is is <code>5px</code> away from the bottom of the browser view port. Depending on
how big your browser screen is, other text from the page might overlap with it. That
proves to be a big challenge with fixed position elements.
</p>
</main>
</body>
</html>
<file_sep>/README.md
# Websites
Building different websites pages in preparation to building an organizational webpage.
<file_sep>/Portfolio Website/README.md
# Welcome to my website's portfolio
## Web Hosting
This website is hosted on Amazon Web Services and uses the following services to reach you through https://ktptran.com/
1. Amazon Route 53 for DNS routing
2. Amazon CloudFront for content distribution and caching
3. AWS Certificate Manager for TLS/SSL security
4. Amazon S3 to host static websites

## Documents
Within here, you will find the following documents that create the home page.
1. home.html
2. home.css
3. script.js
4. video.mp4
5. pics/
## Future Plans
Currently, I am looking to expand the website to satisfy the following functions:
1. Blog webpage for sharing about knowledge
2. System for requesting books
3. Login system
<file_sep>/blog (WIP)/src/components/BlogPost/index.js
import React, { useState, useEffect} from 'react';
import './style.css';
import Card from '../UI/Card';
import blogPost from '../../data/blog.json';
/**
* @author
* @function BlogPost
**/
const BlogPost = (props) => {
const [post, setPost] = useState({});
useEffect(() => {
const postId = props.match.params.postId;
console.log(postId);
const post = blogPost.data.find(post => post.id == postId);
setPost(post);
});
return (
<div className="blogPostContainer">
<Card>
<div className="blogHeader">
<span className="blogCategory">Featured Post</span>
<h1 className="postTitle">{post.postid}</h1>
<span className="postedBy">posted on July 21, 2016 by <NAME></span>
</div>
<div className="postImageContainer">
<img src={require('../../blogPostImages/memories-from.jpg')} alt="Post image" />
</div>
<div className="postContent">
<h3>Post Title</h3>
<p>lorem ipsim</p>
</div>
</Card>
</div>
)
};
export default BlogPost;
<file_sep>/Portfolio Website/script.js
/*
Name: <NAME>
Date: April 15th, 2020
This script.js is for my website focused on giving functionality to the html encoded in
home.html and css encoded in home.css.
*/
// 1. Scrolling function for navbar
$(document).ready(function() {
let scrollLink = $('.scroll');
// Smooth scrolling
scrollLink.click(function(event) {
event.preventDefault();
$('body,html').animate({
scrollTop: $(this.hash).offset().top - 75
}, 750)
})
});
// 2. About me section
// About-me section constants
const TABS = document.querySelectorAll('[data-tab-target]')
const TAB_CONTENTS = document.querySelectorAll('[data-tab-content]')
// About me section TABS
TABS.forEach(tab => {
tab.addEventListener('click', () => {
const target = document.querySelector(tab.dataset.tabTarget)
TAB_CONTENTS.forEach(tabContent => {
tabContent.classList.remove('active')
})
target.classList.add('active')
TABS.forEach(tab => {
tab.classList.remove('active')
})
tab.classList.add('active')
target.classList.add('active')
})
});
// Projects section
const TABS_PROJECT = document.querySelectorAll('[data-tab-target-project]')
const TAB_CONTENTS_PROJECT = document.querySelectorAll('[data-tab-project]')
// About me section TABS
TABS_PROJECT.forEach(tab => {
tab.addEventListener('click', () => {
const target = document.querySelector(tab.dataset.tabTargetProject);
TAB_CONTENTS_PROJECT.forEach(tabContentProject => {
tabContentProject.classList.remove('active')
})
target.classList.add('active')
TABS_PROJECT.forEach(tab => {
tab.classList.remove('active')
})
tab.classList.add('active')
target.classList.add('active')
})
});
// 3. Fading in and out effects
const FADERS = document.querySelectorAll('.fade-in');
const SLIDERS =document.querySelectorAll(".slide-in");
const APPEAR_OPTIONS = {
threshold: 0,
rootMargin: "0px 0px -100px 0px"
};
const appearOnScroll = new IntersectionObserver
(function(
entries,
appearOnScroll
) {
entries.forEach(entry => {
if (!entry.isIntersecting) {
return;
} else {
entry.target.classList.add('appear');
appearOnScroll.unobserve(entry.target);
}
})
},
APPEAR_OPTIONS);
FADERS.forEach(fader => {
appearOnScroll.observe(fader);
});
SLIDERS.forEach(slider => {
appearOnScroll.observe(slider)
});
$(function() {
$(".toggle").on("click", function() {
if($(".item").hasClass("active")) {
$(".item").removeClass("active");
}
else {
$(".item").addClass("active");
}
})
});
<file_sep>/Practice/CSE154/CP1/README.md
# Creative Project 1 Project Specification
## Overview
For your first creative project, you will use what we're learning about HTML and CSS to
make a simple website with at least two HTML pages, both linked to one or more CSS files.
As a creative project, you have the freedom to have more ownership in your work, as long
as you meet the requirements below.
As a reminder, assignments will alternate between creative projects (CPs) and more formal homework
assessments (HWs). We have designed assignments to support each of the 5 modules of this
course, and for creative projects to prepare you for the following HW in each module.
That said, we encourage you to explore the new material covered in class, as well as
related (but optional) content we may link to along the way (e.g. CSS3 animations), as
long as you follow the CSE 154 code quality guidelines. This is your chance to:
1. Build websites that you can link to on your resume or code portfolio (CPs can be
public, most HWs cannot be).
2. Ask instructors and/or TAs about features you want to learn how to implement (we can
provide more support for CPs than HWs) and ask for feedback/ideas on Piazza.
3. Apply what you're learning in CSE 154 to projects you are personally interested in and
may use outside of just a CSE 154 assignment.
4. Optionally showcase your CP work on the CSE 154 Au CP showcase (we'll try to showcase 8-12
websites per CP).
5. Get feedback on code quality when learning new technologies in CSE 154 to implement for
the following HW, which will be worth more points.
In past quarters, some students have built upon their creative project each week. You may
choose to do a new website for each CP, or build on a single project, as long as you meet
each CP requirements (note that you do not need to meet any CP1 requirements in later
CPs).
## Ideas for CP1
As long as you meet the requirements outlined below, you have freedom in what kind of
website you create. Here are some ideas for Autumn 2018 (Your instructors are more than
happy to help discuss more ideas in their office hours!):
* Extend your AboutMe page.
* Turn your current resume into a webpage (make sure you still have a second HTML page to
link to that resume).
* Implement a simple website for an RSO club you're in.
* Write a website for a friend/family member.
* Write a website with facts on your favorite animal/hobby/topic.
* Write a website with a few of your favorite recipes.
* Write a "tutorial" website on the basics of HTML/CSS given what you're learning
(teaching is a great way to reinforce what you're learning!).
* Start a blog website, perhaps documenting what you're learning this quarter in one of
your classes.
* Showcase any work about a hobby you may have (art, 3D printing, sports, travel, etc.)
* Check out your TA's AboutMe pages for some more inspiration!
## External Requirements
* Your website must contain at least two pages that are "linked together" - in other words you can use a link to get from one page to another, and a link to get back to the first page.
* The whole website should have a stylistic “theme” that cohesively connects the pages together. There can be some differences between the different pages, but the reader of your site should be able to tell these are connected.
* Your page should include [school appropriate content](https://courses.cs.washington.edu/courses/cse154/18au/syllabus/conduct.html#content) and [copyrights and citations](https://courses.cs.washington.edu/courses/cse154/18au/syllabus/conduct.html#copyright). If we find plaigarism in CPs
or inappropriate content, **you will be ineligible for any points on the CP**. Ask the instructors if you're unsure if you're work is appropriate.
## Internal Requirements
* Your project must include the following three files at a minimum:
* `index.html` (this file name is required) and one other `.html` file (you can choose the filename) that are linked together (with an `<a>` tag that will count towards your 10 tags in the requirement listed below).
* an `index.css` file.
* You must link `index.css` to `index.html` and your other html page to style the your HTML pages with your consistent look and feel.
* Links to **your** `.html` and `.css` files should be **relative links**, not absolute.
* Do not express style information in the HTML, such as inline styles or presentational HTML tags such as b or font.
* You must use at least 10 different types of HTML tags total (any tag excluding `<!DOCTYPE html>`, `<html>`, `<head>`, and `<body>` will qualify towards this count) in your `index.html` and other HTML page in your site.
* Suggestion: Refer to [this page](https://developer.mozilla.org/en-US/docs/Web/HTML/Element) for a comprehensive list of different HTML tags, and post on Piazza if you have any questions about any!
* You may use ones we haven't talked about in lecture, since there are many more that we could possibly cover in class (ask on Piazza or office hours if you have questions about new tags!).
* Do not use any deprecated HTML tags listed on [this page](http://www.tutorialspoint.com/html5/html5_deprecated_tags.htm).
* At least two of the 10 tags should be semantic tags listed under "HTML Layout Elements in More Detail" [here](https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure#HTML_layout_elements_in_more_detail)
* At least one of your HTML tags should be an inline element (see the Inline section [here] (https://www.w3schools.com/html/html_blocks.asp))
* `index.css` must have at least 5 different CSS selectors. Refer to [this page](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference#Selectors) for a CSS reference of selectors.
* `index.css` must apply at least 10 different CSS rules to content in `index.html`
* Note: You _may_ use a framework such as Bootstrap to help with your styling and helpful responsive layout features, however you must still meet all of the above requirements and demonstrate that you understand the key concepts of how the HTML and CSS work. Any framework code _will not count_ towards HTML/CSS requirements (e.g. if you use the Bootstrap "container" class in your HTML, you cannot count the CSS implementation the bootstrap.css file towards the CSS requirements), however you can add new (not duplicate) CSS for this class to `index.css`. You are not allowed to use any template HTML files for frameworks (this defeats the purpose of writing HTML and CSS from scratch in this first assignment).
* Don't know what any of that means but want to learn how to use a CSS framework? Ask
about them in office hours!
## Style and Documentation
* Your HTML and CSS should demonstrate good code quality
* This is demonstrated in class and detailed in the [CSE 154 Code Quality Guidelines](https://courses.cs.washington.edu/courses/cse154/18au/resources/styleguide/index.html), which can be found as a link off the course home page.
* Part of your grade will come from using consistent indentation, proper naming conventions, curly brace locations, etc.
* Place a comment header in each file with your name, section, a brief description of the assignment, and the files contents. Examples:
HTML File:
```
<!--
Name: <NAME>
Date: September 30, 2018
Section: CSE 154 AB
This is the index.html page for my portfolio of web development work. It includes links to side
projects I have done during CSE 154, including an AboutMe page, a blog template, and
a crytogram generator.
-->
```
CSS File:
```
/*
Name: <NAME>
Date: September 30, 2018
Section: CSE 154 AB
This is the index.css page for my portfolio of web development work.
It is used by all pages in my portfolio to give the site a consistent look and feel.
*/
```
* HTML and CSS files must be well-formed and pass W3C validation (this will be graded).
* The links to the [Code Validators](https://courses.cs.washington.edu/courses/cse154/18au/resources/index.html#validators) can be found in the side bar of the main page of the course website.
* To keep line lengths manageable, do not place more than one block element on the same line or begin a block element past the 100th character on a line.
## Grading
Grading for Creative Projects are lighter as this is your chance to explore and learn without the overhead of
having to match strict external requirements. Our goal is to give you feedback, particularly on the internal
requirements and style and documentation, so you can incorporate this feedback in your homework assignments which
will be worth more towards your final grade.
This CP will be out of 8 points and will likely be distributed as:
* External Correctness (2 pts) - The external requirements listed in this document are met.
* Internal Correctness (3 pts) - The external requirements listed in this document are met.
* Style and Documentation (3 pts) - The style and documentation requirements in this document are met.
## Late Day Challenge
You can earn one extra late day if your website also includes a 404.html page.
In order to receive your extra late day this page must meet the following requirements:
* Your site must already contain the two required pages listed in the External Requirements section above.
* Your 404 page must be in keeping with the theme of your site and also include school appropriate content.
| 6a4773e0f7a102f41b62176ffba07f19811f3f7f | [
"Markdown",
"JavaScript",
"HTML"
] | 6 | HTML | ktptran/practice-websites | c7f38d1abf1b6390ca78a8c1c9ebe004f094a517 | c585730430f2c2044bc6a877510c551409f8458f |
refs/heads/master | <repo_name>manlyindustries/math<file_sep>/system/user/addons/math/addon.setup.php
<?php
if (! defined('MATH_AUTHOR')) {
define('MATH_AUTHOR', '<NAME>');
define('MATH_AUTHOR_URL', 'https://manlyindustries.com');
define('MATH_DESC', 'Math is an ExporessionEngine add-on which enables PHP supported math formulae.');
define('MATH_DOCS_URL', 'https://github.com/manlyindustries/math');
define('MATH_NAME', 'Math');
define('MATH_VERSION', '1');
}
return array(
'author' => MATH_AUTHOR,
'author_url' => MATH_AUTHOR_URL,
'description' => MATH_DESC,
'docs_url' => MATH_DOCS_URL,
'name' => MATH_NAME,
'namespace' => 'manly\Math',
'version' => MATH_VERSION
);
<file_sep>/README.md
## Math 1
Math allows you to execute many PHP math functions in your ExpressionEngine templates without the need to enable PHP parsing.
While this version will work in ExpressionEngine 2, no installation instructions have been provided.
## Quick Tag Reference (full documentation below)
```
formula="(5 * 2) / [1]" — math formula (required) supports the following operators as well as bitwise + - * / % ++ -- < > <= => != <> ==
params="{var}|{var2}" — pipe delimited list of numeric parameters to be replaced into formula, recommended due to use of PHP eval (default: null)
decimals="2" — sets the number of decimal points (default: "0")
dec_point="." — sets the separator for the decimal point (default: ".")
thousands_separator="," — sets the thousands separator; (default: ",")
absolute="yes" — return the absolute number of the result (defaults: "no")
round="up|down|ceil" — whether to round the result up or down (defaults: no rounding)
numeric_error="Error" — message returned when non-numeric parameters are provided (default: "Invalid input")
trailing_zeros="yes" — include trailing 0 decimal places (defaults: "no")
```
## Parameters
More detailed reference.
### formula="(5 * 2) / [1]"
This is a required parameter and supports the standard PHP operators, as well as bitwise operators:
+ - * / % ++ -- < > <= => != <> ==
Example:
{exp:math formula="10 - 2"}
Output: 8
### params="{var}|{var2}"
This is a pipe-delimited list of numeric parameters to be replaced into the formula, recommended for use with dynamic parameters (default: null).
Set your parameters and call them by bracketed number reference. For instance [1] would call the first value, [2] would call the second value, and so forth.
Example:
{exp:math formula="[1] - [2]" params="{var1}|{var2}"}
### decimals="2"
Sets the number of decimal points (default: "0")
Example:
{exp:math formula="((4 * 3) / 5)" decimals="1"}
Output: 2.4
### dec_point="."
Sets the separator for the decimal point (default: ".")
### thousands_separator=","
Sets the thousands separator (default: ",")
### absolute="yes"
Return the absolute value of the result (defaults: "no")
Example:
{exp:math formula="10 - 12" absolute="yes"}
Output: 2
### round="up|down|ceil"
Whether to round the result up or down (defaults: no rounding)
Example:
{exp:math formula="([1] + 1) / [2]" params="{total_results}|2" round="down"}
Output: 5 (where {total_results} is 10)
{exp:math formula="2/3" decimals="2" round="up"}
Output: 0.67
### numeric_error="Error"
Message returned when non-numeric parameters are provided (default: "Invalid input")
### trailing_zeros="yes"
Include trailing 0 decimal places (defaults: "no")
## Installation
1. [Download Math](https://github.com/manlyindustries/math)
2. Move the folder named `math` to the `system/user/addons/` folder of your ExpressionEngine instance.
3. Go to the Add-On Manager in your control panel and click the 'Install' button.
## License
© 2016 [Manly Industries](https://manlyindustries.com). Licensed under the [Apache License, Version 2.0](https://github.com/manlyindustries/math/blob/master/LICENSE).
#### Acknowledgement
Special thanks to the [Caddis Interactive team](https://github.com/caddis) for [their hard work](https://github.com/caddis/math).
| c23b89a95a006c498bf2f1326fff9e92d6a78ffb | [
"Markdown",
"PHP"
] | 2 | PHP | manlyindustries/math | d68896b1f47f1ae2e00290bc464283efd32265d9 | bad5b13bc0f4e2e06551a62a684b1ca52ca04bd3 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FactoryHealth : EntityHealth
{
public Image HealthBar;
public ObjectShaker ObjectShaker;
protected override void OnDamage(float amount)
{
ObjectShaker.Begin();
HealthBar.fillAmount = _entityData.HealthPoints / _entityData.InitialHealthPoints;
}
protected override void Death()
{
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class PaperSoldierAI : MonoBehaviour
{
public ESoldierType Type;
public float AttackRange = 1;
public float AttackInterval = 1;
private float _attackTimer;
private Rigidbody2D _rigidbody2D;
private EntityData _entityData;
private EntityAttack _entityAttack;
private FactoryManager _factoryManager;
private Transform _factoryBound;
private Transform _battlefieldBound;
private bool _insideFactory = true;
private Animator _animator;
private SpriteRenderer _spriteRenderer;
private bool _waitingEnemies;
public Vector2 AttackPosition;
public AudioClip[] AttackClip;
void Awake()
{
_rigidbody2D = GetComponent<Rigidbody2D>();
_entityData = GetComponent<EntityData>();
_entityAttack = GetComponent<EntityAttack>();
_animator = GetComponent<Animator>();
_spriteRenderer = GetComponent<SpriteRenderer>();
_factoryManager = FindObjectOfType<FactoryManager>();
_factoryBound = _factoryManager.Bound;
_battlefieldBound = GameObject.FindGameObjectWithTag("BattlefieldBound").transform;
}
// Update is called once per frame
void Update()
{
_waitingEnemies = false;
// While inside the Factory bound
if (transform.position.x < _factoryBound.position.x)
{
float movementSpeed = 1;
if(Type != ESoldierType.None)
{
movementSpeed = _entityData.MovementSpeed;
}
else
{
movementSpeed = _entityData.MovementSpeed / 3;
}
_rigidbody2D.velocity = transform.right * movementSpeed;
return;
}
else if(_insideFactory == true)
{
_insideFactory = false;
_factoryManager.SoldierLeavedFactory();
}
// Battle AI
if(_attackTimer > 0)
{
_attackTimer -= Time.deltaTime;
}
float distanceToTarget = float.MaxValue;
Transform targetTransform = FindClosesTarget(out distanceToTarget);
if (targetTransform == null)
{
if (transform.position.x > _factoryBound.position.x + 1)
{
_rigidbody2D.velocity = -transform.right * _entityData.MovementSpeed;
}
else
{
_animator.SetTrigger("Rest");
_rigidbody2D.velocity = Vector2.zero;
_waitingEnemies = true;
}
return;
}
if (distanceToTarget < AttackRange)
{
_rigidbody2D.velocity = Vector2.zero;
if(_attackTimer <= 0)
{
_animator.SetTrigger("Attack");
int randomID = Random.Range(0, AttackClip.Length);
AudioSource.PlayClipAtPoint(AttackClip[randomID], Camera.main.transform.position);
AttackPosition = targetTransform.position;
//_entityAttack.Attack(targetTransform.position); CALLED NOW FROM THE ANIMATION
_attackTimer = AttackInterval;
}
return;
}
Vector2 movementDirection = (targetTransform.position - transform.position).normalized;
_rigidbody2D.velocity = movementDirection * _entityData.MovementSpeed;
_animator.SetFloat("Speed", 1);
}
private void LateUpdate()
{
if(_rigidbody2D.velocity != Vector2.zero)
{
_animator.SetFloat("Speed", 1);
}
else if(_waitingEnemies == true)
{
_animator.SetFloat("Speed", 0);
}
if(_rigidbody2D.velocity.x > 0)
{
_spriteRenderer.flipX = false;
}
if (_rigidbody2D.velocity.x < 0)
{
_spriteRenderer.flipX = true;
}
}
private Transform FindClosesTarget(out float distanceToTarget)
{
GameObject[] allEnemies = GameObject.FindGameObjectsWithTag("Enemy");
Transform targetTransform = null;
float minDistance = float.MaxValue;
foreach (var enemy in allEnemies)
{
float dist = Vector2.Distance(transform.position, enemy.transform.position);
if(enemy.transform.position.x < _battlefieldBound.position.x && dist < minDistance)
{
minDistance = dist;
targetTransform = enemy.transform;
}
}
distanceToTarget = minDistance;
return targetTransform;
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, AttackRange);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum WeaponType { None, Sword, Hat, Crossbow }
public class Weapon : MonoBehaviour
{
public Sprite BlueEquivalent;
public Sprite RedEquivalent;
public ESoldierType TransformationType;
public WeaponType WeaponType;
public Color RedColor;
public Color BlueColor;
public AudioClip EquipClip;
public void TransformWeapon(PaintColor newColor)
{
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
switch (newColor)
{
case PaintColor.Red:
spriteRenderer.color = RedColor;
if (WeaponType == WeaponType.Sword)
TransformationType = ESoldierType.RedWarrior;
if (WeaponType == WeaponType.Hat)
TransformationType = ESoldierType.RedMage;
if (WeaponType == WeaponType.Crossbow)
TransformationType = ESoldierType.RedArcher;
break;
case PaintColor.Blue:
spriteRenderer.color = BlueColor;
if (WeaponType == WeaponType.Sword)
TransformationType = ESoldierType.BlueWarrior;
if (WeaponType == WeaponType.Hat)
TransformationType = ESoldierType.BlueMage;
if (WeaponType == WeaponType.Crossbow)
TransformationType = ESoldierType.BlueArcher;
break;
}
}
public void OnGiveWeapon()
{
AudioSource.PlayClipAtPoint(EquipClip, Camera.main.transform.position);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EntityData : MonoBehaviour
{
public float InitialHealthPoints = 5;
public float HealthPoints = 0;
public float MovementSpeed = 2;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIFloatingText : MonoBehaviour
{
public float TTL;
private float _timer;
private void OnEnable()
{
_timer = TTL;
}
private void Update()
{
_timer -= Time.deltaTime;
if (_timer <= 0) this.gameObject.SetActive(false);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AoEProjectile : AttackBase
{
public GameObject ExplosionPrefab;
protected override void OnImpact()
{
GameObject explosionObject = Instantiate(ExplosionPrefab, transform.position, Quaternion.identity);
AttackBase attackBase = explosionObject.GetComponent<AttackBase>();
attackBase?.Initialize(_owner, _teamTag);
if(attackBase == null)
{
Explosion explosion = explosionObject.GetComponent<Explosion>();
explosion?.Initialize(_owner, _teamTag);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
public GameObject[] enemyPrefabs;
public GameObject bossPrefab;
public float xSpawnRangeMin = 10;
public float xSpawnRangeMax = 15;
public float ySpawnRangeMin = -5;
public float ySpawnRangeMax = 5;
public int waveNumber = 1;
public int amountToSpawn = 5;
public int enemyCount;
public GameManager gameManager;
private void Awake()
{
SpawnEnemyWave(amountToSpawn * waveNumber);
}
// Update is called once per frame
void Update()
{
enemyCount = FindObjectsOfType<EnemyAI>().Length;
if (enemyCount == 0)
{
waveNumber++;
SpawnEnemyWave(amountToSpawn * waveNumber);
}
}
Vector2 GenerateSpawnPosition()
{
float spawnX = Random.Range(xSpawnRangeMin, xSpawnRangeMax);
float spawnY = Random.Range(ySpawnRangeMin, ySpawnRangeMax);
Vector2 randomPos = new Vector2(spawnX, spawnY);
return randomPos;
}
void SpawnEnemyWave(int enemiesToSpawn)
{
for (int i = 0; i < enemiesToSpawn; i++)
{
int randomID = Random.Range(0, enemyPrefabs.Length);
Instantiate(enemyPrefabs[randomID], GenerateSpawnPosition(), enemyPrefabs[randomID].transform.rotation);
}
if(waveNumber % 3 == 0)
{
Instantiate(bossPrefab, GenerateSpawnPosition(), bossPrefab.transform.rotation);
}
}
}
<file_sep>using UnityEngine;
public enum ESoldierType
{
None,
WhiteWarrior,
WhiteMage,
WhiteArcher,
RedWarrior,
RedMage,
RedArcher,
BlueWarrior,
BlueMage,
BlueArcher
}
[System.Serializable]
public struct TransformationData
{
public ESoldierType Type;
public GameObject TransformationResult;
}
public class PaperSoldierTransformation : MonoBehaviour
{
public TransformationData[] TransformationData;
public void PerformTransformation(ESoldierType transformationType)
{
GameObject transformationResult = null;
foreach (var transfData in TransformationData)
{
if(transfData.Type == transformationType)
{
transformationResult = transfData.TransformationResult;
}
}
if(transformationResult != null)
{
Instantiate(transformationResult, transform.position, Quaternion.identity);
Destroy(this.gameObject);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Vector2 movement;
public float moveSpeed = 5f;
public Rigidbody2D playerRb;
float horizontalMove;
float verticalMove;
public Transform carryLocation;
Transform currentItem = null;
Transform touchedWeapon = null;
private bool touchingWeapon;
private bool hasWeapon;
private bool touchingSoldier;
private bool touchingPaintBucket;
Transform soldier;
GameObject paintBucket;
private Transform _factoryBound;
private Animator _animator;
public AudioClip[] GrabClips;
public AudioClip[] PaintClips;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody2D>();
_animator = GetComponentInChildren<Animator>();
_factoryBound = FindObjectOfType<FactoryManager>().Bound;
}
// Update is called once per frame
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal");
verticalMove = Input.GetAxisRaw("Vertical");
PickupWeapon();
GiveWeapon();
PaintWeapon();
}
private void FixedUpdate()
{
float horizontal = horizontalMove * moveSpeed;
float vertical = verticalMove * moveSpeed;
playerRb.velocity = new Vector2(horizontal, vertical);
if (transform.position.x > _factoryBound.position.x)
{
Vector3 correctedPosition = transform.position;
correctedPosition.x = _factoryBound.position.x;
transform.position = correctedPosition;
}
}
//Check if the object the player is colliding with is a weapon
private void OnTriggerEnter2D(Collider2D other)
{
//Check to see if the player is colliding with a weapon, and mark true if the player is colliding with an item
if ((other.CompareTag("Sword") || other.CompareTag("Bow") || other.CompareTag("WizardHat")) && touchedWeapon == null)
{
//Debug.Log("Impact with " + other.tag);
//Take a reference to Collided Object
touchingWeapon = true;
touchedWeapon = other.transform;
}
//if (other.CompareTag("PaperSoldier") && currentItem != null)
//{
// Debug.Log("Impact with Soldier");
// touchingSoldier = true;
// soldier = other.transform;
//}
if (other.CompareTag("PaintBucket"))
{
//Debug.Log("Impact with Paint Bucket");
touchingPaintBucket = true;
paintBucket = other.gameObject;
}
}
//Check if the player is leaving the vicinity of a weapon or unit
private void OnTriggerExit2D(Collider2D other)
{
if ((other.CompareTag("Sword") || other.CompareTag("Bow") || other.CompareTag("WizardHat")) && touchedWeapon != null)
{
//Debug.Log("Leaving " + other.tag);
touchingWeapon = false;
touchedWeapon = null;
}
//if (other.CompareTag("PaperSoldier") && currentItem != null)
//{
// Debug.Log("Leaving Soldier");
// touchingSoldier = false;
// soldier = null;
//}
if (other.CompareTag("PaintBucket"))
{
//Debug.Log("Leaving Paint Bucket");
touchingPaintBucket = false;
paintBucket = null;
}
}
//Lets the player pick up a weapon if touchingWeapon is true
void PickupWeapon()
{
if (Input.GetKeyDown(KeyCode.Space) && touchingWeapon == true)
{
//Debug.Log("Pickup Weapon");
//Move it to carrying point
currentItem = touchedWeapon;
currentItem.position = carryLocation.position;
//Make it a child of the player so that it moves along with the player
currentItem.parent = carryLocation;
currentItem.rotation = carryLocation.rotation;
touchingWeapon = false;
hasWeapon = true;
int randomID = UnityEngine.Random.Range(0, GrabClips.Length);
AudioSource.PlayClipAtPoint(GrabClips[randomID], Camera.main.transform.position);
if (hasWeapon == true)
{
//Debug.Log("Player has a weapon");
}
_animator.SetBool("Holding", true);
}
}
void GiveWeapon()
{
if (Input.GetKeyDown(KeyCode.Space) && hasWeapon == true)
{
//Debug.Log("Weapon Given");
Collider2D[] soldiers = Physics2D.OverlapCircleAll(transform.position, 1, 1 << LayerMask.NameToLayer("PaperSoldier"));
float closestDistance = float.MaxValue;
GameObject closestSoldier = null;
foreach (var soldier in soldiers)
{
float distanceToSoldier = Vector2.Distance(transform.position, soldier.transform.position);
if(distanceToSoldier < closestDistance)
{
closestDistance = distanceToSoldier;
closestSoldier = soldier.gameObject;
}
}
if (closestSoldier == null)
return;
Weapon weapon = currentItem.GetComponent<Weapon>();
weapon.OnGiveWeapon();
PaperSoldierTransformation soldierTransformation = closestSoldier.GetComponent<PaperSoldierTransformation>();
if (soldierTransformation == null)
return;
soldierTransformation.PerformTransformation(weapon.TransformationType);
Destroy(currentItem.gameObject);
hasWeapon = false;
currentItem = null;
touchingWeapon = false;
_animator.SetBool("Holding", false);
}
}
private void PaintWeapon()
{
if(Input.GetKeyDown(KeyCode.Space) && hasWeapon == true)
{
Collider2D[] paintBuckets = Physics2D.OverlapCircleAll(transform.position, 1, 1 << LayerMask.NameToLayer("PaintBucket"));
float closestDistance = float.MaxValue;
GameObject closestBucket = null;
foreach (var bucket in paintBuckets)
{
float distanceToSoldier = Vector2.Distance(transform.position, bucket.transform.position);
if (distanceToSoldier < closestDistance)
{
closestDistance = distanceToSoldier;
closestBucket = bucket.gameObject;
}
}
if (closestBucket == null)
return;
int randomID = UnityEngine.Random.Range(0, PaintClips.Length);
AudioSource.PlayClipAtPoint(PaintClips[randomID], Camera.main.transform.position);
PaintColor targetColor = closestBucket.GetComponent<PaintBucket>().MyColor;
currentItem.GetComponent<Weapon>().TransformWeapon(targetColor);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EntityHealth : MonoBehaviour
{
public Action OnDeath;
protected EntityData _entityData;
void Start()
{
_entityData = GetComponent<EntityData>();
_entityData.HealthPoints = _entityData.InitialHealthPoints;
}
public void ApplyDamage(float amount)
{
if (amount <= 0)
return;
_entityData.HealthPoints -= amount;
OnDamage(amount);
if (_entityData.HealthPoints <= 0)
{
OnDeath?.Invoke();
Death();
}
}
protected virtual void Death()
{
Destroy(this.gameObject);
}
protected virtual void OnDamage(float amount)
{
UIFloatingTextsManager.Instance.ShowText(amount, transform);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RedDebuff : MonoBehaviour
{
public int MaxStacksCount;
public float IntervalToDeapply = 2;
private float _deapplyTimer;
private readonly float DAMAGE_AMOUNT = .3f;
private readonly float DAMAGE_INTERVAL = .75f;
private float _damageTimer;
private EntityData _entityData;
private int _stacksCount;
private EntityHealth _entityHealth;
public GameObject RedDebuffIcon;
void Start()
{
_entityData = GetComponent<EntityData>();
_entityHealth = GetComponent<EntityHealth>();
}
private void Update()
{
if (_stacksCount <= 0)
{
_damageTimer = 0;
return;
}
if (_deapplyTimer > 0)
{
_deapplyTimer -= Time.deltaTime;
if (_deapplyTimer <= 0)
{
Deapply();
_deapplyTimer = IntervalToDeapply;
}
}
if(_damageTimer > 0)
{
_damageTimer -= Time.deltaTime;
if(_damageTimer <= 0)
{
_entityHealth.ApplyDamage(_stacksCount * DAMAGE_AMOUNT);
_damageTimer = DAMAGE_INTERVAL;
}
}
}
public void Apply(int stacksAmount)
{
_stacksCount = Mathf.Min(_stacksCount + stacksAmount, MaxStacksCount);
_deapplyTimer = IntervalToDeapply;
if(_damageTimer <= 0)
{
_damageTimer = DAMAGE_INTERVAL;
}
if (RedDebuffIcon.activeSelf == false)
{
RedDebuffIcon.SetActive(true);
}
RedDebuffIcon.transform.localScale = Vector3.one * _stacksCount * .075f;
}
private void Deapply()
{
_stacksCount = Mathf.Max(_stacksCount - 1, 0);
if (_stacksCount <= 0 && RedDebuffIcon.activeSelf == true)
{
RedDebuffIcon.SetActive(false);
}
RedDebuffIcon.transform.localScale = Vector3.one * _stacksCount * .075f;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum EAttackType { None, White, Red, Blue };
public class AttackBase : MonoBehaviour
{
public float Speed;
public int Damage;
public EAttackType AttackType;
public int RedStacksAmount;
public int BlueStacksAmount;
protected GameObject _owner;
protected string _teamTag;
private void Update()
{
transform.position += transform.right * Speed * Time.deltaTime;
}
public void Initialize(GameObject owner, string teamTag)
{
_owner = owner;
_teamTag = teamTag;
}
private void OnTriggerEnter2D(Collider2D collider)
{
if(collider.gameObject == _owner || collider.tag == _teamTag)
return;
EntityHealth targetHealth = collider.GetComponent<EntityHealth>();
if (targetHealth != null)
{
targetHealth.ApplyDamage(Damage);
HandleAttackType(collider.gameObject);
OnImpact();
Destroy(this.gameObject);
}
}
protected virtual void OnImpact()
{
}
protected virtual void HandleAttackType(GameObject target)
{
if(AttackType == EAttackType.Blue)
{
BlueDebuff targetBlueDebuff = target.GetComponent<BlueDebuff>();
if(targetBlueDebuff != null)
{
targetBlueDebuff.Apply(BlueStacksAmount);
}
}
if (AttackType == EAttackType.Red)
{
RedDebuff targetRedDebuff = target.GetComponent<RedDebuff>();
if (targetRedDebuff != null)
{
targetRedDebuff.Apply(RedStacksAmount);
}
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuScreen : MonoBehaviour
{
public GameObject TutorialScreen;
public GameObject MainScreen;
public AudioClip[] ClickClips;
public AudioSource Source;
private void Update()
{
if (Input.anyKeyDown == true && MainScreen.activeSelf == false && TutorialScreen.activeSelf == true)
{
int randomID = Random.Range(0, ClickClips.Length);
AudioSource.PlayClipAtPoint(ClickClips[randomID], Camera.main.transform.position);
MainScreen.SetActive(true);
TutorialScreen.SetActive(false);
}
}
public void StartGame()
{
int randomID = Random.Range(0, ClickClips.Length);
AudioSource.PlayClipAtPoint(ClickClips[randomID], Camera.main.transform.position);
SceneManager.LoadScene("GameScene");
}
public void Tutorial()
{
int randomID = Random.Range(0, ClickClips.Length);
AudioSource.PlayClipAtPoint(ClickClips[randomID], Camera.main.transform.position);
MainScreen.SetActive(false);
TutorialScreen.SetActive(true);
}
public void Quit()
{
int randomID = Random.Range(0, ClickClips.Length);
AudioSource.PlayClipAtPoint(ClickClips[randomID], Camera.main.transform.position);
Application.Quit();
}
}
<file_sep>using System.Collections.Generic;
using UnityEngine;
public class FactoryManager : MonoBehaviour
{
public GameObject GameOverScreen;
public GameObject PureSoldierPrefab;
public float SpawnInterval = 2;
public Transform Bound;
private float _spawnTimer;
private int _soldiersAtFactory;
private Transform[] _spawnPoints;
private const int MAX_UNITS_FACTORY = 3;
public float RandomSpawnAddition = 2;
public AudioClip[] SpawnClips;
private void Awake()
{
_spawnPoints = new Transform[transform.childCount];
for (int i = 0; i < transform.childCount; i++)
{
_spawnPoints[i] = transform.GetChild(i);
}
_spawnTimer = SpawnInterval;
GetComponent<EntityHealth>().OnDeath += OnFactoryDestroyed;
}
private void OnFactoryDestroyed()
{
GameOverScreen.SetActive(true);
PaperSoldierAI[] allPaperSoldiers = FindObjectsOfType<PaperSoldierAI>();
foreach (var paperSoldier in allPaperSoldiers)
{
Destroy(paperSoldier.gameObject);
}
EnemyAI[] allEnemies = FindObjectsOfType<EnemyAI>();
foreach (var enemy in allEnemies)
{
Destroy(enemy.gameObject);
}
ConveryourBelt[] allBelts = FindObjectsOfType<ConveryourBelt>();
foreach (var belt in allBelts)
{
belt.enabled = false;
}
Animator[] spawnersAnimators = FindObjectsOfType<Animator>();
foreach (var spawnerAnimator in spawnersAnimators)
{
spawnerAnimator.speed = 0;
}
SpawnManager spawnManager = FindObjectOfType<SpawnManager>();
spawnManager.enabled = false;
PlayerController playerController = FindObjectOfType<PlayerController>();
Destroy(playerController.gameObject);
}
private void Update()
{
bool canSpawn = _soldiersAtFactory < MAX_UNITS_FACTORY;
if (canSpawn && _spawnTimer > 0)
{
_spawnTimer -= Time.deltaTime;
if (_spawnTimer <= 0)
{
SpawnPureSoldier();
_spawnTimer = SpawnInterval + Random.Range(0f, RandomSpawnAddition);
}
}
}
private void SpawnPureSoldier()
{
bool spawnSuccessful = false;
if (_soldiersAtFactory < MAX_UNITS_FACTORY)
{
int randomID = Random.Range(0, _spawnPoints.Length);
_spawnPoints[randomID].GetComponentInChildren<Animator>().SetTrigger("Spawn");
_soldiersAtFactory++;
spawnSuccessful = true;
randomID = Random.Range(0, SpawnClips.Length);
AudioSource.PlayClipAtPoint(SpawnClips[randomID], Camera.main.transform.position);
}
if (spawnSuccessful == false)
{
_spawnTimer = SpawnInterval;
}
}
public void SoldierLeavedFactory()
{
_soldiersAtFactory--;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnFromAnimation : MonoBehaviour
{
public GameObject PureSoldierPrefab;
public void Spawn()
{
Instantiate(PureSoldierPrefab, transform.position, Quaternion.identity);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EntityAttack : MonoBehaviour
{
public GameObject ProjectilePrefab;
public float AttackOriginOffset;
private PaperSoldierAI _paperSoldierAI;
private EnemyAI _enemyAI;
private void Awake()
{
_paperSoldierAI = GetComponent<PaperSoldierAI>();
_enemyAI = GetComponentInParent<EnemyAI>();
}
public void Attack()
{
Vector2 attackPosition = transform.position;
if(_paperSoldierAI != null)
{
attackPosition = _paperSoldierAI.AttackPosition;
}
if(_enemyAI != null)
{
attackPosition = _enemyAI.AttackPosition;
}
Vector2 attackOrigin = transform.position + transform.right * AttackOriginOffset;
GameObject newProjectile = Instantiate(ProjectilePrefab, attackOrigin, Quaternion.identity);
// RANGED
AttackBase attackBase = newProjectile.GetComponent<AttackBase>();
attackBase?.Initialize(this.gameObject, this.tag);
// MELEE
Explosion explosion = newProjectile.GetComponent<Explosion>();
explosion?.Initialize(this.gameObject, this.tag);
newProjectile.transform.LookAt(attackPosition, Vector3.up);
Vector3 dir = (Vector3)attackPosition - newProjectile.transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
newProjectile.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum PaintColor { None, Red, Blue }
public class PaintBucket : MonoBehaviour
{
public PaintColor MyColor;
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAI : MonoBehaviour
{
public float DamageToFactory = 1;
public float AttackRange = 1;
public float AttackInterval = 1;
private float _attackTimer;
private Rigidbody2D _rigidbody2D;
private EntityData _entityData;
private EntityAttack _entityAttack;
private Animator _animator;
public Vector2 AttackPosition;
public AudioClip AttackClip;
public AudioClip AttackFactoryClip;
void Awake()
{
_rigidbody2D = GetComponent<Rigidbody2D>();
_entityData = GetComponent<EntityData>();
_entityAttack = GetComponent<EntityAttack>();
_animator = GetComponentInChildren<Animator>();
}
// Update is called once per frame
void Update()
{
if (_attackTimer > 0)
{
_attackTimer -= Time.deltaTime;
}
float distanceToTarget = float.MaxValue;
Transform targetTransform = FindClosesTarget(out distanceToTarget);
if (targetTransform != null)
{
_rigidbody2D.velocity = Vector2.zero;
if (_attackTimer <= 0)
{
_animator.SetTrigger("Attack");
AttackPosition = targetTransform.position;
AudioSource.PlayClipAtPoint(AttackClip, Camera.main.transform.position);
//_entityAttack.Attack(targetTransform.position); CALLED NOW FROM THE ANIMATION
_attackTimer = AttackInterval;
}
return;
}
_rigidbody2D.velocity = -transform.right * _entityData.MovementSpeed;
}
private Transform FindClosesTarget(out float distanceToTarget)
{
Collider2D[] closeEnemies = Physics2D.OverlapCircleAll(transform.position, AttackRange);
Transform targetTransform = null;
float minDistance = float.MaxValue;
foreach (var enemy in closeEnemies)
{
if (enemy.gameObject == this.gameObject)
continue;
if (enemy.tag != "PaperSoldier")
continue;
float dist = Vector2.Distance(transform.position, enemy.transform.position);
if (dist < minDistance)
{
minDistance = dist;
targetTransform = enemy.transform;
}
}
distanceToTarget = minDistance;
return targetTransform;
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, AttackRange);
}
private void OnTriggerEnter2D(Collider2D collider)
{
if(collider.tag == "Factory")
{
EntityHealth factoryHealth = collider.GetComponent<EntityHealth>();
if(factoryHealth != null)
{
AudioSource.PlayClipAtPoint(AttackFactoryClip, Camera.main.transform.position);
factoryHealth.ApplyDamage(DamageToFactory);
Destroy(this.gameObject);
}
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.SceneManagement;
public class GameOverScreen : MonoBehaviour
{
public AudioClip[] ClickClips;
public void Retry()
{
int randomID = Random.Range(0, ClickClips.Length);
AudioSource.PlayClipAtPoint(ClickClips[randomID], Camera.main.transform.position);
SceneManager.LoadScene("GameScene");
}
public void ReturnToMenu()
{
int randomID = Random.Range(0, ClickClips.Length);
AudioSource.PlayClipAtPoint(ClickClips[randomID], Camera.main.transform.position);
SceneManager.LoadScene("MenuScene");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
private static GameManager _instance;
public static GameManager Instance => _instance;
private int score;
public TextMeshProUGUI scoreText;
public TextMeshProUGUI waveText;
public TextMeshProUGUI gameOverText;
public TextMeshProUGUI enemiesLeftText;
public bool isGameActive;
public Button restartButton;
public GameObject titleScreen;
public SpawnManager spawnManager;
public GameObject playerObject;
public GameObject playerSpawn;
private void Awake()
{
if(_instance == null)
{
_instance = this;
}
}
//Starts the game when the corresponding button is pressed
public void StartGame()
{
titleScreen.gameObject.SetActive(false); //Turns off the Title Text
isGameActive = true; // Sets the game to active mode, which interacts with the spawn manager
this.GetComponent<SpawnManager>().enabled = true; //Sets the spawnmanager to on.
score = 0; // Makes sure the score is 0.
UpdateScore(0);
//UpdateWave(1); //Makes sure the Wave number is 1.
Instantiate(playerObject, playerSpawn.transform.position, Quaternion.identity); // Spawn player character
}
private void Update()
{
UpdateWave();
UpdateEnemiesLeft();
}
//Makes sure to stop the wave spawner if the Game is over
public void GameOver()
{
isGameActive = false;
gameOverText.gameObject.SetActive(true);
restartButton.gameObject.SetActive(true);
}
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void UpdateScore(int scoreToAdd)
{
score += scoreToAdd;
scoreText.text = score.ToString();
}
public void UpdateWave()
{
waveText.text = spawnManager.waveNumber.ToString();
}
public void UpdateEnemiesLeft()
{
enemiesLeftText.text = spawnManager.enemyCount.ToString();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlueDebuff : MonoBehaviour
{
public int MaxStacksCount;
public float IntervalToDeapply = 2;
private float _deapplyTimer;
private readonly float SPEED_MODIFIER = .075f;
private EntityData _entityData;
private int _stacksCount;
private float _originalSpeed;
public GameObject BlueDebuffIcon;
void Start()
{
_entityData = GetComponent<EntityData>();
_originalSpeed = _entityData.MovementSpeed;
}
private void Update()
{
if (_stacksCount <= 0)
return;
if(_deapplyTimer > 0)
{
_deapplyTimer -= Time.deltaTime;
if(_deapplyTimer <= 0)
{
Deapply();
_deapplyTimer = IntervalToDeapply;
}
}
}
public void Apply(int stacksAmount)
{
_stacksCount = Mathf.Min(_stacksCount + stacksAmount, MaxStacksCount);
_entityData.MovementSpeed = _originalSpeed - (float)_stacksCount * SPEED_MODIFIER;
_entityData.MovementSpeed = Mathf.Max(_entityData.MovementSpeed, 0);
_deapplyTimer = IntervalToDeapply;
if (BlueDebuffIcon.activeSelf == false)
{
BlueDebuffIcon.SetActive(true);
}
BlueDebuffIcon.transform.localScale = Vector3.one * _stacksCount * .09f;
}
private void Deapply()
{
_stacksCount = Mathf.Max(_stacksCount - 1, 0);
_entityData.MovementSpeed = _originalSpeed - (float)_stacksCount * SPEED_MODIFIER;
_entityData.MovementSpeed = Mathf.Max(_entityData.MovementSpeed, 0);
if (_stacksCount <= 0 && BlueDebuffIcon.activeSelf == true)
{
BlueDebuffIcon.SetActive(false);
}
BlueDebuffIcon.transform.localScale = Vector3.one * _stacksCount * .09f;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyHealth : EntityHealth
{
public Image HealthBar;
public int ScorePoints = 1;
protected override void Death()
{
base.Death();
GameManager.Instance.UpdateScore(ScorePoints);
}
protected override void OnDamage(float amount)
{
base.OnDamage(amount);
HealthBar.fillAmount = _entityData.HealthPoints / _entityData.InitialHealthPoints;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Explosion : MonoBehaviour
{
public int Damage;
public EAttackType AttackType;
public int RedStacksAmount;
public int BlueStacksAmount;
private GameObject _owner;
private string _teamTag;
public void Initialize(GameObject owner, string teamTag)
{
_owner = owner;
_teamTag = teamTag;
}
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject == _owner || collider.tag == _teamTag)
return;
EntityHealth targetHealth = collider.GetComponent<EntityHealth>();
if(targetHealth != null)
{
targetHealth.ApplyDamage(Damage);
HandleAttackType(collider.gameObject);
}
}
private void HandleAttackType(GameObject target)
{
if (AttackType == EAttackType.Blue)
{
BlueDebuff targetBlueDebuff = target.GetComponent<BlueDebuff>();
if (targetBlueDebuff != null)
{
targetBlueDebuff.Apply(BlueStacksAmount);
}
}
if (AttackType == EAttackType.Red)
{
RedDebuff targetRedDebuff = target.GetComponent<RedDebuff>();
if (targetRedDebuff != null)
{
targetRedDebuff.Apply(RedStacksAmount);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PaperSoldierHealth : EntityHealth
{
private Animator _animator;
private void Awake()
{
_animator = GetComponent<Animator>();
}
protected override void Death()
{
StartCoroutine(DeathCoroutine());
}
private IEnumerator DeathCoroutine()
{
GetComponent<PaperSoldierAI>().enabled = false;
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Collider2D>().enabled = false;
GetComponent<SpriteRenderer>().sortingLayerName = "DeadPaperSoldiers";
_animator.SetTrigger("Death");
yield return new WaitForSeconds(10);
Destroy(this.gameObject);
}
}
<file_sep># GameJamGame
Game for 9/11-9/14 Game Jam
i am in!
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConveryourBelt : MonoBehaviour
{
public GameObject[] AllWeapons;
public float SpawnInterval = 2;
private float _spawnTimer;
private GameObject[] _spawnedWeapons;
private Transform[] _spawnPoints;
private void Awake()
{
_spawnPoints = new Transform[transform.childCount];
_spawnedWeapons = new GameObject[transform.childCount];
for (int i = 0; i < transform.childCount; i++)
{
_spawnPoints[i] = transform.GetChild(i);
}
_spawnTimer = SpawnInterval;
}
private void Update()
{
if(_spawnTimer > 0)
{
_spawnTimer -= Time.deltaTime;
if(_spawnTimer <= 0)
{
SpawnWeapon();
_spawnTimer = SpawnInterval;
}
}
}
private void SpawnWeapon()
{
for (int i = 0; i < _spawnedWeapons.Length; i++)
{
if(_spawnedWeapons[i] == null)
{
int randomID = Random.Range(0, AllWeapons.Length);
GameObject newWeapon = AllWeapons[randomID];
_spawnedWeapons[i] = Instantiate(newWeapon, _spawnPoints[i].position, Quaternion.identity);
break;
}
}
}
}
<file_sep>using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class UIFloatingTextsManager : MonoBehaviour
{
public static UIFloatingTextsManager Instance { get; private set; }
[SerializeField] private GameObject FloatingTextPrefab = null;
[SerializeField] private int InitialPoolSize = 8;
private Dictionary<GameObject, TextMeshPro> _pool = new Dictionary<GameObject, TextMeshPro>();
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
}
}
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < InitialPoolSize; i++)
{
AddToPool();
}
}
private KeyValuePair<GameObject, TextMeshPro> AddToPool()
{
GameObject popupObject = Instantiate(FloatingTextPrefab, Vector3.zero, Quaternion.identity, this.transform);
popupObject.SetActive(false);
TextMeshPro popupText = popupObject.GetComponentInChildren<TextMeshPro>();
var newEntry = new KeyValuePair<GameObject, TextMeshPro>(popupObject, popupText);
_pool.Add(popupObject, popupText);
return newEntry;
}
private KeyValuePair<GameObject, TextMeshPro> GetFromPool()
{
foreach (var kvp in _pool)
{
if(kvp.Key.activeSelf == false)
{
return kvp;
}
}
return AddToPool();
}
public void ShowText(float amount, Transform targetTransform)
{
var entry = GetFromPool();
entry.Key.transform.position = (Vector2)targetTransform.position + Vector2.up * .5f;
entry.Value.text = amount.ToString();
entry.Key.gameObject.SetActive(true);
}
}
| db6d4b7ed5537690d9d0167e1c48338eecac9a10 | [
"Markdown",
"C#"
] | 27 | C# | MilesButler35/GameJamGame | 7d5fe7fa7250c98afdb1f9096f47a7634af8295b | 3f7161cad9791cafabd2e0fe66d73ae39b11fff6 |
refs/heads/master | <file_sep>var axios=require('axios')
axios.get('http://habrahabr.kz/')
.then(function (response){
var str = response.data;
//console.log(str);
s1=str.indexOf("<h1 class=\"topic-title\">");
s2=str.indexOf("</h1>");
console.log(s1 , s2);
data=str.slice(s1 , s2);
console.log(data);})
//console.log(str.indexOf("<H1>"));
//console.log(str.indexOf("</H1>"));
//s1=str.indexOf("<H1>"+4) ;
//s2=str.indexOf("</H1>");
//str=str.slice(s1 , s2)
//console.log(str);<file_sep>var axios=require('axios')
var str=require('string');
axios.get('http://tengrinews.kz/')
.then(function(response) {
var currency=str(response.data).between("KZT -","<span").s;
console.log("USD/KZT=",currency);
})
<file_sep>var s,r,d,u;
var read = require('read');
read({ prompt : 'Введите первое число'}, function (err, n) {
read({ prompt : 'Введите второе число'}, function (err, n2) {
process.stdin.destroy();
console.log('Введенное вами первое число =',n,'Веденное вами второе число =',n2);
var a = parseFloat(n);
var b = parseFloat(n2);
s=a + b ;
console.log('сумма=',s);
r=a-b;
console.log('разность=',r);
d=a/b;
console.log('деление=',d);
u=a*b;
console.log('умножение=',u)
var max= a;
if(a>b){
console.log("Число",a,"больше","числа",b);
} else {
if(b==a){
console.log("Число",a,"и число",b," являются равными")
}
else {
console.log("Число",b,"больше","числа",a);
}
}
});
})
<file_sep>var mass = [17,6,15,8,2,20,12];
var i;
var res=0;
console.log('массив с вычисленной разницей')
for(i=0;i<= mass.length-2;i++)
{
console.log(mass[i],res=([mass[i]-mass[i+1]]));
} | 7b2d042cea3677fd1cdc0ed478927f03944af9e3 | [
"JavaScript"
] | 4 | JavaScript | AzamatNakispekov/Zadachi | 3d7c0683feba8ab3c9a22b95e1b0531c10087fbf | 1809355a617318e9039bdc1999218b87e262556d |
refs/heads/master | <repo_name>Matthew14/SnakeXNA<file_sep>/Snake/Snake/Grid.cs
using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
namespace Snake
{
public class Grid
{
private int length = Cell.length;
private int sizeX, sizeY;
public Cell[,] gridArray;
public Snake snake;
public Grid() : this(50, 50){}
public Grid(int sizeX, int sizeY)
{
this.sizeX = sizeX;
this.sizeY = sizeY;
gridArray = new Cell[this.sizeX, this.sizeY];
FillGrid();
snake = new Snake(gridArray, length);
Food();//first food piece
}
public void Food()
{
Random r = new Random(DateTime.Now.Millisecond);
int x = r.Next(0, sizeX);
int y = r.Next(0, sizeY);
while (gridArray[x, y].SnakeOnMe)//food can't spawn on the snake
{
x = r.Next(0, sizeX);
y = r.Next(0, sizeY);
}
gridArray[x, y].FoodOnMe = true;
}
public void FillGrid()
{
for (int i = 0; i < sizeX; ++i)
{
for (int j = 0; j < sizeY; ++j)
gridArray[i, j] = new Cell(i * length, j * length);
}
}
public void Update(SoundEffect se)
{
foreach (Cell c in gridArray)
{
if (c.FoodOnMe && c.SnakeOnMe)//snake eats the food
{
se.Play();
c.FoodOnMe = false;
Food();
snake.Grow();
}
}
snake.Update(gridArray);
}
public void Draw(SpriteBatch spritebatch)
{
foreach (Cell c in gridArray)
{
c.Draw(spritebatch);
}
}
}
}
<file_sep>/Snake/Snake/Snake.cs
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace Snake
{
public class Snake
{
private int speed = 10; //used in Game1.Update
public int Speed { get { return speed; } }
private int eaten = 0;
public int Eaten { get { return eaten; } }
private bool moving, growing;
private int length = 5; //length of snake in rects
private int cellSize;
private LinkedList<Rectangle> body; // the squares making up the body first = head etc.
public enum dir {UP, DOWN, RIGHT, LEFT};
private dir direction;
public dir Direction
{
get { return direction; }
set
{
//this prevents direction being set to left if already going
//right and so on
switch (value)
{
case dir.UP:
if (direction != dir.DOWN)
direction = value;
break;
case dir.DOWN:
if (direction != dir.UP)
direction = value;
break;
case dir.LEFT:
if (direction != dir.RIGHT)
direction = value;
break;
case dir.RIGHT:
if (direction != dir.LEFT)
direction = value;
break;
default:
throw new NotSupportedException("Direction must be left, right, up or down");
}
}
}
public Snake(Cell[,] cellArray, int cellSize)
{
this.cellSize = cellSize;
moving = true;
Random r = new Random(DateTime.Now.Millisecond);
int startPos = r.Next(0, cellArray.GetLength(1) - this.length);
direction = dir.UP;
body = new LinkedList<Rectangle>();
body.AddFirst(new Rectangle(startPos, startPos, cellSize, cellSize));
for (int i = 0; i < length; ++i)
body.AddLast(new Rectangle(startPos + i, startPos, cellSize, cellSize));
}
public Snake(Cell[,] cellArray): this(cellArray, 5) { }
public void Grow()
{
speed++;
eaten++;
growing = true;
}
public void Update(Cell[,] cellArray)
{
if (moving)
{
Rectangle toAdd = new Rectangle();
switch (direction)
{
case dir.UP:
if (body.First.Value.Y - 1 >= 0)
toAdd = new Rectangle(body.First.Value.X,
body.First.Value.Y - 1, cellSize, cellSize);
else
toAdd = new Rectangle(body.First.Value.X,
cellArray.GetLength(1) - 1, cellSize, cellSize);
break;
case dir.RIGHT:
if (body.First.Value.X + 1 < cellArray.GetLength(0))
toAdd = new Rectangle(body.First.Value.X + 1,
body.First.Value.Y, cellSize, cellSize);
else
toAdd = new Rectangle(0,
body.First.Value.Y, cellSize, cellSize);
break;
case dir.DOWN:
if (body.First.Value.Y + 1 < cellArray.GetLength(1))
toAdd = new Rectangle(body.First.Value.X,
body.First.Value.Y + 1, cellSize, cellSize);
else
toAdd = new Rectangle(body.First.Value.X,
0, cellSize, cellSize);
break;
case dir.LEFT:
if (body.First.Value.X - 1 >= 0)
toAdd = new Rectangle(body.First.Value.X - 1,
body.First.Value.Y, cellSize, cellSize);
else
toAdd = new Rectangle(cellArray.GetLength(0) - 1,
body.First.Value.Y, cellSize, cellSize);
break;
default:
break;
}
foreach (Rectangle r in body)
{
if (toAdd == r)
{
moving = false;
Game1.gameover = true;
}
}
if (moving)
{
body.AddFirst(toAdd);
cellArray[toAdd.X, toAdd.Y].SnakeOnMe = true;
}
if (!growing)
{
cellArray[body.Last.Value.X, body.Last.Value.Y].SnakeOnMe = false;
body.RemoveLast();
}
growing = false;
}
}
}
}
<file_sep>/README.md
# SnakeXNA
========
<a href="http://goo.gl/YsMvG">Windows Installer</a>
Clone of the classic snake game written in C# using the XNA framework
## Screenshots


## Depends on:
* .Net Framework version 4
* XNA version 4.0
<file_sep>/Snake/Snake/Cell.cs
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace Snake
{
public class Cell
{
public static int length = 10; //size of cell in pixels
private int PosX, PosY; // Cell position
private Rectangle cellRect;
public bool SnakeOnMe { get; set; }
public bool FoodOnMe { get; set; }
public Cell(int PosX, int PosY)
{
this.PosX = PosX;
this.PosY = PosY;
cellRect = new Rectangle(PosX, PosY, length, length);
}
public void Draw(SpriteBatch spriteBatch)
{
if (SnakeOnMe)
spriteBatch.Draw(Game1.cellSprite, cellRect, Color.Black);
else if (FoodOnMe)
spriteBatch.Draw(Game1.cellSprite, cellRect, Color.Blue);
else
{
if (!Game1.gameover)
spriteBatch.Draw(Game1.cellSprite, cellRect, Color.Gray);
else
spriteBatch.Draw(Game1.cellSprite, cellRect, Color.DarkRed);
}
}
}
}<file_sep>/Snake/Snake/Form1.cs
using System;
using System.Windows.Forms;
namespace Snake
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
public IntPtr getDrawSurface()
{
return pctSurface.Handle;
}
public ToolStripLabel getScoreLabel()
{
return scoreLabel;
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
//Make sure the game quits too
Program.game.Exit();
}
private void newGameButton_Click(object sender, EventArgs e)
{
Program.game.NewGame();
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
newGameButton_Click(sender, e);
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
{
Program.game.paused = !Program.game.paused;
pauseToolStripMenuItem.Text = pauseToolStripMenuItem.Text == "Pause" ? "Unpause" : "Pause";
}
private void pctSurface_Click(object sender, EventArgs e)
{
pauseToolStripMenuItem_Click(sender, e);
}
}
}
<file_sep>/Snake/Snake/Program.cs
namespace Snake
{
#if WINDOWS || XBOX
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static Game1 game;
static void Main(string[] args)
{
Form1 form = new Form1();
form.Show();
game = new Game1(form.getDrawSurface(), form.getScoreLabel());
game.Run();
form.Close();
game.Exit();
}
}
#endif
}<file_sep>/Snake/Snake/Game1.cs
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Snake
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
ContentManager content;
KeyboardState lastState;
SoundEffect soundEffect;
public static Texture2D cellSprite;
public bool paused;
public static bool gameover;
public Grid grid; //main game grid
//Windows forms components
public IntPtr drawSurface;
public System.Windows.Forms.ToolStripLabel scoreLabel;
public Game1(IntPtr drawSurface, System.Windows.Forms.ToolStripLabel scoreLabel)
{
this.drawSurface = drawSurface;
this.scoreLabel = scoreLabel;
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 600;
graphics.PreferredBackBufferHeight = 600;
//windows forms setup
graphics.PreparingDeviceSettings +=
new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
System.Windows.Forms.Control.FromHandle((this.Window.Handle)).VisibleChanged +=
new EventHandler(Game1_VisibleChanged);
Window.ClientSizeChanged += new EventHandler<EventArgs>(Window_ClientSizeChanged);
}
void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
{
e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle =
drawSurface;
}
/// <summary>
/// Occurs when the original gamewindows' visibility changes and makes sure it stays invisible
/// </summary>
private void Game1_VisibleChanged(object sender, EventArgs e)
{
if (System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible == true)
System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible = false;
}
void Window_ClientSizeChanged(object sender, EventArgs e)
{
paused = true;
grid = new Grid(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
}
protected override void Initialize()
{
Window.Title = "Snake";
this.IsMouseVisible = true;
lastState = Keyboard.GetState();
content = new ContentManager(Services);
Content.RootDirectory = "Content";
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
soundEffect = Content.Load<SoundEffect>("munch");
cellSprite = new Texture2D(spriteBatch.GraphicsDevice, 1, 1);
cellSprite.SetData(new[] { Color.White });
NewGame();
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
public void NewGame()
{
//Make a new grid to fill the screen
int x = (int)graphics.PreferredBackBufferWidth / Cell.length;
int y = (int)graphics.PreferredBackBufferHeight / Cell.length;
grid = new Grid(x, y);
gameover = false;
}
protected override void Update(GameTime gameTime)
{
KeyboardState state = Keyboard.GetState();
if (!paused)
{
if (state.IsKeyDown(Keys.Up) && lastState.IsKeyUp(Keys.Up))
grid.snake.Direction = Snake.dir.UP;
else if (state.IsKeyDown(Keys.Down) && lastState.IsKeyUp(Keys.Down))
grid.snake.Direction = Snake.dir.DOWN;
else if (state.IsKeyDown(Keys.Right) && lastState.IsKeyUp(Keys.Right))
grid.snake.Direction = Snake.dir.RIGHT;
else if (state.IsKeyDown(Keys.Left) && lastState.IsKeyUp(Keys.Left))
grid.snake.Direction = Snake.dir.LEFT;
grid.Update(soundEffect);
base.Update(gameTime);
}
lastState = state;
if (!gameover)
scoreLabel.Text = "Score: " + grid.snake.Eaten.ToString();
else
{
scoreLabel.Text = "GAME OVER! " + "Score: " + grid.snake.Eaten.ToString();
}
//Update speed changes as the snake's does (food eaten)
this.TargetElapsedTime = TimeSpan.FromSeconds(1.0f / grid.snake.Speed);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
grid.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| 7fc3770bcbc2f658d0edc5c5df33c93302dcd40e | [
"Markdown",
"C#"
] | 7 | C# | Matthew14/SnakeXNA | 6ee2ca8fd101e34d5e885b836b386f7334b1658b | 7f4d28e0d99b614455363d1fa5ed72c5d3c3f8e0 |
refs/heads/master | <repo_name>davidgriffiths-dg/info3180-project1<file_sep>/app/models.py
from . import db
class Property(db.Model):
__tablename__ = "properties"
pid = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(80))
description = db.Column(db.String(1000))
rooms = db.Column(db.Integer)
bathrooms = db.Column(db.Integer)
price = db.Column(db.Integer)
property_type = db.Column(db.String(1000))
location = db.Column(db.String(1000))
photo = db.Column(db.String(30))
def __init__(self, title, description, rooms, bathrooms,price, property_type, location, photo):
self.title=title
self.description=description
self.rooms=rooms
self.bathrooms=bathrooms
self.price=price
self.property_type=property_type
self.location=location
self.photo=photo<file_sep>/app/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, TextField, FileField, TextAreaField, SelectField
from wtforms.validators import DataRequired
from flask_wtf.file import FileField, FileRequired, FileAllowed
class PropertyForm(FlaskForm):
title = TextField("Property Title", validators = [DataRequired()])
description = TextAreaField("Property Description", validators = [DataRequired()])
rooms = TextField("No. of Rooms", validators = [DataRequired()])
bathrooms = TextField("No. of Bathrooms", validators = [DataRequired()])
price = TextField("Price", validators = [DataRequired()])
property_type = SelectField("Property Type", choices = [('House', 'House'), ('Apartment', 'Apartment')], validators = [DataRequired()])
location = TextField("Location", validators = [DataRequired()])
photo = FileField("Photo", validators=[FileRequired(), FileAllowed(['jpg','png'],'Images only!')]) | a624746827c0a1ec781270c79d9cc314e6d708b1 | [
"Python"
] | 2 | Python | davidgriffiths-dg/info3180-project1 | bae26364c917c429bf7d8ae18b5eb84382754a4e | a1c76b63dd9eeb5367715f43de1f98f891657551 |
refs/heads/master | <repo_name>mustangs1552/Ch29--Mission-Demolition<file_sep>/Assets/Scripts/ProjectileLine.cs
// (Unity3D) New monobehaviour script that includes regions for common sections, and supports debugging.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ProjectileLine : MonoBehaviour
{
#region GlobalVareables
#region DefaultVareables
public bool isDebug = false;
private string debugScriptName = "ProjectileLine";
#endregion
#region Static
public static ProjectileLine S;
#endregion
#region Public
public float minDist = .1f;
[Header("For Debug View Only")]
public LineRenderer line = null;
public List<Vector3> points;
#endregion
#region Private
private GameObject _poi = null;
#endregion
#endregion
#region CustomFunction
#region Public
public void Clear()
{
_poi = null;
line.enabled = false;
points = new List<Vector3>();
}
public void AddPoint()
{
Vector3 pt = _poi.transform.position;
if (points.Count > 0 && (pt - lastPoint).magnitude < minDist) return;
if(points.Count == 0)
{
Vector3 launchPos = Slingshot.S.launchPoint.transform.position;
Vector3 launchPosDiff = pt - launchPos;
points.Add(pt + launchPosDiff);
points.Add(pt);
line.SetVertexCount(2);
line.SetPosition(0, points[0]);
line.SetPosition(1, points[1]);
line.enabled = true;
}
else
{
points.Add(pt);
line.SetVertexCount(points.Count);
line.SetPosition(points.Count - 1, lastPoint);
line.enabled = true;
}
}
#endregion
#region Private
#endregion
#region Debug
private void PrintDebugMsg(string msg)
{
if (isDebug) Debug.Log(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintWarningDebugMsg(string msg)
{
Debug.LogWarning(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintErrorDebugMsg(string msg)
{
Debug.LogError(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
#endregion
#region Getters_Setters
public GameObject poi
{
get
{
return (_poi);
}
set
{
_poi = value;
if(poi != null)
{
line.enabled = false;
points = new List<Vector3>();
AddPoint();
}
}
}
public Vector3 lastPoint
{
get
{
if (points == null) return Vector3.zero;
return points[points.Count - 1];
}
}
#endregion
#endregion
#region UnityFunctions
#endregion
#region Start_Update
// Awake is called when the script instance is being loaded.
void Awake()
{
PrintDebugMsg("Loaded.");
S = this;
line = GetComponent<LineRenderer>();
line.enabled = false;
points = new List<Vector3>();
}
// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
void Start()
{
}
// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
void FixedUpdate()
{
if(poi == null)
{
if (FollowCam.S.poi != null)
{
if (FollowCam.S.poi.tag == "Projectile") poi = FollowCam.S.poi;
else return;
}
else return;
}
AddPoint();
if (poi.GetComponent<Rigidbody>().IsSleeping()) poi = null;
}
// Update is called every frame, if the MonoBehaviour is enabled.
void Update()
{
}
// LateUpdate is called every frame after all other update functions, if the Behaviour is enabled.
void LateUpdate()
{
}
#endregion
}<file_sep>/Assets/Scripts/MissionDemolition.cs
// (Unity3D) New monobehaviour script that includes regions for common sections, and supports debugging.
using UnityEngine;
using System.Collections;
public enum GameMode
{
idle,
playing,
levelEnd
}
public class MissionDemolition : MonoBehaviour
{
#region GlobalVareables
#region DefaultVareables
public bool isDebug = false;
private string debugScriptName = "MissionDemolition";
#endregion
#region Static
public static MissionDemolition S = null;
#endregion
#region Public
public GameObject[] castles;
public GUIText gtLevel = null;
public GUIText gtScore = null;
public Vector3 castlePos = Vector3.zero;
[Header("For Debug View Only")]
public int level = 0;
public int levelMax = 0;
public int shotsTaken = 0;
public GameObject castle = null;
public GameMode mode = GameMode.idle;
public string showing = "Slingshot";
#endregion
#region Private
#endregion
#endregion
#region CustomFunction
#region Static
public static void SwitchView(string view)
{
S.showing = view;
switch(S.showing)
{
case "Slingshot":
FollowCam.S.poi = null;
break;
case "Castle":
FollowCam.S.poi = S.castle;
break;
case "Both":
FollowCam.S.poi = GameObject.Find("ViewBoth");
break;
}
}
public static void ShotFired()
{
S.shotsTaken++;
}
#endregion
#region Public
#endregion
#region Private
private void StartLevel()
{
if (castle != null) Destroy(castle);
GameObject[] gos = GameObject.FindGameObjectsWithTag("Projectile");
foreach (GameObject pTemp in gos) Destroy(pTemp);
castle = Instantiate(castles[level]) as GameObject;
castle.transform.position = castlePos;
shotsTaken = 0;
SwitchView("Both");
ProjectileLine.S.Clear();
Goal.goalMet = false;
ShowGT();
mode = GameMode.playing;
}
private void ShowGT()
{
gtLevel.text = "Level: " + (level + 1) + " of " + levelMax;
gtScore.text = "Shots Taken: " + shotsTaken;
}
private void NextLevel()
{
level++;
if (level == levelMax) level = 0;
StartLevel();
}
#endregion
#region Debug
private void PrintDebugMsg(string msg)
{
if (isDebug) Debug.Log(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintWarningDebugMsg(string msg)
{
Debug.LogWarning(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintErrorDebugMsg(string msg)
{
Debug.LogError(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
#endregion
#region Getters
#endregion
#region Setters
#endregion
#endregion
#region UnityFunctions
void OnGUI()
{
Rect buttonRect = new Rect((Screen.width / 2) - 50, 10, 100, 24);
switch(showing)
{
case "Slingshot":
if (GUI.Button(buttonRect, "Show Castle")) SwitchView("Castle");
break;
case "Castle":
if (GUI.Button(buttonRect, "Show Both")) SwitchView("Both");
break;
case "Both":
if (GUI.Button(buttonRect, "Show Slingshot")) SwitchView("Slingshot");
break;
}
}
#endregion
#region Start_Update
// Awake is called when the script instance is being loaded.
void Awake()
{
PrintDebugMsg("Loaded.");
}
// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
void Start()
{
S = this;
level = 0;
levelMax = castles.Length;
StartLevel();
}
// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
void FixedUpdate()
{
}
// Update is called every frame, if the MonoBehaviour is enabled.
void Update()
{
ShowGT();
if(mode == GameMode.playing && Goal.goalMet)
{
mode = GameMode.levelEnd;
SwitchView("Both");
Invoke("NextLevel", 2f);
}
}
// LateUpdate is called every frame after all other update functions, if the Behaviour is enabled.
void LateUpdate()
{
}
#endregion
}<file_sep>/Assets/Scripts/Slingshot.cs
// (Unity3D) New monobehaviour script that includes regions for common sections, and supports debugging.
using UnityEngine;
using System.Collections;
public class Slingshot : MonoBehaviour
{
#region GlobalVareables
#region DefaultVareables
public bool isDebug = false;
private string debugScriptName = "Slingshot";
#endregion
#region Static
public static Slingshot S = null;
#endregion
#region Public
public GameObject prefabProjectile = null;
public float velocityMulti = 4f;
[Header ("For Debug View Only")]
public GameObject launchPoint = null;
public Vector3 launchPos = Vector3.zero;
public GameObject projectile = null;
public bool aimingMode = false;
#endregion
#region Private
#endregion
#endregion
#region CustomFunction
#region Public
#endregion
#region Private
#endregion
#region Debug
private void PrintDebugMsg(string msg)
{
if (isDebug) Debug.Log(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintWarningDebugMsg(string msg)
{
Debug.LogWarning(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintErrorDebugMsg(string msg)
{
Debug.LogError(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
#endregion
#region Getters
#endregion
#region Setters
#endregion
#endregion
#region UnityFunctions
public void OnMouseEnter()
{
PrintDebugMsg("OnMouseEnter() called.");
launchPoint.SetActive(true);
}
public void OnMouseExit()
{
PrintDebugMsg("OnMouseExit() called.");
launchPoint.SetActive(false);
}
public void OnMouseDown()
{
aimingMode = true;
projectile = Instantiate(prefabProjectile) as GameObject;
projectile.transform.position = launchPos;
projectile.GetComponent<Rigidbody>().isKinematic = true;
}
#endregion
#region Start_Update
// Awake is called when the script instance is being loaded.
void Awake()
{
PrintDebugMsg("Loaded.");
S = this;
Transform launchPointTrans = transform.Find("LaunchPoint");
launchPoint = launchPointTrans.gameObject;
launchPoint.SetActive(false);
launchPos = launchPointTrans.position;
}
// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
void Start()
{
}
// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
void FixedUpdate()
{
}
// Update is called every frame, if the MonoBehaviour is enabled.
void Update()
{
if (!aimingMode) return;
Vector3 mousePos2D = Input.mousePosition;
mousePos2D.z = -Camera.main.transform.position.z;
Vector3 mousePos3D = Camera.main.ScreenToWorldPoint(mousePos2D);
Vector3 mouseDelta = mousePos3D - launchPos;
float maxMagnitude = this.GetComponent<SphereCollider>().radius;
if(mouseDelta.magnitude > maxMagnitude)
{
mouseDelta.Normalize();
mouseDelta *= maxMagnitude;
}
Vector3 projPos = launchPos + mouseDelta;
projectile.transform.position = projPos;
if(Input.GetMouseButtonUp(0))
{
aimingMode = false;
Rigidbody rb = projectile.GetComponent<Rigidbody>();
rb.isKinematic = false;
rb.velocity = -mouseDelta * velocityMulti;
FollowCam.S.poi = projectile;
projectile = null;
MissionDemolition.ShotFired();
}
}
// LateUpdate is called every frame after all other update functions, if the Behaviour is enabled.
void LateUpdate()
{
}
#endregion
}<file_sep>/Assets/Scripts/FollowCam.cs
// (Unity3D) New monobehaviour script that includes regions for common sections, and supports debugging.
using UnityEngine;
using System.Collections;
public class FollowCam : MonoBehaviour
{
#region GlobalVareables
#region DefaultVareables
public bool isDebug = false;
private string debugScriptName = "FollowCam";
#endregion
#region Static
public static FollowCam S;
#endregion
#region Public
public float easing = .05f;
public Vector2 minXY = Vector2.zero;
[Header("For Debug View Only")]
public GameObject poi = null;
public float camZ = 0f;
#endregion
#region Private
#endregion
#endregion
#region CustomFunction
#region Public
#endregion
#region Private
#endregion
#region Debug
private void PrintDebugMsg(string msg)
{
if (isDebug) Debug.Log(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintWarningDebugMsg(string msg)
{
Debug.LogWarning(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintErrorDebugMsg(string msg)
{
Debug.LogError(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
#endregion
#region Getters
#endregion
#region Setters
#endregion
#endregion
#region UnityFunctions
#endregion
#region Start_Update
// Awake is called when the script instance is being loaded.
void Awake()
{
PrintDebugMsg("Loaded.");
S = this;
camZ = this.transform.position.z;
}
// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
void Start()
{
}
// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
void FixedUpdate()
{
Vector3 destination = Vector3.zero;
if (poi == null) destination = Vector3.zero;
else
{
destination = poi.transform.position;
if (poi.tag == "Projectile")
{
if (poi.GetComponent<Rigidbody>().IsSleeping())
{
poi = null;
return;
}
}
}
destination.x = Mathf.Max(minXY.x, destination.x);
destination.y = Mathf.Max(minXY.y, destination.y);
destination = Vector3.Lerp(transform.position, destination, easing);
destination.z = camZ;
transform.position = destination;
this.GetComponent<Camera>().orthographicSize = destination.y + 10;
}
// Update is called every frame, if the MonoBehaviour is enabled.
void Update()
{
}
// LateUpdate is called every frame after all other update functions, if the Behaviour is enabled.
void LateUpdate()
{
}
#endregion
}<file_sep>/Assets/Scripts/Goal.cs
// (Unity3D) New monobehaviour script that includes regions for common sections, and supports debugging.
using UnityEngine;
using System.Collections;
public class Goal : MonoBehaviour
{
#region GlobalVareables
#region DefaultVareables
public bool isDebug = false;
private string debugScriptName = "Goal";
#endregion
#region Static
public static bool goalMet = false;
#endregion
#region Public
#endregion
#region Private
#endregion
#endregion
#region CustomFunction
#region Public
#endregion
#region Private
#endregion
#region Debug
private void PrintDebugMsg(string msg)
{
if (isDebug) Debug.Log(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintWarningDebugMsg(string msg)
{
Debug.LogWarning(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
private void PrintErrorDebugMsg(string msg)
{
Debug.LogError(debugScriptName + "(" + this.gameObject.name + "): " + msg);
}
#endregion
#region Getters
#endregion
#region Setters
#endregion
#endregion
#region UnityFunctions
void OnTriggerEnter(Collider otherCol)
{
PrintDebugMsg("Triggered!");
if(otherCol.gameObject.tag == "Projectile")
{
goalMet = true;
Color c = GetComponent<Renderer>().material.color;
PrintDebugMsg("Goal Color = " + c);
c.a = 1;
GetComponent<Renderer>().material.color = c;
}
}
#endregion
#region Start_Update
// Awake is called when the script instance is being loaded.
void Awake()
{
PrintDebugMsg("Loaded.");
}
// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
void Start()
{
}
// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
void FixedUpdate()
{
}
// Update is called every frame, if the MonoBehaviour is enabled.
void Update()
{
}
// LateUpdate is called every frame after all other update functions, if the Behaviour is enabled.
void LateUpdate()
{
}
#endregion
} | 46fd4303d7956c977830bce40e68db7392da79e2 | [
"C#"
] | 5 | C# | mustangs1552/Ch29--Mission-Demolition | f97393dc52034e09558e392b71a4bd8b92e9a735 | 6269ea4ed95e2a790b776395358c20a43ad051d8 |
refs/heads/master | <repo_name>tgujar/fsopen<file_sep>/part2/dataforcountries/src/components/Weather.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function Weather({ place }) {
let [weather, updateWeather] = useState({});
useEffect(() => {
axios
.get('http://api.weatherstack.com/current', {
params: {
access_key: process.env.REACT_APP_API_KEY,
query: place
}
})
.then(({ data }) => {
const curr = data.hasOwnProperty("current") ? data.current : null;
if (!curr) return;
updateWeather({
temp: curr.temperature,
icon: {
src: curr.weather_icons[0],
alt: curr.weather_descriptions[0]
},
wind: `${curr.wind_speed} Kmph direction ${curr.wind_dir}`
});
})
});
if (Object.keys(weather).length === 0) return <p>Waiting for weather in {place}..</p>
return (
<div>
<h2>Weather in {place}</h2>
<p><strong>Temperature:</strong>{weather.temp}</p>
<p><img src={weather.icon.src} alt={weather.icon.alt} /></p>
<p><strong>Wind:</strong>{weather.wind}</p>
</div>
);
}
export default Weather<file_sep>/part2/dataforcountries/src/components/Display.js
import React from 'react';
import Weather from './Weather'
function ShowButton({countryName, handleClick}) {
return <button onClick={() => handleClick(countryName)}>show</button>
}
function CountryInfo({country}) {
return (
<div>
<h2>{country.name}</h2>
<p>Capital: {country.capital}</p>
<p>Population: {country.population}</p>
<h3>Languages</h3>
<ul>
{country.languages.map(info => <li key={info.name}>{info.name}</li>)}
</ul>
<div>
<img src={country.flag} width="200px" height="200px" alt={`flag of ${country.name}`}/>
</div>
<Weather place={country.capital} />
</div>
);
}
function Display({countries, filter, update}) {
if (countries.length === 0) return <p>Waiting for results...</p>
const filtered = countries.filter(({name}) => new RegExp(`${filter}`, "gi").test(name));
if (filtered.length === 1) {
return <CountryInfo country={filtered[0]} />
} else if (filtered.length <= 10) {
return filtered.map(country => {
return (
<p key={country.name}>{country.name}
<ShowButton countryName={country.name} handleClick={update} />
</p>);
});
} else {
return <p>Too many matches, specify another filter</p>
}
}
export default Display<file_sep>/part2/dataforcountries/src/components/Search.js
import React from 'react';
function Search({filter, handleChange}) {
return (
<div>
<label>find countries
<input value={filter} onChange={handleChange} />
</label>
</div>);
}
export default Search<file_sep>/README.md
My solutions to [Full stack open 2020](https://fullstackopen.com/en)
<file_sep>/part1/unicafe/src/index.js
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const Statistic = (props) => {
return (
<>
<td>{props.text}</td>
<td>{props.value}</td>
</>
)
}
const Statistics = ({ good, bad, neutral }) => {
let all = good + neutral + bad;
let average = (good - bad) / all;
let posPercent = (good * 100) / all;
if (all === 0) {
return (
<p>No feedback given</p>
)
}
return (
<table>
<tbody>
<tr>
<Statistic text="good" value={good} />
</tr>
<tr>
<Statistic text="neutral" value={neutral} />
</tr>
<tr>
<Statistic text="bad" value={bad} />
</tr>
<tr>
<Statistic text="all" value={all} />
</tr>
<tr>
<Statistic text="average" value={average} />
</tr>
<tr>
<Statistic text="positive" value={posPercent + '%'} />
</tr>
</tbody>
</table>
)
}
const Button = (props) => {
return (
<button onClick={props.handleClick}>{props.name}</button>
)
}
const App = () => {
const [good, setGood] = useState(0);
const [neutral, setNeutral] = useState(0);
const [bad, setBad] = useState(0);
function increment(f, val) {
return () => f(val + 1);
}
return (
<div className="app">
<h2>give feedback</h2>
<Button handleClick={increment(setGood, good)} name="good" />
<Button handleClick={increment(setNeutral, neutral)} name="neutral" />
<Button handleClick={increment(setBad, bad)} name="bad" />
<h2>statistics</h2>
<Statistics good={good} bad={bad} neutral={neutral} />
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
<file_sep>/part2/phonebook/src/components/Filter.js
import React from 'react';
const Filter = ({ query, handleChange }) => {
return (
<div>
filter shown with <input value={query} onChange={handleChange} />
</div>);
}
export default Filter;<file_sep>/part2/phonebook/src/components/Notification.js
import React from 'react';
function Notification({ message, updateMessage }) {
const notifStyle = {
background: 'lightgrey',
fontSize: 20 + 'px',
borderStyle: 'solid',
borderRadius: 5 + 'px',
padding: 10 + 'px',
marginBottom: 10 + 'px'
};
const error = { ...notifStyle, color: 'red' };
const success = { ...notifStyle, color: 'green' };
if (message === null) return null;
else {
setTimeout(() => updateMessage(null), 5000);
return (
<div style={message.success ? success : error}>
{message.note}
</div>);
}
}
export default Notification | 54065b4f2b78697ebb8cd158b8eaab81ac429f26 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | tgujar/fsopen | 8ef43de875f97dc09d49f9771eacb56719f819e4 | c9dd28a4d3f03eebfb9df193d71716f3ca866091 |
refs/heads/master | <file_sep>import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
import 'bootstrap-social/bootstrap-social.css';
import './css/styles.css';
import helper from './helpers';
| 7325c04a89e10269b6ed3a80adf49ccc85829197 | [
"JavaScript"
] | 1 | JavaScript | jameslinjl/skycafephilly | 235fb9300616968a128f41260505e7cb9a31376a | 129dc87cfd20173b8550fb6f266d31a3234400f9 |
refs/heads/master | <file_sep>'use strict'
if (this.GithubBrowser === undefined) this.GithubBrowser = {};
(function(context) {
var $followersList;
function loadFollowers(folUrl) {
$.ajax(folUrl)
.done(function(data){
createDOM(data);
});
}
function createDOM (followers){
$followersList.empty();
console.log('Here is a thing you need!');
var $template = $('#followers-template');
var templateText = $template.html();
var templateFunc = _.template(templateText);
for (var follower of followers) {
var html = templateFunc(follower);
$followersList.append(html);
}
}
function reset() {
$('.follower-list').empty();
}
function init(folUrl) {
$followersList = $('.follower-list');
loadFollowers(folUrl);
}
context.FollowersView = {
init: init,
reset: reset
};
})(window.GithubBrowser);
| 7c2713cad88f7d8b47014970154cce526fe10a71 | [
"JavaScript"
] | 1 | JavaScript | Eric-Humpert-tiy-assignments/github-browser | 68a9e623b9befc56bb62218f4c589c095bef932d | e36d8d0bfce4e8f8a9f1e58da415008474c8b5c5 |
refs/heads/master | <file_sep>package de.hhn.helper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class that helps validating parameters. E.g. Validates if a String is not {code Null} or <code>""</code>
* Created by SHauck on 17.05.2017.
*/
public class Validation {
private static final Logger log = LoggerFactory.getLogger(Validation.class);
/**
* validates if the given {@link String} objects are not null and not empty
*
* @param strings
* must not be null
*
* @return <code>false</code> if atleast one string is invalid. <code>true</code> if all strings are valid
* @throws AssertionError
* if a parameter is invalid
*/
public static boolean validateStrings(String[] strings) {
log.debug("Validate Strings" + strings);
//validates parameter
if (strings == null) {
throw new AssertionError("The given String array can not be null!");
}
for (String currentString : strings) {
if (currentString == null || currentString.isEmpty()) {
return false;
}
}
return true;
}
/**
* validates if all given parameters are not null
*
* @param objects
* can not be {@code null}. Contains the parameters that should be tested
*
* @return <code>false</code> if parameter is invalid and <code>true</code> if all parameters are not null
* @throws AssertionError
* if a parameter is invalid
*/
public static boolean validateNullObjects(Object[] objects) {
log.debug("Validate NullObjects" + objects);
if (objects == null) {
throw new AssertionError("The parameter can not be null");
}
for (Object object : objects) {
if (object == null) {
return false;
}
}
return true;
}
}
<file_sep>package de.hhn.login;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Mocks the Methods for the authentication erver
* Created by SimonHauck-GamingPC on 30.04.2017.
*/
@RestController
public class LoginController {
/**
* accepts a user with the {@link User#getUsername()} <code>mustermann</code> and the {@link User#getPassword()}
* with <oode>1234</oode>
*
* @param user
* can not be null
* @return <code>true</code> if the user is authenticated, <code>false</code> if not
*/
@RequestMapping(value = "/employee", method = RequestMethod.POST)
public ResponseEntity<Boolean> login(@RequestBody User user) {
if (user != null &&
user.getUsername().equals("mustermann") &&
user.getPassword().equals("<PASSWORD>")) {
return new ResponseEntity<Boolean>(true, HttpStatus.OK);
} else {
return new ResponseEntity<Boolean>(false, HttpStatus.OK);
}
}
}
<file_sep>package de.hhn.lab;
import de.hhn.exceptions.InvalidParameterException;
import de.hhn.helper.Validation;
import de.hhn.models.LocationStrings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Random;
/**
* mocks the methods for the lab controller
* Created by SimonHauck-GamingPC on 18.05.2017.
*/
@RestController
public class LabController {
private static final Logger log = LoggerFactory.getLogger(LabController.class);
/**
* generates a order for the given destination. The order contains the given amount of {@link Order#getPrimerUID()}
*
* @param location
* the destination of the order
* @param amount
* the amount of {@link Order#getPrimerUID()}
* @return the generated Order
*/
private static Order generateOrder(String location, int amount) {
long id = IDGenerator.generateID();
Order order = new Order(id, location, new ArrayList<>());
for (int i = 0; i < amount; i++) {
order.getPrimerUID().add("id:" + id + "-index:" + i);
}
return order;
}
/**
* returns a list with Location as a destination for a {@link Order}. the storage will not appear as destination.
* If the given type is <code>"ALL"</code> it will return all locations except of the storage
*
* @param type
* locations that can process the given type of procedure. If the given parameter is emtpy, all locations
* except from the storage will be returned
* @return a list with location
*/
private static List<String> getDestination(String type) {
ArrayList<String> destinations = new ArrayList<>();
switch (type) {
case "S":
//Add only robot 1/2
destinations.add(LocationStrings.ROBOT1.getName());
destinations.add(LocationStrings.ROBOT2.getName());
return destinations;
case "M":
case "E":
//add all locations except the Storage location
ArrayList<LocationStrings> locationStrings = new ArrayList<>(EnumSet.allOf(LocationStrings.class));
locationStrings.remove(LocationStrings.STORAGE);
locationStrings.remove(LocationStrings.ROBOT1);
locationStrings.remove(LocationStrings.ROBOT2);
for (LocationStrings locationString : locationStrings) {
destinations.add(locationString.getName());
}
return destinations;
case "ALL":
ArrayList<LocationStrings> locationStrings2 = new ArrayList<>(EnumSet.allOf(LocationStrings.class));
locationStrings2.remove(LocationStrings.STORAGE);
for (LocationStrings locationString : locationStrings2) {
destinations.add(locationString.getName());
}
return destinations;
}
return null;
}
/**
* returns a {@link List} with {@link Order} objects.
*
* @param listType
* must be S, M, E
* @return ResponseEntity with a List of Orders
*/
@RequestMapping(value = "/primerlist/{listType}", method = RequestMethod.GET)
public ResponseEntity<List<Order>> getListFromType(@PathVariable("listType") String listType) {
log.info("getListFromType called with parametrs: " + listType);
List<Order> orders = new ArrayList<>();
Random rnd = new Random();
switch (listType) {
case "S":
for (String location : getDestination("S")) {
orders.add(generateOrder(location, 10));
}
return new ResponseEntity<List<Order>>(orders, HttpStatus.OK);
case "M":
for (String location : getDestination("M")) {
orders.add(generateOrder(location, 10));
}
return new ResponseEntity<List<Order>>(orders, HttpStatus.OK);
case "E":
for (String location : getDestination("E")) {
orders.add(generateOrder(location, 10));
}
return new ResponseEntity<List<Order>>(orders, HttpStatus.OK);
default:
throw new InvalidParameterException("The given parameter can not be recognized");
}
}
/**
* generates and returns a order list for all types of procedures
*
* @return list with {@link Order} objects
*/
@RequestMapping(value = "/primerlist", method = RequestMethod.GET)
public ResponseEntity<List<Order>> getAllOrders() {
log.info("getAllOrders called...");
List<Order> orders = new ArrayList<>();
Random rnd = new Random();
for (String location : getDestination("ALL")) {
orders.add(generateOrder(location, 10));
}
return new ResponseEntity<List<Order>>(orders, HttpStatus.OK);
}
/**
* returns if the corresponding list is successfully processed or not
*
* @param id
* of the list
* @param success
* status of the list
* @return a {@link ResponseEntity} with a status code
*/
@RequestMapping(value = "/list/{id}/{success}", method = RequestMethod.GET)
public ResponseEntity<Void> returnList(@PathVariable("id") long id, @PathVariable("success") boolean success) {
log.info("returnList called with parametsr: id: " + id + ", success: " + success);
return new ResponseEntity<Void>(HttpStatus.OK);
}
/**
* returns the status of the primer if known
*
* @param primerUID
* can not be {@code null} or empty
* @param location
* can not be {@code null} or empty
* @return ResponseEntity with a status code
*/
@RequestMapping(value = "/threshold/{primerUID}", method = RequestMethod.POST)
public ResponseEntity<Integer> getPrimerStatus(@PathVariable("primerUID") String primerUID, @RequestBody String location) {
log.info("getPrimerStatus called with parameters: PrimerUID: " + primerUID + ", Location: " + location);
if (!Validation.validateStrings(new String[]{primerUID, location})) {
throw new InvalidParameterException("Method received invalid parameters!");
}
if (location.equals(LocationStrings.ROBOT1.getName()) || location.equals(LocationStrings.ROBOT2.getName())) {
Random rnd = new Random();
if (rnd.nextInt(1) == 0) {
return new ResponseEntity<Integer>(0, HttpStatus.OK);
} else {
return new ResponseEntity<Integer>(3, HttpStatus.OK);
}
} else {
return new ResponseEntity<Integer>(199, HttpStatus.OK);
}
}
}
<file_sep>package de.hhn.storage;
import de.hhn.exceptions.InvalidParameterException;
import de.hhn.helper.Validation;
import de.hhn.models.LocationStrings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Eddy on 11.05.2017.
*/
@RestController
@RequestMapping("/list")
public class StorageController {
private static final Logger LOGGER = LoggerFactory.getLogger(StorageController.class);
@RequestMapping(value = "/primer/{primertubeid}/{username}/{password}", method = RequestMethod.PUT)
public ResponseEntity<Void> takePrimer(@PathVariable("username") String pUsername,
@PathVariable("password") String pPassword,
@PathVariable("primertubeid") String pPrimerTubeID,
@RequestBody String pLocation) {
LOGGER.info("takePrimer method called with parameters: username" + pUsername + ", password: " + <PASSWORD> + ", primertTubeId: " + pPrimerTubeID + ", location: " + pLocation);
if (!Validation.validateStrings(new String[]{pUsername, pPassword, pPrimerTubeID, pLocation})) {
throw new InvalidParameterException("A given parameter is empty!");
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@RequestMapping(value = "/primer/{primertubeid}/{status}/{username}/{password}", method = RequestMethod.GET)
public ResponseEntity<Void> returnPrimer(@PathVariable("username") String pUsername,
@PathVariable("password") String pPassword,
@PathVariable("primertubeid") String pPrimerTubeID,
@PathVariable("status") int status) {
LOGGER.info("return Primer valled with paramters: username" + pUsername + ", password: " + <PASSWORD> + ", primertubeid: " + pPrimerTubeID + ", status: " + status);
if (!Validation.validateStrings(new String[]{pUsername, pPassword, pPrimerTubeID})) {
throw new InvalidParameterException("A given paramter is invalid!");
}
if (status < 0) {
throw new InvalidParameterException("A given parameter is invalid");
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@RequestMapping(value = "/defectprimer/{primertubeid}/{username}/{password}", method = RequestMethod.PUT)
public ResponseEntity<Void> defectPrimer(@PathVariable("username") String pUsername,
@PathVariable("password") String pPassword,
@PathVariable("primertubeid") String pPrimerTubeID,
@RequestBody String pMessage) {
LOGGER.info("Method defectPrimer called with parameters: primertubeid: " + pPrimerTubeID + ", message: " + pMessage + ", username: " + pUsername + ", password: " + pPassword);
if (!Validation.validateStrings(new String[]{pUsername, pPassword, pPrimerTubeID, pMessage})) {
throw new InvalidParameterException("A given parameter is invalid!");
} else return new ResponseEntity<Void>(HttpStatus.OK);
}
@RequestMapping(value = "/primer/{primertubeid}/{username}/{password}", method = RequestMethod.DELETE)
public ResponseEntity<Void> emptyPrimer(@PathVariable("username") String pUsername,
@PathVariable("password") String pPassword,
@PathVariable("primertubeid") String pPrimerTubeID) {
LOGGER.info("Method emptyPrimer called with parameters: primertubeid: " + pPrimerTubeID + ", username: " + pUsername + ", password: " + pPassword);
if (!Validation.validateStrings(new String[]{pUsername, pPassword, pPrimerTubeID})) {
throw new InvalidParameterException("A given parameter is invalid!");
} else return new ResponseEntity<Void>(HttpStatus.OK);
}
@RequestMapping(value = "/primerlist/{primeruid}/{amount}/{username}/{password}", method = RequestMethod.GET)
public ResponseEntity<List<PrimerTubeListPOJO>> requestPrimerByPrimerUID(@PathVariable("username") String pUsername,
@PathVariable("password") String p<PASSWORD>,
@PathVariable("primeruid") String pPrimerTypeUID,
@PathVariable("amount") int pAmount) {
LOGGER.info("Method requestPrimerByPrimerUID is called with parameters: primertubeUID: " + pPrimerTypeUID + ", amount: " + pAmount + ", username: " + pUsername + ", password: " + pPassword);
if (!Validation.validateStrings(new String[]{pUsername, pPassword, pPrimerTypeUID}) || pAmount < 1) {
throw new InvalidParameterException("A given parameter is invalid!");
}
List<PrimerTubeListPOJO> primerTubes = new ArrayList<>();
for (int i = 0; i < pAmount; i++) {
PrimerTubeListPOJO primerTubeListPOJO = new PrimerTubeListPOJO(
"name" + i + "-" + pPrimerTypeUID,
LocationStrings.STORAGE.getName(),
"primerTubeID" + i + "-" + pPrimerTypeUID,
StorageCoordinate.generateStorageCoordinate(),
"lotNr" + i + "-" + pPrimerTypeUID,
true,
pPrimerTypeUID,
"manufacturer" + i + "-" + pPrimerTypeUID
);
primerTubes.add(primerTubeListPOJO);
}
return new ResponseEntity<List<PrimerTubeListPOJO>>(primerTubes, HttpStatus.OK);
}
@RequestMapping(value = "/search/storage/{name}/{username}/{password}", method = RequestMethod.GET)
public ResponseEntity<List<PrimerTubeListPOJO>> searchPrimerStorage(@PathVariable("username") String pUsername,
@PathVariable("password") String pPassword,
@PathVariable("name") String pName) {
LOGGER.info("Method searchPrimerStorage called with parameters: searchname: " + pName + ", username: " + pUsername + ", password: " + pPassword);
if (!Validation.validateStrings(new String[]{pUsername, pPassword, pName})) {
throw new InvalidParameterException("A given Parameter is invalid");
}
List<PrimerTubeListPOJO> primerTubes = new ArrayList<>();
for (int i = 0; i < 5; i++) {
primerTubes.add(generatePrimerTube(LocationStrings.STORAGE.getName(), i));
}
return new ResponseEntity<List<PrimerTubeListPOJO>>(primerTubes, HttpStatus.OK);
}
@RequestMapping(value = "/location/{primertubeid}/{username}/{password}", method = RequestMethod.PUT)
public ResponseEntity<Void> setLocation(@PathVariable("username") String pUsername,
@PathVariable("password") String pPassword,
@PathVariable("primertubeid") String pPrimerTubeID,
@RequestBody String pLocation) {
LOGGER.info("Method setLocation called with parameters: primerTubeID: " + pPrimerTubeID + ", location: " + pLocation + ", username: " + pUsername + ", password: " + pPassword);
if (!Validation.validateStrings(new String[]{pPrimerTubeID, pUsername, pPassword, pLocation})) {
throw new InvalidParameterException("A given parameter is invalid!");
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
@RequestMapping(value = "/search/gathered/{name}/{username}/{password}", method = RequestMethod.GET)
public ResponseEntity<List<PrimerTubeListPOJO>> searchGatheredPrimerByName(@PathVariable("username") String pUsername,
@PathVariable("password") String pPassword,
@PathVariable("name") String pName) {
LOGGER.info("Method searchPrimerByName called with parameters: name: " + pName + ", username: " + pUsername + ", password: " + pPassword);
if (!Validation.validateStrings(new String[]{pUsername, pPassword, pName})) {
throw new InvalidParameterException("A given Parameter is invaid!");
}
List<PrimerTubeListPOJO> primerTubes = new ArrayList<>();
List<LocationStrings> locations = new ArrayList<>(Arrays.asList(LocationStrings.values()));
for (int i = 0; i < 5; i++) {
primerTubes.add(generatePrimerTube(locations.get(i).getName(), i));
}
return new ResponseEntity<List<PrimerTubeListPOJO>>(primerTubes, HttpStatus.OK);
}
@RequestMapping(value = "/gathered/{username}/{password}", method = RequestMethod.GET)
public ResponseEntity<List<PrimerTubeListPOJO>> getAllGatheredPrimers(@PathVariable("username") String pUsername,
@PathVariable("password") String pPassword) {
LOGGER.info("Method getAllGatheredPrimers called with parameters: username: " + pUsername + ", password: " + pPassword);
if (!Validation.validateStrings(new String[]{pUsername, pPassword})) {
throw new InvalidParameterException("A given parameter is invalid!");
}
List<LocationStrings> locations = new ArrayList<>(Arrays.asList(LocationStrings.values()));
locations.remove(LocationStrings.STORAGE);
List<PrimerTubeListPOJO> tubes = new ArrayList<>();
for (int i = 0; i < locations.size(); i++) {
for (int j = 0; j < 5; j++) {
tubes.add(generatePrimerTube(locations.get(i).getName(), j));
}
}
return new ResponseEntity<List<PrimerTubeListPOJO>>(tubes, HttpStatus.OK);
}
public static PrimerTubeListPOJO generatePrimerTube(String location, int index) {
PrimerTubeListPOJO primerTubeListPOJO = new PrimerTubeListPOJO(
"name-" + index,
location,
"primerTubeID-" + index,
StorageCoordinate.generateStorageCoordinate(),
"lotNr" + index,
true,
"uid:" + index,
"manufacturer-" + index
);
return primerTubeListPOJO;
}
}
| 71de2354f53b7e8c7e7119643e97432980502fc0 | [
"Java"
] | 4 | Java | simonhauck/restmock | 5b466391c4ac9feb4b2afc9954b8825c5d1aa59d | d04022d6733642f1b44483dcb67192a49e3ba696 |
refs/heads/master | <file_sep><?php
if(isset($_POST)){
echo var_dump($_POST);
//include("views/resume.php");
exit;
}<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Filtres pour photos de profil Facebook</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="dist/jquery.cropit.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="src/bootstrap-cstm.css" type="text/css" />
<link rel="stylesheet" href="src/style.css" type="text/css" />
<link rel="stylesheet" href="src/styles.css" type="text/css" />
</head>
<body>
<div id="overlay" class="text-center">
<div id="loader" class="text-center">
<div class='uil-ripple-css' style='transform:scale(0.6);'><div></div><div></div></div>
<h3>Création de l'image...</h3>
</div>
</div>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a>Filtres personnalisés pour photos de profil Facebook</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="row">
<div class="container">
<div class="image-editor"><div id="overlay-editor" class="text-center"><img src="src/imgs/swipe-up.png" /><h2>Pour commencer, chargez une image de votre ordinateur</h2></div>
<div class="col-lg-12 text-center" id="fileInput">
<input type="file" id="chooseFile" class="btn btn-lg btn-primary cropit-image-input">
</div><hr />
<div class="col-lg-6 first">
<div class="cropit-preview"></div>
<img src="" class="filter" id="filterId" name="noel4"/>
<div id="msgResize" class="text-center"><h4>Votre image est trop petite pour être zoomée correctement</h4></div>
<div class="resize">
<i class="fa fa-search-minus fa-lg" aria-hidden="true" id="minus"></i>
<input type="range" class="cropit-image-zoom-input">
<i class="fa fa-search-plus fa-lg" aria-hidden="true" id="plus"></i>
</div>
<button class="rotate-ccw btn btn-default"><i class="fa fa-undo" aria-hidden="true"></i></i></button>
<button class="rotate-cw btn btn-default"><i class="fa fa-repeat" aria-hidden="true"></i></button>
</div>
<div class="col-lg-6 text-center second">
<h4>Choisissez parmis les filtres originaux</h4>
<select id="selectFilter" class="form-control">
<?php
echo $categories;
?>
</select>
<div id="resultFilters" class="text-center"></div>
<button class="export btn btn-annule" id="reset">Annuler</button>
<button class="export btn btn-facebook" id="generate">Générer !</button>
</div>
</div>
</div>
</div>
<script>
$(function() {
Lg = $(".cropit-preview").width();
$(".cropit-preview").height(Lg);
LgFirst = $(".first").height();
$(".second").height(LgFirst);
$("#fileInput").on("click","#chooseFile",function(){
$("#overlay-editor").fadeOut();
})
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 20,
smallImage:'stretch',
onZoomDisabled:function(){
$("#msgResize").show();
$(".resize").css({"opacity":0.2,"cursor":"not-allowed"});
},
onZoomEnabled:function(){
$("#msgResize").hide();
$(".resize").css({"opacity":1,"cursor":"pointer"});
}
});
$('.rotate-cw').click(function() {
$('.image-editor').cropit('rotateCW');
});
$('.rotate-ccw').click(function() {
$('.image-editor').cropit('rotateCCW');
});
$('.export').click(function() {
$("#overlay").show();
var imageData = $('.image-editor').cropit('export',{type: 'image/jpeg',quality: 1,originalSize: true});
var filter = $("#filterId").attr("name");
url = "index.php";
$.ajax({
type: "POST",
url: url,
data: {"imageData" : imageData, "filter":filter},
success:function(data){
$("#loader").empty().append(data);
}
});
});
$("#resultFilters").on("click",".img-thumbnail",function(){
src = $(this).attr("id");
Nsrc = "filters/" + src + ".png";
$("#filterId").attr("src", Nsrc);
$("#filterId").attr("name", src);
});
$("#selectFilter").change(function () {
$("#resultFilters").empty().append("<img src=\"src/imgs/loader.gif\" style=\"margin-top:50px;\" />");
var id = $( "#selectFilter option:selected").attr("id");
url = "index.php";
$.ajax({
type: "POST",
url: url,
data: {"categorieId" : id},
success: function(data){
$("#resultFilters").empty().append(data);
}
});
});
});
</script>
<script src="https://use.fontawesome.com/3ea4e2de6c.js"></script>
</body>
</html><file_sep><?php
define("USER","root");
define("PASS","");
$dbh = new PDO('mysql:host=localhost;dbname=filters', USER, PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
return $dbh;<file_sep><?php
// Création des instances d'image
$width = 500;
$height = 500;
$src = imagecreatefrompng('../filters/noel4.png');
$image_p = imagecreatetruecolor($width, $height);
$dest = imagecreatefrompng('../filters/pays_de_galles.png');
imagecopyresampled($image_p, $dest, 0, 0, 0, 0, $width, $height, 900, 900);
/*$w = imagesx($dest);
$h = imagesy($dest);*/
imagealphablending($src,true);
// Copie et fusionne
imagecopymerge($image_p, $src, 0, 100, 0, 100, 500, 500, 100);
// Affichage et libération de la mémoire
header('Content-Type: image/png');
imagepng($image_p,"monimage2.png");
?><file_sep><?php
//$image1 = $_POST['imageData'];
// base64_to_png($image1, 'filename.png');
$src = imagecreatefrompng('../filters/noel4.png');
$dest = imagecreatefrompng('../filters/pays_de_galles.png');
imagealphablending($dest, false);
imagesavealpha($dest, true);
imagecopymerge($dest, $src, 10, 9, 0, 0, 181, 180, 100); //have to play with these numbers for it to work for you, etc.
function base64_to_png($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
imagepng($dest);
// echo base64_encode($result);
// echo $result;<file_sep><?php
require_once("classes/manager.class.php");
require_once("classes/connect.php");
$manager = new manager($dbh);
if(isset($_POST['categorieId'])){
$id = (int) $_POST['categorieId'];
return $result = $manager->getFiltres($id);
}
if(isset($_POST['imageData']) and isset($_POST['filter'])){
$background = $_POST['imageData'];
$filter = $_POST['filter'];
$manager->createImage($background,$filter);
exit;
}
$categories = $manager->getCategories();
include("views/home.php");
exit;
<file_sep><?php
class manager
{
private $_dbh;
public function __construct($dbh){
$this->_dbh = $dbh;
}
public function test(){
echo "Hello World !";
}
public function createImage($background,$filter){
define("WIDTH", 900);
define("HEIGHT", 900);
$filterPath = "filters/HD/".htmlentities($filter).".png";
$backgroundPath = htmlentities($background);
$imageSize = getimagesize($backgroundPath);
$widthBG = $imageSize[0];
$heightBG = $imageSize[1];
$filter = imagecreatefrompng($filterPath);
imagealphablending($filter,true);
$image_p = imagecreatetruecolor(WIDTH, WIDTH);
$dest = imagecreatefromjpeg($backgroundPath);
imagecopyresampled($image_p, $dest, 0, 0, 0, 0, WIDTH, WIDTH, $widthBG, $heightBG);
/*$w = imagesx($dest);
$h = imagesy($dest);*/
/*$white = imagecolorallocate($image_p, 255, 255, 255);
imagecolortransparent ( $image_p , $white );*/
imagealphablending($image_p, true);
// Copie et fusionne
imagecopy($image_p, $filter, 0, 0, 0, 0, WIDTH, WIDTH);
$auj = date('d-m-Y');
$mili = time();
$ext = $auj."-".$mili;
$imgToSave = "imgs/img_".$ext.".png";
// Affichage et libération de la mémoire
imagepng($image_p,$imgToSave);
echo "<img src=\"".$imgToSave."\" class=\"img-result\" /><hr /><a href=\"index.php\" id=\"restart\" class=\"btn btn-restart\">Recommencer</a>
<a href=\"".$imgToSave."\" download id=\"download\" class=\"btn btn-facebook\">Télécharger</a>";
}
public function getFiltres($categorieId){
$id = (int) $categorieId;
$q = "SELECT * FROM filtres WHERE id_categorie=:id";
$sth = $this->_dbh->prepare($q);
$sth->bindParam(":id",$id,PDO::PARAM_INT);
$sth->execute();
$qr = "SELECT path FROM categories WHERE id=:id";
$sth2 = $this->_dbh->prepare($qr);
$sth2->bindParam(":id",$id,PDO::PARAM_INT);
$sth2->execute();
$path = $sth2->fetch();
$path = $path[0];
$output = $sth->fetchAll(PDO::FETCH_ASSOC);
$result = "";
foreach($output as $data){
$result .= "<img src=\"filters/preview/".$path."/".$data['path'].".png\" alt=\"".$data['nom']."\" id=\"".$path."/".$data['path']."\" class=\"img-thumbnail col-lg-3 thmbs\">";
}
echo $result;
}
public function getCategories(){
$q = "SELECT * FROM categories";
$sth = $this->_dbh->query($q);
$output = $sth->fetchAll(PDO::FETCH_ASSOC);
$categories = "";
foreach($output as $data){
$categories .= "<option id=\"".$data['id']."\">".$data['nom']."</option>";
}
return $categories;
}
} | 8fc5c758f04d1f8d8a565f4dcb1e81d884b1e566 | [
"PHP"
] | 7 | PHP | chicharlito/Filters | 601818e321b12db02aac38fcd754f8031b84e2c2 | 74e13bf1c30d2ee41a92fba6fc6309c9b2191719 |
refs/heads/master | <repo_name>grguang/algorithm<file_sep>/test/7.test.js
/**
* create by grguang
*
* @flow
*/
const {reverse} = require('../code/7.integer-inversion');
describe('reverse', () => {
it('reverse 1534236469', () => {
expect(reverse(1534236469)).toEqual(0);
});
it('reverse 123', () => {
expect(reverse(123)).toEqual(321);
});
it('reverse -123', () => {
expect(reverse(-123)).toEqual(-321);
});
});
<file_sep>/test/chainCallsClass.test.js
/**
*
* create by grg on 2022/7/7
*
* @flow
*/
const {PlayBoy} = require('../code/chainCallsClass');
describe('isPalindrome', () => {
it('PlayBoy', () => {
const tom = new PlayBoy('Tom');
tom.sayHi('Lili').sleep(2).play('王者').sleep(3).play('手机')
});
});
<file_sep>/test/hello.test.js
/**
* create by grguang
*
* @flow
*/
const { handleOffsetValueByPoint } = require('../code/hello');
describe('handleOffsetValueByPoint', () => {
it('component all in mainPad', () => {
const layers = [{
width: 50,
height: 30,
point: [100,50]
},{
width: 200,
height: 30,
point: [100,150]
},{
width: 80,
height: 30,
point: [125,200]
}];
const result = {
offsetPoint: [100,50],
width: 200,
height: 180,
};
expect(handleOffsetValueByPoint(layers)).toEqual(result);
});
it('component all in mainPad 2', () => {
const layers = [{
width: 75,
height: 30,
point: [200,50]
},{
width: 200,
height: 30,
point: [50,150]
},{
width: 50,
height: 30,
point: [50,250]
}];
const result = {
offsetPoint: [50,50],
width: 225,
height: 230,
};
expect(handleOffsetValueByPoint(layers)).toEqual(result);
});
it('component one in forkPad', () => {
const layers = [{
width: 75,
height: 30,
point: [-100,50]
},{
width: 200,
height: 30,
point: [50,100]
},{
width: 50,
height: 30,
point: [75,200]
}];
const result = {
offsetPoint: [-100,50],
width: 350,
height: 180,
};
expect(handleOffsetValueByPoint(layers)).toEqual(result);
});
it('component one in forkPad 1', () => {
const layers = [{
width: 250,
height: 30,
point: [-300,50]
},{
width: 200,
height: 30,
point: [50,100]
},{
width: 50,
height: 30,
point: [75,200]
}];
const result = {
offsetPoint: [-300,50],
width: 550,
height: 180,
};
expect(handleOffsetValueByPoint(layers)).toEqual(result);
});
it('component one in forkPad 2', () => {
const layers = [{
width: 50,
height: 30,
point: [-300,50]
},{
width: 200,
height: 30,
point: [50,100]
},{
width: 50,
height: 30,
point: [75,200]
}];
const result = {
offsetPoint: [-300,50],
width: 550,
height: 180,
};
expect(handleOffsetValueByPoint(layers)).toEqual(result);
});
it('component some in forkPad', () => {
const layers = [{
width: 300,
height: 30,
point: [50,-100]
},{
width: 150,
height: 30,
point: [50,75]
},{
width: 100,
height: 30,
point: [-150,50]
}];
const result = {
offsetPoint: [-150,-100],
width: 500,
height: 205,
};
expect(handleOffsetValueByPoint(layers)).toEqual(result);
});
it('component some in forkPad 1', () => {
const layers = [{
width: 300,
height: 30,
point: [50,-100]
},{
width: 150,
height: 30,
point: [50,75]
},{
width: 100,
height: 30,
point: [-150,50]
},{
width: 250,
height: 30,
point: [150,150]
}];
const result = {
offsetPoint: [-150,-100],
width: 550,
height: 280,
};
expect(handleOffsetValueByPoint(layers)).toEqual(result);
});
});
<file_sep>/test/14.test.js
/**
* create by grguang
*
* @flow
*/
const {longestCommonPrefix} = require('../code/14.longestCommonPrefix');
describe('longestCommonPrefix', () => {
it('longestCommonPrefix ["flower","flow","flight"]', () => {
expect(longestCommonPrefix(["flower","flow","flight"])).toBe('fl');
});
it('longestCommonPrefix ["dog","racecar","car"]', () => {
expect(longestCommonPrefix(["dog","racecar","car"])).toBe('');
});
});
<file_sep>/test/234.test.js
/**
* create by grguang
*
* @flow
*/
const {isPalindrome} = require('../code/234.isPalindrome');
describe('isPalindrome', () => {
it('isPalindrome [1,2]', () => {
expect(isPalindrome({val: 1, next: {val: 2, next: null}})).toBe(false);
});
it('isPalindrome [1]', () => {
expect(isPalindrome({val: 1, next: null})).toBe(true);
});
it('isPalindrome [1,2,1]', () => {
expect(isPalindrome({val: 1, next: {val: 2, next: {val: 1, next: null}}})).toBe(true);
});
it('isPalindrome [1,2,2,1]', () => {
expect(isPalindrome({val: 1, next: {val: 2, next: {val: 2, next: {val: 1, next: null}}}})).toBe(true);
});
});
<file_sep>/test/1.test.js
/**
* create by grguang
*
* @flow
*/
const {twoSum} = require('../code/1.two-sum');
describe('twoSum', () => {
it('twoSum', () => {
expect(twoSum([2, 1, 3, 9], 3)).toEqual([0, 1]);
});
});
<file_sep>/test/9.test.js
/**
* create by grguang
*
* @flow
*/
const {isPalindrome} = require('../code/9.palindrome');
describe('isPalindrome', () => {
it('isPalindrome 121', () => {
expect(isPalindrome(121)).toBe(true);
});
it('isPalindrome 0', () => {
expect(isPalindrome(0)).toBe(true);
});
it('isPalindrome 1000000001', () => {
expect(isPalindrome(1000000001)).toBe(true);
});
});
<file_sep>/code/14.longestCommonPrefix.js
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if(!strs || !strs.length) return '';
let minLengthStr = strs[0];
strs.forEach(item => {
const itemLength = item.length;
if(itemLength < minLengthStr.length){
minLengthStr = item;
}
});
let sameStr = '';
for(let i = 0; i< minLengthStr.length; i++){
const everyStr = minLengthStr[i];
const diffrent = strs.filter(item => {
return item[i] !==everyStr
});
if(diffrent.length){
return sameStr
}else{
sameStr = sameStr + everyStr;
}
}
return sameStr;
};
exports.longestCommonPrefix = longestCommonPrefix;
<file_sep>/test/13.test.js
/**
* create by grguang
*
* @flow
*/
const {romanToInt} = require('../code/13.romanToInt');
describe('romanToInt', () => {
it('romanToInt III', () => {
expect(romanToInt("III")).toBe(3);
});
it('romanToInt IV', () => {
expect(romanToInt("IV")).toBe(4);
});
it('romanToInt LVIII', () => {
expect(romanToInt("LVIII")).toBe(58);
});
it('romanToInt MCMXCIV', () => {
expect(romanToInt("MCMXCIV")).toBe(1994);
});
});
<file_sep>/code/9.palindrome.js
/**
* @param {number} x
* @return {boolean}
*/
// var isPalindrome = function (x) {
// if (x === 0) {
// return true;
// }
// if (x < 0) {
// return false;
// }
// const str = x.toString();
// // const reverseStr = str.split('').reverse().join('');
// let reverseStr = '';
// for(let i = 0; i < str.length; i++){
// reverseStr = str[i] + reverseStr;
// }
// return str === reverseStr;
// };
// var isPalindrome = function (x) {
// if (x === 0) {
// return true;
// }
// if (x < 0) {
// return false;
// }
// if (x < 10) {
// return true;
// }
// const xStr = x.toString();
// const xStrLength = xStr.length;
// const lastIndex = xStrLength - 1;
// const middleNum = Math.ceil(xStrLength / 2);
// for (let i = 0; i < middleNum; i++) {
// const symmetry = xStr[lastIndex - i];
// if (xStr[i] !== symmetry) {
// return false
// }
// }
// return true
// };
var isPalindrome = function (x) {
if (x === 0) {
return true;
}
if (x < 0) {
return false;
}
if (x < 10) {
return true;
}
const xStr = x.toString();
const reverseStr = xStr.split('').reverse().join('');
return reverseStr === xStr;
};
exports.isPalindrome = isPalindrome
<file_sep>/code/7.integer-inversion.js
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
if (!x) return 0;
const str = x.toString();
const res = str.split('').reverse();
const lastValue = res[res.length - 1];
if (lastValue === '0' || lastValue === '-') {
res.pop();
if(lastValue === '-'){
res.unshift(lastValue);
}
}
const result = Number(res.join(''));
const max = Math.pow(2, 31) - 1;
const min = Math.pow(-2, 31);
const diffMax = result - max;
const diffMin = min - result;
if ((result > 0 && diffMax > 0) || (result < 0 && diffMin > 0)) {
return 0
}
return result
};
exports.reverse = reverse;
| f90cf6bf4c984375dd6f175b15795a5ff326778f | [
"JavaScript"
] | 11 | JavaScript | grguang/algorithm | eaf8a4ba187a16772e47b0b39366222d6cc653f9 | 7539da1d8762a6ac10ab84923c295be114e9c8e8 |
refs/heads/master | <repo_name>christvl/php_login<file_sep>/home.php
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location: login.php?mustlogin=0");
exit;
}
echo "Welcome " . ucfirst($_SESSION['username']);
?>
<br />
<a href="logout.php">Log out</a><file_sep>/login.php
<?php
session_start();
$msg="";
//login try
if(isset($_POST['doLogin'])){
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
if($username == "admin" && $password == "<PASSWORD>") {
$_SESSION['username'] = $username;
header("Location: home.php");
exit;
} else {
$msg = "Wrong username or password, Please try again.";
}
}
//Error message
if(isset($_GET['mustlogin'])){
$msg="Warning this a protected site so pls login with the right credentials";
}
//logout message
if(isset($_GET['logout'])) {
$msg="you logged out.";
}
?>
<form action="" method="POST" >
<fieldset>
<legend>Log in please</legend>
<?php echo $msg;?>
<p>
<label >Username:</label><br>
<input class="text" type="text" name="username">
</p>
<p>
<label>Password:</label><br>
<input class="text" type="<PASSWORD>" name="<PASSWORD>">
</p>
<p>
<input type="submit" name="doLogin" value="Login">
</p>
</fieldset>
</form>
<file_sep>/README.md
# php_login
a simple log in form
| 3815bde4fbfdef6fb8984bb230344241e996e9be | [
"Markdown",
"PHP"
] | 3 | PHP | christvl/php_login | 77a072c5fb245173affd4982467966a93c59e11f | 804deeabf0717506421a1a0aaf1c64df88c2f90d |
refs/heads/main | <repo_name>AhmedAli-IB/RecipeApp<file_sep>/RecipeApp/ViewController.swift
//
// ViewController.swift
// RecipeApp
//
// Created by <NAME> on 27/03/2021.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 20c099470d7003a5c7813af4ec864e568536d81a | [
"Swift"
] | 1 | Swift | AhmedAli-IB/RecipeApp | 74cde1ef70964c3f19b2806f46c7ac8731bbde41 | 6584f3b433ff41f68c0a3e324ac558be59ebb2a9 |
refs/heads/master | <file_sep>'use strict'
const Hapi = require('hapi')
const _ = require('highland')
const JSONStream = require('JSONStream')
const request = require('request')
const server = new Hapi.Server()
const ObjStream = require('objstream')
server.connection({ port: 3000, host: '0.0.0.0' })
// Create a highland stream of API requests
function makeRequest(endpoints) {
return _(
endpoints.map((path) => _(request(`http://jsonplaceholder.typicode.com/${path}`)))
)
}
// Create a processing pipeline that handles incoming response streams
function processRequests() {
return _.pipeline(
// flatten the incoming array of streams into a single stream
_.sequence(),
// Parse JSON out of each stream
JSONStream.parse(),
// Do a special transform for certain payload content
_.map(specialHello)
)
}
// Example of detecting and touching an individual payload
function specialHello(payload) {
if (payload.hello) {
payload.hello += '!!!!!'
}
return payload
}
// Convert objectMode stream to a "normal" mode stream (necessary after JSONStream.parse())
//
// NB: this was tricky. Hapi will consume streams _only_ if they're in *not* in
// Object Mode, which our Highland streams get put into as a side effect of
// parsing them. Streams only contain strings or buffers by default
// (objectMode: false), so Hapi doesn't make any assumptions about how it
// should serialize a stream of objects for you, go figure. Issue documented
// here: https://github.com/hapijs/hapi/issues/2252
function readResultStream(results) {
const stream = new ObjStream()
results.pipe(stream)
return stream
}
// Helper for making a pre method of API Request streams
function apiProxy(endpoints) {
return (req, reply) => {
const stream = makeRequest(endpoints)
.pipe(processRequests())
reply(null, stream)
}
}
server.route({
path: '/',
method: 'GET',
config: {
pre: [
{
method: apiProxy([ 'users', 'todos', 'posts' ]),
assign: 'stream'
}
]
},
handler: (req, reply) => {
reply(readResultStream(req.pre.stream))
}
})
server.start((err) => {
if (err) {
throw err
}
console.log('Server running at:', server.info.uri)
})
<file_sep># highland-todo
Example of how to use streams to transform data
| 6fe5d7be63303a518cab450ed2c6e85e5b21c750 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | nnance/highland-proxy | dc469da291e0844effb1c4d1f7fb1d81eaf0211f | 5ae32a606839851024c3b5e01a9bd6dd80bb9e9b |
refs/heads/master | <repo_name>fadjar-setiawan/fdrs<file_sep>/yakin1.php
<?php
include("atas.php");
?>
<!-- ======= Hero Section ======= -->
<section id="hero" class="d-flex justify-cntent-center align-items-center">
<div id="heroCarousel" data-bs-interval="5000" class="container carousel carousel-fade" data-bs-ride="carousel">
<!-- Slide 1 -->
<div class="carousel-item active">
<div class="carousel-container">
<h2 class="animate__animated animate__fadeInDown">Udah Siap Belum</h2>
<a href="yakin2.php" class="btn-get-started animate__animated animate__fadeInUp scrollto">Udah</a>
</div>
</div>
</div>
</section><!-- End Hero -->
<?php
include("bawah.php");
?>
<file_sep>/akhir4.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>Kakau Digital Media</title>
<meta content="" name="description">
<meta content="" name="keywords">
<!-- Favicons -->
<!--<link href="assets/img/favicon.png" rel="icon">
<link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">-->
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<!-- Vendor CSS Files -->
<link href="assets/vendor/animate.css/animate.min.css" rel="stylesheet">
<link href="assets/vendor/aos/aos.css" rel="stylesheet">
<link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
<link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
<link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet">
<link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
<link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet">
<!-- Template Main CSS File -->
<link href="assets/css/style.css" rel="stylesheet">
<!-- My Css -->
<!-- =======================================================
* Template Name: Anyar - v4.0.1
* Template URL: https://bootstrapmade.com/anyar-free-multipurpose-one-page-bootstrap-theme/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>
<body>
<!-- ======= Why Us Section ======= -->
<section id="why-us" class="why-us about">
<div class="container-fluid">
<div class="row">
<div class="col-lg-5 align-items-stretch position-relative video-box" style='background-image: url("assets/img/vega.jpeg");' data-aos="fade-right">
</div>
<div class="col-lg-7 d-flex flex-column justify-content-center align-items-stretch" data-aos="fade-left">
<div class="content">
<h3 class="text-center"><strong>Love You Vega Silviana</strong></h3>
<div class="row content">
<div class="col-lg-100%">
<a href="https://api.whatsapp.com/send?phone=+6281286504530&text=Love You Too, Udah Selesai." class="btn-learn-more">Lanjut Whatsapp Klik Tombol Ini</a>
</div>
</div>
</div>
</div>
<br>
</div>
</section><!-- End Why Us Section -->
<?php
include("bawah.php");
?>
<file_sep>/index.php
<?php
include("atas.php");
?>
<?php
include("jumbotron.php");
?>
<?php
include("bawah.php");
?> | 81ebfcf4eb64e8932b29b28a07214933d84864ce | [
"PHP"
] | 3 | PHP | fadjar-setiawan/fdrs | 495608d7f37e4cf9f13dafc9f4efe900652d5e03 | 91727a7b0efb06025bf05ada2562bf027256a037 |
refs/heads/master | <file_sep>namespace ProyectoProgra04.Datos
{
public class datatable
{
}
}<file_sep>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 ProyectoProgra04.Presentacion
{
public partial class Cliente : Form
{
public Cliente()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CreditoCliente cred = new CreditoCliente();
cred.Show();
}
private void btnlogout_Click(object sender, EventArgs e)
{
LogIn log = new LogIn();
log.Show();
this.Close();
}
private void btnClientes_Click(object sender, EventArgs e)
{
}
private void btnExpo_Click(object sender, EventArgs e)
{
exportar ex = new exportar();
ex.Show();
}
private void btnimp_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void Cliente_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>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 ProyectoProgra04.Presentacion
{
public partial class Credito : Form
{
double intereses2;
double tasa2;
double saldo2;
double periodo2;
bool banderaid = false;
bool banderacred = false;
string cancelado;
string nocancelado;
public Credito()
{
InitializeComponent();
}
private void Credito_Load(object sender, EventArgs e)
{
consultartablacontrolcredito();
}
private void lblIdCliente_Click(object sender, EventArgs e)
{
}
private void lblTasa_Click(object sender, EventArgs e)
{
}
private void dtgCredito_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
llenarcamposact();
}
private void lblAmortizacion_Click(object sender, EventArgs e)
{
}
private void cmbIdCliente_Click(object sender, EventArgs e)
{
llenarcomboid();
}
public void llenarcomboid()
{
try
{
Logica.Credito datos = new Logica.Credito();
DataTable dtdatos = new DataTable();
dtdatos = datos.llenarcomboid();
cmbIdCliente.DisplayMember = "IdCliente";
cmbIdCliente.DataSource = dtdatos;
cmbid.DisplayMember = "IdCliente";
cmbid.DataSource = dtdatos;
}
catch
{
MessageBox.Show("Error al cargar datos");
}
}
public void llenarcomboperiodo()
{
try
{
Logica.Credito datos = new Logica.Credito();
DataTable dtdatos = new DataTable();
dtdatos = datos.llenarcomboperiodo(cmbIdCliente.Text);
cmbperiodo.DisplayMember = "Periodo";
cmbperiodo.DataSource = dtdatos;
}
catch
{
MessageBox.Show("Error al cargar datos");
}
}
public void GenerarPago()
{
try
{
Logica.Credito datos = new Logica.Credito();
Datos.credito cred = new Datos.credito();
list = new List<Creditos>();
Creditos obj = new Creditos();
obj.IdCliente = Convert.ToInt32(cmbIdCliente.Text);
obj.Periodo = Convert.ToInt32(cmbperiodo.Text);
obj.Cancelado = Convert.ToInt32(cancelado);
list.Add(obj);
datos.genpago(obj);
}
catch (Exception e)
{
MessageBox.Show("Error al actualizar datos" + e);
}
}
public void llenarcamposact()
{
try
{
cmbIdCliente.Text = dgvCredito.CurrentRow.Cells[0].Value.ToString();
cmbperiodo.Text = dgvCredito.CurrentRow.Cells[5].Value.ToString();
string rb = dgvCredito.CurrentRow.Cells[10].Value.ToString();
if (rb == "True")
{
rbnocancelado.Checked = true;
}
if (rb == "False")
{
rbnocancelado.Checked = false;
}
}
catch (Exception e)
{
MessageBox.Show("Error al cargar los campos" + "" + e);
}
}
public void limpiar()
{
cmbperiodo.Text = "";
txt_insertamort.Text = "";
txt_insertidcliente.Text = "";
txt_insertidcred.Text = "";
txt_insertintere.Text = "";
txt_insertmontoapr.Text = "";
txt_insertperi.Text = "";
txt_insertsaldo.Text = "";
txt_inserttasa.Text = "";
cmbconsultacreditos.Text = "";
cmbid.Text = "";
cmbconsultacreditos.Text = "";
}
public void llenarcomboidcredito()
{
try
{
Logica.Credito datos = new Logica.Credito();
DataTable dtdatos = new DataTable();
dtdatos = datos.llenarcomboidcredito();
cmbconsultacreditos.ValueMember = "IdCredito";
cmbconsultacreditos.DataSource = dtdatos;
}
catch
{
MessageBox.Show("Error al cargar datos");
}
}
private void cmbidcredito_Click(object sender, EventArgs e)
{
llenarcomboidcredito();
}
private void consultartablacontrolcredito()
{
try
{
Logica.Credito datos = new Logica.Credito();
DataTable dtcontrol = new DataTable();
dtcontrol = datos.ConsultarTablaControl();
dgvCredito.DataSource = dtcontrol;
//llenardgvinsert();
dgvconsulta.DataSource = dtcontrol;
}
catch
{
MessageBox.Show("Error al cargar datos");
}
}
private void btnrefrescar_Click(object sender, EventArgs e)
{
consultartablacontrolcredito();
}
private void cmbidcredito_SelectedIndexChanged(object sender, EventArgs e)
{
consultartablacontrolcredito();
}
private void consultarcreditoid(string id)
{
try
{
Logica.Credito datos = new Logica.Credito();
DataTable dtcredito = new DataTable();
dtcredito = datos.consultarcreditoidcliente(id);
dgvconsulta.DataSource = dtcredito;
}
catch (Exception e)
{
MessageBox.Show("Error al consultar datos" + " " + e);
}
}
private void consultarporcredito(string credito)
{
try
{
Logica.Credito datos = new Logica.Credito();
DataTable dtcredito = new DataTable();
dtcredito = datos.consultarcreditocliente(credito);
dgvconsulta.DataSource = dtcredito;
}
catch (Exception e)
{
MessageBox.Show("Error al consultar datos" + " " + e);
}
}
private void cmbIdCliente_SelectedIndexChanged(object sender, EventArgs e)
{
}
List<Creditos> list;
private void btnGenerarCredito_Click(object sender, EventArgs e)
{
}
private void btngenerarpago_Click(object sender, EventArgs e)
{
GenerarPago();
consultartablacontrolcredito();
}
private void tabPage3_Click(object sender, EventArgs e)
{
}
private void btn_Insertar_Click(object sender, EventArgs e)
{
generarcredito();
consultartablacontrolcredito();
}
private void btn_refrescar_Click(object sender, EventArgs e)
{
consultartablacontrolcredito();
}
private void cmbid_SelectedIndexChanged(object sender, EventArgs e)
{
banderaid = true;
banderacred = false;
consultartablacontrolcredito();
try
{
if (banderaid == true)
{
consultarcreditoid(cmbid.Text);
}
if (banderacred == true)
{
consultarporcredito(cmbconsultacreditos.Text);
}
}
catch
{
MessageBox.Show("Error al cargar datos");
}
}
private void cmbid_Click(object sender, EventArgs e)
{
llenarcomboid();
consultartablacontrolcredito();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (banderaid == true)
{
consultarcreditoid(cmbid.Text);
}
if (banderacred == true)
{
consultarporcredito(cmbconsultacreditos.Text);
}
}
catch
{
MessageBox.Show("Error al cargar datos");
}
}
private void cmbconsultacreditos_Click(object sender, EventArgs e)
{
llenarcomboidcredito();
}
private void cmbconsultacreditos_SelectedIndexChanged(object sender, EventArgs e)
{
banderacred = true;
banderaid = false;
try
{
if (banderaid == true)
{
consultarcreditoid(cmbid.Text);
}
if (banderacred == true)
{
consultarporcredito(cmbconsultacreditos.Text);
}
}
catch
{
MessageBox.Show("Error al cargar datos");
}
}
private void tabPage4_Click(object sender, EventArgs e)
{
}
private void btnconsultarefrescar_Click(object sender, EventArgs e)
{
consultartablacontrolcredito();
}
private void btnlimpiar_Click(object sender, EventArgs e)
{
limpiar();
}
private void Limpiar_Click(object sender, EventArgs e)
{
limpiar();
}
private void button1_Click_1(object sender, EventArgs e)
{
}
private void dgvCredito_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
llenarcamposact();
}
public double PMT(double capital, double tasa, double periodo)
{
double pago;
pago = (tasa * capital) / (1 - (Math.Pow((1 + tasa), (-1 * periodo))));
return pago;
}
public double calculointereses(double capital, double tasa)
{
double intereses;
intereses = (capital * tasa);
return intereses;
}
public double calculoamortizacion(double pago, double intereses)
{
double amortizacion;
amortizacion = pago - intereses;
return amortizacion;
}
public double calculonuevocapital(double capital, double amotizacion)
{
double nuevocapital;
nuevocapital = capital - amotizacion;
return nuevocapital;
}
private void rb_cancelado_CheckedChanged(object sender, EventArgs e)
{
cancelado = "1";
}
private void rbnocancelado_CheckedChanged(object sender, EventArgs e)
{
cancelado = "0";
}
private void cmbperiodo_MouseClick(object sender, MouseEventArgs e)
{
llenarcomboperiodo();
}
private void btnproyeccion_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void btnproyeccion_Click_1(object sender, EventArgs e)
{
list = new List<Creditos>();
try
{
if (chklp.Checked)
{
tasa2 = ((Convert.ToDouble(txt_inserttasa.Text)) / 100) / 12;
periodo2 = (Convert.ToDouble(txt_insertperi.Text)) * 12;
double pmt = PMT(Convert.ToDouble(txt_insertmontoapr.Text), Convert.ToDouble(tasa2), Convert.ToDouble(periodo2));
txtcuota.Text = Convert.ToString(pmt);
double Intereses = calculointereses(Convert.ToDouble(txt_insertmontoapr.Text), Convert.ToDouble(tasa2));
txt_insertintere.Text = Convert.ToString(Intereses);
double Amort = calculoamortizacion(Convert.ToDouble(txtcuota.Text), Convert.ToDouble(txt_insertintere.Text));
txt_insertamort.Text = Convert.ToString(Amort);
double Saldo = calculonuevocapital(Convert.ToDouble(txt_insertmontoapr.Text), Convert.ToDouble(Amort));
txt_insertsaldo.Text = Convert.ToString(Saldo);
}
else
{
tasa2 = ((Convert.ToDouble(txt_inserttasa.Text)) / 100);
double pmt = PMT(Convert.ToDouble(txt_insertmontoapr.Text), Convert.ToDouble(tasa2), Convert.ToDouble(txt_insertperi.Text));
txtcuota.Text = Convert.ToString(pmt);
double Intereses = calculointereses(Convert.ToDouble(txt_insertmontoapr.Text), Convert.ToDouble(tasa2));
txt_insertintere.Text = Convert.ToString(Intereses);
double Amort = calculoamortizacion(Convert.ToDouble(txtcuota.Text), Convert.ToDouble(txt_insertintere.Text));
txt_insertamort.Text = Convert.ToString(Amort);
double Saldo = calculonuevocapital(Convert.ToDouble(txt_insertmontoapr.Text), Convert.ToDouble(Amort));
txt_insertsaldo.Text = Convert.ToString(Saldo);
}
generarcredito();
// llenardgvinsert();
dgv_insertar.DataSource = list;
}
catch (Exception ea)
{
MessageBox.Show("Error de Proyeccion" + "" + ea);
}
}
private void chklp_CheckedChanged(object sender, EventArgs e)
{
}
private void btn_insertar_Click_1(object sender, EventArgs e)
{
insertarcredito();
}
public void generarcredito()
{
Logica.Credito INSERTAR = new Logica.Credito();
try
{
list = new List<Creditos>();
Logica.Credito datos = new Logica.Credito();
Datos.credito cred = new Datos.credito();
list = new List<Creditos>();
Creditos obj = new Creditos();
DataTable dt = new DataTable();
double capital = Convert.ToDouble(txt_insertmontoapr.Text);
double pago;
double intereses;
double amortizacion;
double tasa = Convert.ToDouble(txt_inserttasa.Text)/100;
saldo2 = capital;
int periodo1 = 0;
double periodo = Convert.ToDouble(txt_insertperi.Text);
if (chklp.Checked)
{
tasa2 = tasa / 12;
periodo2 = periodo * 12;
obj = new Creditos();
pago = PMT(capital, tasa2, periodo2);
intereses = calculointereses(obj.Monto, tasa2);
amortizacion = calculoamortizacion(pago, intereses);
obj.Monto = capital;
obj.Periodo = 0;
obj.Intereses = 0;
obj.Amort = 0;
list.Add(obj);
//INSERTAR.generarproyeccion(obj);
while (saldo2 > 0)
{
pago = PMT(capital, tasa2, periodo2);
periodo1 = periodo1 + 1;
obj = new Creditos();
intereses = calculointereses(saldo2, tasa2);
amortizacion = calculoamortizacion(pago, intereses);
saldo2 = calculonuevocapital(saldo2, amortizacion);
obj.Monto = saldo2;
obj.Intereses = intereses;
obj.Amort = amortizacion;
obj.Periodo = periodo1;
list.Add(obj);
//INSERTAR.generarproyeccion(obj);
}
MessageBox.Show("Proyección creada satisfactoriamente ");
}
else
{
obj = new Creditos();
pago = PMT(capital, tasa, periodo);
intereses = calculointereses(obj.Monto, obj.tasa);
amortizacion = calculoamortizacion(pago, intereses);
obj.Monto = capital;
obj.Periodo = 0;
obj.Intereses = 0;
obj.Amort = 0;
list.Add(obj);
//INSERTAR.generarproyeccion(obj);
while (saldo2 > 0)
{
pago = PMT(capital, tasa, periodo);
periodo1 = periodo1 + 1;
obj = new Creditos();
intereses = calculointereses(saldo2, tasa);
amortizacion = calculoamortizacion(pago, intereses);
saldo2 = calculonuevocapital(saldo2, amortizacion);
obj.Monto = saldo2;
obj.Intereses = intereses;
obj.Amort = amortizacion;
obj.Periodo = periodo1;
list.Add(obj);
//INSERTAR.generarproyeccion(obj);
}
MessageBox.Show("Proyección creada satisfactoriamente ");
}
}
catch (Exception e)
{
MessageBox.Show("Error al Insertar datos: " + e);
}
}
public void insertarcredito()
{
Logica.Credito INSERTAR = new Logica.Credito();
try
{
list = new List<Creditos>();
Logica.Credito datos = new Logica.Credito();
Datos.credito cred = new Datos.credito();
list = new List<Creditos>();
Creditos obj = new Creditos();
DataTable dt = new DataTable();
double capital = Convert.ToDouble(txt_insertmontoapr.Text);
double pago;
double intereses;
double amortizacion;
double tasa = Convert.ToDouble(txt_inserttasa.Text) / 100;
saldo2 = capital;
int periodo1 = 0;
double periodo = Convert.ToDouble(txt_insertperi.Text);
if (chklp.Checked)
{
tasa2 = tasa / 12;
periodo2 = periodo * 12;
obj = new Creditos();
pago = PMT(capital, tasa2, periodo2);
intereses = calculointereses(obj.Monto, tasa2);
amortizacion = calculoamortizacion(pago, intereses);
obj.Saldo = capital;
obj.Periodo = 0;
obj.Intereses = 0;
obj.Amort = 0;
obj.IdCredito = Convert.ToInt32(txt_insertidcred.Text);
obj.IdCliente = Convert.ToInt32(txt_insertidcliente.Text);
obj.Monto = capital;
obj.tasa = tasa;
obj.Pago = 0;
obj.Cancelado = 1;
obj.IdLote = Convert.ToInt32(txtidlote.Text);
list.Add(obj);
INSERTAR.gencredit(obj);
while (saldo2 > 0)
{
pago = PMT(capital, tasa2, periodo2);
periodo1 = periodo1 + 1;
obj = new Creditos();
intereses = calculointereses(saldo2, tasa2);
amortizacion = calculoamortizacion(pago, intereses);
saldo2 = calculonuevocapital(saldo2, amortizacion);
obj.Saldo = saldo2;
obj.Intereses = intereses;
obj.Amort = amortizacion;
obj.Periodo = periodo1;
obj.IdCredito = Convert.ToInt32(txt_insertidcred.Text);
obj.IdCliente = Convert.ToInt32(txt_insertidcliente.Text);
obj.Monto = capital;
obj.tasa = tasa;
obj.Pago = pago;
obj.Cancelado = 0;
obj.IdLote = Convert.ToInt32(txtidlote.Text);
list.Add(obj);
INSERTAR.gencredit(obj);
}
MessageBox.Show("Proyección creada satisfactoriamente ");
}
else
{
obj = new Creditos();
pago = PMT(capital, tasa, periodo);
intereses = calculointereses(obj.Monto, obj.tasa);
amortizacion = calculoamortizacion(pago, intereses);
obj.Saldo = capital;
obj.Periodo = 0;
obj.Intereses = 0;
obj.Amort = 0;
obj.IdCredito = Convert.ToInt32(txt_insertidcred.Text);
obj.IdCliente = Convert.ToInt32(txt_insertidcliente.Text);
obj.Monto = capital;
obj.tasa = tasa;
obj.Pago = 0;
obj.Cancelado = 1;
obj.IdLote = Convert.ToInt32(txtidlote.Text);
list.Add(obj);
INSERTAR.gencredit(obj);
while (saldo2 > 0)
{
pago = PMT(capital, tasa, periodo);
periodo1 = periodo1 + 1;
obj = new Creditos();
intereses = calculointereses(saldo2, tasa);
amortizacion = calculoamortizacion(pago, intereses);
saldo2 = calculonuevocapital(saldo2, amortizacion);
obj.Saldo = saldo2;
obj.Intereses = intereses;
obj.Amort = amortizacion;
obj.Periodo = periodo1;
obj.IdCredito = Convert.ToInt32(txt_insertidcred.Text);
obj.IdCliente = Convert.ToInt32(txt_insertidcliente.Text);
obj.Monto = capital;
obj.tasa = tasa;
obj.Pago = pago;
obj.Cancelado = 0;
obj.IdLote = Convert.ToInt32(txtidlote.Text);
list.Add(obj);
INSERTAR.gencredit(obj);
}
MessageBox.Show("Proyección creada satisfactoriamente ");
}
}
catch (Exception e)
{
MessageBox.Show("Error al Insertar datos: " + e);
}
}
private void btn_refrescar_Click_1(object sender, EventArgs e)
{
}
public void llenardgvinsert()
{
Logica.Credito consulta = new Logica.Credito();
DataTable dtconsulta = new DataTable();
dtconsulta = consulta.consultarproyeccion();
dgv_insertar.DataSource = dtconsulta;
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>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 ProyectoProgra04.Presentacion
{
public partial class Banco : Form
{
public Banco()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AgregarClientes agregar = new AgregarClientes();
agregar.Show();
}
private void btncredito_Click(object sender, EventArgs e)
{
Credito credito = new Credito();
credito.Show();
}
private void btnlogout_Click(object sender, EventArgs e)
{
LogIn log = new LogIn();
log.Show();
this.Close();
}
private void btnExpo_Click(object sender, EventArgs e)
{
exportar ex = new exportar();
ex.Show();
}
private void btnimp_Click(object sender, EventArgs e)
{
Import ex = new Import();
ex.Show();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoProgra04.Datos
{
public class credito
{
CRUD conect = new CRUD();
CRUD consultar = new CRUD();
public DataTable llenarcomboidcliente()
{
CRUD conectar = new CRUD();
DataTable dtidclientes;
dtidclientes = conect.ejecutar("select distinct IdCliente from Credito");
return dtidclientes;
}
public DataTable llenarcomboperiodo(String idcliente)
{
CRUD conectar = new CRUD();
DataTable dtidclientes;
dtidclientes = conect.ejecutar("select Periodo from Credito where IdCliente="+ idcliente+"");
return dtidclientes;
}
public DataTable llenarcomboidcredito()
{
CRUD conectar = new CRUD();
DataTable dtidcredito;
dtidcredito = conect.ejecutar("select distinct IdCredito from Credito");
return dtidcredito;
}
public DataTable ConsultarTablaControl()
{
CRUD conectar = new CRUD();
DataTable dtcontrolcredito;
dtcontrolcredito = conect.ejecutar("select * from Credito");
return dtcontrolcredito;
}
public DataTable consultarcreditoidcliente(string idcliente)
{
CRUD conectar = new CRUD();
DataTable dtcredito;
dtcredito = conect.ejecutar("Select IdCliente,IdCredito, Periodo,Pago,Intereses,Amortizacion,Saldo,Cancelado from Credito where IdCliente = " + idcliente+"");
return dtcredito;
}
public DataTable consultarcreditoporid(string idcredito)
{
CRUD conectar = new CRUD();
DataTable dtcredito;
dtcredito = conect.ejecutar("Select IdCliente,IdCredito, Periodo,Pago,Intereses,Amortizacion,Saldo,Cancelado from Credito where IdCredito ="+idcredito+"");
return dtcredito;
}
public void gencred(Presentacion.Creditos c)
{
string query = "insert into Credito"+
" values("+c.IdCredito+","+c.IdCliente+","+c.IdLote + "," + c.Monto+","+c.tasa+","+c.Periodo+","+c.Pago+","+c.Intereses+","+c.Amort+","+c.Saldo+","+c.Cancelado+")";
conect.ejecutarInsert(query);
}
public void genpago( Presentacion.Creditos c)
{
CRUD conectar= new CRUD();
string query = "Update Credito set Cancelado="+c.Cancelado+" where IdCliente= "+c.IdCliente+" and Periodo="+c.Periodo+"";
// string query2 = "Update ContrCreditos set MontoCredito=" + c.Monto + " where IdCliente= " + c.IdCliente + "";
conect.ejecutar(query);
//conect.ejecutar(query2);
}
public void consultarcreditosporcedula( String idcedula)
{
CRUD conectar = new CRUD();
string query = "select MontoAprovado,Tasa=,Periodo,UltimaProyeccion,Intereses,Amortizacion,Saldo,Cancelado from Credito where IdCliente= " + idcedula + "";
conect.ejecutar(query);
}
public void generarproyeccion(Presentacion.Creditos c)
{
conect.ejecutarInsert("insert into proyeccion (Cuota,Intereses,Amortizacion,Saldo) idcliente, idcliente, montoaprovado, tasa,periodo,ultimaproyeccion,pago,intereses,amortizacion,saldo,canceladovalues ('" + c.Pago+"','"+c.Intereses+"','"+c.Amort+"','"+c.Monto+"')");
}
public DataTable consultarproyeccion()
{
Datos.CRUD conectar = new Datos.CRUD();
DataTable dtproyeccion;
dtproyeccion = conectar.ejecutar("select * from proyeccion");
return dtproyeccion;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoProgra04.Logica
{
public class Credito
{
public DataTable llenarcomboid()
{
Datos.credito datos = new Datos.credito();
return datos.llenarcomboidcliente();
}
public DataTable llenarcomboidcredito()
{
Datos.credito datos = new Datos.credito();
return datos.llenarcomboidcredito();
}
public DataTable llenarcomboperiodo(String idcliente)
{
Datos.credito datos = new Datos.credito();
return datos.llenarcomboperiodo(idcliente);
}
public DataTable ConsultarTablaControl()
{
Datos.credito datos = new Datos.credito();
return datos.ConsultarTablaControl();
}
public DataTable consultarcreditoidcliente(string idcliente)
{
Datos.credito datos = new Datos.credito();
return datos.consultarcreditoidcliente(idcliente);
}
public DataTable consultarcreditocliente(string creditocliente)
{
Datos.credito datos = new Datos.credito();
return datos.consultarcreditoporid(creditocliente);
}
public void gencredit(Presentacion.Creditos obj)
{
Datos.credito cred = new Datos.credito();
cred.gencred(obj);
}
public void genpago(Presentacion.Creditos obj)
{
Datos.credito cred = new Datos.credito();
cred.genpago(obj);
}
public DataTable consultarclientes()
{
Datos.Agregarclientes datos = new Datos.Agregarclientes();
return datos.ConsultarClientes();
}
public bool agregarclientes(string idcliente, string Nombre, string Apellido1, string Apellido2, string idinstitucion, string pass)
{
return new Datos.Agregarclientes().agregarclientes(idcliente, Nombre, Apellido1, Apellido2, idinstitucion, pass);
}
public void generarproyeccion(Presentacion.Creditos c)
{
new Datos.credito().generarproyeccion(c);
}
public DataTable consultarproyeccion()
{
Datos.credito datos = new Datos.credito();
return datos.consultarproyeccion();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoProgra04.Datos
{
public class Agregarclientes
{
CRUD conect = new CRUD();
CRUD consultar = new CRUD();
public DataTable ConsultarClientes()
{
Datos.CRUD conectar = new Datos.CRUD();
DataTable dttablas;
dttablas = conectar.ejecutar("select IdCliente,Nombre,Apellido1,Apellido2, IdInstitucion,pass from Cliente where TipoUsuario = 3;");
return dttablas;
}
public bool agregarclientes(string idcliente, string Nombre, string Apellido1, string Apellido2, string idinstitucion, string pass)
{
bool agregandoclientes;
agregandoclientes = conect.ejecutarInsert("insert into Cliente values ('"+idcliente+"','"+Nombre+"','"+Apellido1+"','"+Apellido2+"','"+idinstitucion+"','"+pass+"',3)");
if (agregandoclientes)
{
return true;
}
return false;
}
}
}
<file_sep>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 ProyectoProgra04.Presentacion
{
public partial class LogIn : Form
{
public LogIn()
{
InitializeComponent();
}
private void LogIn_Load(object sender, EventArgs e)
{
this.AcceptButton = btnin;
}
private void btnin_Click(object sender, EventArgs e)
{
Datos.Login log = new Datos.Login();
int res;
try
{
if (txtuser.Text == "")
{
MessageBox.Show("Ingrese un ID de usuario");
}
else
{
if (txtpass.Text == "")
{
MessageBox.Show("Ingrese una contraseña valida");
}
else
{
res = log.comprobar(txtuser.Text, txtpass.Text);
Banco ban = new Banco();
Cliente cli = new Cliente();
MASTER mas = new MASTER();
if (res > 0)
{
if (res == 1)
{
MessageBox.Show("Bienvenido");
mas.Show();
this.Hide();
}
if (res == 2)
{
MessageBox.Show("Bienvenido");
ban.Show();
this.Hide();
}
if (res == 3)
{
MessageBox.Show("Bienvenido");
cli.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Usuario o Contraseña Invalida");
txtpass.Text = "";
}
}
}
}
catch
{
MessageBox.Show("Usuario Incorrecto");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoProgra04.Logica
{
class export
{
Datos.export ex = new Datos.export();
public DataTable cargardatos(string lote)
{
DataTable dt;
dt = ex.cargardatos(lote);
return dt;
}
public DataTable Cargarcbo()
{
DataTable dt;
dt = ex.Cargarcbo();
return dt;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoProgra04.Presentacion
{
public class Creditos
{
public int IdCredito { get; set; }
public int IdCliente { get; set; }
public double Monto { get; set; }
public double tasa { get; set; }
public int Periodo { get; set; }
public decimal LastProy { get; set; }
public double Pago { get; set; }
public double Intereses { get; set; }
public double Amort { get; set; }
public double Saldo { get; set; }
public int Cancelado { get; set; }
public int IdLote { get; set; }
}
}
<file_sep>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 ProyectoProgra04.Presentacion
{
public partial class AgregarClientes : Form
{
public AgregarClientes()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void AgregarClientes_Load(object sender, EventArgs e)
{
consultarclientes();
}
private void btnlimpiar_Click(object sender, EventArgs e)
{
try
{
limpiar();
}
catch
{
MessageBox.Show("Error de Sintaxis, favor revisar");
}
}
private void limpiar()
{
txtidcliente.Text = "";
txtnombre.Text = "";
txtapellido1.Text = "";
txtapellido2.Text = "";
txtidinstitucion.Text = "";
txtpass.Text = "";
}
private void consultarclientes()
{
Logica.Credito datos = new Logica.Credito();
DataTable dttablas = new DataTable();
dttablas = datos.consultarclientes();
dtgclientes.DataSource = dttablas;
}
private void dtgclientes_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void btnagregarcliente_Click(object sender, EventArgs e)
{
agregarclientes();
}
public void agregarclientes()
{
Logica.Credito agregar = new Logica.Credito();
try
{
if (txtidcliente.Text == "")
{
MessageBox.Show("Favor agregar ID de cliente");
}
else
{
if (txtnombre.Text == "")
{
MessageBox.Show("Favor agregar Nombre de cliente");
}
else
{
if (txtapellido1.Text == "")
{
MessageBox.Show("Favor agregar Primer Apellido");
}
else
{
if (txtapellido2.Text == "")
{
MessageBox.Show("Favor agregar Segundo Apellido");
}
else
{
if (txtidinstitucion.Text == "")
{
MessageBox.Show("Favor agregar ID de Institución");
}
else
{
if (txtpass.Text == "")
{
MessageBox.Show("Favor agregar una Contraseña");
}
else
{
agregar.agregarclientes(txtidcliente.Text, txtnombre.Text, txtapellido1.Text, txtapellido2.Text, txtidinstitucion.Text, txtpass.Text);
MessageBox.Show("Cliente Agregado Correctamente");
limpiar();
}
}
}
}
}
}
}
catch
{
MessageBox.Show("Error de Sintaxis, favor revisar");
}
consultarclientes();
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProyectoProgra04.Presentacion
{
public partial class exportar : Form
{
public exportar()
{
InitializeComponent();
}
Logica.export ex = new Logica.export();
private void exportar_Load(object sender, EventArgs e)
{
try
{
DataTable dt = ex.Cargarcbo();
cbolote.DataSource = dt;
cbolote.ValueMember = "idlote";
}
catch
{
}
}
public void Elote()
{
try
{
DataTable dt;
dt = ex.cargardatos(cbolote.Text);
dgvlote.DataSource = dt;
}
catch
{
}
}
private void cbolote_Click(object sender, EventArgs e)
{
Elote();
}
private void cbolote_SelectedIndexChanged(object sender, EventArgs e)
{
Elote();
}
private void btnexport_Click(object sender, EventArgs e)
{
try
{
if (Excel.Checked)
{
toExcel();
}
else
{
if (txt.Checked)
{
toText();
}
else
{
if (aXml.Checked)
{
toXML();
}
else
{
MessageBox.Show("Seleccione un metodo");
}
}
}
}
catch { }
}
private void toExcel()
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //creo el objeto, creo el archivo de excel desde cero
excel.Application.Workbooks.Add(true); //aca se agrega una hoja de excel
int IndiceColumna = 0;
foreach (DataGridViewColumn col in dgvlote.Columns)
{
IndiceColumna++;
excel.Cells[1, IndiceColumna] = col.Name;
}
int IndiceFila = 0;
foreach (DataGridViewRow row in dgvlote.Rows)
{
IndiceFila++;
IndiceColumna = 0;
foreach (DataGridViewColumn col in dgvlote.Columns)
{
IndiceColumna++;
excel.Cells[IndiceFila + 1, IndiceColumna] = row.Cells[col.Name].Value;
}
}
excel.Visible = true;
}
private void toXML()
{
if (!Directory.Exists(@"C:\BancoLosCositos"))
{
Directory.CreateDirectory(@"C:\BancoLosCositos");
}
DataTable dt = new DataTable();
DataSet ds = new DataSet();
dt = ex.cargardatos(cbolote.Text);
ds.Tables.Add(dt);
dt.WriteXml(@"C:\BancoLosCositos\Deducciones.xml");
}
private void toText()
{
try
{
if (!Directory.Exists(@"C:\BancoLosCositos"))
{
Directory.CreateDirectory(@"C:\BancoLosCositos");
}
TextWriter sw = new StreamWriter(@"C:\BancoLosCositos\Deducciones.txt");
int rowcount = dgvlote.Rows.Count;
Console.WriteLine(rowcount.ToString());
sw.WriteLine(dgvlote.Columns[0].Name.ToString() + "/"
+ dgvlote.Columns[1].Name.ToString() + "/"
+ dgvlote.Columns[2].Name.ToString());
for (int i = 0; i <= rowcount - 1; i = i + 1)
{
sw.WriteLine(dgvlote.Rows[i].Cells[0].Value.ToString() + "/"
+ dgvlote.Rows[i].Cells[1].Value.ToString() + "/"
+ dgvlote.Rows[i].Cells[2].Value.ToString());
}
sw.Close();
MessageBox.Show("Datos Exportados correctamente");
}
catch
{
MessageBox.Show("Error al exportar datos");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace ProyectoProgra04.Presentacion
{
public partial class Import : Form
{
public Import()
{
InitializeComponent();
}
OpenFileDialog openfiledialog1 = new OpenFileDialog();
public string archivo = "";
private void Import_Load(object sender, EventArgs e)
{
}
public void fromExcel()
{
OleDbConnection conn; //permite la conexion de excel con c#
OleDbDataAdapter MySataAdapter; //almacena la info y se la manda al datatable y este llena el datagridview
DataTable dt;//se llena con la info del oledbdataadapter
String ruta = "";
try
{
OpenFileDialog openfile1 = new OpenFileDialog(); //ver y busca archivos dentro del ordenador
//openfile1.Filter = "Excel files |*,xlsx"; //filtro de archivos que tengan esa extension
//openfile1.Title = "Seleccione el archivo de Excel";
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (openfile1.FileName.Equals("") == false) //nombre, ruta, comparada con vacio y da false , existe una ruta, no es vacia
{
ruta = openfile1.FileName;
}
}
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEBD.4.0;Data Source" + ruta + ";Extended Properties='Excel 8.0; HDR=Yes'");
//conn =new OleDbConnection("Provider=Microsoft.ACE.OLEBD.12.0;Data Source" + ruta + ";Extended Properties='Excel 12.0 Xml; HDR=Yes'");
MySataAdapter = new OleDbDataAdapter("Select * from [Sheet1$]", conn);
dt = new DataTable();
MySataAdapter.Fill(dt);
dgvlote.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void fromXML()
{
try
{
XmlReader xmlFile = XmlReader.Create(@"C:\BancoLosCositos\Deducciones.xml", new XmlReaderSettings());
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFile);
dgvlote.DataSource = dataSet.Tables["Table1"];
xmlFile.Close();
}
catch { MessageBox.Show("Error al cargar"); }
}
public void fromText()
{
try
{
this.openfiledialog1.ShowDialog();
if (!string.IsNullOrEmpty(this.openfiledialog1.FileName))
{
archivo = this.openfiledialog1.FileName;
lecturaarchivo(dgvlote, '/', archivo);
}
}
catch
{
MessageBox.Show("Error al cargar archivo");
}
}
public void lecturaarchivo(DataGridView tabla, char carcater, string ruta)
{
StreamReader objreader = new StreamReader(ruta);
string sLine = "";
int fila = 0;
tabla.Rows.Clear();
tabla.AllowUserToAddRows = false;
do
{
sLine = objreader.ReadLine();
if ((sLine != null))
{
if (fila == 0)
{
tabla.ColumnCount = sLine.Split(carcater).Length;
nombrarTitulo(tabla, sLine.Split(carcater));
fila = 1;
}
else
{
agregarFilaDatagridview(tabla, sLine, carcater);
fila = fila + 1;
}
}
}
while (!(sLine == null));
objreader.Close();
}
public static void nombrarTitulo(DataGridView tabla, string[] titulos)
{
for (int x = 0; x <= tabla.ColumnCount - 1; x++)
{
tabla.Columns[x].HeaderText = titulos[x];
}
}
private void btnImp_Click(object sender, EventArgs e)
{
{
try
{
if (Excel.Checked)
{
fromExcel();
}
else
{
if (txt.Checked)
{
fromText();
}
else
{
if (aXml.Checked)
{
fromXML();
}
else
{
MessageBox.Show("Seleccione un metodo");
}
}
}
}
catch { }
}
}
public static void agregarFilaDatagridview(DataGridView tabla, string linea, char caracter)
{
string[] arreglo = linea.Split(caracter);
tabla.Rows.Add(arreglo);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoProgra04.Datos
{
public class CRUD
{
private SqlConnection oCN = new SqlConnection(@"Data Source=progra04.database.windows.net;Initial Catalog=BancoLosCositos;Persist Security Info=True;User ID=progra4 ;Password=<PASSWORD>");
public bool abrirConexion()
{
try
{
oCN.Open();
return true;
}
catch (Exception)
{
return false;
}
}
public bool cerrarConexion()
{
try
{
if (oCN.State == ConnectionState.Closed)
{
return true;
}
oCN.Close();
return true;
}
catch (Exception)
{
throw;
}
finally
{
oCN.Close();
}
}
public DataTable ejecutar(String txtSelect)
{
SqlCommand cSelect = new SqlCommand();
DataTable oDT = new DataTable();
SqlDataAdapter oSQLDA = new SqlDataAdapter(cSelect);
try
{
cSelect.CommandText = txtSelect;
cSelect.Connection = oCN;
}
catch (Exception)
{
throw;
}
if (abrirConexion())
{
oSQLDA.Fill(oDT);
}
cerrarConexion();
return oDT;
}
public bool ejecutarInsert(String txtInsert)
{
SqlCommand cInsert = new SqlCommand(txtInsert);
try
{
cInsert.Connection = oCN;
cInsert.CommandType = CommandType.Text;
if (abrirConexion())
{
cInsert.ExecuteNonQuery();
}
cerrarConexion();
return true;
}
catch (Exception e)
{
throw e;
}
}
public DataTable consultar(String consulta)
{
abrirConexion();
SqlCommand comando = new SqlCommand(consulta, oCN);
SqlDataAdapter dataAdapter = new SqlDataAdapter(comando);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
cerrarConexion();
return dt;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoProgra04.Datos
{
public class Login
{
Datos.CRUD datos = new CRUD();
public int comprobar(string user, string password)
{
int res=0;
string con;
DataTable dt;
con = "select * from cliente where idcliente="+user+"and pass= '"+password+"'";
dt = datos.consultar(con);
if (dt.Rows.Count > 0)
{
res = Convert.ToInt32(dt.Rows[0][6].ToString());
}else
{
res = 0;
}
return res;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoProgra04.Datos
{
class export
{
CRUD conect = new CRUD();
public DataTable Cargarcbo()
{
DataTable dt;
string query;
query = " select distinct idlote from credito";
dt = conect.ejecutar(query);
return dt;
}
public DataTable cargardatos(string lote)
{
DataTable dt;
string query;
query = " select idcliente as Cedula,Pago as Cuota, saldo as Saldo from Credito where Idlote="+lote+" and periodo=( select min(Periodo) from credito where Cancelado=0)";
dt = conect.ejecutar(query);
return dt;
}
}
}
<file_sep>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;
using System.Xml;
using System.IO;
using System.Data.OleDb;
using System.Data.Odbc;
namespace ProyectoProgra04.Presentacion
{
public partial class CreditoCliente : Form
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
public string archivo = "";
public CreditoCliente()
{
InitializeComponent();
}
private void btnCargar_Click(object sender, EventArgs e)
{
try
{
if (fExcel.Checked)
{
fromExcel();
}
else
{
if (ftxt.Checked)
{
fromText();
}
else
{
if (fXml.Checked)
{
fromXML();
}
else
{
MessageBox.Show("Seleccione un metodo");
}
}
}
}
catch { }
}
public void fromExcel()
{
OleDbConnection conn; //permite la conexion de excel con c#
OleDbDataAdapter MySataAdapter; //almacena la info y se la manda al datatable y este llena el datagridview
DataTable dt;//se llena con la info del oledbdataadapter
String ruta = "";
try
{
OpenFileDialog openfile1 = new OpenFileDialog(); //ver y busca archivos dentro del ordenador
//openfile1.Filter = "Excel files |*,xlsx"; //filtro de archivos que tengan esa extension
//openfile1.Title = "Seleccione el archivo de Excel";
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (openfile1.FileName.Equals("") == false) //nombre, ruta, comparada con vacio y da false , existe una ruta, no es vacia
{
ruta = openfile1.FileName;
}
}
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEBD.4.0;Data Source" + ruta + ";Extended Properties='Excel 8.0; HDR=Yes'");
//conn =new OleDbConnection("Provider=Microsoft.ACE.OLEBD.12.0;Data Source" + ruta + ";Extended Properties='Excel 12.0 Xml; HDR=Yes'");
MySataAdapter = new OleDbDataAdapter("Select * from [Sheet1$]", conn);
dt = new DataTable();
MySataAdapter.Fill(dt);
dgvCred.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void fromXML()
{
try
{
XmlReader xmlFile = XmlReader.Create(@"C:\BancoLosCositos\Deducciones.xml", new XmlReaderSettings());
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFile);
dgvCred.DataSource = dataSet.Tables["Table1"];
xmlFile.Close();
}
catch { MessageBox.Show("Error al cargar"); }
}
public void fromText()
{
try
{
this.openfiledialog1.ShowDialog();
if (!string.IsNullOrEmpty(this.openfiledialog1.FileName))
{
archivo = this.openfiledialog1.FileName;
lecturaarchivo(dgvCred, '/', archivo);
}
}
catch
{
MessageBox.Show("Error al cargar archivo");
}
}
public void lecturaarchivo(DataGridView tabla, char carcater, string ruta)
{
StreamReader objreader = new StreamReader(ruta);
string sLine = "";
int fila = 0;
tabla.Rows.Clear();
tabla.AllowUserToAddRows = false;
do
{
sLine = objreader.ReadLine();
if ((sLine != null))
{
if (fila == 0)
{
tabla.ColumnCount = sLine.Split(carcater).Length;
nombrarTitulo(tabla, sLine.Split(carcater));
fila = 1;
}
else
{
agregarFilaDatagridview(tabla, sLine, carcater);
fila = fila + 1;
}
}
}
while (!(sLine == null));
objreader.Close();
}
public static void agregarFilaDatagridview(DataGridView tabla, string linea, char caracter)
{
string[] arreglo = linea.Split(caracter);
tabla.Rows.Add(arreglo);
}
public static void nombrarTitulo(DataGridView tabla, string[] titulos)
{
for (int x = 0; x <= tabla.ColumnCount - 1; x++)
{
tabla.Columns[x].HeaderText = titulos[x];
}
}
private void Excel_CheckedChanged(object sender, EventArgs e)
{
}
private void CreditoCliente_Load(object sender, EventArgs e)
{
}
private void btnExp_Click(object sender, EventArgs e)
{
try
{
if (tExcel.Checked)
{
toExcel(); ;
}
else
{
if (tText.Checked)
{
toText();
}
else
{
if (tXML.Checked)
{
toXML();
}
else
{
MessageBox.Show("Seleccione un metodo");
}
}
}
}
catch { }
}
public void toExcel()
{
}
public void toXML()
{
if (!Directory.Exists(@"C:\BancoLosCositos"))
{
Directory.CreateDirectory(@"C:\BancoLosCositos");
}
DataTable dt = new DataTable();
#region from dgv to dt
DataColumn[] dcs = new DataColumn[] { };
foreach (DataGridViewColumn c in dgvCred.Columns)
{
DataColumn dc = new DataColumn();
dc.ColumnName = c.Name;
dc.DataType = c.ValueType;
dt.Columns.Add(dc);
}
foreach (DataGridViewRow r in dgvCred.Rows)
{
DataRow drow = dt.NewRow();
foreach (DataGridViewCell cell in r.Cells)
{
drow[cell.OwningColumn.Name] = cell.Value;
}
dt.Rows.Add(drow);
}
#endregion
try
{
DataSet ds = new DataSet();
ds.Tables.Add(dt);
dt.WriteXml(@"C:\BancoLosCositos\DeduccionesAplicadas");
MessageBox.Show("Se genero exitosamente el archivo");
}
catch
{
MessageBox.Show("No se pudo generar el archivo");
}
}
public void toText()
{
}
}
}
| afe2bdbf356feb702a3592ffe0376cf4d8734a85 | [
"C#"
] | 17 | C# | gavc1000/ProyectoProgra04 | fde9a8acbb7ded108546e7398f8450e306727489 | 855967229f2ff95d53e0c846d3c7488aecc2cf31 |
refs/heads/master | <repo_name>ffarhhan/UrlShortener<file_sep>/config/routes.rb
Rails.application.routes.draw do
root 'url_shortener#new'
get '/stats' => "url_shortener#show"
post 'url_shortener/create'
get 'url_shortener/show'
get '/:id' => "url_shortener#redirect"
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
<file_sep>/config/initializers/shortener.rb
Shortener.unique_key_length = 6
Shortener.default_redirect = "http://www.google.com"<file_sep>/app/models/url.rb
class Url < ApplicationRecord
validates :url, presence:true
has_many :addresses, dependent: :destroy
end<file_sep>/app/controllers/url_shortener_controller.rb
class UrlShortenerController < ApplicationController
def new
@url = Url.new
end
def create
@new_url = Url.new(url_params)
host = Rails.env == "production" ? "https://aqueous-tor-85493.herokuapp.com" : "http://localhost:3000"
begin
shorten_key = Shortener::ShortenedUrl.generate(@new_url.url, expires_at: 30.days.since).unique_key
shorten_url = "#{host}/#{shorten_key}"
rescue Exception => e
puts e
end
@new_url.shorten_url = shorten_url
@new_url.uuid = shorten_key
@new_url.save
end
def redirect
token = ::Shortener::ShortenedUrl.extract_token(params[:id])
url = ::Shortener::ShortenedUrl.fetch_with_token(token: token, additional_params: params)
if url.present?
url = url[:url]
url.slice!(0)
url = "https://" + url
update_location_and_clicked(params[:id])
redirect_to url, status: :moved_permanently
else
redirect_to root_url
end
end
def show
@urls = Url.all
end
private
def update_location_and_clicked(uuid)
@url = Url.find_by(uuid: uuid)
@url.update(clicked: @url.clicked + 1)
@url.addresses.create(ip_address: request.remote_ip,city: request.location.city )
end
def url_params
params.require(:url).permit(:url)
end
end
| 0f1c58a78562cea14a27266dc11a99210c0d9be2 | [
"Ruby"
] | 4 | Ruby | ffarhhan/UrlShortener | 98547fd1c2e9761f84fe43f1d6ee203e3a89bbab | 8433d270653b56657f936513722c955d249f18a2 |
refs/heads/master | <repo_name>Rouz1130/planet<file_sep>/js/planet-interface.js
var url = "https://api.planet.com/v0/";
var key = "7790520033804be09ff351a9b61ba6a2";
var auth_header = {
Authorization: "api-key " + key
};
$.ajax({
url: url,
headers: auth_header
});
$(document).ready(function() {
$(".user-input").submit(function(event){
event.preventDefault();
var planet = $("#planet-input").val();
$("#planet-input").val("");
$(".display-planet").text(planet);
$.get(url + key, function(response) {
console.log(response);
});
});
});
console.log(auth_header);
| b1409e431e8f7c0a8cc7e1fbe8d009682e9be9f6 | [
"JavaScript"
] | 1 | JavaScript | Rouz1130/planet | 4b969e02e3a5cf0b70e200a27f4315b46c139648 | 13feb26ac6e6733d4b9d271a9f98c8b68f7b93e4 |
refs/heads/master | <file_sep>
import { mat4, vec3, vec4 } from 'gl-matrix';
import { assert } from './auxiliaries';
import { decode_float24x1_from_uint8x3, decode_uint32_from_rgba8 } from './gl-matrix-extensions';
import { Context } from './context';
import { Framebuffer } from './framebuffer';
import { Initializable } from './initializable';
import { NdcFillingTriangle } from './ndcfillingtriangle';
import { Program } from './program';
import { Shader } from './shader';
import { Texture2 } from './texture2';
/**
* This stage provides means to sample G-Buffers, in order to give access to world space coordinates, depth values and
* IDs. World space coordinates are calculated by sampling the depth value and unprojecting the normalized device
* coordinates. Depth and ID values are read from the GPU by rendering the requested pixel to a 1x1 texture and reading
* back the value from this texture. Note that depth and ID values are cached as long as no redraw (frame) was invoked.
*/
export class ReadbackPass extends Initializable {
/**
* Read-only access to the objects context, used to get context information and WebGL API access.
*/
protected _context: Context;
/** @see {@link cache} */
protected _cache = false;
/** @see {@link depthFBO} */
protected _depthFBO: Framebuffer; // This is used if depth is already uint8x3 encoded
/** @see {@link depthAttachment} */
protected _depthAttachment: GLenum = 0;
/**
* Cache providing previously read depth values for a given position hash.
*/
protected _cachedDepths = new Map<GLsizei, GLfloat | undefined>();
/** @see {@link idFBO} */
protected _idFBO: Framebuffer;
/** @see {@link idAttachment} */
protected _idAttachment: GLenum;
/**
* Cache providing previously read id values for a given position hash.
*/
protected _cachedIDs = new Map<GLsizei, GLsizei | undefined>();
/**
* Buffer to read into.
*/
protected _buffer = new Uint8Array(4);
/**
* Properties required for 24bit depth readback workaround. If a valid depth format is available as renderable
* texture format, a single fragment is rasterized in order to encode the depth of at a specific location into
* uint8x3 format, rendered into a RGBA texture for readback. This workaround is currently necessary since reading
* back depth buffer data is not supported. All following protected properties are undefined when this workaround
* is not required (i.e., in IE11), since the depth texture is already rendered explicitly in a previous render
* pass.
*/
protected _texture: Texture2;
protected _framebuffer: Framebuffer;
/**
* Geometry used to draw on. This is not provided by default to allow for geometry sharing. If no triangle is given,
* the ndc triangle will be created and managed internally.
*/
protected _ndcTriangle: NdcFillingTriangle;
/**
* Tracks ownership of the ndc-filling triangle.
*/
protected _ndcTriangleShared = false;
protected _program: Program;
protected _uOffset: WebGLUniformLocation;
protected _uScale: WebGLUniformLocation;
/**
* Retrieve the depth of a fragment in normalized device coordinates. The implementation of this function is
* assigned at initialization based on the available WebGL features.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
*/
depthAt: (x: GLsizei, y: GLsizei) => GLfloat | undefined;
constructor(context: Context) {
super();
this._context = context;
}
/**
* Frame implementation clearing depth and ID caches. To avoid unnecessary readbacks (potentially causing sync
* points), the requested and found IDs and depths are cached by position. Hence, these cached values have to be
* cleared whenever the framebuffers are written/rendered to.
*/
protected onFrame(): void {
this._cachedDepths.clear();
this._cachedIDs.clear();
}
/**
* Create a numerical hash that can be used for efficient look-up (number preferred, no string for now). Note that
* the implementation assumes that we do not exceed 65k pixel in horizontal or vertical resolution soon.
* @param x - Horizontal coordinate from the upper left corner of the viewport origin.
* @param y - Vertical coordinate from the upper left corner of the viewport origin.
*/
protected hash(x: GLsizei, y: GLsizei): GLsizei {
return 0xffff * y + x;
}
/**
* Retrieve the depth of a fragment in normalized device coordinates. This function implements the direct readback
* of uint8x3 encoded depth values from a given framebuffer (see depthFBO and depthAttachment).
* @param x - Horizontal coordinate from the upper left corner of the viewport origin.
* @param y - Vertical coordinate from the upper left corner of the viewport origin.
* @returns - Either the depth at location x, y or undefined, if the far plane was hit.
*/
@Initializable.assert_initialized()
protected directReadDepthAt(x: GLsizei, y: GLsizei): GLfloat | undefined {
const hash = this.hash(x, y);
if (this._cache && this._cachedDepths.has(hash)) {
return this._cachedDepths.get(hash);
}
assert(this._depthFBO !== undefined && this._depthFBO.valid, `valid depth FBO expected for reading back depth`);
const texture = this._depthFBO.texture(this._depthAttachment) as Texture2;
const gl = this._context.gl;
const size = texture.size;
this._depthFBO.bind();
if (this._context.isWebGL2 || this._context.supportsDrawBuffers) {
gl.readBuffer(this._depthAttachment);
}
gl.readPixels(x, size[1] - (y + 0.5), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, this._buffer);
let depth: GLfloat | undefined = decode_float24x1_from_uint8x3(
vec3.fromValues(this._buffer[0], this._buffer[1], this._buffer[2]));
/** @todo fix far plane depth to be at 1.0 */
depth = depth > 0.996 ? undefined : depth;
if (this._cache) {
this._cachedDepths.set(hash, depth);
}
return depth;
}
/**
* Retrieve the depth of a fragment in normalized device coordinates.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
* @returns - Either the depth at location x, y or undefined, if the far plane was hit.
*/
@Initializable.assert_initialized()
renderThenReadDepthAt(x: GLsizei, y: GLsizei): GLfloat | undefined {
const hash = this.hash(x, y);
if (this._cache && this._cachedDepths.has(hash)) {
return this._cachedDepths.get(hash);
}
assert(this._depthFBO !== undefined && this._depthFBO.valid, `valid depth FBO expected for reading back depth`);
const texture = this._depthFBO.texture(this._depthAttachment) as Texture2;
const gl = this._context.gl;
const size = texture.size;
/* Render a single fragment, thereby encoding the depth render texture data of the requested position. */
gl.viewport(0, 0, 1, 1);
this._program.bind();
gl.uniform2f(this._uOffset, x / size[0], (size[1] - y) / size[1]);
gl.uniform2f(this._uScale, 1.0 / size[0], 1.0 / size[1]);
texture.bind(gl.TEXTURE0);
this._framebuffer.bind();
this._ndcTriangle.bind();
this._ndcTriangle.draw();
this._ndcTriangle.unbind();
texture.unbind();
/** Every stage is expected to bind its own program when drawing, thus, unbinding is not necessary. */
// this.program.unbind();
/* Bind the framebuffer and read back the requested pixel. */
if ((this._context.isWebGL2 || this._context.supportsDrawBuffers) && gl.readBuffer) {
gl.readBuffer(gl.COLOR_ATTACHMENT0);
}
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, this._buffer);
this._framebuffer.unbind();
let depth: GLfloat | undefined = decode_float24x1_from_uint8x3(
vec3.fromValues(this._buffer[0], this._buffer[1], this._buffer[2]));
/** @todo fix far plane depth to be at 1.0 */
depth = depth > 0.996 ? undefined : depth;
if (this._cache) {
this._cachedDepths.set(hash, depth);
}
return depth;
}
/**
* Specializes this pass's initialization. If required. ad screen-filling triangle geometry and a single program
* are created. All attribute and dynamic uniform locations are cached.
* @param ndcTriangle - If specified, assumed to be used as shared geometry. If none is specified, a ndc-filling
* triangle will be created internally.
*/
@Initializable.initialize()
initialize(ndcTriangle: NdcFillingTriangle | undefined): boolean {
const gl = this._context.gl;
const gl2facade = this._context.gl2facade;
/* If depth is already uint8x3 encoded into a rgb/rgba target no readback workaround is required. */
if (this._context.isWebGL1 && !this._context.supportsDepthTexture) {
this.depthAt = this.directReadDepthAt;
return true;
}
/* Configure read back for depth data. */
this.depthAt = this.renderThenReadDepthAt;
const vert = new Shader(this._context, gl.VERTEX_SHADER, 'ndcvertices.vert (readback)');
vert.initialize(require('./shaders/ndcvertices.vert'));
const frag = new Shader(this._context, gl.FRAGMENT_SHADER, 'readbackdepth.frag');
frag.initialize(require('./shaders/readbackdepth.frag'));
this._program = new Program(this._context, 'ReadbackDepthProgram');
this._program.initialize([vert, frag]);
this._uOffset = this._program.uniform('u_offset');
this._program.bind();
gl.uniform1i(this._program.uniform('u_texture'), 0);
this._program.unbind();
/* Configure read back framebuffer and color attachment. */
this._texture = new Texture2(this._context, 'ReadbackRenderTexture');
this._texture.initialize(1, 1, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE);
this._framebuffer = new Framebuffer(this._context, 'ReadbackFBO');
this._framebuffer.initialize([[gl2facade.COLOR_ATTACHMENT0, this._texture]]);
if (ndcTriangle === undefined) {
this._ndcTriangle = new NdcFillingTriangle(this._context);
} else {
this._ndcTriangle = ndcTriangle;
this._ndcTriangleShared = true;
}
if (!this._ndcTriangle.initialized) {
const aVertex = this._program.attribute('a_vertex', 0);
this._ndcTriangle.initialize(aVertex);
} else {
this._program.attribute('a_vertex', this._ndcTriangle.aVertex);
}
return true;
}
/**
* Specializes this stage's uninitialization. Program and geometry resources are released (if allocated). Cached
* uniform and attribute locations are invalidated.
*/
@Initializable.uninitialize()
uninitialize(): void {
if (this._context.isWebGL1 && !this._context.supportsDepthTexture) {
return;
}
if (!this._ndcTriangleShared && this._ndcTriangle.initialized) {
this._ndcTriangle.uninitialize();
}
this._program.uninitialize();
this._texture.uninitialize();
this._framebuffer.uninitialize();
}
/**
* Retrieving the world space coordinate of a fragment.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
* @param zInNDC - optional depth parameter (e.g., from previous query).
* @param viewProjectionInverse - matrix used to unproject the coordinate from ndc to world space.
* @returns - The unprojected world space coordinate at location x, y.
*/
@Initializable.assert_initialized()
coordsAt(x: GLsizei, y: GLsizei, zInNDC: number | undefined, viewProjectionInverse: mat4): vec3 | undefined {
const size = (this._depthFBO.texture(this._depthAttachment) as Texture2).size;
const depth = zInNDC === undefined ? this.depthAt(x, y) : zInNDC;
if (depth === undefined) {
return undefined;
}
const p = vec3.fromValues(x * 2.0 / size[0] - 1.0, 1.0 - y * 2.0 / size[1], depth * 2.0 - 1.0);
return vec3.transformMat4(vec3.create(), p, viewProjectionInverse);
}
/**
* Retrieve the id of an object at fragment position.
* @param x - Horizontal coordinate for the upper left corner of the viewport origin.
* @param y - Vertical coordinate for the upper left corner of the viewport origin.
* @returns - The id rendered at location x, y.
*/
@Initializable.assert_initialized()
idAt(x: GLsizei, y: GLsizei): GLsizei | undefined {
const hash = this.hash(x, y);
if (this._cache && this._cachedIDs.has(hash)) {
return this._cachedIDs.get(hash);
}
const gl = this._context.gl;
const size = (this._idFBO.texture(this._idAttachment) as Texture2).size;
this._idFBO.bind();
if ((this._context.isWebGL2 || this._context.supportsDrawBuffers) && gl.readBuffer) {
gl.readBuffer(this._idAttachment);
}
gl.readPixels(x, size[1] - (y + 0.5), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, this._buffer);
const id = decode_uint32_from_rgba8(
vec4.fromValues(this._buffer[0], this._buffer[1], this._buffer[2], this._buffer[3]));
if (this._cache) {
this._cachedIDs.set(hash, id);
}
return id;
}
/**
* Invokes the frame implementation @see{@link onFrame}.
*/
frame(): void {
this.onFrame();
}
/**
* Whether or not caching of requested depths and ids should be used to reduce performance impact.
*/
set cache(value: boolean) {
this._cache = value;
}
/**
* Sets the framebuffer object that is to be used for depth readback.
* @param framebuffer - Framebuffer that is to be used for depth readback.
*/
set depthFBO(framebuffer: Framebuffer) {
this._depthFBO = framebuffer;
}
/**
* Sets the framebuffer's {@link depthFBO} depth attachment that is to be used for depth readback.
* @param attachment - Depth attachment that is to be used for depth readback.
*/
set depthAttachment(attachment: GLenum) {
this._depthAttachment = attachment;
}
/**
* Sets the framebuffer object that is to be used for id readback.
* @param framebuffer - Framebuffer that is to be used for id readback.
*/
set idFBO(framebuffer: Framebuffer) {
this._idFBO = framebuffer;
}
/**
* Sets the framebuffer's {@link idFBO} id attachment that is to be used for id readback.
* @param attachment - ID attachment that is to be used for id readback.
*/
set idAttachment(attachment: GLenum) {
this._idAttachment = attachment;
}
}
<file_sep>
import { assert, log, LogLevel } from './auxiliaries';
import { Context } from './context';
import { AbstractObject } from './object';
/**
* WebGL shader wrapper encapsulating shader creation, compilation, and deletion. A shader can be attached to multiple
* Programs for linking, and can be deleted if detached from all (linked) programs.
*
* ```
* var frag = new gloperate.Shader(context, context.gl.FRAGMENT_SHADER, 'EmptyFragmentShader');
* var vert = new gloperate.Shader(context, context.gl.VERTEX_SHADER, 'EmptyVertexShader');
* vert.initialize('void main() { }');
* frag.initialize('void main() { }');
*
* var prog = new gloperate.Program(context, 'EmptyProgram');
* prog.initialize([frag, vert]);
* ```
*/
export class Shader extends AbstractObject<WebGLShader> {
/** @see {@link type} */
protected _type: GLenum;
/**
* Object constructor, requires a context and a valid identifier.
* @param context - Valid context to create the object for.
* @param type - Either GL_VERTEX_SHADER or GL_FRAGMENT_SHADER.
* @param identifier - Meaningful name for identification of this instance.
*/
constructor(context: Context, type: GLenum, identifier?: string) {
const gl = context.gl;
if (identifier === undefined) {
switch (type) {
case context.gl.FRAGMENT_SHADER:
identifier = 'FragmentShader';
break;
case context.gl.VERTEX_SHADER:
identifier = 'VertexShader';
break;
default:
assert(false, `expected either a FRAGMENT_SHADER (${gl.FRAGMENT_SHADER}) ` +
`or a VERTEX_SHADER (${gl.VERTEX_SHADER}), given ${type}`);
}
}
super(context, identifier);
this._type = type;
}
/**
* Creates a shader, sets the shader source, and compiles the shader. If the shader source cannot be compiled, the
* identifier and an info log are logged to console and the shader object is deleted. Note that a '#version 300 es'
* is added in case the shader source is compiled in a WebGL2 context.
* @param source - Shader source.
* @returns - Either a new shader or undefined if compilation failed.
*/
protected create(source: string): WebGLShader | undefined {
const gl = this._context.gl;
this._object = gl.createShader(this._type);
assert(this._object instanceof WebGLShader, `expected WebGLShader object to be created`);
if (this._context.isWebGL2) {
source = '#version 300 es\n' + source;
}
gl.shaderSource(this._object, source);
gl.compileShader(this._object);
if (!gl.getShaderParameter(this._object, gl.COMPILE_STATUS)) {
const infoLog: string = gl.getShaderInfoLog(this._object);
log(LogLevel.Error, `compilation of shader '${this._identifier}' failed: ${infoLog}`);
this.delete();
return undefined;
}
this._valid = gl.isShader(this._object);
return this._object;
}
/**
* Delete the shader object. This should have the reverse effect of `create`.
*/
protected delete(): void {
assert(this._object !== undefined, `expected WebGLShader object`);
this._context.gl.deleteShader(this._object);
this._object = undefined;
this._valid = false;
}
/**
* Either VERTEX_SHADER or FRAGMENT_SHADER.
*/
get type(): GLenum {
this.assertInitialized();
return this._type;
}
}
| 87fd29852da888eed1e58a32c8dce18eecda0297 | [
"TypeScript"
] | 2 | TypeScript | technologyarts/webgl-operate | 8953207435e0509cbf3a46897832f4b89decb49e | a9d7da5b808d79c8896d3541c2f5517bf144b8cd |
refs/heads/master | <file_sep>import soundfile as sf
import logging
WAVFILE_CONV_SUBTYPE = "PCM_16"
class DecoderQueue:
def __init__(self):
pass
def start(self, num):
pass
def stop(self):
pass
def submit(self, wavfilename, onfinish, args):
onfinish(wavfilename, {
"raw_packets": [],
"corrected_packets": [],
}, args)
@staticmethod
def get_audio_info(filename):
data, sample_rate = sf.read(filename)
nframes = len(data)
duration = nframes / sample_rate
return sample_rate, duration, nframes
@staticmethod
def convert_audiofile(filename, subtype=WAVFILE_CONV_SUBTYPE):
""" Converts the given file to a .wav file with the given subtype"""
try:
data, sample_rate = sf.read(filename)
doti = filename.rfind(".")
if doti == -1:
wavfilename = filename + ".wav"
else:
wavfilename = filename[:doti] + ".wav"
sf.write(wavfilename, data, sample_rate, subtype=subtype)
nframes = len(data)
duration = nframes / sample_rate
return wavfilename, sample_rate, duration, nframes
except RuntimeError as ex: # soundfile error
logging.error("Error converting audio file '%s' to wav", filename)
logging.exception(ex)
return None, 0, 0, 0
@staticmethod
def slice_audiofile(filename, start_s, stop_s, sample_rate):
""" Slices the given audio file from start_s seconds to end_s seconds
and overwrites the file. If start_s or end_s are negative,
they reference from the end of the file.
Returns whether the process was successful and the new duration """
if start_s is None:
start_i = 0
else:
start_i = start_s * sample_rate
if stop_s is None:
stop_i = None
else:
stop_i = stop_s * sample_rate
try:
data, _ = sf.read(filename, start=start_i, stop=stop_i)
sf.write(filename, data, sample_rate)
duration = len(data) / sample_rate
return True, duration
except RuntimeError as ex: # soundfile error
logging.error("Error slicing audio file '%s'", filename)
logging.exception(ex)
return False, 0<file_sep>#!/usr/bin/python
from flask import request, Flask, render_template
from werkzeug.utils import secure_filename
import requests
import yaml
import os
import yagmail
from yagmail import validate
from yagmail.error import YagInvalidEmailAddress
import datetime
import logging
import urllib
from bs4 import BeautifulSoup
import config
if config.decoder_enabled:
from decoder import DecoderQueue
else:
print("Decoder disabled; using fake decoder")
from fake_decoder import DecoderQueue
# config
NUM_DECODER_PROCESSES = 2
AUDIO_UPLOAD_FOLDER = 'wav_uploads/'
MAX_AUDIOFILE_DURATION_S = 480
MAX_AUDIOFILE_SIZE_B = 20e6 # set in nginx config for production server
PACKET_API_ROUTE = "http://api.brownspace.org/equisat/receive/raw"
app = Flask(__name__)
decoder = DecoderQueue(in_logger=app.logger)
# limit upload file size
app.logger.setLevel(logging.DEBUG)
# setup email
if hasattr(config, "gmail_user") and hasattr(config, "gmail_user"):
yag = yagmail.SMTP(config.gmail_user, config.gmail_pass)
else:
app.logger.warning("incomplete config.py; will not send emails")
yag = None
@app.route('/')
def root():
return render_template('index.html', max_audiofile_size_b=MAX_AUDIOFILE_SIZE_B, max_audiofile_duration_s=MAX_AUDIOFILE_DURATION_S)
@app.errorhandler(413)
def too_large_request(e):
return render_template('error_page.html', error=e, msg="Your uploaded file was too large"), 413
@app.errorhandler(404)
def page_not_found(e):
return render_template('error_page.html', error=e, msg=""), 404
## File decoding
@app.route('/decode_file', methods=["POST"])
def decode_file():
# initial validation
valid, ret = validate_email(request.form["email"])
if not valid:
return ret
try:
# parse in rx_time as local time
rx_time = datetime.datetime.strptime(request.form["rx_time_date"] + " " + request.form["rx_time_time"], "%Y-%m-%d %H:%M")
except ValueError:
title = "Invalid received time provided or left out"
message = "It appears that you didn't enter the time you received the data correctly. Please make sure you correctly entered the date, time, and timezone in which you received your data."
return render_template("decode_submit.html", title=title, message=message)
# convert RX time fields into datetime
# then convert to UTC time using entered timezone
rx_time_timezone = request.form["rx_time_timezone"]
tz_hours = int(rx_time_timezone[:3])
tz_minutes = int(60*(float(rx_time_timezone[4:])/100.0))
rx_time = rx_time - datetime.timedelta(hours=tz_hours, minutes=tz_minutes)
app.logger.debug("parsed rx_time as %s" % rx_time)
if rx_time > datetime.datetime.utcnow():
title = "Your received time was in the future"
message = "It appears that you entered a time in the future for the time you received this transmission. Check that you chose the correct time zone and entered the date and time correctly."
return render_template("decode_submit.html", title=title, message=message)
# audio file validation
filename = save_audiofile()
if filename is None:
title = "No audio file provided"
message = "Please make sure to upload an audio file using the form."
else:
# convert audio file to WAV and get metadata for filtering
wavfilename, sample_rate, duration, _ = decoder.convert_audiofile(filename)
# remove original file now, unless it was originally a wav
if filename != wavfilename:
os.remove(filename)
if wavfilename is None:
title = "Audio file conversion failed"
message = "We need to convert your audio file to a 16-bit PCM WAV file, but the conversion failed. " \
"Make sure your audio file format is supported by libsndfile (see link on main page)." \
"You can also try converting the file yourself using a program such as Audacity or ffmpeg."
elif duration > MAX_AUDIOFILE_DURATION_S:
title = "Audio file too long"
message = "Your submitted file was too long (maximum duration is %ds, yours was %ds). " \
"You can try shortening the audio duration using a program such as Audacity." % (MAX_AUDIOFILE_DURATION_S, duration)
# remove the unused file
os.remove(wavfilename)
else:
app.logger.info("[%s] submitting FILE decode request; rx_time: %s, submit_to_db: %s, post_publicly: %s, wavfilename: %s",
request.form["station_name"], rx_time, request.form.has_key("submit_to_db"), request.form.has_key("post_publicly"), wavfilename)
title = "Audio file submitted successfully!"
decoder.submit(wavfilename, on_complete_decoding, args={
"email": request.form["email"],
"rx_time": rx_time,
"station_name": request.form["station_name"],
"submit_to_db": request.form.has_key("submit_to_db") or request.form.has_key("post_publicly"), # submit to db is prereq
"post_publicly": request.form.has_key("post_publicly"),
"satnogs": False,
"obs_id": None
})
message = "Your file is queued to be decoded. You should be receiving an email shortly (even if there were no results). "
if request.form.has_key("submit_to_db"):
message += "Thank you so much for your help in providing us data on EQUiSat!"
else:
message += "Thank you for your interest in EQUiSat!"
return render_template("decode_submit.html", title=title, message=message)
def save_audiofile():
# check if the post request has the file part
if 'audiofile' not in request.files:
app.logger.warning("Invalid form POST for file upload")
return None
audiofile = request.files['audiofile']
# if user does not select file, browser also
# submit an empty part without filename
if audiofile.filename == '':
return None
if audiofile:
# clean filename for security
filename = secure_filename(audiofile.filename)
filepath = os.path.join(AUDIO_UPLOAD_FOLDER, filename)
audiofile.save(filepath)
return filepath
## SatNOGS decoding
@app.route('/decode_satnogs', methods=["POST"])
def decode_satnogs():
# initial validation
valid, ret = validate_email(request.form["email"])
if not valid:
return ret
try:
int(request.form["obs_id"])
except ValueError:
title = "Invalid observation ID"
message = "Your observation ID was not a valid integer number"
return render_template("decode_submit.html", title=title, message=message)
if request.form["start_s"] == "":
start_s = 0
else:
try:
start_s = int(request.form["start_s"])
if start_s < 0:
title = "Negative start time"
message = "Your start time must be positive; leave the field blank to use the start of the file"
return render_template("decode_submit.html", title=title, message=message)
except ValueError:
title = "Invalid start time"
message = "Your start time (%s) was not a valid integer number" % request.form["start_s"]
return render_template("decode_submit.html", title=title, message=message)
if request.form["stop_s"] == "":
stop_s = start_s + MAX_AUDIOFILE_DURATION_S-1 # minus one to not go over (need a buffer region)
else:
try:
stop_s = int(request.form["stop_s"])
if stop_s < 0:
title = "Negative stop time"
message = "Your stop time must be positive; leave the field blank to use the end of the file"
return render_template("decode_submit.html", title=title, message=message)
except ValueError:
title = "Invalid stop time"
message = "Your stop time (%s) was not a valid integer number" % request.form["stop_s"]
return render_template("decode_submit.html", title=title, message=message)
app.logger.debug("parsed start and stop time as %s and %s", start_s, stop_s)
if start_s != 0 and stop_s is not None and start_s >= stop_s:
title = "Start time wasn't before stop time"
message = "Your start time (%d) needs to be less than your stop time (%d)" % (start_s, stop_s)
return render_template("decode_submit.html", title=title, message=message)
# try to get observation data
app.logger.info("[obs %s] pulling data from SatNOGS" % request.form["obs_id"])
obs_data = scrape_satnogs_metadata(request.form["obs_id"])
app.logger.debug("[obs %s] got SatNOGS data: %s" % (request.form["obs_id"], obs_data))
# validate the observation properties
if obs_data is None:
title = "Observation not found or incomplete"
message = "We could not find an observation under the ID you provided, or the page for observation was incomplete. " \
"Make sure the page for that observation is available on SatNOGS "
return render_template("decode_submit.html", title=title, message=message)
elif obs_data["status"] == "pending":
title = "Observation is in the future"
message = "The observation had status 'future' so there is no data available to decode"
return render_template("decode_submit.html", title=title, message=message)
elif obs_data["audio_url"] is None:
title = "No audio found for observation"
message = "We couldn't find an audio file listed under this observation. " \
"It's possible that the observation failed and the station did not upload audio."
return render_template("decode_submit.html", title=title, message=message)
rx_time = obs_data["start_time"] + datetime.timedelta(seconds=start_s)
# get file
filename = AUDIO_UPLOAD_FOLDER + os.path.basename(obs_data["audio_url"])
app.logger.info("[obs %s] retrieving audio file from %s" % (request.form["obs_id"], obs_data["audio_url"]))
urllib.urlretrieve(obs_data["audio_url"], filename)
# convert audio file to WAV and get metadata for filtering
wavfilename, sample_rate, duration, _ = decoder.convert_audiofile(filename)
os.remove(filename) # remove original file
if wavfilename is None:
title = "Audio file conversion failed"
message = "Converting from the SatNOGS format failed. This is likely a bug with our software, " \
"but could be an issue with the SatNOGS observation. Please try another observation" \
"or email us at <EMAIL>"
return render_template("decode_submit.html", title=title, message=message)
elif start_s >= duration:
title = "Start time was larger than the duration of the observation"
message = "You specified a start time of %ss but the observation was only %ss long." % (start_s, duration)
return render_template("decode_submit.html", title=title, message=message)
# slice audio file to desired duration
success, duration = decoder.slice_audiofile(wavfilename, start_s, stop_s, sample_rate)
if not success:
title = "Audio file slicing failed"
message = "We were unable to shorten the audio file according to the start and end times you specified. " \
"You can try removing these values or not using negative values."
# remove the unused file
os.remove(wavfilename)
elif duration > MAX_AUDIOFILE_DURATION_S:
title = "Specified duration too long"
message = "The duration you specified with your start and end times was too long. " \
"You can try specifying a shorter or more specific duration (i.e. try not leaving the fields blank)."
# remove the unused file
os.remove(wavfilename)
else:
station_name = "%s #%s" % (obs_data["station_name"], request.form["obs_id"])
app.logger.info("Submitting SATNOGS decode request; station_name: %s, time interval: [%ss, %ss], rx_time: %s, submit_to_db: %s, post_publicly: %s, wavfilename: %s",
station_name, start_s, stop_s, rx_time, request.form.has_key("submit_to_db"), request.form.has_key("post_publicly"), wavfilename)
decoder.submit(wavfilename, on_complete_decoding, args={
"email": request.form["email"],
"rx_time": rx_time,
"station_name": station_name,
"submit_to_db": request.form.has_key("submit_to_db") or request.form.has_key("post_publicly"), # submit to db is prereq
"post_publicly": request.form.has_key("post_publicly"),
"satnogs": True,
"obs_id": request.form["obs_id"]
})
title = "SatNOGS observation submitted successfully!"
message = "The observation is queued to be decoded. You should be receiving an email shortly (even if there were no results). "
if request.form.has_key("submit_to_db"):
message += "Thank you so much for your help in providing us data on EQUiSat!"
else:
message += "Thank you for your interest in EQUiSat!"
return render_template("decode_submit.html", title=title, message=message)
def scrape_satnogs_metadata(obs_id):
page = requests.get("https://network.satnogs.org/observations/%s" % obs_id)
if page.status_code == 404:
# no observation found
return None
else:
soup = BeautifulSoup(page.text, 'html.parser')
try:
# get side column
side_col_rows = soup.body.find_all(attrs={"class":"front-line"})
# extract status
# <span class ="label label-xs label-good" aria-hidden="true" data-toggle="tooltip" data-placement="right" title=""
# data-original-title="Vetted good on 2019-01-07 00:16:28 by Brown Space Engineering">Good</span>
status_span = side_col_rows[3].findChildren()[2] # findChildren returns flat list of all nested children
status = status_span.text.lower()
# extract station name
# <a href="/stations/291/">
# 291 - COSPAR 8049
# </a>
full_station_name = side_col_rows[1].a.text
dash_i = full_station_name.index("-")
station_name = full_station_name[dash_i+1:].strip()
# extract and convert observation start time
start_time_span = side_col_rows[7].findChildren()[2]
start_time_str = start_time_span.contents[1].text + "T" + start_time_span.contents[3].text
start_time = datetime.datetime.strptime(start_time_str, "%Y-%m-%dT%H:%M:%S")
# extract URL of audio file
# <a href="/media/data_obs/399165/satnogs_399165_2019-01-07T00-01-01.ogg" target="_blank" download="">
# <button type="button" class="btn btn-default btn-xs" >
# <span class ="glyphicon glyphicon-download"></span>
# Audio
# </button>
# </a>
if len(side_col_rows) < 15:
audio_url = None
else:
first_a = side_col_rows[14].a
# check if the icon exists and if it's the audio one
if first_a is None or first_a["href"].find(".ogg") == -1:
audio_url = None
else:
audio_url = "https://network.satnogs.org" + first_a["href"]
return {
"status": str(status),
"station_name": str(station_name),
"start_time": start_time,
"audio_url": str(audio_url)
}
except IndexError or ValueError as ex:
app.logger.error("Error while parsing SatNOGS station page for observation %s", obs_id)
app.logger.exception(ex)
return None
## Post-decoding helpers
def validate_email(email):
try:
validate.validate_email_with_regex(email)
return True, None
except YagInvalidEmailAddress:
title = "Invalid email address"
message = "We send you the results of the decoding by email, so we'll need a valid email address. We don't store your address after sending you the results."
return False, render_template("decode_submit.html", title=title, message=message)
def on_complete_decoding(wavfilename, packets, args, err):
# remove wavfile because we're done with it (but leave it around on error for debugging)
if err is None:
app.logger.debug("[%s] removing used wavfile %s", args["station_name"], wavfilename)
os.remove(wavfilename)
# publish packet if user desires
if err is None:
num_published = publish_packets(packets, args)
else:
num_published = 0
# send email to person with decoded packet info
send_decode_results(wavfilename, packets, args, num_published, err)
def publish_packets(packets, args):
num_published = 0
if args["submit_to_db"]:
for packet in packets["corrected_packets"]:
if len(packet["decode_errs"]) == 0:
published = submit_packet(packet["raw"], packet["corrected"], args["post_publicly"], args["rx_time"], args["station_name"], config.api_key)
if published:
num_published += 1
else:
app.logger.debug("[%s] did not submit packet to DB due to decode errors: %s", args["station_name"], packet["decode_errs"])
return num_published
def submit_packet(raw, corrected, post_publicly, rx_time, station_name, api_key):
epoch = datetime.datetime(1970, 1, 1)
rx_time_posix = (rx_time - epoch).total_seconds()*1000 # ms since 1970
jsn = {
"raw": raw,
"corrected": corrected,
"station_name": station_name,
"post_publicly": post_publicly,
"source": "decoder.brownspace.org",
"rx_time": rx_time_posix,
"secret": api_key,
}
try:
r = requests.post(PACKET_API_ROUTE, json=jsn)
if r.status_code == requests.codes.ok or r.status_code == 201:
app.logger.info("[%s] submitted %spacket successfully" %
(station_name, "duplicate " if r.status_code == 201 else ""))
del jsn["secret"] # remove hidden info
app.logger.debug("Full POST request:\n%s", jsn)
return True
else:
app.logger.warning("[%s] couldn't submit packet (%d): %s" % (station_name, r.status_code, r.text))
return False
except Exception as ex:
app.logger.error("[%s] couldn't submit packet", station_name)
app.logger.exception(ex)
return False
def send_decode_results(wavfilename, packets, args, num_published, err):
raw_packets = packets["raw_packets"]
corrected_packets = packets["corrected_packets"]
cleaned_wavfilename = os.path.basename(wavfilename)
if err is not None:
body = """Unfortunately, the server encountered an error while attempting to decode your file and couldn't continue.
This is likely a bug with our software, so we'd appreciate it if you forwarded this email to <EMAIL>.
If you're curious, this is the error message that was produced: %s
""" % err
else:
raw_packets_summary = "Raw packets (%d detected):\n" % len(raw_packets)
for i in range(len(raw_packets)):
raw_packets_summary += "packet #%d hex:\n\t%s\n" % (i+1, raw_packets[i])
corrected_packets_summary = "Valid error-corrected packets (%d detected):\n" % len(corrected_packets)
for i in range(len(corrected_packets)):
parsed_yaml = yaml.dump(corrected_packets[i]["parsed"], default_flow_style=False)
decode_errs_s = "none" if len(corrected_packets[i]["decode_errs"]) == 0 else ", ".join(corrected_packets[i]["decode_errs"])
corrected_packets_summary += "packet #%d:\nhex:\n\t%s\nerrors in decoding: %s\ndecoded data:\n %s\n\n" % \
(i+1, corrected_packets[i]["corrected"], decode_errs_s, parsed_yaml)
if len(corrected_packets) > 0:
corrected_packets_summary += "To learn more about the decoded data, see this table: <a href=\"https://goo.gl/Kj9RkY\">https://goo.gl/Kj9RkY</a>"
extra_msg = ""
if len(raw_packets) == 0 or len(corrected_packets) == 0:
extra_msg = "\nSorry nothing was found! We're still working on the decoder, so keep trying and check back later!\n"
if num_published > 0:
if args["post_publicly"]:
extra_msg = "\n%d of your packets were added to our database and should have been posted to <a href=\"https://twitter.com/equisat_bot\">Twitter</a>!\n" % num_published
else:
extra_msg = "\n%d of your packets were added to our database!\n" % num_published
elif args["submit_to_db"]:
extra_msg = "\nYour packets unfortunately had too many errors to be added to our database or posted publicly.\n"
body = """%s
%s
%s""" % (raw_packets_summary, corrected_packets_summary, extra_msg)
subject = "EQUiSat Decoder Results for %s" % args["station_name"]
intro_sentence = 'Here are your results from the EQUiSat Decoder <a href="http://decoder.brownspace.org">decoder.brownspace.org</a>'
if args["satnogs"]:
header = """Hello,
%s, for SatNOGS observation #%s:
""" % (intro_sentence, args["obs_id"])
else:
header = """Hello %s,
%s, for your converted file '%s':
""" % (args["station_name"], intro_sentence, cleaned_wavfilename)
footer = """Thank you so much for your interest in EQUiSat!
Best,
The Brown Space Engineering Team
Our website: <a href="brownspace.org">brownspace.org</a>
EQUiSat homepage: <a href="equisat.brownspace.org">equisat.brownspace.org</a>
Twitter: <a href="twitter.com/BrownCubeSat">twitter.com/BrownCubeSat</a>
Facebook: <a href="facebook.com/browncubesat">facebook.com/BrownCubeSat</a>
GitHub: <a href="github.com/brownspaceengineering">github.com/BrownSpaceEngineering</a>
Email us: <a href="mailto:<EMAIL>"><EMAIL></a>
"""
contents = "%s\n%s\n%s" % (header, body, footer)
if yag is not None:
try:
yag.send(to=args["email"], subject=subject, contents=contents)
app.logger.debug("[%s] sent email with info on packets (raw: %d, corrected: %d, err: %s)",
args["station_name"], len(raw_packets), len(corrected_packets), err)
except Exception as ex:
app.logger.error("[%s] email failed to send", args["station_name"])
app.logger.exception(ex)
def start_decoder(num_procs=NUM_DECODER_PROCESSES):
decoder.start(num_procs)
if __name__ == "__main__":
start_decoder()
app.run(debug=True)
# see run.py for production runner
<file_sep>import multiprocessing
import Queue # for Queue.Empty
from equisat_fm_demod import equisat_fm_demod
from packetparse import packetparse
import binascii
import pmt
import soundfile as sf
import sys
import time
import logging
QUEUE_EMPTY_POLL_PERIOD = 2
FLOWGRAPH_POLL_PERIOD_S = 2
MAX_FLOWGRAPH_RUNTIME = 20
WAVFILE_CONV_SUBTYPE = "PCM_16"
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
class DecoderQueue:
def __init__(self, in_logger=None):
self.queue = multiprocessing.Queue()
self.procs = []
self.stopping = multiprocessing.Value("b", False)
if in_logger:
global logger
logger = in_logger
def start(self, num):
""" Spawns a new set of num processes which reads requests off the decode queue and performs them """
for i in range(num):
proc = multiprocessing.Process(target=self.decode_worker, args=(self.queue, self.stopping))
proc.start()
self.procs.append(proc)
def stop(self):
self.stopping.value = True
def submit(self, wavfilename, onfinish, args):
""" Submits an FM decode job (wavfilename) to the decoder queue.
The onfinish callback receives wavfilename, a dict containing raw_packets and corrected_packets lists,
the passed in args, and any error message (or None otherwise) """
self.queue.put_nowait({
"wavfilename": str(wavfilename),
"onfinish": onfinish,
"args": args
})
@staticmethod
def get_audio_info(filename):
data, sample_rate = sf.read(filename)
nframes = len(data)
duration = nframes / sample_rate
return sample_rate, duration, nframes
@staticmethod
def convert_audiofile(filename, subtype=WAVFILE_CONV_SUBTYPE):
""" Converts the given file to a .wav file with the given subtype"""
try:
data, sample_rate = sf.read(filename)
doti = filename.rfind(".")
if doti == -1:
wavfilename = filename + ".wav"
else:
wavfilename = filename[:doti] + ".wav"
sf.write(wavfilename, data, sample_rate, subtype=subtype)
nframes = len(data)
duration = nframes / sample_rate
return wavfilename, sample_rate, duration, nframes
except RuntimeError as ex: # soundfile error
logger.error("Error converting audio file '%s' to wav", filename)
logger.exception(ex)
return None, 0, 0, 0
@staticmethod
def slice_audiofile(filename, start_s, stop_s, sample_rate):
""" Slices the given audio file from start_s seconds to end_s seconds
and overwrites the file. If start_s or end_s are negative,
they reference from the end of the file.
Returns whether the process was successful and the new duration """
if start_s is None:
start_i = 0
else:
start_i = start_s * sample_rate
if stop_s is None:
stop_i = None
else:
stop_i = stop_s * sample_rate
try:
data, _ = sf.read(filename, start=start_i, stop=stop_i)
sf.write(filename, data, sample_rate)
duration = len(data) / sample_rate
return True, duration
except RuntimeError as ex: # soundfile error
logger.error("Error slicing audio file '%s'", filename)
logger.exception(ex)
return False, 0
@staticmethod
def decode_worker(dec_queue, stopping):
try:
while not stopping.value:
try:
# block until next demod is in
next_demod = dec_queue.get(timeout=QUEUE_EMPTY_POLL_PERIOD)
except Queue.Empty:
# check for stopped condition if queue empty after timeout
continue
except KeyboardInterrupt:
return
try:
wavfilename = next_demod["wavfilename"]
sample_rate, duration, nframes = DecoderQueue.get_audio_info(wavfilename)
# spawn the GNU radio flowgraph and run it
tb = equisat_fm_demod(wavfile=wavfilename, sample_rate=sample_rate)
logger.debug("[%s] Starting demod flowgraph" % wavfilename)
tb.start()
# run until the wav source block has completed
# (GNU Radio has a bug such that flowgraphs with Python message passing blocks won't terminate)
# (see https://github.com/gnuradio/gnuradio/pull/797, https://www.ruby-forum.com/t/run-to-completion-not-working-with-message-passing-blocks/240759)
start = time.time()
while tb.blocks_wavfile_source_0.nitems_written(0) < nframes \
and (time.time() - start) < MAX_FLOWGRAPH_RUNTIME:
time.sleep(FLOWGRAPH_POLL_PERIOD_S)
if tb.blocks_wavfile_source_0.nitems_written(0) < nframes:
logger.warn("[%s] Flowgraph timed out (%d/%d frames)" % \
(wavfilename, tb.blocks_wavfile_source_0.nitems_written(0), nframes))
logger.debug("[%s] Stopping demod flowgraph" % wavfilename)
tb.stop()
tb.wait()
logger.debug("[%s] Demod flowgraph terminated" % wavfilename)
# we have a block to store both all valid raw packets and one to store
# all those that passed error correction (which includes the corresponding raw)
raw_packets = []
corrected_packets = []
for i in range(tb.message_store_block_raw.num_messages()):
msg = tb.message_store_block_raw.get_message(i)
raw_packets.append(binascii.hexlify(bytearray(pmt.u8vector_elements(pmt.cdr(msg)))))
for i in range(tb.message_store_block_corrected.num_messages()):
msg = tb.message_store_block_corrected.get_message(i)
corrected = pmt.u8vector_elements(pmt.cdr(msg))
raw = pmt.u8vector_elements(pmt.dict_ref(pmt.car(msg), pmt.intern("raw"), pmt.get_PMT_NIL()))
decoded, decode_errs = packetparse.parse_packet(binascii.hexlify(bytearray(corrected)))
corrected_packets.append({
"raw": binascii.hexlify(bytearray(raw)),
"corrected": binascii.hexlify(bytearray(corrected)),
"parsed": decoded,
"decode_errs": decode_errs
})
onfinish = next_demod["onfinish"]
onfinish(wavfilename, {
"raw_packets": raw_packets,
"corrected_packets": corrected_packets,
}, next_demod["args"], None)
except KeyboardInterrupt:
return
except Exception as ex:
logger.error("Exception in decoder worker, skipping job")
logger.exception(ex)
onfinish = next_demod["onfinish"]
onfinish(next_demod["wavfilename"], {
"raw_packets": [],
"corrected_packets": [],
}, next_demod["args"], ex.message)
finally:
print("Stopping decoder worker")
def onfinish_cli(wf, packets, args, err):
print("done; %d raw, %d corrected, err: %s" % (len(packets["raw_packets"]), len(packets["corrected_packets"]), err))
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage: decoder.py <wavfilename>")
exit(1)
dec = DecoderQueue()
dec.start(1)
dec.submit(sys.argv[1], onfinish_cli, None)
time.sleep(5)
dec.stop()
<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Equisat Fm Demod
# Description: This flowgraph generates the flowgraph used in decode.py
# Generated: Mon Mar 11 19:26:09 2019
##################################################
from gnuradio import blocks
from gnuradio import digital
from gnuradio import eng_notation
from gnuradio import filter
from gnuradio import gr
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser
import equisat_decoder
class equisat_fm_demod(gr.top_block):
def __init__(self, sample_rate=48000, wavfile=""):
gr.top_block.__init__(self, "Equisat Fm Demod")
##################################################
# Parameters
##################################################
self.sample_rate = sample_rate
self.wavfile = wavfile
##################################################
# Variables
##################################################
self.symbol_depth = symbol_depth = 40
self.decimation = decimation = 2
self.variable_rrc_filter_taps_0 = variable_rrc_filter_taps_0 = firdes.root_raised_cosine(1.0, sample_rate/decimation, 4800, 0.2, symbol_depth*(sample_rate/decimation/4800))
self.gain_mu = gain_mu = 0.050
##################################################
# Blocks
##################################################
self.message_store_block_raw = blocks.message_debug()
self.message_store_block_corrected = blocks.message_debug()
self.fir_filter_xxx_0 = filter.fir_filter_fff(decimation, (variable_rrc_filter_taps_0))
self.fir_filter_xxx_0.declare_sample_delay(0)
self.equisat_decoder_equisat_fec_decoder_0 = equisat_decoder.equisat_fec_decoder()
self.equisat_decoder_equisat_4fsk_preamble_detect_0 = equisat_decoder.equisat_4fsk_preamble_detect(255,0.33, 40)
self.equisat_decoder_equisat_4fsk_block_decode_0 = equisat_decoder.equisat_4fsk_block_decode(255, False)
self.digital_clock_recovery_mm_xx_0 = digital.clock_recovery_mm_ff((sample_rate/decimation)/4800.0, 0.25*gain_mu*gain_mu, 0.5, gain_mu, 0.005)
self.blocks_wavfile_source_0 = blocks.wavfile_source(wavfile, False)
self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vff((10, ))
self.blocks_message_debug_0 = blocks.message_debug()
##################################################
# Connections
##################################################
self.msg_connect((self.equisat_decoder_equisat_4fsk_block_decode_0, 'out'), (self.equisat_decoder_equisat_fec_decoder_0, 'in'))
self.msg_connect((self.equisat_decoder_equisat_4fsk_block_decode_0, 'out'), (self.message_store_block_raw, 'store'))
self.msg_connect((self.equisat_decoder_equisat_4fsk_preamble_detect_0, 'out'), (self.equisat_decoder_equisat_4fsk_block_decode_0, 'in'))
self.msg_connect((self.equisat_decoder_equisat_fec_decoder_0, 'out'), (self.message_store_block_corrected, 'store'))
self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.fir_filter_xxx_0, 0))
self.connect((self.blocks_wavfile_source_0, 0), (self.blocks_multiply_const_vxx_0_0, 0))
self.connect((self.digital_clock_recovery_mm_xx_0, 0), (self.equisat_decoder_equisat_4fsk_preamble_detect_0, 0))
self.connect((self.fir_filter_xxx_0, 0), (self.digital_clock_recovery_mm_xx_0, 0))
def get_sample_rate(self):
return self.sample_rate
def set_sample_rate(self, sample_rate):
self.sample_rate = sample_rate
self.digital_clock_recovery_mm_xx_0.set_omega((self.sample_rate/self.decimation)/4800.0)
def get_wavfile(self):
return self.wavfile
def set_wavfile(self, wavfile):
self.wavfile = wavfile
def get_symbol_depth(self):
return self.symbol_depth
def set_symbol_depth(self, symbol_depth):
self.symbol_depth = symbol_depth
def get_decimation(self):
return self.decimation
def set_decimation(self, decimation):
self.decimation = decimation
self.digital_clock_recovery_mm_xx_0.set_omega((self.sample_rate/self.decimation)/4800.0)
def get_variable_rrc_filter_taps_0(self):
return self.variable_rrc_filter_taps_0
def set_variable_rrc_filter_taps_0(self, variable_rrc_filter_taps_0):
self.variable_rrc_filter_taps_0 = variable_rrc_filter_taps_0
self.fir_filter_xxx_0.set_taps((self.variable_rrc_filter_taps_0))
def get_gain_mu(self):
return self.gain_mu
def set_gain_mu(self, gain_mu):
self.gain_mu = gain_mu
self.digital_clock_recovery_mm_xx_0.set_gain_omega(0.25*self.gain_mu*self.gain_mu)
self.digital_clock_recovery_mm_xx_0.set_gain_mu(self.gain_mu)
def argument_parser():
description = 'This flowgraph generates the flowgraph used in decode.py'
parser = OptionParser(usage="%prog: [options]", option_class=eng_option, description=description)
parser.add_option(
"", "--sample-rate", dest="sample_rate", type="intx", default=48000,
help="Set Sample Rate [default=%default]")
parser.add_option(
"", "--wavfile", dest="wavfile", type="string", default="",
help="Set Input WAV File [default=%default]")
return parser
def main(top_block_cls=equisat_fm_demod, options=None):
if options is None:
options, _ = argument_parser().parse_args()
tb = top_block_cls(sample_rate=options.sample_rate, wavfile=options.wavfile)
tb.start()
tb.wait()
if __name__ == '__main__':
main()
<file_sep>#!/usr/bin/env bash
echo "killing old processes"
sudo killall python
nohup python run.py &
<file_sep>decoder_enabled = False
gmail_user = "<EMAIL>"
gmail_pass = "<PASSWORD>"
api_key = "myapikey"<file_sep>#!/usr/bin/env python
from gevent.pywsgi import WSGIServer
from server import app
from server import start_decoder
import logging
# start decoder worker process
start_decoder()
# setup logging
app.logger.setLevel(logging.DEBUG)
# see nginx config for port 80 proxy
http_server = WSGIServer(('', 5000), app)
try:
app.logger.info("Started server")
http_server.serve_forever()
except KeyboardInterrupt:
pass<file_sep>flask
werkzeug
yagmail
pyyaml
requests
gevent
pysoundfile<file_sep># EQUiSat Decode Server
A Python server providing a backend and interface to decode and submit EQUiSat transmissions.
## Install
Install gr-equisat_decoder on the system
Do `pip install -r requirements.txt`
## Run
Development: `python server.py`
Production: `python run.py` or `./run`<file_sep>#!/usr/bin/env bash
echo "WARNING: may overwrite certbot configuration!"
sleep 10
git submodule init
git submodule update
pip install -r requirements.txt
sudo apt install nginx
sudo rm /etc/nginx/sites-enabled/default
sudo cp decoder.brownspace.org.conf /etc/nginx/sites-available/
sudo ln -s /etc/nginx/sites-available/decoder.brownspace.org.conf /etc/nginx/sites-enabled/decoder.brownspace.org.conf | afeaa0ffcb3d0d757b685ff6ba745baf90351f63 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 10 | Python | BrownSpaceEngineering/equisat-decode-server | 4541d181cea2581739c431b4cd34d0f7e0364fbb | 46d3da9fd9137a2fba018387e3772f890b81e9c0 |
refs/heads/master | <file_sep># frozen_string_literal: true
require "logidze"
module Logidze
class Engine < Rails::Engine # :nodoc:
config.logidze = Logidze
initializer "extend ActiveRecord with Logidze" do |_app|
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.send :include, Logidze::HasLogidze
end
end
end
end
<file_sep>PS1="[\[\e[34m\]\w\[\e[0m\]] "
alias be="bundle exec"
<file_sep>CREATE TRIGGER logidze_on_<%= table_name %>
BEFORE UPDATE OR INSERT ON <%= table_name %> FOR EACH ROW
WHEN (coalesce(current_setting('logidze.disabled', true), '') <> 'on')
-- Parameters: history_size_limit (integer), timestamp_column (text), filtered_columns (text[]),
-- include_columns (boolean), debounce_time_ms (integer)
EXECUTE PROCEDURE logidze_logger(<%= logidze_logger_parameters %>);
<file_sep># frozen_string_literal: true
if ENV["HISTFILE"]
hist_dir = ENV["HISTFILE"].sub(/\/[^\/]+$/, "")
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = File.join(hist_dir, ".irb_history")
end
<file_sep># frozen_string_literal: true
require File.expand_path("../boot", __FILE__)
require "rails"
require "action_controller/railtie"
require "active_record/railtie"
Bundler.require(*Rails.groups)
# Conditionally load fx
USE_FX = ENV["USE_FX"] == "true"
require "logidze"
if USE_FX
require "fx"
$stdout.puts "🔩 Fx is loaded"
end
unless ActiveRecord::Migration.respond_to?(:[])
ActiveRecord::Migration.singleton_class.send(:define_method, :[]) { |_| self }
end
module Dummy
class Application < Rails::Application
config.eager_load = false
end
end
<file_sep># frozen_string_literal: true
require "rails/generators"
require "rails/generators/active_record"
require_relative "../inject_sql"
require_relative "../fx_helper"
using RubyNext
module Logidze
module Generators
class InstallGenerator < ::Rails::Generators::Base # :nodoc:
include Rails::Generators::Migration
include InjectSql
include FxHelper
class FuncDef < Struct.new(:name, :version, :signature); end
source_root File.expand_path("templates", __dir__)
source_paths << File.expand_path("functions", __dir__)
class_option :update, type: :boolean, optional: true,
desc: "Define whether this is an update migration"
def generate_migration
migration_template = fx? ? "migration_fx.rb.erb" : "migration.rb.erb"
migration_template migration_template, "db/migrate/#{migration_name}.rb"
end
def generate_hstore_migration
return if update?
migration_template "hstore.rb.erb", "db/migrate/enable_hstore.rb"
end
def generate_fx_functions
return unless fx?
function_definitions.each do |fdef|
next if fdef.version == previous_version_for(fdef.name)
template "#{fdef.name}.sql", "db/functions/#{fdef.name}_v#{fdef.version.to_s.rjust(2, "0")}.sql"
end
end
no_tasks do
def migration_name
if update?
"logidze_update_#{Logidze::VERSION.delete(".")}"
else
"logidze_install"
end
end
def migration_class_name
migration_name.classify
end
def update?
options[:update]
end
def previous_version_for(name)
all_functions.filter_map { |path| Regexp.last_match[1].to_i if path =~ %r{#{name}_v(\d+).sql} }.max
end
def all_functions
@all_functions ||=
begin
res = nil
in_root do
res = if File.directory?("db/functions")
Dir.entries("db/functions")
else
[]
end
end
res
end
end
def function_definitions
@function_definitions ||=
begin
Dir.glob(File.join(__dir__, "functions", "*.sql")).map do |path|
name = path.match(/([^\/]+)\.sql/)[1]
file = File.open(path)
header = file.readline
version = header.match(/version:\s+(\d+)/)[1].to_i
parameters = file.readline.match(/CREATE OR REPLACE FUNCTION\s+[\w_]+\((.*)\)/)[1]
signature = parameters.split(/\s*,\s*/).map { |param| param.split(/\s+/, 2).last.sub(/\s+DEFAULT .*$/, "") }.join(", ")
FuncDef.new(name, version, signature)
end
end
end
end
def self.next_migration_number(dir)
::ActiveRecord::Generators::Base.next_migration_number(dir)
end
end
end
end
<file_sep># frozen_string_literal: true
module Logidze
VERSION = "0.12.0"
end
<file_sep># frozen_string_literal: true
module Logidze
module IgnoreLogData
# Fixes unexpected behavior (see more https://github.com/rails/rails/pull/34528):
# instead of using a type passed to `attribute` call, ignored column uses
# a type coming from the DB (in this case `.log_data` would return a plain hash
# instead of `Logidze::History`)
module CastAttributePatch
def log_data
return attributes["log_data"] if attributes["log_data"].is_a?(Logidze::History)
self.log_data = Logidze::History::Type.new.cast_value(super)
end
end
end
end
<file_sep># frozen_string_literal: true
class NotLoggedPost < ActiveRecord::Base
has_logidze ignore_log_data: true
self.table_name = "posts"
belongs_to :user
has_many :comments, class_name: "NotLoggedPostComment", foreign_key: :post_id
end
<file_sep>version: '2.4'
services:
dev:
command: bash
image: ruby:2.7.1
volumes:
- ..:/${PWD}:cached
- bundler_data:/usr/local/bundle
- history:/usr/local/hist
- ./.bashrc:/root/.bashrc:ro
- ./.irbrc:/root/.irbrc:ro
- ./.pryrc:/root/.pryrc:ro
environment:
HISTFILE: /usr/local/hist/.bash_history
LANG: C.UTF-8
PROMPT_DIRTRIM: 2
PS1: '[\W]\! '
DATABASE_URL: postgres://postgres:postgres@postgres:5432
working_dir: ${PWD}
tmpfs:
- /tmp
depends_on:
postgres:
condition: service_healthy
postgres:
image: postgres:11.7
volumes:
- ../bench:/bench:cached
- history:/usr/local/hist
- ./.psqlrc:/root/.psqlrc:ro
- postgres:/var/lib/postgresql/data
environment:
PSQL_HISTFILE: /usr/local/hist/.psql_history
POSTGRES_PASSWORD: <PASSWORD>
PGPASSWORD: <PASSWORD>
ports:
- 5432
healthcheck:
test: pg_isready -U postgres -h 127.0.0.1
interval: 5s
volumes:
bundler_data:
postgres:
history:
| 1ac1c664892b5e76418d231f3798562895789552 | [
"SQL",
"Ruby",
"YAML",
"Shell"
] | 10 | Ruby | artplan1/logidze | 96dc7a78bf8b683a78495afeef04308b14789ffd | 75826d0f4e148aaa6a193019d51594397fabe82c |
refs/heads/master | <file_sep>import React from "react";
import { StyleSheet, Text, View, Button } from "react-native";
const Settings = ({ navigation }) => (
<View>
<Text>Settings</Text>
<Button onPress={() => navigation.navigate("Home")} title="Home" />
</View>
);
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// alignItems: "center",
// justifyContent: "center",
// },
// });
export default Settings;
| 4688af29b119858241baa71500a423c0c6326317 | [
"JavaScript"
] | 1 | JavaScript | PaulCroitoriu/Life-Met | cd52964e903e348b81eb1fd5057ae5cf09ee6901 | e92970f1a792d7785b6565ba78a88a4e3dc8afcf |
refs/heads/master | <file_sep>import cv2, os
from confapp import conf
from pyforms.controls import ControlDockWidget
from pythonvideoannotator.utils.tools import list_folders_in_path
from pythonvideoannotator_models_gui.models import Project
from pythonvideoannotator_models_gui.dialogs import Dialog
class Module(object):
def __init__(self):
"""
This implements the Path edition functionality
"""
super(Module, self).__init__()
self._right_docker = ControlDockWidget('Videos list',side=ControlDockWidget.SIDE_LEFT, order=0, margin=5)
self._right_details = ControlDockWidget('Details',side=ControlDockWidget.SIDE_RIGHT, order=1, margin=5)
self._right_docker.value = self._project
#self._right_docker.hide()
#self._right_details.hide()
self.mainmenu[2]['Windows'].append({'Videos': self.__show_objects_list_event, 'icon':conf.ANNOTATOR_ICON_MOVIES })
def __show_objects_list_event(self):
self._right_docker.show()
self._right_details.show()
def process_frame_event(self, frame):
"""
Function called before render each frame
"""
if self._player.video_index is not None:
self._project.draw(frame, self._player.video_index-1)
return super().process_frame_event(frame)
def add_graph(self, name, data): self._time.add_graph(name, data)
######################################################################################
#### IO FUNCTIONS ####################################################################
######################################################################################
######################################################################################
#### PROPERTIES ######################################################################
######################################################################################
@property
def objects(self): return self._project.objects
@property
def details(self): return self._right_details.value
@details.setter
def details(self, value): self._right_details.value = value
<file_sep>
__version__ = "0.5.28"
| 4e610466983abedea8e0b7b165e9597bf47c12a1 | [
"Python"
] | 2 | Python | video-annotator/pythonvideoannotator-module-patheditor | 31612ea9620c2c247c22c55a93fb13f8a0834691 | 7528afb30237b2156e1ad5350159c0eb5afa6978 |
refs/heads/master | <file_sep>import numpy as np
import math
# Valuation of a European call option by Monte Carlo simulation
# Considering a Black-Scholes-Merton setup in which the option's underlying risk factor follows a geometric Brownian motion
# Parameters values
S0 = 100. # initial index level
K = 105. # strike price
T = 1.0 # time-to-maturity
r = 0.5 # riskless short rate
sigma = 0.2 # volatility
I = 100000 # nb of simulations
# Valuation algorithm
z = np.random.standard_normal(I) # pseudo-random nbs
# Index values at maturity
ST = S0 * np.exp((r - 0.5 * sigma ** 2) * T + sigma * math.sqrt(T) * z)
hT = np.maximum(ST - K, 0) # payoff at maturity
C0 = math.exp(-r * T) * np.mean(hT) # Monte Carlo estimator
# Result output
print("Value of the European call option %5.3f." % C0)
| 1aa11e265492ea095d0f65a599d761d31d27711c | [
"Python"
] | 1 | Python | seivin/finance | 1b5e2328156e50b199deb3c1bfce2e463ce27e5f | ea90258e4c38beb8adf6de4730edb9443364734f |
refs/heads/master | <file_sep># Tokens Input
Text input that tokenifies the values (eg tags, recipients).
Uses [suggest-box](https://www.npmjs.com/package/suggest-box).

```jsx
import TokensInput from 'patchkit-tokens-input'
const suggestOptions = [
{ title: 'Alice', subtitle: '<NAME>', value: 1 },
{ title: 'Bob', subtitle: '<NAME>', value: 2 },
{ title: 'Carla', subtitle: '<NAME>', value: 3 },
{ title: 'Dan', subtitle: '<NAME>', value: 4 }
]
const onAdd = listKey => t => {
// find and add to list
if (this.state.tokens.filter(t2 => t.value == t2.value).length === 0)
this.state.tokens.push(t)
this.setState(this.state)
}
const onRemove = listKey => t => {
// find and remove form list
var i = this.state.tokens.indexOf(t)
if (i !== -1)
this.state.tokens.splice(i, 1)
this.setState(this.state)
}
// Standard usage:
<TokensInput
label="Users:"
placeholder="Enter user names here"
suggestOptions={suggestOptions}
tokens={this.state.tokens}
onAdd={onAdd}
onRemove={onRemove} />
// Allow 'arbitrary' inputs (not suggested):
<TokensInput
allowArbitrary
label="Users:"
placeholder="Enter user names here"
suggestOptions={suggestOptions}
tokens={this.state.tokens}
onAdd={onAdd}
onRemove={onRemove} />
// Enforce a token limit:
<TokensInput
limit=2
limitErrorMsg="Limit reached"
label="Users:"
placeholder="Enter user names here"
suggestOptions={suggestOptions}
tokens={this.state.tokens}
onAdd={onAdd}
onRemove={onRemove} />
// Read-only:
<TokensInput
readOnly
label="Users:"
tokens={this.state.tokens} />
```
## Styles
Use the .less file:
```less
@import "node_modules/patchkit-tokens-input/styles.less"
```
If you don't have suggest-box styles yet, include the following:
```less
@import "node_modules/patchkit-tokens-input/suggest-box.less"
```<file_sep>import React from 'react'
import suggestBox from 'suggest-box'
import cls from 'classnames'
class Token extends React.Component {
render() {
return <span className="token">
{this.props.token.title}
{this.props.readOnly ? '' : <a onClick={() => this.props.onRemove(this.props.token)}><i className="fa fa-remove"/></a>}
</span>
}
}
export default class TokensInput extends React.Component {
static propTypes = {
suggestOptions: React.PropTypes.array,
tokens: React.PropTypes.array.isRequired,
onAdd: React.PropTypes.func,
label: React.PropTypes.string,
placeholder: React.PropTypes.string,
limitErrorMsg: React.PropTypes.string,
className: React.PropTypes.string,
limit: React.PropTypes.number,
allowArbitrary: React.PropTypes.bool,
readOnly: React.PropTypes.bool
}
constructor(props) {
super(props)
this.state = { inputText: '' }
}
componentDidMount() {
this.setupSuggest()
}
componentDidUpdate() {
this.setupSuggest()
}
setupSuggest() {
// setup the suggest-box
const input = this.refs && this.refs.input
if (!input || input.isSetup)
return
input.isSetup = true
suggestBox(input, { any: this.props.suggestOptions }, { cls: 'token-input-options' })
input.addEventListener('suggestselect', this.onSuggestSelect.bind(this))
}
onChange(e) {
this.setState({ inputText: e.target.value })
}
onSuggestSelect(e) {
if (this.props.onAdd)
this.props.onAdd(e.detail)
this.setState({ inputText: '' })
}
onKeyDown(e) {
if (!this.props.allowArbitrary)
return
const v = this.state.inputText.trim()
if (e.keyCode === 13 && v) {
this.props.onAdd(v)
this.setState({ inputText: '' })
}
}
render() {
const isAtLimit = (this.props.limit && this.props.tokens.length >= this.props.limit)
const limitErrorMsg = this.props.limitErrorMsg
const inputReadOnly = (isAtLimit || this.props.readOnly)
const inputStyle = (inputReadOnly) ? { display: 'none' } : undefined
return <div className={cls('tokens-input', this.props.className)}>
<div>
{this.props.label} {this.props.tokens.map(t => <Token key={t.value} token={t} onRemove={this.props.onRemove} readOnly={this.props.readOnly} />)}
<input ref="input" type="text" placeholder={this.props.placeholder} value={this.state.inputText} onChange={this.onChange.bind(this)} onKeyDown={this.onKeyDown.bind(this)} readOnly={inputReadOnly} style={inputStyle} />
</div>
{ isAtLimit && limitErrorMsg ? <div className="warning">{limitErrorMsg}</div> : '' }
</div>
}
}<file_sep>import React from 'react'
import TokensInput from './index'
const suggestOptions = [
{ title: 'Alice', subtitle: '<NAME>', value: 1 },
{ title: 'Bob', subtitle: '<NAME>', value: 2 },
{ title: 'Carla', subtitle: '<NAME>', value: 3 },
{ title: 'Dan', subtitle: '<NAME>', value: 4 }
]
export default class TokensInputDemo extends React.Component {
constructor(props) {
super(props)
this.state = {
tokens1: [],
tokens2: [],
tokens3: []
}
}
render() {
const onAdd = listKey => t => {
console.log('add', t)
// convert to object, if an arbitrary string input
if (typeof t == 'string')
t = { title: t, value: t }
// find and add to list
var list = this.state[listKey]
if (list.filter(t2 => t.value == t2.value).length === 0)
list.push(t)
this.setState(this.state)
}
const onRemove = listKey => t => {
console.log('remove', t)
// find and remove form list
var list = this.state[listKey]
var i = list.indexOf(t)
if (i !== -1)
list.splice(i, 1)
this.setState(this.state)
}
return <div>
<h1>patchkit-tokens-input</h1>
<section className="demo-tokens-input">
<header><TokensInput label="Users:" placeholder="alice, bob, carla, dan" suggestOptions="..."></header>
<div className="content">
<TokensInput label="Users:" placeholder="alice, bob, carla, dan" suggestOptions={suggestOptions} tokens={this.state.tokens1} onAdd={onAdd('tokens1')} onRemove={onRemove('tokens1')} />
</div>
</section>
<section className="demo-tokens-input-arbitrary">
<header><TokensInput allowArbitrary label="Users:" placeholder="alice, bob, carla, dan" suggestOptions="..."></header>
<div className="content">
<TokensInput allowArbitrary label="Users:" placeholder="alice, bob, carla, dan" suggestOptions={suggestOptions} tokens={this.state.tokens2} onAdd={onAdd('tokens2')} onRemove={onRemove('tokens2')} />
</div>
</section>
<section className="demo-tokens-input">
<header><TokensInput limit=2 limitErrorMsg="Limit reached" label="Users:" placeholder="alice, bob, carla, dan" suggestOptions="..."></header>
<div className="content">
<TokensInput limit={2} limitErrorMsg="Limit reached" label="Users:" placeholder="alice, bob, carla, dan" suggestOptions={suggestOptions} tokens={this.state.tokens3} onAdd={onAdd('tokens3')} onRemove={onRemove('tokens3')} />
</div>
</section>
<section className="demo-tokens-readonly">
<header><TokensInput readOnly label="Users:" tokens="..."></header>
<div className="content">
<TokensInput readOnly label="Users:" tokens={suggestOptions} />
</div>
</section>
</div>
}
} | 63ead14fd7b853e39be695bbbc3116134477f525 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | patchkit/patchkit-tokens-input | 9bea3ef0d2981ea3e2a26dd0cf28fa10853137ff | 839a3a19d36747b007c5f7ec4a435aa84cb135be |
refs/heads/master | <repo_name>pchinjr/25-days-of-serverless-solutions<file_sep>/week-1/challenge-2/readme.md
Coffee (25 minutes) - coffee takes 25 minutes to brew
deliver cofee - two cups, it takes 4 minutes to bring coffee and 4 minutes to return
Scheduled Functions:
relight candles - every 10 minutes
pour coffee into cups - when coffee is done
deliver batches of coffee - takes 4 minutes to deliver and 4 minutes to return <file_sep>/README.md
# 25-days-of-serverless-solutions
My answers for 25DaysofServerless
Week 1: https://eh78toievi.execute-api.us-east-1.amazonaws.com/production/dreidel<file_sep>/week-1/challenge-2/src/scheduled/light-candles/index.js
// learn more about scheduled functions here: https://arc.codes/primitives/scheduled
exports.handler = async function scheduled (event) {
console.log(JSON.stringify(event, null, 2))
return
}<file_sep>/week-1/challenge-1/src/http/get-dreidel/index.js
let arc = require('@architect/functions')
function route(req, res) {
const sides = [' נ (Nun)',' ג (Gimmel)',' ה (Hay)',' ש (Shin)']
let result = sides[Math.floor(Math.random()*4)]
res({
json: {
'data': result,
'image': 'https://i.ytimg.com/vi/kqbF2fjSiqE/hqdefault.jpg',
'video': 'https://www.youtube.com/watch?v=kqbF2fjSiqE'
}
})
}
exports.handler = arc.http(route)<file_sep>/week-1/challenge-1/readme.md
This week is a GET endpoint that returns a random face of the dreidel.
Relevant Nic Cage: https://www.youtube.com/watch?v=kqbF2fjSiqE | 8a19950436b3ccc262ae78d1c13aaa3ec4424e4c | [
"Markdown",
"JavaScript"
] | 5 | Markdown | pchinjr/25-days-of-serverless-solutions | 091128ad7375676117a0ca902bf5e4db2895fbea | ddcbba963d7346ee47aa7ee57af4a80caf9b5ee2 |
refs/heads/master | <repo_name>sisama2323/gp_map<file_sep>/src/run_ifom.cpp
/*
Some Notes:
1. Only publish the point that are marked as occupied otherwise it is hard to see what is going on
2. Global variable Sig_mat is empty after passing into callback function, need to fix this
*/
// ros
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <message_filters/subscriber.h>
#include <tf/transform_listener.h>
// pcl
#include <pcl/PCLPointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_cloud.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/filters/voxel_grid.h>
// eigen
#include <Eigen/Sparse>
// stl
#include <cmath>
#include <vector>
#include <limits>
#include <std_msgs/String.h>
#include <set>
#include <random>
#include <chrono>
#include <iostream>
// local
#include "markerarray_pub.h"
#include "InformationFilterOccupancyMap.h"
void QuatToRot( double qx, double qy, double qz, double qw,
Eigen::Matrix<double,3,3>& R )
{
R << 1.0-2.0*(qy*qy+qz*qz),
2.0*qx*qy-2.0*qw*qz,
2.0*qw*qy+2.0*qx*qz,
2.0*qx*qy+2.0*qw*qz,
1.0-2.0*(qx*qx+qz*qz),
2.0*qy*qz-2.0*qw*qx,
2.0*qx*qz-2.0*qw*qy,
2.0*qy*qz+2.0*qw*qx,
1.0-2.0*(qx*qx+qy*qy);
}
// save time
void WriteVectorToFile(const std::vector<double>& vector,std::string filename)
{
std::ofstream ofs(filename,std::ios::out | std::ofstream::binary);
std::ostream_iterator<double> osi{ofs, "\n"};
std::copy(vector.begin(),vector.end(),osi);
}
class RunIfomFromBag{
// parameter
tf::Vector3 last_position;
tf::Quaternion last_orientation;
ros::NodeHandle nh_;
double delta_; // delta for information vector p(y=1)
double thresh_; // threshold for posterier
// map range in meter lower
std::vector<double> devmin_;
// map range in meter upper
std::vector<double> devmax_;
size_t num_iter_;
double free_step_size_;
// kernel sigma
std::vector<double> kern_stdev_;
// for tum bag
std::string frame_id_;
bool first;
double position_change_thresh_;
double orientation_change_thresh_;
double sensor_max_range_; // Maximum range of the sensor
std::vector<double> map_mu;
// generate random number
std::default_random_engine random_engine;
std::exponential_distribution<> exponential_distribution;
// map resolution
std::vector<double> res_;
ifom::InformationFilterOccupancyMap info_filter_map;
// tum bag store transformation in tf but simulation get pose directly from gazebo
tf::TransformListener listener;
// information vecoter map
gpoctomap::MarkerArrayPub m_pub;
// true posteior map
gpoctomap::MarkerArrayPub final_map_pub;
// information matrix map
gpoctomap::MarkerArrayPub cov_map_pub;
bool save_file_;
std::vector<double> time_file;
std::string file_name_;
bool debug_;
public:
// init
RunIfomFromBag(ros::NodeHandle nh,
const double& sensor_max_range, // Maximum range of the sensor
const std::vector<double>& devmin,
const std::vector<double>& devmax,
const std::vector<double>& resolution,
const int& iter,
const std::vector<double>& kern_stdev,
const double& noise_cov, // noise covariacne
const double& thresh, // threshold for posterier
const double& delta, // delta for information vector p(y=1)
const double& free_step_size,
const double& kernel_radius, // radius of pseudo point
const std::string& frame_id,
const bool& debug,
const bool& save_file,
const std::string& file_name)
: exponential_distribution(0.4), info_filter_map(devmin, devmax, resolution, kern_stdev, noise_cov, kernel_radius),
m_pub(nh, "/occ_map", 0.1f), final_map_pub(nh, "/full_map", 0.1f), cov_map_pub(nh, "/cov_map", 0.1f)
{
nh_ = nh;
delta_ = delta; // delta for information vector p(y=1)
thresh_ = thresh; // threshold for posterier
devmin_ = devmin; // map range in meter lower
devmax_ = devmax; // map range in meter upper
num_iter_ = iter;
free_step_size_ = free_step_size; // kernel sigma
kern_stdev_ = kern_stdev;
frame_id_ = frame_id;
first = true;
position_change_thresh_ = 0.1;
orientation_change_thresh_ = 0.2;
sensor_max_range_ = sensor_max_range; // Maximum range of the sensor
res_ = resolution; // map resolution
ROS_INFO_STREAM("Initialization finished");
// subscriber
ros::Subscriber point_cloud_sub = nh_.subscribe<sensor_msgs::PointCloud2>("cloud", 1, &RunIfomFromBag::PointCloudCallback, this);
// recover whole map signal
ros::Subscriber sub = nh_.subscribe<std_msgs::String>("/chatter", 1000, &RunIfomFromBag::ChatterCallback, this);
save_file_ = save_file;
file_name_ = file_name;
debug_ = debug;
ros::spin();
};
// callback function
void PointCloudCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg_ptr)
{
// laser pose
std::vector<double> translation;
Eigen::Matrix3d rotation;
tf::StampedTransform transform;
try {
listener.waitForTransform(frame_id_, cloud_msg_ptr->header.frame_id, cloud_msg_ptr->header.stamp, ros::Duration(3.0));
listener.lookupTransform(frame_id_, cloud_msg_ptr->header.frame_id, cloud_msg_ptr->header.stamp, transform);
} catch (tf::TransformException ex) {
ROS_ERROR("%s", ex.what());
return;
}
tf::Vector3 position = transform.getOrigin();
tf::Quaternion orientation = transform.getRotation();
if (first || orientation.angleShortestPath(last_orientation) > orientation_change_thresh_ ||
position.distance(last_position) > position_change_thresh_) {
first = false;
last_position = position;
last_orientation = orientation;
QuatToRot((double) orientation.x(),
(double) orientation.y(),
(double) orientation.z(),
(double) orientation.w(),
rotation);
translation = {(double) position.x(),
(double) position.y(),
(double) position.z()};
// Transform the points to the world frame and call bresenham
// use PLC to convert point
pcl::PCLPointCloud2 pcl_cloud;
pcl_conversions::toPCL(*cloud_msg_ptr, pcl_cloud);
pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_msg(new pcl::PointCloud<pcl::PointXYZ>());
pcl::fromPCLPointCloud2(pcl_cloud, *pcl_msg);
auto proc_time = tic();
double sx = translation[0];
double sy = translation[1];
double sz = translation[2];
// start loop the points
for (const auto &point : pcl_msg->points) {
if ((!std::isnan(point.x)) && (!std::isnan(point.y)) && (!std::isnan(point.z))) {
// ROS_INFO_STREAM(point);
// point in camera frame
Eigen::Vector3d pt_c;
pt_c << point.x, point.y, point.z;
// point in world frame
Eigen::Vector3d pt_w = rotation * pt_c;
pt_w(0) += translation[0];
pt_w(1) += translation[1];
pt_w(2) += translation[2];
double ex = pt_w(0);
double ey = pt_w(1);
double ez = pt_w(2);
// Remove all the points out of the sensor max range.
double ray_length = sqrt(pow((sx - ex), 2) + pow((sy - ey), 2) + pow((sz - ez), 2));
if ( ray_length * ray_length < pow(sensor_max_range_, 2)) {
// add occupied point to observation, make sure this point is within the size of map
if ((pt_w(0) < devmax_[0]) && (pt_w(1) < devmax_[1]) && (pt_w(2) < devmax_[2]) &&
(pt_w(0) > devmin_[0]) && (pt_w(1) > devmin_[1]) && (pt_w(2) > devmin_[2])) {
// occupied point
info_filter_map.addObservation(pt_w, kern_stdev_, true, debug_);
}
} else {
// out of range point mark as free
if ((pt_w(0) < devmax_[0]) && (pt_w(1) < devmax_[1]) && (pt_w(2) < devmax_[2]) &&
(pt_w(0) > devmin_[0]) && (pt_w(1) > devmin_[1]) && (pt_w(2) > devmin_[2])) {
// free points
info_filter_map.addObservation(pt_w, kern_stdev_, false, debug_);
}
}
// clear free points
Eigen::Vector3d rb_p;
// find line in 3D p = p0 + vt
Eigen::Vector3d v = rb_p - pt_w;
Eigen::Vector3d p0 = rb_p;
// determine which direction to travel
double factor;
if (sx < ex) {
factor = 1;
} else {
factor = -1;
}
// n number of free point needed based on the length of the ray
int n = static_cast<int> (floor(ray_length / free_step_size_) - 1);
double fx = sx;
double fy = sy;
double fz = sz;
auto pf_time = tic();
// travel in that direction
for (int i=0; i<=n; ++i){
if (factor * fx < factor * ex) {
if ((fx < devmax_[0]) && (fy < devmax_[1]) && (fz < devmax_[2]) &&
(fx > devmin_[0]) && (fy > devmin_[1]) && (fz > devmin_[2])) {
rb_p << fx, fy, fz;
// free point
info_filter_map.addObservation(rb_p, kern_stdev_, false, debug_);
}
}
// new point
fx = sx + exponential_distribution(random_engine); // generate a random step size based on poisson distribution
double r = (fx - p0(0)) / v(0);
fy = p0(1) + v(1) * r;
fz = p0(2) + v(2) * r;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (save_file_){
time_file.push_back(toc(proc_time));
}
// publish information vector build map for visualization purpose
ROS_INFO_STREAM("One Cloud finished in " << toc(proc_time) << " sec!");
m_pub.clear();
cov_map_pub.clear();
std::vector<double> observation = info_filter_map.alpha; // observation value + 1 occupied -1 free
std::vector<double> num = info_filter_map.obs_num_; // number of observation lay in this grid
std::vector<std::map<int, double>> informat = info_filter_map.beta;
// threshold information matrix directly
for (int idx=0; idx<observation.size(); idx++) {
if ( observation[idx] > delta_ ){
std::vector<int> pt_idx = info_filter_map.converter.ind2subv_rowmajor(idx);
float xx = pt_idx[0] * res_[0] + devmin_[0];
float yy = pt_idx[1] * res_[1] + devmin_[1];
float zz = pt_idx[2] * res_[2] + devmin_[2];
m_pub.insert_point3d(xx, yy, zz, devmin_[2], devmax_[2], res_[0]);
double cov = informat[idx][idx];
cov_map_pub.insert_color_point3d(xx, yy, zz, 0, 150, cov, res_[0]);
} // end if loop
} // end publish map loop
m_pub.publish();
cov_map_pub.publish();
}
};
// subscribe to keyboard, if say recovermap then this will start the map recover stage
void ChatterCallback(const std_msgs::String::ConstPtr& msg)
{
std::string key_input = msg->data.c_str();
ROS_INFO("! Got Message !");
std::string first_string = key_input.substr(0, 10);
auto const pos=key_input.find_last_of('p');
if(first_string.compare("RecoverMap") == 0){
auto recover_time = tic();
ROS_INFO("Recover Map Now... / ...");
if (map_mu.size() < 1){
auto t1 = tic();
map_mu = info_filter_map.latentMean(num_iter_);
if (save_file_){
time_file.push_back(toc(t1));
}
ROS_INFO_STREAM("map_mu " << toc(t1) << " sec!");
}
ROS_INFO_STREAM("Map Recovering computation done in " << toc(recover_time) << " sec!");
// should only publish points that are occupied
final_map_pub.clear();
for (int idx = 0; idx < map_mu.size(); ++idx ){
if (map_mu[idx] > thresh_){
if (debug_) {
ROS_INFO_STREAM("map_mu[idx] " << map_mu[idx]);
}
std::vector<int> pt_idx;
pt_idx = info_filter_map.converter.ind2subv_rowmajor(idx);
final_map_pub.insert_point3d(pt_idx[0]*res_[0]+devmin_[0],
pt_idx[1]*res_[1]+devmin_[1],
pt_idx[2]*res_[2]+devmin_[2],
devmin_[2], devmax_[2], res_[2]);
}
}
final_map_pub.publish();
ROS_INFO("Finish Publishing Map");
if (save_file_){
WriteVectorToFile(time_file, file_name_);
ROS_INFO("Finish Save Map");
}
}
};
};
// main function
int main( int argc, char** argv)
{
// initialize ros
ros::init(argc, argv, "ifom");
ros::NodeHandle nh;
// get parameter
double sensor_max_range; // Maximum range of the sensor
double xmin;
double ymin;
double zmin;
double xmax;
double ymax;
double zmax;
double xres;
double yres;
double zres;
int iter;
double kernel_sigma_x; // kernel x width
double kernel_sigma_y; // kernel y width
double kernel_sigma_z; // kernel z width
double noise_cov; // noise covariacne
double thresh; // threshold for posterier
double delta; // delta for information vector p(y=1)
double free_step_size;
double kernel_radius; // radius of pseudo point
std::string frame_id("/map");
bool debug = false;
bool save_file;
std::string file_name;
nh.param<double>("sensor_max_range", sensor_max_range, 10);
nh.param<double>("xmin", xmin, -10);
nh.param<double>("ymin", ymin, -10);
nh.param<double>("zmin", zmin, -10);
nh.param<double>("xmax", xmax, 10);
nh.param<double>("ymax", ymax, 10);
nh.param<double>("zmax", zmax, 10);
nh.param<double>("xres", xres, 1);
nh.param<double>("yres", yres, 1);
nh.param<double>("zres", zres, 1);
nh.param<int>("iter", iter, 1);
nh.param<double>("kernel_sigma_x", kernel_sigma_x, 0.75);
nh.param<double>("kernel_sigma_y", kernel_sigma_y, 0.75);
nh.param<double>("kernel_sigma_z", kernel_sigma_z, 0.75);
nh.param<double>("noise_cov", noise_cov, 0.5);
nh.param<double>("thresh", thresh, 0.5);
nh.param<double>("delta", delta, 0.1);
nh.param<double>("free_step_size", free_step_size, 0.1);
nh.param<double>("kernel_radius", kernel_radius, 0.05);
nh.param<std::string>("frame_id", frame_id, frame_id);
nh.param<bool>("debug", debug, debug);
nh.param<bool>("save_file", save_file, false);
nh.param<std::string>("file_name", file_name, "/home/parallels/map_ws/plot/1.txt");
std::vector<double> devmin = {xmin, ymin, zmin};
std::vector<double> devmax = {xmax, ymax, zmax};
std::vector<double> resolution = {xres, yres, zres};
std::vector<double> kern_stdev = {kernel_sigma_x, kernel_sigma_y, kernel_sigma_z};
// initialize class
RunIfomFromBag RunIfomFromBag(nh, sensor_max_range,
devmin,
devmax,
resolution,
iter,
kern_stdev,
noise_cov, thresh, delta, free_step_size,
kernel_radius,
frame_id, debug, save_file, file_name);
return 0;
}
<file_sep>/src/key_wait.cpp
#include <ros/ros.h>
#include <std_msgs/String.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "gp_map");
ros::NodeHandle nh;
ros::Publisher p = nh.advertise<std_msgs::String> ("chatter", 1);
while(true)
{
std::string inputString;
std::cout << "Type [RecoverMap] to start map recovery" << std::endl;
std::getline(std::cin, inputString);
std_msgs::String msg;
std::string first_string = inputString.substr(0, 10);
if(first_string.compare("RecoverMap") == 0)
{
//send a request to the node serving out the messages
//print out recieved messages.
msg.data = inputString;
p.publish(msg);
} else {
std::cout << "Don't understand what you want to do. Please type [RecoverMap]" << std::endl;
}
ros::spinOnce();
}
return 0;
}<file_sep>/src/accuracy.py
#!/usr/bin/env python
import numpy as np
from visualization_msgs.msg import MarkerArray
import rospy
import matplotlib.pyplot as plt
class Accuracy(object):
def __init__(self, xmin, ymin, zmin, resolution):
self.truth = None
self.resolution = resolution
self.xmin = xmin
self.ymin = ymin
self.zmin = zmin
############################################# initialize subscriber ###########################################################
rospy.init_node('accuracy', anonymous=True)
self.map1_sub = rospy.Subscriber("map1_topic", MarkerArray, self.truth_call_back, queue_size = 10)
self.map2_sub = rospy.Subscriber("truth_map", MarkerArray, self.callback2, queue_size = 100)
def truth_call_back(self, map_msg):
# map1
print("Get truth map")
self.truth = map_msg
def callback2(self, map_msg):
print("get map")
# ground truth
if self.truth is not None:
truth_marker = self.truth.markers
marker2 = map_msg.markers
point2 = []
for m in marker2:
if m.points:
for p_tmp in m.points:
point2.append([p_tmp.x, p_tmp.y, p_tmp.z])
point2 = np.floor((np.array(point2)) * self.resolution - np.array([xmin, ymin, zmin])).astype(int)
truth_point = []
for m in truth_marker:
if m.points:
for p_tmp in m.points:
truth_point.append([p_tmp.x, p_tmp.y, p_tmp.z])
truth_point = (np.array(truth_point) - np.array([xmin, ymin, zmin]) / self.resolution).astype(int)
x_min = min(np.min(truth_point[:, 0]), np.min(point2[:, 0]))
x_max = max(np.max(truth_point[:, 0]), np.max(point2[:, 0]))
y_min = min(np.min(truth_point[:, 1]), np.min(point2[:, 1]))
y_max = max(np.max(truth_point[:, 1]), np.max(point2[:, 1]))
z_min = min(np.min(truth_point[:, 2]), np.min(point2[:, 2]))
z_max = max(np.max(truth_point[:, 2]), np.max(point2[:, 2]))
truth_point = truth_point - np.array([x_min, y_min, z_min])
point2 = point2 - np.array([x_min, y_min, z_min])
grid_map_t = np.zeros((x_max - x_min + 1, y_max - y_min + 1, z_max - z_min + 1))
grid_map_t[truth_point[:, 0], truth_point[:, 1], truth_point[:, 2]] += 1
grid_map = np.zeros((x_max - x_min + 1, y_max - y_min + 1, z_max - z_min + 1))
grid_map[point2[:, 0], point2[:, 1], point2[:, 2]] += 1
error = np.sum(abs(grid_map_t - grid_map)) / (grid_map_t.ravel().shape[0])
print("error rate for if is: ", error)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(point2[:, 0], point2[:, 1], point2[:, 2], 'b.', alpha = 0.4)
ax.plot(truth_point[:, 0], truth_point[:, 1], truth_point[:, 2], 'r.', alpha = 0.2)
plt.show()
if __name__ == '__main__':
try:
xmin = rospy.get_param('xmin')
ymin = rospy.get_param('ymin')
zmin = rospy.get_param('zmin')
resolution = rospy.get_param('resolution')
accuracy = Accuracy(xmin, ymin, zmin, resolution)
rospy.spin()
except KeyboardInterrupt:
print("Shutting down ROS")
<file_sep>/include/nx_map_utils.h
#ifndef __NX_MAP_UTILS_H_
#define __NX_MAP_UTILS_H_
#include <cmath>
#include <vector>
#include <limits>
//#include <iostream> // for debugging
// for saving the map
#include <fstream> // std::ofstream
#include <yaml-cpp/yaml.h>
#include <boost/filesystem.hpp> // boost::filesystem::path
#include <typeinfo>
namespace nx
{
inline int meters2cells( double datam, double min, double res )
{
return static_cast<int>(std::floor( (datam - min)/res ));
}
inline double cells2meters( int datac, double min, double res )
{
return (static_cast<double>(datac)+0.5)*res + min;
}
inline double meters2cells_cont( double datam, double dim_min, double res)
{
return (datam - dim_min)/res - 0.5;
}
// returns the first odd integer larger than x
inline int odd_ceil(double x)
{
if( std::abs( std::floor(x) - x ) <= std::numeric_limits<double>::epsilon() )
x = std::floor(x);
int ocx = static_cast<int>(std::ceil(x));
return ( ocx % 2 == 0 ) ? (ocx+1) : (ocx);
}
// Row major order as in C++
inline int subv2ind_rowmajor( std::vector<int>::const_iterator const & datac_begin,
std::vector<int>::const_iterator const & datac_end,
std::vector<int>::const_iterator const & size_begin,
std::vector<int>::const_iterator const & size_end )
{
if(datac_end <= datac_begin || size_end <= size_begin) return -1;
int idx = *(datac_end-1); int prod = 1;
std::vector<int>::const_iterator it1 = datac_end-2;
std::vector<int>::const_iterator it2 = size_end-1;
for( ; it1 != (datac_begin - 1) && it2 != size_begin; --it1, --it2 )
{
prod *= (*it2);
idx += prod * (*it1);
}
return idx;
}
inline std::vector<int> ind2subv_rowmajor( int ind,
const std::vector<int>::const_iterator& size_begin,
const std::vector<int>::const_iterator& size_end )
{
const size_t ndims = std::distance(size_begin, size_end);
std::vector<int> subv(ndims);
std::vector<int>::const_iterator it = size_end-1;
for( int k=ndims-1; k>=0; --k, --it)
{
subv[k] = ind%(*it);
ind -= subv[k];
ind /= (*it);
}
return subv;
}
inline std::vector<size_t> ind2subv_rowmajor( size_t ind,
const std::vector<size_t>::const_iterator& size_begin,
const std::vector<size_t>::const_iterator& size_end )
{
const size_t ndims = std::distance(size_begin, size_end);
std::vector<size_t> subv(ndims);
std::vector<size_t>::const_iterator it = size_end-1;
for( long signed int k=ndims-1; k>=0; --k, --it)
{
subv[k] = ind%(*it);
ind -= subv[k];
ind /= (*it);
}
return subv;
}
// Column major order as in MATLAB
inline int subv2ind_colmajor( std::vector<int>::const_iterator const & datac_begin,
std::vector<int>::const_iterator const & datac_end,
std::vector<int>::const_iterator const & size_begin,
std::vector<int>::const_iterator const & size_end )
{
if(datac_end <= datac_begin || size_end <= size_begin) return -1;
int idx = *datac_begin; int prod = 1;
std::vector<int>::const_iterator it1 = datac_begin+1;
std::vector<int>::const_iterator it2 = size_begin;
for( ; it1 != datac_end && it2 != (size_end-1); ++it1, ++it2 )
{
prod *= (*it2);
idx += (*it1) * prod;
}
return idx;
}
inline std::vector<int> ind2subv_colmajor( int ind,
const std::vector<int>::const_iterator& size_begin,
const std::vector<int>::const_iterator& size_end )
{
const size_t ndims = std::distance(size_begin, size_end);
std::vector<int> subv(ndims);
std::vector<int>::const_iterator it = size_begin;
for(size_t k=0; k<ndims; ++k, ++it)
{
subv[k] = ind%(*it);
ind -= subv[k];
ind /= (*it);
}
return subv;
}
/******************************************************************************/
// Vector Implementations
inline std::vector<int> meters2cells( std::vector<double>::const_iterator const & datam_begin,
std::vector<double>::const_iterator const & datam_end,
std::vector<double>::const_iterator const & dim_min_begin,
std::vector<double>::const_iterator const & dim_min_end,
std::vector<double>::const_iterator const & res_begin,
std::vector<double>::const_iterator const & res_end )
{
std::vector<int> datac;
std::vector<double>::const_iterator it1 = datam_begin;
std::vector<double>::const_iterator it2 = dim_min_begin;
std::vector<double>::const_iterator it3 = res_begin;
for( ; it1 != datam_end ; ++it1, ++it2, ++it3 )
datac.push_back(meters2cells( *it1, *it2, *it3 ));
return datac;
}
inline std::vector<double> cells2meters( std::vector<int>::const_iterator const & datac_begin,
std::vector<int>::const_iterator const & datac_end,
std::vector<double>::const_iterator const & dim_min_begin,
std::vector<double>::const_iterator const & dim_min_end,
std::vector<double>::const_iterator const & res_begin,
std::vector<double>::const_iterator const & res_end )
{
std::vector<double> datam;
std::vector<int>::const_iterator it1 = datac_begin;
std::vector<double>::const_iterator it2 = dim_min_begin;
std::vector<double>::const_iterator it3 = res_begin;
for( ; it1 != datac_end ; ++it1, ++it2, ++it3 )
datam.push_back(meters2cells( *it1, *it2, *it3 ));
return datam;
}
inline std::vector<double> meters2cells_cont(
std::vector<double>::const_iterator const & datam_begin,
std::vector<double>::const_iterator const & datam_end,
std::vector<double>::const_iterator const & dim_min_begin,
std::vector<double>::const_iterator const & dim_min_end,
std::vector<double>::const_iterator const & res_begin,
std::vector<double>::const_iterator const & res_end )
{
std::vector<double> datac;
std::vector<double>::const_iterator it1 = datam_begin;
std::vector<double>::const_iterator it2 = dim_min_begin;
std::vector<double>::const_iterator it3 = res_begin;
for( ; it1 != datam_end ; ++it1, ++it2, ++it3 )
datac.push_back(meters2cells_cont( *it1, *it2, *it3 ));
return datac;
}
inline std::vector<int> meters2cells( std::vector<double> const & datam,
std::vector<double> const & dim_min,
std::vector<double> const & res )
{
std::vector<int> datac(datam.size());
for( unsigned k = 0; k < datam.size(); ++k )
datac[k] = meters2cells( datam[k], dim_min[k], res[k] );
return datac;
}
inline std::vector<int> meters2cells( std::vector<double> const & datam,
std::vector<double> const & dim_min, double res )
{
std::vector<int> datac(datam.size());
for( unsigned k = 0; k < datam.size(); ++k )
datac[k] = meters2cells( datam[k], dim_min[k], res );
return datac;
}
inline std::vector<double> cells2meters( std::vector<int> const & datac,
std::vector<double> const & dim_min, std::vector<double> const & res )
{
std::vector<double> datam(datac.size());
for( unsigned k = 0; k < datac.size(); ++k )
datam[k] = cells2meters( datac[k], dim_min[k], res[k] );
return datam;
}
inline std::vector<double> cells2meters( std::vector<int> const & datac,
std::vector<double> const & dim_min, double res )
{
std::vector<double> datam(datac.size());
for( unsigned k = 0; k < datac.size(); ++k )
datam[k] = cells2meters( datac[k], dim_min[k], res );
return datam;
}
inline std::vector<double> meters2cells_cont( const std::vector<double>& datam,
const std::vector<double>& dim_min,
const std::vector<double>& res )
{
std::vector<double> datac(datam.size());
for( unsigned k = 0; k < datam.size(); ++k )
datac[k] = meters2cells_cont( datam[k], dim_min[k], res[k] );
return datac;
}
inline std::vector<double> meters2cells_cont( const std::vector<double>& datam,
const std::vector<double>& dim_min,
double res )
{
std::vector<double> datac(datam.size());
for( unsigned k = 0; k < datam.size(); ++k )
datac[k] = meters2cells_cont( datam[k], dim_min[k], res );
return datac;
}
class map_nd
{
std::vector<double> min_;
std::vector<double> max_;
std::vector<double> res_;
std::vector<int> size_;
std::vector<double> origin_;
std::vector<int> origincells_;
public:
map_nd(){} // default constructor
map_nd(std::vector<double> const & devmin, std::vector<double> const & devmax,
std::vector<double> const & resolution)
: res_(resolution)
{
double dev;
for( unsigned k = 0; k < devmin.size(); ++k )
{
origin_.push_back( (devmin[k] + devmax[k])/2 );
size_.push_back( nx::odd_ceil( (devmax[k] - devmin[k]) / resolution[k] ) );
dev = size_[k] * resolution[k] / 2;
min_.push_back( origin_[k] - dev );
max_.push_back( origin_[k] + dev );
origincells_.push_back( (size_[k]-1)/2 );
}
}
map_nd(std::vector<double> const & devmin, std::vector<double> const & devmax,
double resolution)
: res_(devmin.size(),resolution)
{
double dev;
for( unsigned k = 0; k < devmin.size(); ++k )
{
origin_.push_back( (devmin[k] + devmax[k])/2 );
size_.push_back( nx::odd_ceil( (devmax[k] - devmin[k]) / resolution ) );
dev = size_[k] * resolution / 2;
min_.push_back( origin_[k] - dev );
max_.push_back( origin_[k] + dev );
origincells_.push_back( (size_[k]-1)/2 );
}
}
map_nd( size_t num_dim, double *devmin, double *devmax, double *resolution)
: res_(resolution,resolution+num_dim)
{
double dev;
for( unsigned k = 0; k < num_dim; ++k )
{
origin_.push_back( (devmin[k] + devmax[k])/2 );
size_.push_back( nx::odd_ceil( (devmax[k] - devmin[k]) / resolution[k] ) );
dev = size_[k] * resolution[k] / 2;
min_.push_back( origin_[k] - dev );
max_.push_back( origin_[k] + dev );
origincells_.push_back( (size_[k]-1)/2 );
}
}
map_nd( size_t num_dim, double *devmin, double *devmax, double resolution)
: res_(num_dim,resolution)
{
double dev;
for( unsigned k = 0; k < num_dim; ++k )
{
origin_.push_back( (devmin[k] + devmax[k])/2 );
size_.push_back( nx::odd_ceil( (devmax[k] - devmin[k]) / resolution ) );
dev = size_[k] * resolution / 2;
min_.push_back( origin_[k] - dev );
max_.push_back( origin_[k] + dev );
origincells_.push_back( (size_[k]-1)/2 );
}
}
map_nd( const std::vector<int>& oddsize, const std::vector<double>& origin,
const std::vector<double>& resolution )
: res_(resolution), size_(oddsize), origin_(origin)
{
double dev;
for( unsigned k = 0; k < size_.size(); ++k )
{
if( size_[k] % 2 == 0 )
size_[k] += 1; // ensure the map size is odd!
dev = size_[k] * res_[k] / 2;
min_.push_back( origin_[k] - dev );
max_.push_back( origin_[k] + dev );
origincells_.push_back( (size_[k]-1)/2 );
}
}
// Methods
std::vector<double> const & min( void ) const{ return min_; }
std::vector<double> const & max( void ) const{ return max_; }
std::vector<double> const & res( void ) const{ return res_; }
std::vector<int> const & size( void ) const{ return size_; }
std::vector<double> const & origin( void ) const{ return origin_; }
std::vector<int> const & origincells( void ) const{ return origincells_; }
std::vector<int> meters2cells( const std::vector<double>& datam) const
{ return nx::meters2cells( datam, min_, res_ ); }
std::vector<double> cells2meters( const std::vector<int>& datac) const
{ return nx::cells2meters( datac, min_, res_ ); }
std::vector<double> meters2cells_cont( const std::vector<double>& datam) const
{ return nx::meters2cells_cont( datam, min_, res_ ); }
std::vector<int> meters2cells( const std::vector<double>::const_iterator& datam_begin,
const std::vector<double>::const_iterator& datam_end) const
{ return nx::meters2cells( datam_begin, datam_end, min_.begin(), min_.end(), res_.begin(), res_.end() ); }
std::vector<double> cells2meters( const std::vector<int>::const_iterator& datac_begin,
const std::vector<int>::const_iterator& datac_end ) const
{ return nx::cells2meters( datac_begin, datac_end, min_.begin(), min_.end(), res_.begin(), res_.end() ); }
std::vector<double> meters2cells_cont( const std::vector<double>::const_iterator& datam_begin,
const std::vector<double>::const_iterator& datam_end ) const
{ return nx::meters2cells_cont( datam_begin, datam_end, min_.begin(), min_.end(), res_.begin(), res_.end() ); }
// Row major order as in C++
int subv2ind_rowmajor( std::vector<int> const & datac ) const
{
const size_t ndims = datac.size();
if( ndims == 0) return -1;
int idx = datac.back(); int prod = 1;
for( int k = ndims-1; k > 0; --k )
{
prod = prod * size_[k];
idx += datac[k-1] * prod;
}
return idx;
}
std::vector<int> ind2subv_rowmajor( int ind ) const
{
const size_t ndims = size_.size();
std::vector<int> subv(ndims);
for( int k=ndims-1; k>=0; --k)
{
subv[k] = ind%size_[k];
ind -= subv[k];
ind /= size_[k];
}
return subv;
}
// Column major order as in MATLAB
int subv2ind_colmajor( std::vector<int> const & datac ) const
{
const size_t ndims = datac.size();
if( ndims == 0) return -1;
int idx = datac[0]; int prod = 1;
for( size_t k = 1; k < ndims; ++k )
{
prod *= size_[k-1];
idx += datac[k] * prod;
}
return idx;
}
std::vector<int> ind2subv_colmajor( int ind ) const
{
const size_t ndims = size_.size();
std::vector<int> subv(ndims);
for(size_t k=0; k<ndims; ++k)
{
subv[k] = ind%size_[k];
ind -= subv[k];
ind /= size_[k];
}
return subv;
}
std::vector<double> meter2meter( std::vector<double>& datam )
{
double x_cell = round( (datam[0])/res_[0] ) * res_[0];
double y_cell = round( (datam[1])/res_[1] ) * res_[1];
double z_cell = round( (datam[2])/res_[2] ) * res_[2];
std::vector<double> pt_c = {x_cell, y_cell, z_cell};
return pt_c;
}
template <class T>
std::vector<T> rowmajor2colmajor( const std::vector<T>& map ) const
{
const size_t mapsz = map.size();
std::vector<T> newmap(mapsz);
for( int k = 0; k < mapsz; ++k)
newmap[subv2ind_colmajor(ind2subv_rowmajor(k))] = map[k];
return newmap;
}
template <class T>
std::vector<T> colmajor2rowmajor( const std::vector<T>& map ) const
{
const size_t mapsz = map.size();
std::vector<T> newmap(mapsz);
for( int k = 0; k < mapsz; ++k)
newmap[subv2ind_rowmajor(ind2subv_colmajor(k))] = map[k];
return newmap;
}
template <class T>
void saveToYaml( const std::vector<T>& map, std::string pathToYaml) const
{
saveToYaml(map, pathToYaml, "rowmajor");
}
/*
* storageorder in {rowmajor, colmajor}
*/
template <class T>
void saveToYaml( const std::vector<T>& map, std::string pathToYaml, std::string storageorder ) const
{
// Find the file path and file name
boost::filesystem::path bfp(pathToYaml);
std::string yaml_parent_path(bfp.parent_path().string());
std::string yaml_name(bfp.stem().string());
// Generate the YAML file
YAML::Emitter out;
out << YAML::BeginMap;
out << YAML::Key << "mapmin";
out << YAML::Value << YAML::Flow;
out << YAML::BeginSeq;
for( int k = 0; k < min_.size(); ++k )
out << min_[k];
out << YAML::EndSeq;
out << YAML::Key << "mapmax";
out << YAML::Value << YAML::Flow;
out << YAML::BeginSeq;
for( int k = 0; k < max_.size(); ++k )
out << max_[k];
out << YAML::EndSeq;
out << YAML::Key << "mapres";
out << YAML::Value << YAML::Flow;
out << YAML::BeginSeq;
for( int k = 0; k < res_.size(); ++k )
out << res_[k];
out << YAML::EndSeq;
out << YAML::Key << "mapdim";
out << YAML::Value << YAML::Flow;
out << YAML::BeginSeq;
for( int k = 0; k < size_.size(); ++k )
out << size_[k];
out << YAML::EndSeq;
out << YAML::Key << "origin";
out << YAML::Value << YAML::Flow;
out << YAML::BeginSeq;
for( int k = 0; k < origin_.size(); ++k )
out << origin_[k];
out << YAML::EndSeq;
out << YAML::Key << "origincells";
out << YAML::Value << YAML::Flow;
out << YAML::BeginSeq;
for( int k = 0; k < origincells_.size(); ++k )
out << origincells_[k];
out << YAML::EndSeq;
out << YAML::Key << "datatype";
out << YAML::Value << typeid(T).name();
out << YAML::Key << "storage";
out << YAML::Value << storageorder;
out << YAML::Key << "mappath";
out << YAML::Value << yaml_name + ".cfg";
out << YAML::EndMap;
// Save yaml file
std::ofstream ofs;
ofs.open( yaml_parent_path + "/" + yaml_name + ".yaml", std::ofstream::out | std::ofstream::trunc);
ofs << out.c_str();
ofs.close();
// Save cfg file
ofs.open( yaml_parent_path + "/" + yaml_name + ".cfg", std::ofstream::out | std::ofstream::trunc);
for( int k = 0; k < map.size(); ++k)
ofs << map[k];
ofs.close();
}
template <class T>
void initFromYaml( std::vector<T>& map, std::string pathToYaml )
{
// Set map size
YAML::Node map_spec = YAML::LoadFile(pathToYaml);
if( map_spec["mapdim"] && map_spec["origin"] && map_spec["mapres"] && map_spec["mappath"] )
{
size_ = map_spec["mapdim"].as<std::vector<int>>();
origin_ = map_spec["origin"].as<std::vector<double>>();
res_ = map_spec["mapres"].as<std::vector<double>>();
double dev;
for( unsigned k = 0; k < size_.size(); ++k )
{
if( size_[k] % 2 == 0 )
size_[k] += 1; // ensure the map size is odd!
dev = size_[k] * res_[k] / 2;
min_.push_back( origin_[k] - dev );
max_.push_back( origin_[k] + dev );
origincells_.push_back( (size_[k]-1)/2 );
}
}
else if( map_spec["mapmin"] && map_spec["mapmax"] && map_spec["mapres"] && map_spec["mappath"] )
{
const std::vector<double>& devmin = map_spec["mapmin"].as<std::vector<double>>();
const std::vector<double>& devmax = map_spec["mapmax"].as<std::vector<double>>();
res_ = map_spec["mapres"].as<std::vector<double>>();
double dev;
for( unsigned k = 0; k < devmin.size(); ++k )
{
origin_.push_back( (devmin[k] + devmax[k])/2 );
size_.push_back( nx::odd_ceil( (devmax[k] - devmin[k]) / res_[k] ) );
dev = size_[k] * res_[k] / 2;
min_.push_back( origin_[k] - dev );
max_.push_back( origin_[k] + dev );
origincells_.push_back( (size_[k]-1)/2 );
}
}
// Read the map
if( size_.size() > 0 )
{
std::string yaml_parent_path(boost::filesystem::path(pathToYaml).parent_path().string());
std::ifstream fsr( yaml_parent_path + "/" + map_spec["mappath"].as<std::string>(), std::ifstream::in);
int mapsz = 1;
for( size_t k = 0; k < size_.size(); ++k )
mapsz *= size_[k];
map.resize(mapsz);
for( int k = 0; k < mapsz; ++k)
fsr >> map[k];
fsr.close();
}
}
};
/******************************************************************************/
inline void bresenham( double sx, double sy,
double ex, double ey,
double xmin, double ymin,
double xres, double yres,
std::vector<int>& xvec,
std::vector<int>& yvec )
{
xvec.clear(); yvec.clear();
// local function
auto get_step = [] ( double dv, double sv, int svc, double vmin, double vres,
int& stepV, double& tDeltaV, double& tMaxV )
{
if( dv > 0 )
{
stepV = 1;
tDeltaV = vres/dv;
tMaxV = (vmin + (svc+1)*vres - sv)/dv; // parametric distance until the first crossing
}
else if( dv < 0 )
{
stepV = -1;
tDeltaV = vres/-dv;
tMaxV = (vmin + svc*vres - sv)/dv;
}
else
{
stepV = 0;
tDeltaV = 0.0;
tMaxV = std::numeric_limits<double>::infinity(); // the line doesn't cross the next plane
}
};
// find start and end cells
int sxc = meters2cells(sx,xmin,xres);
int exc = meters2cells(ex,xmin,xres);
int syc = meters2cells(sy,ymin,yres);
int eyc = meters2cells(ey,ymin,yres);
double dx = ex-sx;
double dy = ey-sy;
int stepX, stepY; // direction of grid traversal
double tDeltaX, tDeltaY; // parametric step size along different dimensions
double tMaxX, tMaxY; // used to determine the dimension of the next step along the line
get_step( dx, sx, sxc, xmin, xres, stepX, tDeltaX, tMaxX );
get_step( dy, sy, syc, ymin, yres, stepY, tDeltaY, tMaxY );
// Add initial voxel to the list
xvec.push_back(sxc);
yvec.push_back(syc);
while ((sxc!=exc)||(syc!=eyc))
{
if (tMaxX<tMaxY)
{
sxc += stepX;
tMaxX += tDeltaX;
}
else
{
syc += stepY;
tMaxY += tDeltaY;
}
xvec.push_back(sxc);
yvec.push_back(syc);
}
}
// http://www.cse.yorku.ca/~amana/research/grid.pdf
// <NAME>, <NAME>, "A Fast Voxel Traversal Algorithm for Ray Tracing"
// https://www.mathworks.com/matlabcentral/fileexchange/56527-fast-raytracing-through-a-3d-grid
inline void bresenham3d( double sx, double sy, double sz,
double ex, double ey, double ez,
double xmin, double ymin, double zmin,
double xres, double yres, double zres,
std::vector<int>& xvec,
std::vector<int>& yvec,
std::vector<int>& zvec )
{
xvec.clear(); yvec.clear(); zvec.clear();
// local function
auto get_step = [] ( double dv, double sv, int svc, double vmin, double vres,
int& stepV, double& tDeltaV, double& tMaxV )
{
if( dv > 0 )
{
stepV = 1;
tDeltaV = vres/dv;
tMaxV = (vmin + (svc+1)*vres - sv)/dv; // parametric distance until the first crossing
}
else if( dv < 0 )
{
stepV = -1;
tDeltaV = vres/-dv;
tMaxV = (vmin + svc*vres - sv)/dv;
}
else
{
stepV = 0;
tDeltaV = 0.0;
tMaxV = std::numeric_limits<double>::infinity(); // the line doesn't cross the next plane
}
};
// find start and end cells
int sxc = meters2cells(sx,xmin,xres);
int exc = meters2cells(ex,xmin,xres);
int syc = meters2cells(sy,ymin,yres);
int eyc = meters2cells(ey,ymin,yres);
int szc = meters2cells(sz,zmin,zres);
int ezc = meters2cells(ez,zmin,zres);
double dx = ex-sx;
double dy = ey-sy;
double dz = ez-sz;
int stepX, stepY, stepZ; // direction of grid traversal
double tDeltaX, tDeltaY, tDeltaZ; // parametric step size along different dimensions
double tMaxX, tMaxY, tMaxZ; // used to determine the dim of the next step along the line
get_step( dx, sx, sxc, xmin, xres, stepX, tDeltaX, tMaxX );
get_step( dy, sy, syc, ymin, yres, stepY, tDeltaY, tMaxY );
get_step( dz, sz, szc, zmin, zres, stepZ, tDeltaZ, tMaxZ );
// Add initial voxel to the list
xvec.push_back(sxc);
yvec.push_back(syc);
zvec.push_back(szc);
while ((sxc!=exc)||(syc!=eyc)||(szc!=ezc))
{
if (tMaxX<tMaxY)
{
if (tMaxX<tMaxZ)
{
sxc += stepX;
tMaxX += tDeltaX;
}
else
{
szc += stepZ;
tMaxZ += tDeltaZ;
}
}
else
{
if (tMaxY<tMaxZ)
{
syc += stepY;
tMaxY += tDeltaY;
}
else
{
szc += stepZ;
tMaxZ += tDeltaZ;
}
}
xvec.push_back(sxc);
yvec.push_back(syc);
zvec.push_back(szc);
}
}
}
#endif
<file_sep>/include/SymPersymMat.h
#ifndef __SYMPERSYMMAT_
#define __SYMPERSYMMAT_
#include <cmath>
#include <vector>
#include <sstream>
namespace ifom
{
const double sqrt_pi = std::sqrt(M_PI);
const double sqrt_2 = std::sqrt(2);
// Storage class for a square symmetric and persymmetric matrix
class SymPersymMat
{
size_t n_, n_half_;
std::vector<std::vector<double>> contents_;
public:
SymPersymMat(size_t n)
: n_(n), n_half_( static_cast<size_t>(std::floor((n+1)/2.0)) ),
contents_(n_half_,std::vector<double>())
{
for( size_t i = 0; i < n_half_; ++i )
contents_[i].resize(n_-2*i);
}
size_t n() const
{ return n_; }
size_t n_half() const
{return n_half_;}
SymPersymMat square() const
{
SymPersymMat M(n_);
for( size_t i = 0; i < n_half_; ++i )
for( size_t j = i; j < n_-i; ++j)
{
M(i,j) = operator()(i,0) * operator()(0,j);
for( size_t k = 1; k < n_; ++k)
M(i,j) += operator()(i,k) * operator()(k,j);
}
return M;
}
double& operator()(size_t i, size_t j)
{
// top triangle
if( 0 <= i && i < n_half_ && i <= j && j < n_-i )
return contents_[i][j-i];
// right triangle
if( n_-j <= i && i <= j && n_half_ <= j && j < n_ )
return contents_[n_-j-1][j-i];
// left triangle
if( 0<= j && j < n_half_ && j + 1 <= i && i < n_-j)
return contents_[j][i-j];
// bottom triangle
if( n_half_ <= i && i < n_ && n_-i <= j && j < i)
return contents_[n_-i-1][i-j];
}
// https://stackoverflow.com/questions/5762042/const-overloaded-operator-function-and-its-invocation
double operator()(size_t i, size_t j) const
{
// top triangle
if( 0 <= i && i < n_half_ && i <= j && j < n_-i )
return contents_[i][j-i];
// right triangle
if( n_-j <= i && i <= j && n_half_ <= j && j < n_ )
return contents_[n_-j-1][j-i];
// left triangle
if( 0<= j && j < n_half_ && j + 1 <= i && i < n_-j)
return contents_[j][i-j];
// bottom triangle
if( n_half_ <= i && i < n_ && n_-i <= j && j < i)
return contents_[n_-i-1][i-j];
}
std::string to_str() const
{
std::stringstream ss;
for( size_t i = 0; i < n_; ++i )
{
for( size_t j = 0; j < n_; ++j )
ss << operator()(i,j) << " ";
ss << std::endl;
}
return ss.str();
}
friend std::ostream& operator<<(std::ostream &os, const SymPersymMat& M)
{
return os << M.to_str();
}
};
inline double gaussianKernel(int i, int j, double a, double b)
{
if(i == j) return 1.0/b;
return std::pow(a,(i-j)*(i-j))/b;
}
inline SymPersymMat gaussianKernel( size_t n, double a, double b )
{
SymPersymMat Sigma(n);
for(size_t i = 0; i < Sigma.n_half(); ++i)
for( size_t j = i; j < n-i; ++j)
Sigma(i,j) = gaussianKernel(i,j,a,b);
return Sigma;
}
inline SymPersymMat gaussianKernelInverse( size_t n, double a, double b )
{
SymPersymMat Omega(n);
if( n == 1 )
Omega(0,0) = b;
if( n <= 1)
return Omega;
std::vector<double> one_a2k(n-1);
double a2 = a*a;
double a_2k = a2;
for( size_t k = 0; k < n-1; ++k )
{
one_a2k[k] = 1 - a_2k;
a_2k *= a2;
}
// Compute the (0,0) element of the inverse kernel
Omega(0,0) = 1.0/one_a2k[0];
for( size_t k = 1; k < n-1; ++k )
Omega(0,0) = Omega(0,0)/one_a2k[k];
// Compute the first row of the inverse kernel
std::vector<double> Kinv1_Kinv11(n-1);
for( size_t k = 0; k < n-1; ++k )
{
Omega(0,k+1) = -a*one_a2k[n-k-2]/one_a2k[k]*Omega(0,k);
Kinv1_Kinv11[k] = Omega(0,k+1) / Omega(0,0);
}
// Initialize the recursion
// See: <NAME>, "PROPERTIES OF THE INVERSE OF THE GAUSSIAN MATRIX,"
// SIAM J. MATRIX ANAL. APPL. Vol. 12, No. 3, pp. 541-548, July 1991
std::vector<double> X(n-2);
for(size_t j = 0; j < n-2; ++j)
X[j] = one_a2k[n-j-2]*Omega(0,j);
for(size_t i = 1; i < Omega.n_half(); ++i)
{
for(size_t j = 0; j < n-2*i-1; ++j)
{
double Y = Kinv1_Kinv11[i-1]*Omega(0,j+i);
Omega(i,j+i) = X[j] + Y;
X[j] += one_a2k[n-j-2*i-2]*Y; // note: when j = n-2*i-1, the update for X is garbage
}
Omega(i,n-i-1) = X[n-2*i-1] + Kinv1_Kinv11[i-1]*Omega(0,n-i-1);
}
// Scale the Kernel
for( size_t i = 0; i < Omega.n_half(); ++i )
for( size_t j = i; j < n-i; ++j)
Omega(i,j) *= b;
return Omega;
}
/*
inline double kroneckerProductIJ( size_t i, size_t j, const std::vector<size_t>& dims, const std::vector<SymPersymMat>& A )
{
std::vector<size_t> subvi = ind2subv_rowmajor(i, dims.cbegin(), dims.cend());
std::vector<size_t> subvj = ind2subv_rowmajor(j, dims.cbegin(), dims.cend());
double Aij = 1.0;
for(size_t d = 0; d < dims.size(); ++d)
Aij *= A[d](subvi[d], subvj[d]);
return Aij;
}
*/
// multiplication of a vector and a matrix built up from a kronecker product
inline std::vector<double> vecKronProd( const std::vector<double>& p,
const std::vector<size_t>& dims,
const std::vector<SymPersymMat>& A )
{
std::vector<double> q1(p);
std::vector<double> q2(p.size());
size_t i_left = 1;
size_t i_right = 1;
for( size_t d = 1; d<dims.size(); ++d )
i_right *= dims[d];
for( size_t d = 0; d<dims.size(); ++d )
{
size_t base_i = 0;
size_t base_j = 0;
for( size_t il = 0; il<i_left; ++il )
{
for( size_t ir = 0; ir<i_right; ++ir )
{
size_t index_j = base_j + ir;
for( size_t row = 0; row < dims[d]; ++row )
{
size_t index_i = base_i + ir;
q2[index_j] = A[d](row,0) * q1[index_i];
index_i += i_right;
for( size_t col = 1; col < dims[d]; ++col )
{
q2[index_j] += A[d](row,col) * q1[index_i];
index_i += i_right;
}
index_j += i_right;
}
}
base_i += dims[d]*i_right;
base_j += dims[d]*i_right;
}
q1 = q2;
if( d == dims.size()-1 ) break;
i_left = i_left * dims[d];
i_right = i_right / dims[d+1];
}
return q1;
}
// conjugate gradient descent
inline std::vector<double> conjugateGradSolver( const std::vector<size_t>& dims,
const std::vector<ifom::SymPersymMat> &A,
const std::vector<double> &b,
size_t num_iter )
{
size_t D = b.size();
std::vector<double> r(b);
std::vector<double> x(D,0.0);
std::vector<double> p,q;
double alpha, beta, rho, rho_1, pq;
for (size_t k = 0; k < num_iter; ++k)
{
rho = 0.0;
for(size_t i = 0; i < D; ++i)
rho += r[i]*r[i];
if( k == 0)
p = r;
else
{
beta = rho / rho_1;
for(size_t i = 0; i < D; ++i)
p[i] = r[i] + beta*p[i];
}
q = vecKronProd( p, dims, A );
pq = 0.0;
for(size_t i = 0; i < D; ++i)
pq += p[i]*q[i];
alpha = rho / pq;
for(size_t i = 0; i < D; ++i)
{
x[i] += alpha * p[i];
r[i] -= alpha * q[i];
}
rho_1 = rho;
}
return x;
}
}
#endif
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(gp_map)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)
find_package(Boost REQUIRED COMPONENTS system timer)
find_package(Eigen3 REQUIRED)
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
tf
nav_msgs
sensor_msgs
geometry_msgs
eigen_conversions
tf_conversions
message_generation
message_filters
pcl_conversions
pcl_ros
laser_geometry
)
FIND_PACKAGE(VTK REQUIRED)
include_directories(${VTK_USE_FILE})
include_directories(${EIGEN3_INCLUDE_DIRS})
find_package(PCL 1.7.2 REQUIRED)
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
###################################
## catkin specific configuration ##
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
catkin_package(
INCLUDE_DIRS include
# LIBRARIES
CATKIN_DEPENDS
roscpp std_msgs tf nav_msgs sensor_msgs geometry_msgs
eigen_conversions tf_conversions message_runtime
message_filters pcl_conversions pcl_ros
DEPENDS
Boost EIGEN3
)
###########
## Build ##
###########
install(DIRECTORY include
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
FILES_MATCHING PATTERN "*.h"
PATTERN ".svn" EXCLUDE)
## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
include
${catkin_INCLUDE_DIRS}
${EIGEN3_INCLUDE_DIR}
${Boost_INCLUDE_DIRS}
)
link_directories(
${catkin_LIBRARY_DIRS}
)
#add_library(gp_map
# src/bresenham_nx.cpp
#)
#add_dependencies(gp_map
# ${${PROJECT_NAME}_EXPORTED_TARGETS}
# ${catkin_EXPORTED_TARGETS}
#)
#target_link_libraries(gp_map
# ${catkin_LIBRARIES}
# ${Boost_LIBRARIES}
#)
## Declare a C++ library
# add_library(${PROJECT_NAME}
# src/${PROJECT_NAME}/gp_map.cpp
# )
## Add cmake target dependencies of the library
## as an example, code may need to be generated before libraries
## either from message generation or dynamic reconfigure
# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
## Declare a C++ executable
## With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
# add_executable(${PROJECT_NAME}_node src/gp_map_node.cpp)
## Rename C++ executable without prefix
## The above recommended prefix causes long target names, the following renames the
## target back to the shorter version for ease of user use
## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")
## Add cmake target dependencies of the executable
## same as for the library above
# add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
## Specify libraries to link a library or executable target against
# target_link_libraries(${PROJECT_NAME}_node
# ${catkin_LIBRARIES}
# )
#############
## Install ##
#############
# all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html
## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
# install(PROGRAMS
# scripts/my_python_script
# DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )
## Mark executables and/or libraries for installation
# install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_node
# ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
# LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
# RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )
## Mark cpp header files for installation
# install(DIRECTORY include/${PROJECT_NAME}/
# DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
# FILES_MATCHING PATTERN "*.h"
# PATTERN ".svn" EXCLUDE
# )
## Mark other files for installation (e.g. launch and bag files, etc.)
# install(FILES
# # myfile1
# # myfile2
# DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
# )
#############
## Testing ##
#############
## Add gtest based cpp test target and link libraries
# catkin_add_gtest(${PROJECT_NAME}-test test/test_gp_map.cpp)
# if(TARGET ${PROJECT_NAME}-test)
# target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
# endif()
## Add folders to be run by python nosetests
# catkin_add_nosetests(test)
add_executable(key_wait src/key_wait.cpp)
target_link_libraries(key_wait ${catkin_LIBRARIES} ${VTK_LIBRARIES} ${PCL_LIBRARIES})
add_executable(run_ifom src/run_ifom.cpp)
target_link_libraries(run_ifom ${catkin_LIBRARIES} ${VTK_LIBRARIES} ${PCL_LIBRARIES})
<file_sep>/include/InformationFilterOccupancyMap.h
#ifndef __INFORMATION_FILTER_OCCUPANCY_MAP_
#define __INFORMATION_FILTER_OCCUPANCY_MAP_
#include "nx_map_utils.h"
#include "SymPersymMat.h"
#include <Eigen/Sparse>
#include <chrono>
inline std::chrono::high_resolution_clock::time_point tic()
{ return std::chrono::high_resolution_clock::now(); }
inline double toc( const std::chrono::high_resolution_clock::time_point& t2)
{ return std::chrono::duration<double>(std::chrono::high_resolution_clock::now()-t2).count(); }
namespace ifom
{
inline double GaussianCDF(double x)
{
// constants
double a1 = 0.254829592;
double a2 = -0.284496736;
double a3 = 1.421413741;
double a4 = -1.453152027;
double a5 = 1.061405429;
double p = 0.3275911;
// Save the sign of x
int sign = 1;
if (x < 0)
sign = -1;
x = std::fabs(x)/std::sqrt(2.0);
// A&S formula 7.1.26
double t = 1.0/(1.0 + p*x);
double y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*std::exp(-x*x);
return 0.5*(1.0 + sign*y);
}
// calculate gaussian kernel based on two points
double GaussianKernel(const std::vector<double> kernel_sigma, const std::vector<int> &pt1, const std::vector<int> &pt2){
int x1 = pt1[0];
int y1 = pt1[1];
int z1 = pt1[2];
int x2 = pt2[0];
int y2 = pt2[1];
int z2 = pt2[2];
int dis = pow((x1 - x2) / kernel_sigma[0], 2) + pow((y1 - y2) / kernel_sigma[1], 2) + pow((z1 - z2) / kernel_sigma[2], 2);
double det_sigma = std::sqrt(kernel_sigma[0] * kernel_sigma[1] * kernel_sigma[2]);
double gk = (1 / (15.73 * det_sigma)) * std::exp (-static_cast<double>(dis) / 2.0);
return gk;
}
class InformationFilterOccupancyMap
{
// Map dimensions
size_t num_dim_; // number of dimensions (usually 3 but can be more or fewer)
size_t half_cell_;
std::vector<size_t> dims_;
// Inverse Gaussian Kernel
std::vector<SymPersymMat> kinv_; // num_dim_ x halfsize_ x (num_cell_, num_cell_-2, num_cell_-4,...)
std::vector<double> omega0_diag_; // diagonal of the initial information matrix
double knn_; // kernel with itself
std::vector<double> res_; // map resolution
std::vector<double> devm_; // map minimum
// Observations
double obs_stdev2_; // squared standard deviation of the observation noise
double radius_;
double ad;
double bd;
std::vector<SymPersymMat> kmm;
// compute pseudo point index mask
int x_idx_range_;
int y_idx_range_;
int z_idx_range_;
public:
std::vector<double> alpha; // difference of 1 and -1 observations per cell
std::vector<double> obs_num_; // number of observations per cell
std::vector<std::map<int, double>> beta;
size_t num_cell_; // total number of cells in the map
nx::map_nd converter;
InformationFilterOccupancyMap( const std::vector<double>& devmin,
const std::vector<double>& devmax,
const std::vector<double>& resolution,
const std::vector<double>& kernel_stdev,
double observation_stdev,
double r)
: num_dim_(devmin.size()), num_cell_(1), dims_(devmin.size()),
obs_stdev2_(observation_stdev*observation_stdev),
converter(devmin, devmax, resolution)
{
res_ = resolution; // need resolution for later use
devm_ = devmin;
radius_ = r;
// compute how many closest points to keep
x_idx_range_ = static_cast<int>(floor(radius_ / res_[0]));
y_idx_range_ = static_cast<int>(floor(radius_ / res_[1]));
z_idx_range_ = static_cast<int>(floor(radius_ / res_[2]));
for( size_t d = 0; d < num_dim_; ++d )
{
dims_[d] = static_cast<size_t>(converter.size()[d]);
ad = std::exp(-1/2.0/kernel_stdev[d]/kernel_stdev[d]);
bd = sqrt_pi*sqrt_2*kernel_stdev[d];
num_cell_ *= dims_[d];
kinv_.push_back(gaussianKernelInverse(dims_[d], ad, bd ));
}
half_cell_ = static_cast<size_t>(std::floor((num_cell_+1)/2.0));
obs_num_.resize(num_cell_,0);
alpha.resize(num_cell_,0);
beta.resize(num_cell_);
// Precompute the diagonal of the inverse Kernel and the squared inverse Kernel
omega0_diag_.resize(num_cell_,1.0);
for( size_t i = 0; i < num_cell_; ++i )
{
std::vector<int> subvi = nx::ind2subv_rowmajor(i, converter.size().cbegin(), converter.size().cend());
for(size_t d = 0; d < num_dim_; ++d)
{
omega0_diag_[i] *= kinv_[d](subvi[d], subvi[d]);
}
}
// compute kernel with itself
std::vector<double> pt = {0, 0, 0};
knn_ = GaussianKernel( kernel_stdev, point2ind(pt), point2ind(pt));
}
size_t num_cells() const
{ return num_cell_; }
size_t half_cells() const
{ return half_cell_; }
// convert coordinate to index
std::vector<int> point2ind( std::vector<double>& pt_h){
return std::vector<int>{static_cast<int>(floor((pt_h[0] - devm_[0])/res_[0] + 0.0001)),
static_cast<int>(floor((pt_h[1] - devm_[1])/res_[1] + 0.0001)),
static_cast<int>(floor((pt_h[2] - devm_[2])/res_[2] + 0.0001))};
}
std::vector<double> ind2point( std::vector<int>& pt_w, std::vector<double> r, std::vector<double> minx){
return std::vector<double>{static_cast<double>(pt_w[0]) * r[0] + minx[0],
static_cast<double>(pt_w[1]) * r[1] + minx[1],
static_cast<double>(pt_w[2]) * r[2] + minx[2]};
}
int omega_sub2ind(const int row,const int col) {
return row*num_cell_+col;
}
void omega_ind2sub(const int sub, int &row, int &col) {
row=sub/num_cell_;
col=sub%num_cell_;
}
double loop_x(const std::vector<std::map<int, double>>& X_1,
const std::vector<double>& X_2, int i){
std::map<int, double> x1 = X_1[i];
std::map<int, double>::iterator it;
double result = 0;
for ( it = x1.begin(); it != x1.end(); it++ )
{
int index = it->first; // string (key)
double value = it->second; // string's value
result += value * X_2[index];
}
return result;
}
/*
* pt_w: new point location in meter, kernel_sigma: kernel width, f: whether this is a free space or not, debug: debug will print stuff
*/
void addObservation(Eigen::Vector3d& pt_w, const std::vector<double> kernel_sigma, const bool f, const bool debug)
{
std::vector<double> pt_w_v = {pt_w(0), pt_w(1), pt_w(2)};
// get closest pseudo point
std::vector<double> pt_h_c = converter.meter2meter( pt_w_v );
// convert eigen to std::vector
// store all the p point
std::vector< std::vector<double> > p_point(0);
// find all closed by pseudo points based on kernel radius
std::vector<double> pt_h;
for (int i=-x_idx_range_; i<=x_idx_range_; ++i){
for (int j=-y_idx_range_; j<=y_idx_range_; ++j) {
for (int k=-z_idx_range_; k<=z_idx_range_; ++k) {
pt_h = {static_cast<double> (pt_h_c[0]) + i * res_[0],
static_cast<double> (pt_h_c[1]) + j * res_[1],
static_cast<double> (pt_h_c[2]) + k * res_[2]};
// check if pt_h is within the circle
if (pow(pt_h[0]-pt_w(0), 2) + pow(pt_h[1]-pt_w(1), 2) + pow(pt_h[2]-pt_w(2), 2) <= pow(radius_, 2)) {
// find pseudo point idx
int idx = converter.subv2ind_rowmajor(point2ind(pt_h));
// make sure point fall inside the grid
if (idx < num_cell_) {
double kmn = GaussianKernel(kernel_sigma, point2ind(pt_h), point2ind(pt_w_v));
double kmm_inv = omega0_diag_[idx];
double z = 1 / (knn_ - kmn * kmm_inv * kmn + obs_stdev2_);
if (debug) {
std::cout << "kmn " << kmn << std::endl;
std::cout << "kmm_inv " << kmm_inv << std::endl;
std::cout << "z " << z << std::endl;
std::cout << "knn_ " << knn_ << std::endl;
std::cout << "denominator " << (knn_ - kmn * kmm_inv * kmn + obs_stdev2_) << std::endl;
}
std::map<int, double> lb = beta[idx];
if (lb.find(idx) == lb.end()){ // doesn't exist
lb.insert(std::pair<int, double>(idx, kmn * z * kmn));
} else {
lb[idx] = lb[idx] + kmn * z * kmn;
}
// now update the non diag value of beta
for (int j=0; j<p_point.size(); j++){
std::vector<double> p2 = p_point[j];
double z_2 = p2[3];
p2.pop_back();
double knm_i = GaussianKernel(kernel_sigma, point2ind(pt_h), point2ind(p2));
int idx_2 = converter.subv2ind_rowmajor(point2ind(p2));
if (idx_2 < num_cell_) {
if (lb.find(idx_2) == lb.end()){ // doesn't exist
lb.insert(std::pair<int, double>(idx_2, knm_i * z * knm_i));
} else {
lb[idx_2] = lb[idx_2] + knm_i * z * knm_i;
}
beta[idx] = lb;
std::map<int, double> lb_2 = beta[idx_2];
if (lb_2.find(idx) == lb.end()){ // doesn't exist
lb_2.insert(std::pair<int, double>(idx, knm_i * z_2 * knm_i));
} else {
lb_2[idx] = lb_2[idx] + knm_i * z_2 * knm_i;
}
beta[idx_2] = lb_2;
}
}
beta[idx] = lb;
if (f) {
if (alpha[idx] < 255) {
alpha[idx] += kmn * z;
}
} else {
if (alpha[idx] > -255) {
alpha[idx] -= kmn * z;
}
}
pt_h.push_back(z);
p_point.push_back(pt_h);
if (debug) {
std::cout << "alpha " << alpha[idx] << std::endl;
}
}
}
}
}
}
if (debug){
std::cout << "pseudo size " << p_point.size() << std::endl;
}
}
std::vector<double> latentInfoVector() const
{
std::vector<double> v(num_cell_);
for( size_t i = 0; i < num_cell_; ++i )
v[i] = static_cast<double>(alpha[i]) / obs_stdev2_;
return v;
}
std::vector<double> deltaInfoMat() const
{
std::vector<double> d(num_cell_);
for( size_t i = 0; i < num_cell_; ++i )
d[i] = static_cast<double>(obs_num_[i]) / obs_stdev2_;
return d;
}
std::vector<double> latentMean( size_t num_iter )
{
std::vector<double> x(num_cell_,0.0);
// Initialize residual as the information mean
std::vector<double> r(num_cell_);
r = alpha;
// compute kernel
for( size_t d = 0; d < num_dim_; ++d ) {
kmm.push_back(gaussianKernel( dims_[d], ad, bd ));
};
std::vector<double> p(r);
std::vector<double> q;
double al, be, rho, rho_1, pq;
for (size_t k = 0; k < num_iter; ++k)
{
rho = 0.0;
for(size_t i = 0; i < num_cell_; ++i)
rho += r[i]*r[i];
if( k > 0)
{
be = rho / rho_1;
for(size_t i = 0; i < num_cell_; ++i)
p[i] = r[i] + be*p[i];
}
// Main computation
q = vecKronProd( p, dims_, kmm );
for(size_t i = 0; i < num_cell_; ++i)
q[i] += loop_x(beta, p, i);
pq = 0.0;
for(size_t i = 0; i < num_cell_; ++i)
pq += p[i]*q[i];
al = rho / pq;
for(size_t i = 0; i < num_cell_; ++i)
{
x[i] += al * p[i];
r[i] -= al * q[i];
}
rho_1 = rho;
double sum_of_elems = 0;
for (auto& n : r)
sum_of_elems += n;
std::cout << "iter " << k << " residue: " << sum_of_elems << std::endl;
}
return x;
}
std::vector<double> latentCov() const
{
std::vector<double> CovDiag(num_cell_);
for( size_t i = 0; i < num_cell_; ++i ) {
std::map<int, double> x1 = beta[i];
std::map<int, double>::iterator it;
double denom = 0;
for ( it = x1.begin(); it != x1.end(); it++ ) {
int index = it->first; // string (key)
double value = it->second; // string's value
double kmm_i = 1;
std::vector<int> subvi_col = nx::ind2subv_rowmajor(index, converter.size().cbegin(), converter.size().cend());
std::vector<int> subvi_row = nx::ind2subv_rowmajor(i, converter.size().cbegin(), converter.size().cend());
for(size_t d = 0; d < num_dim_; ++d)
{
kmm_i *= kmm[d](subvi_row[d], subvi_col[d]);
}
denom += value + kmm_i;
}
CovDiag[i] = (omega0_diag_[i] + x1[i]) / denom;
}
return CovDiag;
}
std::vector<double> latentMeanfromNum( size_t num_iter, std::vector<int> obs_num_tt, std::vector<int> obs_diff_tt ) const
{
std::vector<double> x(num_cell_,0.0);
// Initialize residual as the information mean
std::vector<double> r(num_cell_);
for( size_t i = 0; i < num_cell_; ++i )
r[i] = static_cast<double>(obs_diff_tt[i]) / obs_stdev2_;
// Compute the matrix containing the number of observations
std::vector<double> D(num_cell_);
for( size_t i = 0; i < num_cell_; ++i )
D[i] = static_cast<double>(obs_num_tt[i]) / obs_stdev2_;
std::vector<double> p(r);
std::vector<double> q;
double al, be, rho, rho_1, pq;
for (size_t k = 0; k < num_iter; ++k)
{
rho = 0.0;
for(size_t i = 0; i < num_cell_; ++i)
rho += r[i]*r[i];
if( k > 0)
{
be = rho / rho_1;
for(size_t i = 0; i < num_cell_; ++i)
p[i] = r[i] + be*p[i];
}
// Main computation
q = vecKronProd( p, dims_, kinv_ );
for(size_t i = 0; i < num_cell_; ++i)
q[i] += D[i]*p[i];
pq = 0.0;
for(size_t i = 0; i < num_cell_; ++i)
pq += p[i]*q[i];
al = rho / pq;
for(size_t i = 0; i < num_cell_; ++i)
{
x[i] += al * p[i];
r[i] -= al * q[i];
}
rho_1 = rho;
}
return x;
}
std::vector<double> mapPdf( const std::vector<double>& Mu,
const std::vector<double>& CovDiag )
{
std::vector<double> mpdf(num_cell_);
for( size_t i = 0; i < num_cell_; ++i )
mpdf[i] = GaussianCDF(Mu[i] / std::sqrt(CovDiag[i]+obs_stdev2_));
return mpdf;
}
};
}
#endif
<file_sep>/README.md
### Dependencies
1. catkin: `sudo apt install python-catkin-tools`
2. octomap and teleop: `sudo apt install ros-melodic-octomap-ros ros-melodic-teleop-twist-joy`
3. catkin simple: `git clone https://github.com/catkin/catkin_simple.git`
4. download data in the gp_map/data folder:
+ Simulation data: https://drive.google.com/file/d/1J0Kzdzu7LQ28e7qOVWhR3hqLXAY_GXNo/view?usp=sharing
+ TUM data: https://vision.in.tum.de/data/datasets/rgbd-dataset
- `wget https://vision.in.tum.de/rgbd/dataset/freiburg3/rgbd_dataset_freiburg3_cabinet.bag`
- `wget https://vision.in.tum.de/rgbd/dataset/freiburg3/rgbd_dataset_freiburg3_large_cabinet.bag`
- `wget https://vision.in.tum.de/rgbd/dataset/freiburg1/rgbd_dataset_freiburg1_teddy.bag`
### Demo (Simulation):
1. Run bag: `roslaunch gp_map play_tum_bag.launch rosbag_path:=$(rospack find gp_map)/data/simulation_2`
2. Run ifom: `roslaunch gp_map mapping_3d_simulation.launch`
### Demo (TUM):
1. Run bag: `roslaunch gp_map play_tum_bag.launch rosbag_path:=$(rospack find gp_map)/data/rgbd_dataset_freiburg3_cabinet`
2. Run ifom: `roslaunch gp_map mapping_3d.launch`
### Package Useage
1. config: rviz config for tum and simulation
2. gp_map: utils, how to communicate with rosbag and read laser and pose messages
### Run from a ros bag
1. Run bag:
* Simulation Bag:
`roslaunch gp_map play_tum_bag.launch rosbag_path:=/home/parallels/map2_ws/src/ros_bag/simulation_2`
* TUM Bag:
`roslaunch gp_map play_tum_bag.launch rosbag_path:=/home/parallels/map2_ws/src/ros_bag/rgbd_dataset_freiburg3_large_cabinet`
2. Run IFOM:
* For simulation:
`roslaunch gp_map mapping_3d.launch param_file:=$(rospack find gp_map)/param/simulation.yaml`
* For TUM Bag:
`roslaunch gp_map mapping_3d_simulation.launch param_file:=$(rospack find gp_map)/param/cabinet.yaml`
3. When you want to recover the map (compute the posterior) type `RecoverMap` in the same terminal of mapping_3d.launch
### Time and accuracy
1. Time will be print out for every cloud
2. accuracy
`roslaunch gp_map accuracy.launch`
### Parameter
1. mapping_3d:
* `save_file`: whether to save time file
* `file_name`: file location
* `debug`: will print all sorts of stuff for debug use, use as mean and covariance when update the model
* `sensor_max_range`: laser/depth maximum range, anything outside this range will be considered as free
* `xmin`: map size, xmin
* `ymin`: map size, ymin
* `zmin`: map size, zmin
* `xmax`: map size, xmax
* `ymax`: map size, ymax
* `zmax`: map size, zmax
* `xres`: x axis grid resolution
* `yres`: y axis grid resolution
* `zres`: z axis grid resolution
* `iter`: conjugate gradient iteration
* `frame_id`: laser point frame id
* `kernel_sigma_x`: kernel width in x direction
* `kernel_sigma_y`: kernel width in y direction
* `kernel_sigma_z`: kernel width in z direction
* `free_step_size`: sample free points along a ray of laser, how far away should you sample free points
* `kernel_radius`: how many closest points to keep
* `thresh`: threshold for posterior to determine a cell is occupied
* `delta`: delta for information vector p(y=1), used for visualization before recover the map
* `noise_cov`: observation noise
2. play_tum_bag.launch:
* `cloud_input_ns`: input cloud topic name
* `rosbag_path`: rosbag path
* `rosbag_delay`: bag delay in second
* `speed`: play bag speed
| 92b284ff2960dc8c418e7554d534c198dbcaf5b0 | [
"Markdown",
"Python",
"CMake",
"C++"
] | 8 | C++ | sisama2323/gp_map | 96f008484b4ad6266479cd7ed024acb141f0f092 | 98b05b5481c0719846df4896831dcc8f8ac11a3c |
refs/heads/master | <file_sep>var express = require('express');
var request = require('request');
var app = express();
var passport = require('passport');
var CustomStrategy = require('passport-custom');
var opAuth = require('opskins-oauth');
app.use(passport.initialize());
let OpskinsAuth = new opAuth.init({
name: 'Echo WAX ExpressTrade',
returnURL: 'http://chatahah.com/auth/login/user',
apiKey: '<KEY>',
scopes: 'identity trades items manage_items',
mobile: true
});
passport.use('custom', new CustomStrategy(function (req, done) {
OpskinsAuth.authenticate(req, (err, user) => {
if (err) {
done(err);
} else {
done(null, user);
}
});
}));
var server = require('http').Server(app);
var io = require('socket.io')(server);
var states = {};
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('pages/home');
});
app.get('/auth/login', function (req, res) {
OpskinsAuth.getFetchUrl(function(returnUri, state) {
res.redirect(returnUri);
states[state] = {};
});
});
app.get('/auth/login/user', passport.authenticate('custom', {
failureRedirect: '/'
}), function (req, res) {
states[req.query.state] = req.user;
states[req.query.state].refresh_token = req.user.refresh_token;
states[req.query.state].expires = time()+1800;
res.redirect('/?state=' + req.query.state + "&refresh_token=" + req.user.refresh_token + "&type=login");
});
server.listen(80, function() {
console.log(new Date() + ' Server is up an running!');
});
var users = {};
io.on('connection', function(socket) {
var user = null;
socket.on('log', function(state) {
if(states.hasOwnProperty(state)) {
user = state;
users[state] = states[state];
users[state].state = state;
socket.emit('user info', users[state]);
if(states[state].expires-time() <= 0) new_tokens(users[state]);
}
});
socket.on('user trade', function(trade) {
if(!user) return;
getContentsTrade(users[user], trade, function(err, useru, items) {
if(err) return socket.emit('user eoare', 'There was a problem while getting the inventory of user set!');
GetMyInventory(users[user], 1, function(err, myitems) {
if(err) return socket.emit('user eoare', 'There was a problem while getting your inventory!');
socket.emit('user trade', useru, items, myitems);
});
});
});
socket.on('user send trade', function(_2fa, msg, itbs, itbr, trade_user) {
if(!user) return;
userMakeTrade(users[user], _2fa, msg, itbs, itbr, trade_user, function(err, msg) {
if(err) return socket.emit('user eroare', msg);
socket.emit('user alerta', msg);
});
});
socket.on('user offers', function() {
if(!user) return;
getOffers(users[user], function(err, offers) {
if(err) return socket.emit('user eroare', 'An error occured while getting your ' + type + ' offers!');
socket.emit('user offers', offers);
});
});
socket.on('user change game', function(appid, trade) {
if(!user) return;
userChangeGame(users[user], appid, trade, function(err, myitems, items) {
if(err) return socket.emit('user eroare', 'An error ocurred whle getting both users inventory!');
socket.emit('user change game', myitems, items, appid);
});
});
socket.on('user change inventory', function(appid) {
if(!user) return;
userChangeInventory(users[user], appid, function(err, items) {
if(err) return socket.emit('user eroare', 'An error ocurred whle getting your inventory!');
socket.emit('user change inventory', items);
});
});
socket.on('user withdraw to opskins', function(iteme) {
if(!user) return;
var items = decodeURIComponent(iteme);
if(items.split(',').length == 0) return socket.emit('user eroare', 'You need to select at least one item to Withdraw to OPSkins!');
userWithdrawToOPSkins(users[user], items, function(err) {
if(err) return socket.emit('user eroare', 'There was a problem while withdrawing items to OPSkins!');
socket.emit('user withdraw to opskins success');
});
});
socket.on('user get trade', function(trade) {
if(!user) return;
userGetTradeInformations(users[user], trade, function(err, td) {
if(err) socket.emit('user eroare', 'An error occurred while checking the trade!');
var type;
var tip;
if(td.sent_by_you == true) type = 'self';
else type = 'other';
if(td.is_gift == true) tip = 'accepto';
socket.emit('user get trade', trade, td.sender, td.recipient, td.state, td.state_name, td.is_case_opening, type, tip);
});
});
socket.on('user accept trade', function(trade, _2fa) {
if(!user) return;
userSetTrade(users[user], 'accept', trade, _2fa, function(err) {
if(err) return socket.emit('user eroare', 'An error occurred while accepting the trade #' + trade + '!');
socket.emit('user alerta', 'Successfully accepted the trade #' + trade + '!');
});
});
socket.on('user decline trade', function(trade) {
if(!user) return;
userSetTrade(users[user], 'decline', trade, _2fa, function(err) {
if(err) return socket.emit('user eroare', 'An error occurred while declining the trade #' + trade + '!');
socket.emit('user alerta', 'Successfully declined the trade #' + trade + '!');
});
});
socket.on('logout', function() {
if(!user);
delete users[user];
delete states[user];
});
});
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
function time() {
return parseInt(new Date().getTime()/1000);
}
function getContentsTrade(user, link, cb) {
var trade = decodeURIComponent(link);
if(trade.includes('https://trade.opskins.com') || trade.includes('http://trade.opskins.com')) {
var userid = trade.split('/')[4];
GetUserInventory(user, 1, userid, function(err, user, items) {
cb(err, user, items);
});
} else if(trade.includes('trade.opskins.com')) {
var userid = trade.split('/')[2];
GetUserInventory(user, 1, userid, function(err, user, items) {
cb(err, user, items);
});
} else {
var userid = trade;
GetUserInventoryFromSteamId(user, 1, userid, function(err, user, items) {
cb(err, user, items);
});
}
}
function getOffers(user, cb) {
arequest(user, 'https://api-trade.opskins.com/ITrade/GetOffers/v1/', 'GET', {}, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
cb(0, resp.response.offers);
});
}
function userChangeGame(user, appid, trade, cb) {
GetUserInventory(user, appid, trade, function(err, useru, items) {
if(err) return cb(err, useru);
GetMyInventory(user, appid, function(err, itemss) {
if(err) return cb(err, itemss);
cb(0, itemss, items);
});
});
}
function userChangeInventory(user, appid, cb) {
GetMyInventory(user, appid, function(err, items) {
cb(err, items);
});
}
function userWithdrawToOPSkins(user, items, cb) {
arequest(user, 'https://api-trade.opskins.com/IItem/WithdrawToOpskins/v1/', 'POST', {
'item_id': items
}, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
cb(0);
});
}
function userGetTradeInformations(user, trade, cb) {
arequest(user, 'https://api-trade.opskins.com/ITrade/GetOffer/v1/?offer_id=' + trade, 'GET', {}, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
cb(0, resp.response.offer);
});
}
function userMakeTrade(user, _2fa, msg, itbs, itbr, trade_user, cb) {
var trade = decodeURIComponent(trade_user);
var it_s = decodeURIComponent(itbs);
var it_r = decodeURIComponent(itbr);
if(itbs == 0) itbs = "";
if(itbr == 0) itbr = "";
if(trade.includes('https://trade.opskins.com') || trade.includes('http://trade.opskins.com')) {
var userid = trade.split('/')[4];
var token = trade.split('/')[5];
SendOffer(user, _2fa, userid, token, it_s, it_r, msg, function(err, msg) {
cb(err, msg);
});
} else if(trade.includes('trade.opskins.com')) {
var userid = trade.split('/')[2];
var token = trade.split('/')[3];
SendOffer(user, _2fa, userid, token, it_s, it_r, msg, function(err, msg) {
cb(err, msg);
});
} else {
var userid = trade;
SendOfferToSteamId(user, _2fa, userid, it_s, it_r, msg, function(err, msg) {
cb(err, msg);
});
}
}
function SendOffer(user, _2fa, userid, token, to_be_sended, to_be_received, trade_msg, cb) {
arequest(user, 'https://api-trade.opskins.com/ITrade/SendOffer/v1/', 'POST', {
twofactor_code: _2fa,
uid: userid,
token: token,
items_to_send: to_be_sended,
items_to_receive: to_be_received,
message: trade_msg
}, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
if(resp.response.offer.state == 2) cb(0, 'Trade successfully sent to user ' + resp.response.offer.recipient.display_name);
else cb(1, 'There was a problem while sending the trade offer!');
});
}
function SendOfferToSteamId(user, _2fa, userid, to_be_sended, to_be_received, trade_msg, cb) {
arequest(user, 'https://api-trade.opskins.com/ITrade/SendOffer/v1/', 'POST', {
twofactor_code: _2fa,
steam_id: userid,
items_to_send: to_be_sended,
items_to_receive: to_be_received,
message: trade_msg
}, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
if(resp.response.offer.state == 2) cb(0, 'Trade successfully sent to user ' + resp.response.offer.recipient.display_name);
else cb(1, 'There was a problem while sending the trade offer!');
});
}
function userSetTrade(user, type, tid, _2fa, cb) {
var url = "";
var json = {};
if(type == 'accept') url = 'https://api-trade.opskins.com/ITrade/AcceptOffer/v1/';
else if(type == 'decline') url = 'https://api-trade.opskins.com/ITrade/CancelOffer/v1/';
if(type == 'accept') {
json = {
'twofactor_code': _2fa,
'offer_id': tid
};
} else if(type == 'decline') {
json = {
'offer_id': tid
};
}
arequest(user, url, 'POST', json, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
if(type == 'accept' && resp.response.offer.state == 3) cb(0);
else if(type == 'decline' && ( resp.response.offer.state == 7 || resp.response.offer.state == 6)) cb(0);
else cb(1);
});
}
function new_tokens(user) {
OpskinsAuth.getClientDetails((clientid, secret) => {
request({
headers: {
Authorization: 'Basic ' + Buffer.from(clientid + ':' + secret).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: "https://oauth.opskins.com/v1/access_token",
method: "POST",
form: {
grant_type: 'refresh_token',
refresh_token: user.refresh_token
}
}, function(err, res, bodi) {
if(err) throw err;
var response = JSON.parse(bodi);
users[user.state].expires = time()+1800;
users[user.state].access_token = response.access_token;
});
});
}
function arequest(user, url, method, body, cb) {
request({
headers: {
'Authorization': 'Bearer ' + user.access_token,
},
uri: url,
method: method,
form: body
}, function(err, res, bodi) {
if(err) throw err;
var response = JSON.parse(bodi);
cb(response);
});
}
function GetUserInventory(user, appid, userid, cb) {
arequest(user, 'https://api-trade.opskins.com/ITrade/GetUserInventory/v1/?uid=' + userid + '&app_id=' + appid + '&page=1&per_page=500', 'GET', {}, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
var utilizator = resp.response.user_data;
var items = resp.response.items;
cb(0, utilizator, items);
});
}
function GetUserInventoryFromSteamId(user, appid, userid, cb) {
arequest(user, 'https://api-trade.opskins.com/ITrade/GetUserInventoryFromSteamId/v1/?steam_id=' + userid + '&app_id=' + appid + '&page=1&per_page=500', 'GET', {}, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
var utilizator = resp.response.user_data;
var items = resp.response.items;
cb(0, utilizator, items);
});
}
function GetMyInventory(user, appid, cb) {
arequest(user, 'https://api-trade.opskins.com/IUser/GetInventory/v1/?app_id=' + appid + '&page=1&per_page=500', 'GET', {}, function(resp) {
if(!resp.hasOwnProperty('response')) return cb(1, resp);
cb(0, resp.response.items);
});
}
process.on('uncaughtException', function (err) {
console.log(new Date() + ' [ERROR]');
console.log(err);
});
// SCRIPT MADE BY @ALADYN172 [TWITTER] - v1.8<file_sep># WAX-ExpressTrade-App
This project is the source code of the WAX ExpressTrade App
https://play.google.com/store/apps/details?id=xyz.echoservices.wax
| 87772f40f3d21ca9a162defb9c3f618420614441 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | AlaDyn172/WAX-ExpressTrade-App | bc4ef1138781ed3aa7eefc65a7dae7c3d08a3026 | fa438d745cfaf712fd2422d5a48e6b527a29fbb8 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Models
{ public class Tweet
{ [Required]
public string TweetHashTag { get; set; }
public string Message { get; set; }
public string Author { get; set; }
public string AuthorPic { get; set; }
public string TimePosted { get; set; }
public int RetweetCount { get; set; }
public int LikesCount { get; set; }
}
public class ExtendedTweet
{
public int Type { get; set; }
public int ID { get; set; }
public int UserID { get; set; }
public object ScreenName { get; set; }
public int SinceID { get; set; }
public int MaxID { get; set; }
public int Count { get; set; }
public int Cursor { get; set; }
public bool IncludeRetweets { get; set; }
public bool ExcludeReplies { get; set; }
public bool IncludeEntities { get; set; }
public bool IncludeUserEntities { get; set; }
public bool IncludeMyRetweet { get; set; }
public object OEmbedUrl { get; set; }
public int OEmbedMaxWidth { get; set; }
public bool OEmbedHideMedia { get; set; }
public bool OEmbedHideThread { get; set; }
public bool OEmbedOmitScript { get; set; }
public int OEmbedAlign { get; set; }
public object OEmbedRelated { get; set; }
public object OEmbedLanguage { get; set; }
public string CreatedAt { get; set; }
public int StatusID { get; set; }
public object Text { get; set; }
public object FullText { get; set; }
// public object ExtendedTweet { get; set; }
public object Source { get; set; }
public bool Truncated { get; set; }
public object DisplayTextRange { get; set; }
public int TweetMode { get; set; }
public int InReplyToStatusID { get; set; }
public int InReplyToUserID { get; set; }
public object FavoriteCount { get; set; }
public bool Favorited { get; set; }
public object InReplyToScreenName { get; set; }
public object User { get; set; }
public object Users { get; set; }
public object Contributors { get; set; }
public object Coordinates { get; set; }
public object Place { get; set; }
public object Annotation { get; set; }
public object Entities { get; set; }
public object ExtendedEntities { get; set; }
public bool TrimUser { get; set; }
public bool IncludeContributorDetails { get; set; }
public int RetweetCount { get; set; }
public bool Retweeted { get; set; }
public bool PossiblySensitive { get; set; }
public object RetweetedStatus { get; set; }
public int CurrentUserRetweet { get; set; }
public bool IsQuotedStatus { get; set; }
public int QuotedStatusID { get; set; }
public object QuotedStatus { get; set; }
public object Scopes { get; set; }
public bool WithheldCopyright { get; set; }
public object WithheldInCountries { get; set; }
public object WithheldScope { get; set; }
public object MetaData { get; set; }
public object Lang { get; set; }
public bool Map { get; set; }
public object TweetIDs { get; set; }
public int FilterLevel { get; set; }
public object EmbeddedStatus { get; set; }
public object CursorMovement { get; set; }
}
public class CursorMovement
{
public int Next { get; set; }
public int Previous { get; set; }
}
public class Status2
{
public int Type { get; set; }
public int ID { get; set; }
public int UserID { get; set; }
public object ScreenName { get; set; }
public int SinceID { get; set; }
public int MaxID { get; set; }
public int Count { get; set; }
public int Cursor { get; set; }
public bool IncludeRetweets { get; set; }
public bool ExcludeReplies { get; set; }
public bool IncludeEntities { get; set; }
public bool IncludeUserEntities { get; set; }
public bool IncludeMyRetweet { get; set; }
public object OEmbedUrl { get; set; }
public int OEmbedMaxWidth { get; set; }
public bool OEmbedHideMedia { get; set; }
public bool OEmbedHideThread { get; set; }
public bool OEmbedOmitScript { get; set; }
public int OEmbedAlign { get; set; }
public object OEmbedRelated { get; set; }
public object OEmbedLanguage { get; set; }
public string CreatedAt { get; set; }
public int StatusID { get; set; }
public object Text { get; set; }
public object FullText { get; set; }
public object ExtendedTweet { get; set; }
public object Source { get; set; }
public bool Truncated { get; set; }
public object DisplayTextRange { get; set; }
public int TweetMode { get; set; }
public int InReplyToStatusID { get; set; }
public int InReplyToUserID { get; set; }
public object FavoriteCount { get; set; }
public bool Favorited { get; set; }
public object InReplyToScreenName { get; set; }
public object User { get; set; }
public object Users { get; set; }
public object Contributors { get; set; }
public object Coordinates { get; set; }
public object Place { get; set; }
public object Annotation { get; set; }
public object Entities { get; set; }
public object ExtendedEntities { get; set; }
public bool TrimUser { get; set; }
public bool IncludeContributorDetails { get; set; }
public int RetweetCount { get; set; }
public bool Retweeted { get; set; }
public bool PossiblySensitive { get; set; }
public object RetweetedStatus { get; set; }
public int CurrentUserRetweet { get; set; }
public bool IsQuotedStatus { get; set; }
public int QuotedStatusID { get; set; }
public object QuotedStatus { get; set; }
public object Scopes { get; set; }
public bool WithheldCopyright { get; set; }
public object WithheldInCountries { get; set; }
public object WithheldScope { get; set; }
public object MetaData { get; set; }
public object Lang { get; set; }
public bool Map { get; set; }
public object TweetIDs { get; set; }
public int FilterLevel { get; set; }
public object EmbeddedStatus { get; set; }
public object CursorMovement { get; set; }
}
public class User
{
public int Type { get; set; }
public int UserID { get; set; }
public object UserIdList { get; set; }
public object ScreenName { get; set; }
public object ScreenNameList { get; set; }
public int Page { get; set; }
public int Count { get; set; }
public int Cursor { get; set; }
public object Slug { get; set; }
public object Query { get; set; }
public bool IncludeEntities { get; set; }
public bool SkipStatus { get; set; }
public string UserIDResponse { get; set; }
public string ScreenNameResponse { get; set; }
public int ImageSize { get; set; }
public CursorMovement CursorMovement { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public string Description { get; set; }
public string ProfileImageUrl { get; set; }
public string ProfileImageUrlHttps { get; set; }
public bool DefaultProfileImage { get; set; }
public string Url { get; set; }
public bool DefaultProfile { get; set; }
public bool Protected { get; set; }
public int FollowersCount { get; set; }
public string ProfileBackgroundColor { get; set; }
public string ProfileTextColor { get; set; }
public string ProfileLinkColor { get; set; }
public string ProfileSidebarFillColor { get; set; }
public string ProfileSidebarBorderColor { get; set; }
public int FriendsCount { get; set; }
public string CreatedAt { get; set; }
public int FavoritesCount { get; set; }
public int UtcOffset { get; set; }
public string TimeZone { get; set; }
public string ProfileBackgroundImageUrl { get; set; }
public string ProfileBackgroundImageUrlHttps { get; set; }
public bool ProfileBackgroundTile { get; set; }
public bool ProfileUseBackgroundImage { get; set; }
public int StatusesCount { get; set; }
public bool Notifications { get; set; }
public bool GeoEnabled { get; set; }
public bool Verified { get; set; }
public bool ContributorsEnabled { get; set; }
public bool IsTranslator { get; set; }
public bool Following { get; set; }
public Status2 Status { get; set; }
public List<object> Categories { get; set; }
public object Lang { get; set; }
public string LangResponse { get; set; }
public bool ShowAllInlineMedia { get; set; }
public int ListedCount { get; set; }
public bool FollowRequestSent { get; set; }
public object ProfileImage { get; set; }
public string ProfileBannerUrl { get; set; }
public List<object> BannerSizes { get; set; }
public object Email { get; set; }
}
public class Coordinates
{
public object Type { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public bool IsLocationAvailable { get; set; }
}
public class Place
{
public object Name { get; set; }
public object CountryCode { get; set; }
public object ID { get; set; }
public object Country { get; set; }
public object PlaceType { get; set; }
public object Url { get; set; }
public object FullName { get; set; }
public object Attributes { get; set; }
public object BoundingBox { get; set; }
public object Geometry { get; set; }
public object PolyLines { get; set; }
public object ContainedWithin { get; set; }
}
public class Attributes
{
}
public class Elements
{
}
public class Annotation
{
public object Type { get; set; }
public Attributes Attributes { get; set; }
public Elements Elements { get; set; }
}
public class Entities
{
public List<object> UserMentionEntities { get; set; }
public List<object> UrlEntities { get; set; }
public List<object> HashTagEntities { get; set; }
public List<object> MediaEntities { get; set; }
public List<object> SymbolEntities { get; set; }
}
public class ExtendedEntities
{
public List<object> UserMentionEntities { get; set; }
public List<object> UrlEntities { get; set; }
public List<object> HashTagEntities { get; set; }
public List<object> MediaEntities { get; set; }
public List<object> SymbolEntities { get; set; }
}
public class RetweetedStatus
{
public int Type { get; set; }
public int ID { get; set; }
public int UserID { get; set; }
public object ScreenName { get; set; }
public int SinceID { get; set; }
public int MaxID { get; set; }
public int Count { get; set; }
public int Cursor { get; set; }
public bool IncludeRetweets { get; set; }
public bool ExcludeReplies { get; set; }
public bool IncludeEntities { get; set; }
public bool IncludeUserEntities { get; set; }
public bool IncludeMyRetweet { get; set; }
public object OEmbedUrl { get; set; }
public int OEmbedMaxWidth { get; set; }
public bool OEmbedHideMedia { get; set; }
public bool OEmbedHideThread { get; set; }
public bool OEmbedOmitScript { get; set; }
public int OEmbedAlign { get; set; }
public object OEmbedRelated { get; set; }
public object OEmbedLanguage { get; set; }
public string CreatedAt { get; set; }
public int StatusID { get; set; }
public object Text { get; set; }
public object FullText { get; set; }
public object ExtendedTweet { get; set; }
public object Source { get; set; }
public bool Truncated { get; set; }
public object DisplayTextRange { get; set; }
public int TweetMode { get; set; }
public int InReplyToStatusID { get; set; }
public int InReplyToUserID { get; set; }
public object FavoriteCount { get; set; }
public bool Favorited { get; set; }
public object InReplyToScreenName { get; set; }
public object User { get; set; }
public object Users { get; set; }
public object Contributors { get; set; }
public object Coordinates { get; set; }
public object Place { get; set; }
public object Annotation { get; set; }
public object Entities { get; set; }
public object ExtendedEntities { get; set; }
public bool TrimUser { get; set; }
public bool IncludeContributorDetails { get; set; }
public int RetweetCount { get; set; }
public bool Retweeted { get; set; }
public bool PossiblySensitive { get; set; }
//public object RetweetedStatus { get; set; }
public int CurrentUserRetweet { get; set; }
public bool IsQuotedStatus { get; set; }
public int QuotedStatusID { get; set; }
public object QuotedStatus { get; set; }
public object Scopes { get; set; }
public bool WithheldCopyright { get; set; }
public object WithheldInCountries { get; set; }
public object WithheldScope { get; set; }
public object MetaData { get; set; }
public object Lang { get; set; }
public bool Map { get; set; }
public object TweetIDs { get; set; }
public int FilterLevel { get; set; }
public object EmbeddedStatus { get; set; }
public object CursorMovement { get; set; }
}
public class QuotedStatus
{
public int Type { get; set; }
public int ID { get; set; }
public int UserID { get; set; }
public object ScreenName { get; set; }
public int SinceID { get; set; }
public int MaxID { get; set; }
public int Count { get; set; }
public int Cursor { get; set; }
public bool IncludeRetweets { get; set; }
public bool ExcludeReplies { get; set; }
public bool IncludeEntities { get; set; }
public bool IncludeUserEntities { get; set; }
public bool IncludeMyRetweet { get; set; }
public object OEmbedUrl { get; set; }
public int OEmbedMaxWidth { get; set; }
public bool OEmbedHideMedia { get; set; }
public bool OEmbedHideThread { get; set; }
public bool OEmbedOmitScript { get; set; }
public int OEmbedAlign { get; set; }
public object OEmbedRelated { get; set; }
public object OEmbedLanguage { get; set; }
public string CreatedAt { get; set; }
public int StatusID { get; set; }
public object Text { get; set; }
public object FullText { get; set; }
public object ExtendedTweet { get; set; }
public object Source { get; set; }
public bool Truncated { get; set; }
public object DisplayTextRange { get; set; }
public int TweetMode { get; set; }
public int InReplyToStatusID { get; set; }
public int InReplyToUserID { get; set; }
public object FavoriteCount { get; set; }
public bool Favorited { get; set; }
public object InReplyToScreenName { get; set; }
public object User { get; set; }
public object Users { get; set; }
public object Contributors { get; set; }
public object Coordinates { get; set; }
public object Place { get; set; }
public object Annotation { get; set; }
public object Entities { get; set; }
public object ExtendedEntities { get; set; }
public bool TrimUser { get; set; }
public bool IncludeContributorDetails { get; set; }
public int RetweetCount { get; set; }
public bool Retweeted { get; set; }
public bool PossiblySensitive { get; set; }
public object RetweetedStatus { get; set; }
public int CurrentUserRetweet { get; set; }
public bool IsQuotedStatus { get; set; }
public int QuotedStatusID { get; set; }
// public object QuotedStatus { get; set; }
public object Scopes { get; set; }
public bool WithheldCopyright { get; set; }
public object WithheldInCountries { get; set; }
public object WithheldScope { get; set; }
public object MetaData { get; set; }
public object Lang { get; set; }
public bool Map { get; set; }
public object TweetIDs { get; set; }
public int FilterLevel { get; set; }
public object EmbeddedStatus { get; set; }
public object CursorMovement { get; set; }
}
public class Scopes
{
}
public class MetaData
{
public string ResultType { get; set; }
public string IsoLanguageCode { get; set; }
}
public class Status
{
public int Type { get; set; }
public int ID { get; set; }
public int UserID { get; set; }
public object ScreenName { get; set; }
public int SinceID { get; set; }
public int MaxID { get; set; }
public int Count { get; set; }
public int Cursor { get; set; }
public bool IncludeRetweets { get; set; }
public bool ExcludeReplies { get; set; }
public bool IncludeEntities { get; set; }
public bool IncludeUserEntities { get; set; }
public bool IncludeMyRetweet { get; set; }
public object OEmbedUrl { get; set; }
public int OEmbedMaxWidth { get; set; }
public bool OEmbedHideMedia { get; set; }
public bool OEmbedHideThread { get; set; }
public bool OEmbedOmitScript { get; set; }
public int OEmbedAlign { get; set; }
public object OEmbedRelated { get; set; }
public object OEmbedLanguage { get; set; }
public string CreatedAt { get; set; }
public object StatusID { get; set; }
public string Text { get; set; }
public object FullText { get; set; }
public ExtendedTweet ExtendedTweet { get; set; }
public string Source { get; set; }
public bool Truncated { get; set; }
public object DisplayTextRange { get; set; }
public int TweetMode { get; set; }
public long InReplyToStatusID { get; set; }
public long InReplyToUserID { get; set; }
public int FavoriteCount { get; set; }
public bool Favorited { get; set; }
public string InReplyToScreenName { get; set; }
public User User { get; set; }
public List<object> Users { get; set; }
public List<object> Contributors { get; set; }
public Coordinates Coordinates { get; set; }
public Place Place { get; set; }
public Annotation Annotation { get; set; }
public Entities Entities { get; set; }
public ExtendedEntities ExtendedEntities { get; set; }
public bool TrimUser { get; set; }
public bool IncludeContributorDetails { get; set; }
public int RetweetCount { get; set; }
public bool Retweeted { get; set; }
public bool PossiblySensitive { get; set; }
public RetweetedStatus RetweetedStatus { get; set; }
public int CurrentUserRetweet { get; set; }
public bool IsQuotedStatus { get; set; }
public int QuotedStatusID { get; set; }
public QuotedStatus QuotedStatus { get; set; }
public Scopes Scopes { get; set; }
public bool WithheldCopyright { get; set; }
public List<object> WithheldInCountries { get; set; }
public object WithheldScope { get; set; }
public MetaData MetaData { get; set; }
public string Lang { get; set; }
public bool Map { get; set; }
public object TweetIDs { get; set; }
public int FilterLevel { get; set; }
public object EmbeddedStatus { get; set; }
public object CursorMovement { get; set; }
}
public class SearchMetaData
{
public double CompletedIn { get; set; }
public int MaxID { get; set; }
public string NextResults { get; set; }
public string Query { get; set; }
public object RefreshUrl { get; set; }
public int Count { get; set; }
public int SinceID { get; set; }
}
public class Operation
{
public int Type { get; set; }
public string Query { get; set; }
public object SearchLanguage { get; set; }
public object Locale { get; set; }
public int Count { get; set; }
public string Until { get; set; }
public int SinceID { get; set; }
public int MaxID { get; set; }
public object GeoCode { get; set; }
public int ResultType { get; set; }
public bool IncludeEntities { get; set; }
public int TweetMode { get; set; }
public List<Status> Statuses { get; set; }
public SearchMetaData SearchMetaData { get; set; }
}
public class RootObject
{
public List<Operation> operations { get; set; }
}
}
<file_sep>function TweetViewModel($scope, $http) {
$scope.Tweet = {
"TweetHashTag": "",
"Message": "",
"Author": "",
"AuthorPic": "",
"TimePosted": "",
"RetweetCount": 0,
"LikesCount": 0
};
$scope.Tweets = {};
$scope.LoadByTag = function () {
$http({
method: "POST",
data: $scope.Tweet,
url: "Tweets"
}).
success(function (data, status, headers, config) {
$scope.Tweets = data;
});
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Models;
namespace GetTweets.ViewModel
{
public class TweetViewModel
{
public Tweet tweet { get; set; }
public List<Tweet> tweets { get; set; }
}
}<file_sep>using LinqToTwitter;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebAPI.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
private static string accessToken = "<KEY>";
private static string accessTokenSecret = "<KEY>";
private static string consumerKey = "<KEY>";
private static string consumerSecret = "<KEY>";
private static string twitterAcccountToDisplay = "jonam25";
private static string searchTweet = "EVMkaBahana";
private static int tweetCount=10;
var authorizer = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore()
{
ConsumerKey = "<KEY>", //consumerKey,
ConsumerSecret = "<KEY>", //consumerSecret,
OAuthToken = "<KEY>", //accessToken,
OAuthTokenSecret = "<KEY>", //accessTokenSecret,
ScreenName = "jonam25", //twitterAcccountToDisplay,
UserID = 66370920
}
};
var twitterContext = new TwitterContext(authorizer);
List<Search> statusTweets = new List<Search>();
try
{
statusTweets = (from tweet in twitterContext.Search
where tweet.Type == SearchType.Search && tweet.Query == searchTweet
&& tweet.Count == tweetCount
&& tweet.ResultType == ResultType.Popular
select tweet).ToList();
}
catch (AggregateException e)
{
Console.WriteLine("AggregateException {0}", e.InnerExceptions[0]);
}
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Web.Script.Serialization;
using LinqToTwitter;
using Newtonsoft.Json;
using GetTweets.ViewModel;
using Models;
namespace GetTweets.Controllers
{
public class TweetController : Controller
{
private static string searchTweet = "#DWTS";
private static Int64 tweetCount = 10;
public JsonResult Tweets(Tweet t)
{
var authorizer = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore()
{
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
OAuthToken = ConfigurationManager.AppSettings["OAuthToken"],
OAuthTokenSecret = ConfigurationManager.AppSettings["OAuthTokenSecret"],
ScreenName= ConfigurationManager.AppSettings["ScreenName"],
UserID = Convert.ToUInt64(ConfigurationManager.AppSettings["UserID"])
}
};
var twitterContext = new TwitterContext(authorizer);
List<Search> statusTweets = new List<Search>();
statusTweets = (from tweet in twitterContext.Search
where tweet.Type == SearchType.Search && tweet.Query == searchTweet
&& tweet.Count == tweetCount
&& tweet.ResultType == ResultType.Popular
select tweet).ToList();
var json = JsonConvert.SerializeObject(new
{
operations = statusTweets
});
var result= Json(json, JsonRequestBehavior.AllowGet);
var root = new JavaScriptSerializer().Deserialize<RootObject>(result.Data.ToString());
var ops = root.operations.FirstOrDefault();
TweetViewModel tvm = new TweetViewModel();
tvm.tweet = new Tweet() { Message=ops.Query };
tvm.tweets = new List<Tweet>();
foreach (var status in ops.Statuses)
{
Tweet twt = new Tweet();
twt.Message = status.Text;
twt.LikesCount = status.FavoriteCount;
twt.TimePosted = status.CreatedAt;
twt.RetweetCount = status.RetweetCount;
twt.Author = status.User.Name;
twt.AuthorPic = status.User.ProfileImageUrl;
tvm.tweets.Add(twt);
}
return Json(tvm, JsonRequestBehavior.AllowGet);
}
public ActionResult Tweet1()
{
var authorizer = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore()
{
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
OAuthToken = ConfigurationManager.AppSettings["OAuthToken"],
OAuthTokenSecret = ConfigurationManager.AppSettings["OAuthTokenSecret"],
ScreenName = ConfigurationManager.AppSettings["ScreenName"],
UserID = Convert.ToUInt64(ConfigurationManager.AppSettings["UserID"])
}
};
var twitterContext = new TwitterContext(authorizer);
List<Search> statusTweets = new List<Search>();
statusTweets = (from tweet in twitterContext.Search
where tweet.Type == SearchType.Search && tweet.Query == searchTweet
&& tweet.Count == tweetCount
&& tweet.ResultType == ResultType.Popular
select tweet).ToList();
var json = JsonConvert.SerializeObject(new
{
operations = statusTweets
});
var result = Json(json, JsonRequestBehavior.AllowGet);
var root = new JavaScriptSerializer().Deserialize<RootObject>(result.Data.ToString());
var ops = root.operations.FirstOrDefault();
TweetViewModel tvm = new TweetViewModel();
tvm.tweet = new Tweet() { Message = ops.Query };
tvm.tweets = new List<Tweet>();
foreach (var status in ops.Statuses)
{
Tweet twt = new Tweet();
twt.Message = status.Text;
twt.LikesCount = status.FavoriteCount;
twt.TimePosted = status.CreatedAt;
twt.RetweetCount = status.RetweetCount;
twt.Author = status.User.Name;
twt.AuthorPic = status.User.ProfileImageUrl;
tvm.tweets.Add(twt);
}
return View(tvm);
}
public ActionResult Home()
{
ViewBag.Message = "Your application description page.";
return View();
}
}
} | 681938daa9d8fc9119b124cfacd961807dbb1393 | [
"JavaScript",
"C#"
] | 5 | C# | jonam25/TwitterApp | 8df91c909fc69752ad67f66cbdb2e682e73cf11f | db5e283bb55af5a68978f12540068eee41c10820 |
refs/heads/master | <repo_name>edikar/LearnOpenGL<file_sep>/02_lesson_shaders/lesson_shaders.cpp
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
#include <math.h>
#include "shader_class.h"
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
/*const char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"in vec4 vertexColor; // the input variable from the vertex shader (same name and same type) \n"
"void main()\n"
"{\n"
" FragColor = vertexColor;\n"
"}\n\0";*/
int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
//the following 3 lines define opengl version 4.5 and the core profile
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
Shader ourShader("shaders/shader.vs", "shaders/shader.fs"); // you can name your shader files however you like
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
//positions //colors
0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // top
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom left
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//define the position attribute for the shaders
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//define the color attribute for the shaders
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
//filled or wireframe triangles
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
while(!glfwWindowShouldClose(window))
{ // input
// -----
processInput(window);
// render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
ourShader.setFloat("horizontatlPos", -0.1f);
ourShader.use();
//update 'ourColor' uniform location
/*
float timeValue = glfwGetTime();
float greenValue = (sin(timeValue)/2.0f) + 0.5f;
int vertexColorLocation = glGetUniformLocation(shaderProgram, "ourColor");
glUseProgram(shaderProgram);
glUniform4f(vertexColorLocation, 0.0f, greenValue, 0.0f, 1.0f);*/
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
//glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}<file_sep>/spheres/cpu_noised_sphere.cpp
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
#include <math.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
/*#include <glm/ext/matrix_clip_space.hpp>*/
#include <glm/gtc/type_ptr.hpp>
#include "shader_class.h"
#include "utils.h"
#include "camera.h"
#include "model.h"
#include "PerlinNoise.h"
using namespace std;
using namespace glm;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void processInput(GLFWwindow *window);
STATUS init();
void showFrameRate();
unsigned int loadTexture(const char *path);
void drawSphere();
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
#define DETALIZATION_ITERATIONS 6
#define NUM_FACES (1<<(5+DETALIZATION_ITERATIONS*2))
#define NUM_VERTICES ((1<<(4+DETALIZATION_ITERATIONS*2)) + 2)
// camera
Camera camera(glm::vec3(0.0f, 0.0f, 5.0f));
float lastX = SCR_WIDTH / 2.0f;
float lastY = SCR_HEIGHT / 2.0f;
bool firstMouse = true;
// timing
float deltaTime = 0.0f; // time between current frame and last frame
float lastFrame = 0.0f;
GLFWwindow* window;
Shader *planetShader;
Shader *oceanShader;;
Shader *normalsShader;
//light position
glm::vec3 lightPos(0.0f, 0.0f, 8.0f);
typedef struct {
vec3 position;
vec3 normal;
} VERTEX;
VERTEX *vertices;
int *normalsPerVertex; //this is needed to count number of faces each vertex involved in to average the normal
typedef struct {
int numNeighbours;
int neighbours[6];
int middleVertex[6];
} USED_VERTICES;
USED_VERTICES *usedVertices; //this array stores the vertices which were already split in current iteration - to prevent creating same vertex twice
typedef struct {
vec3 position;
vec3 normal;
} NOISED_VERTEX;
NOISED_VERTEX *noisedVertices;
typedef struct {
vec3 position;
} NORMAL_POSITION;
NORMAL_POSITION *normalsPositions;
typedef struct {
unsigned int v1;
unsigned int v2;
unsigned int v3;
} FACE;
FACE *faces;
int numVertices = 6;
int numFaces = 8;
unsigned int sphereVBO, sphereVAO, sphereEBO;
unsigned int oceanVBO, oceanVAO, oceanEBO;
unsigned int normalsVBO, normalsVAO;
int getMiddleVertex(int p1, int p2){
for(int i = 0; i < usedVertices[p1].numNeighbours; i++){
if(usedVertices[p1].neighbours[i] == p2){
return usedVertices[p1].middleVertex[i];
}
}
int nextNeighbour1 = usedVertices[p1].numNeighbours;
int nextNeighbour2 = usedVertices[p2].numNeighbours;
vec3 v1 = vertices[p1].position;
vec3 v2 = vertices[p2].position;
vertices[numVertices].position = vertices[numVertices].normal = normalize((v2 - v1) * 0.5f + v1);
usedVertices[p1].neighbours[nextNeighbour1] = p2;
usedVertices[p1].middleVertex[nextNeighbour1] = numVertices;
usedVertices[p1].numNeighbours++;
usedVertices[p2].neighbours[nextNeighbour2] = p1;
usedVertices[p2].middleVertex[nextNeighbour2] = numVertices;
usedVertices[p2].numNeighbours++;
return numVertices++;
}
void initializeSphere(){
numVertices = 6;
numFaces = 8;
//generate sphere vertices
for(int iteration = 0; iteration <= DETALIZATION_ITERATIONS; iteration++){
memset(usedVertices, 0, NUM_VERTICES * sizeof(USED_VERTICES));
unsigned int currentNumFaces = numFaces;
for(int face = 0; face < currentNumFaces; face++){
/* p3
/\
n6 /__\ n5
/\ /\
/__\/__\
p1 n4 p2
*/
unsigned int p1 = faces[face].v1;
unsigned int p2 = faces[face].v2;
unsigned int p3 = faces[face].v3;
vec3 v1 = vertices[p1].position;
vec3 v2 = vertices[p2].position;
vec3 v3 = vertices[p3].position;
unsigned int n4, n5, n6; // new vertices
n4 = getMiddleVertex(p1,p2);
n5 = getMiddleVertex(p2,p3);
n6 = getMiddleVertex(p3,p1);
//old big face becomes the middle triangle
faces[face].v1 = n4;
faces[face].v2 = n5;
faces[face].v3 = n6;
// 3 new faces are added
faces[numFaces].v1 = p1;
faces[numFaces].v2 = n4;
faces[numFaces].v3 = n6;
faces[numFaces + 1].v1 = n4;
faces[numFaces + 1].v2 = p2;
faces[numFaces + 1].v3 = n5;
faces[numFaces + 2].v1 = n6;
faces[numFaces + 2].v2 = n5;
faces[numFaces + 2].v3 = p3;
numFaces += 3;
}
printf("iteration: %d, numFaces = %d (0x%x), numVertices = %d (0x%x)\n", iteration, numFaces, numFaces, numVertices, numVertices);
}
printf("numVertices = %d NUM_VERTICES = %d\n", numVertices, NUM_VERTICES);
printf("max vertices = 0x%x\n", NUM_VERTICES);
printf("max faces = 0x%x\n", NUM_FACES);
}
void applyNoise(){
int seed = rand()/10000 % 10000;
printf("seed = %d\n", seed);
PerlinNoise pn(seed);
for(int v = 0; v < numVertices; v++){
vec3 pos = vertices[v].position;
float noise = 0;
float amplitude = 0.6f;
float frequency = 1.0f;
for(int i = 0; i < 5; i++){
noise += amplitude * (pn.noise(pos.x * frequency , pos.y * frequency , pos.z * frequency) + 0.3);
frequency *= 2;
amplitude *= 0.5f;
}
noisedVertices[v].position = vertices[v].position * noise;
noisedVertices[v].normal = normalize(noisedVertices[v].position);
//noisedVertices[v].normal = normalize(c1);
//make some waves in the ocean
frequency = 40.0f;
vertices[v].position = vertices[v].position + vec3(0.005f * pn.noise(pos.x * frequency , pos.y * frequency , pos.z * frequency));
normalsPositions[2 * v].position = noisedVertices[v].position;
normalsPositions[2 * v + 1].position = noisedVertices[v].position + normalize(noisedVertices[v].position)/40.0f;
}
//land normals calculation
memset(normalsPerVertex, 0, NUM_VERTICES * sizeof(int));
for(int f = 0; f < numFaces; f++){
vec3 v1 = noisedVertices[faces[f].v1].position;
vec3 v2 = noisedVertices[faces[f].v2].position;
vec3 v3 = noisedVertices[faces[f].v3].position;
noisedVertices[faces[f].v1].normal += normalize(cross(v2-v1 , v3 - v1));
normalsPerVertex[faces[f].v1]++;
noisedVertices[faces[f].v2].normal += normalize(cross(v3-v2 , v1 - v2));
normalsPerVertex[faces[f].v2]++;
noisedVertices[faces[f].v3].normal += normalize(cross(v1-v3 , v2 - v3));
normalsPerVertex[faces[f].v3]++;
}
for(int v = 0; v < numVertices; v++){
noisedVertices[v].normal /= normalsPerVertex[v];
normalsPositions[2 * v].position = noisedVertices[v].position;
normalsPositions[2 * v + 1].position = noisedVertices[v].position + noisedVertices[v].normal/40.0f;
vertices[v].normal /= normalsPerVertex[v];
}
//ocean normals calculations
memset(normalsPerVertex, 0, NUM_VERTICES * sizeof(int));
for(int f = 0; f < numFaces; f++){
vec3 v1 = vertices[faces[f].v1].position;
vec3 v2 = vertices[faces[f].v2].position;
vec3 v3 = vertices[faces[f].v3].position;
vertices[faces[f].v1].normal += normalize(cross(v2-v1 , v3 - v1));
normalsPerVertex[faces[f].v1]++;
vertices[faces[f].v2].normal += normalize(cross(v3-v2 , v1 - v2));
normalsPerVertex[faces[f].v2]++;
vertices[faces[f].v3].normal += normalize(cross(v1-v3 , v2 - v3));
normalsPerVertex[faces[f].v3]++;
}
for(int v = 0; v < numVertices; v++){
vertices[v].normal /= normalsPerVertex[v];
}
}
int main()
{
STATUS status = OK;
//init project
status = init();
if(status != OK)
{
cout << "init() failed at " << __FILE__ << ":" << __LINE__ << __FUNCTION__ << endl;
return ERROR;
}
glEnable(GL_DEPTH_TEST);
planetShader = new Shader("shaders/planetShader2.vs", "shaders/planetShader2.fs"/*, "shaders/planetShader2.gs"*/);
oceanShader = new Shader("shaders/oceanShader.vs", "shaders/oceanShader.fs"/*, "shaders/planetShader2.gs"*/);
normalsShader = new Shader("shaders/normalsShader.vs", "shaders/normalsShader.fs"/*, "shaders/planetShader2.gs"*/);
//alloate all memories
faces = new FACE[NUM_FACES];// (FACE*)malloc(NUM_FACES * sizeof(FACE));
memset(faces, 0, NUM_FACES * sizeof(FACE));
faces[0] = { 0, 4, 2 }; //0
faces[1] = { 4, 1, 2 }; //1
faces[2] = { 0, 3, 4 }; //2
faces[3] = { 4, 3, 1 }; //3
faces[4] = { 0, 2, 5 }; //4
faces[5] = { 1, 5, 2 }; //5
faces[6] = { 0, 5, 3 }; //6
faces[7] = { 3, 5, 1 }; //7
vertices = new VERTEX[NUM_VERTICES]; //(VERTEX*)malloc(NUM_VERTICES * sizeof(VERTEX));
memset(vertices, 0, NUM_VERTICES * sizeof(VERTEX));
vertices[0] = { vec3(-1.0f, 0.0f, 0.0f), vec3(-1.0f, 0.0f, 0.0f) }; //0
vertices[1] = { vec3(1.0f, 0.0f, 0.0f), vec3(1.0f, 0.0f, 0.0f) }; //1
vertices[2] = { vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f) }; //2
vertices[3] = { vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, -1.0f, 0.0f) }; //3
vertices[4] = { vec3(0.0f, 0.0f, 1.0f), vec3(0.0f, 0.0f, 1.0f) }; //4
vertices[5] = { vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 0.0f, -1.0f) }; //5
normalsPerVertex = new int[NUM_VERTICES]; //(int*)malloc(NUM_VERTICES * sizeof(int));
memset(normalsPerVertex, 0, NUM_VERTICES * sizeof(int));
usedVertices = new USED_VERTICES[NUM_VERTICES];
memset(usedVertices, 0, NUM_VERTICES * sizeof(USED_VERTICES));
noisedVertices = new NOISED_VERTEX[NUM_VERTICES];
memset(noisedVertices, 0, NUM_VERTICES * sizeof(NOISED_VERTEX));
normalsPositions = new NORMAL_POSITION[ 2 * NUM_VERTICES];
memset(normalsPositions, 0, 2 * NUM_VERTICES * sizeof(NORMAL_POSITION));
initializeSphere();
applyNoise();
glGenBuffers(1, &sphereVBO);
glGenBuffers(1, &sphereEBO);
glGenVertexArrays(1, &sphereVAO);
glBindVertexArray(sphereVAO);
glBindBuffer(GL_ARRAY_BUFFER, sphereVBO);
glBufferData(GL_ARRAY_BUFFER, NUM_VERTICES * sizeof(NOISED_VERTEX), noisedVertices, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_FACES * sizeof(FACE), faces, GL_STATIC_DRAW);
//vertex position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glGenBuffers(1, &oceanVBO);
glGenBuffers(1, &oceanEBO);
glGenVertexArrays(1, &oceanVAO);
glBindVertexArray(oceanVAO);
glBindBuffer(GL_ARRAY_BUFFER, oceanVBO);
glBufferData(GL_ARRAY_BUFFER, NUM_VERTICES * sizeof(VERTEX), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oceanEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_FACES * sizeof(FACE), faces, GL_STATIC_DRAW);
//vertex position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glGenBuffers(1, &normalsVBO);
glGenVertexArrays(1, &normalsVAO);
glBindVertexArray(normalsVAO);
glBindBuffer(GL_ARRAY_BUFFER, normalsVBO);
glBufferData(GL_ARRAY_BUFFER, 2 * NUM_VERTICES * sizeof(NORMAL_POSITION), normalsPositions, GL_STATIC_DRAW);
//vertex position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//free malloced arrays
delete[] faces;
delete[] vertices;
delete[] normalsPerVertex;
delete[] usedVertices;
delete[] noisedVertices;
delete[] normalsPositions;
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
//filled or wireframe triangles
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// per-frame time logic
// --------------------
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2f, 0.2f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawSphere();
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
showFrameRate();
}
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
void drawSphere(){
static float perlinOffset = 1.0;
perlinOffset += 0.001;
//applyNoise();
//glm::mat4 lightPosTransform = glm::rotate(glm::mat4(1.0f),0.01f, glm::vec3(0.0f, -1.0f, 0.0f));
//lightPos = lightPosTransform * glm::vec4(lightPos,1.0f);
//create model, view and projection matrices for box
mat4 model = glm::mat4(1.0f);
model = glm::rotate(model, (float)glfwGetTime()/5, glm::vec3(0.0f, 1.0f, 0.0f));
mat4 view = camera.GetViewMatrix();
mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
mat4 normalMat = glm::transpose(glm::inverse(model));
// activate shader
planetShader->use();
planetShader->setVec3("objectColor", glm::vec3(0.4f, 0.4f, 0.4f));
planetShader->setVec3("lightColor", glm::vec3(1.0f, 1.0f, 1.0f));
planetShader->setVec3("lightPos", lightPos);
planetShader->setVec3("viewPos", camera.Position);
// set the model, view and projection matrix uniforms
planetShader->setMat4("model", model);
planetShader->setMat4("view", view);
planetShader->setMat4("projection", projection);
planetShader->setMat4("normalMat", normalMat);
glBindVertexArray(sphereVAO);
glBindBuffer(GL_ARRAY_BUFFER, sphereVBO);
//glBufferData(GL_ARRAY_BUFFER, NUM_VERTICES * sizeof(NOISED_VERTEX), noisedVertices, GL_DYNAMIC_DRAW);
// glDrawArrays(GL_TRIANGLES, 0, numTriangles);
glDrawElements(GL_TRIANGLES, NUM_FACES * sizeof(FACE), GL_UNSIGNED_INT, 0);
// activate shader
oceanShader->use();
oceanShader->setVec3("lightColor", glm::vec3(1.0f, 1.0f, 1.0f));
oceanShader->setVec3("lightPos", lightPos);
oceanShader->setVec3("viewPos", camera.Position);
// set the model, view and projection matrix uniforms
oceanShader->setMat4("model", model);
oceanShader->setMat4("view", view);
oceanShader->setMat4("projection", projection);
oceanShader->setMat4("normalMat", normalMat);
oceanShader->setVec3("objectColor", glm::vec3(0.0f, 0.0f, 0.5f));
oceanShader->setFloat("time", (float)glfwGetTime()/100);
glBindVertexArray(oceanVAO);
glDrawElements(GL_TRIANGLES, NUM_FACES * sizeof(FACE), GL_UNSIGNED_INT, 0);
// activate shader
normalsShader->use();
// set the model, view and projection matrix uniforms
normalsShader->setMat4("model", model);
normalsShader->setMat4("view", view);
normalsShader->setMat4("projection", projection);
normalsShader->setMat4("normalMat", normalMat);
glBindVertexArray(normalsVAO);
//glDrawArrays(GL_LINES, 0, 2*numVertices);
}
void showFrameRate(){
static double previousTime;
static int frameCount;
double currentTime = glfwGetTime();
double deltaMs = (currentTime - previousTime) * 1000;
frameCount++;
if ( currentTime - previousTime >= 1.0 )
{
// Display the frame count here any way you want.
std::stringstream ss;
ss << "FPS: " << frameCount;
glfwSetWindowTitle(window, ss.str().c_str());
frameCount = 0;
previousTime = currentTime;
}
}
//Init glfw, create and init window, init glew
STATUS init()
{
srand(time(0));
// glfw: initialize and configure
// ------------------------------
glfwInit();
//the following 3 lines define opengl version 4.5 and the core profile
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return ERROR;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return ERROR;
}
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
return OK;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
// glfw: whenever the mouse moves, this callback is called
// -------------------------------------------------------
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
// glfw: whenever the mouse scroll wheel scrolls, this callback is called
// ----------------------------------------------------------------------
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(char const * path)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}<file_sep>/01_hello_triangle/Makefile
appname := hello_window
CXX := g++
CXXFLAGS := -std=c++11
srcfiles := $(shell find . -name "*.cpp" -not -path "./exercise/*")
objects := $(patsubst %.cpp, %.o, $(srcfiles))
LDFLAGS :=
LDLIBS := -lGLEW -lglfw -lGL -lX11 -lpthread -lXrandr
all: $(appname)
./$(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
ex1:
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o ./exercise/ex1 exercise/ex1.cpp $(LDLIBS)
./exercise/ex1
ex2:
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o ./exercise/ex2 exercise/ex2.cpp $(LDLIBS)
./exercise/ex2
ex3:
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o ./exercise/ex3 exercise/ex3.cpp $(LDLIBS)
./exercise/ex3
ex-clean:
rm ./exercise/ex1
rm ./exercise/ex2
rm ./exercise/ex3
include .depend<file_sep>/README.md
# LearnOpenGL
Exercises from learnopengl.com course
Some implementations were taken from the course site, some written by me.
Each lesson has own makefile, just go to lesson folder and type 'make' it will build and run the application.
<file_sep>/create_lesson.sh
#!/bin/bash
if [ $# != 2 ]; then
echo "Usage:"
echo "./create_lesson from to"
exit;
fi
if [ ! -d $1 ]; then
echo "dir $1 does not exist"
exit;
fi
if [ -d $2 ]; then
echo "dir $2 already exist"
exit;
fi
cp -r $1 $2; cd $2; make clean; mv *.cpp `basename $(pwd)`.cpp<file_sep>/17_face_culling/17_face_culling.cpp
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
#include <math.h>
#include "shader_class.h"
#include "utils.h"
#include "camera.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/ext/matrix_clip_space.hpp>
#include <glm/gtc/type_ptr.hpp>
using namespace std;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void processInput(GLFWwindow *window);
STATUS init();
void showFrameRate();
unsigned int loadTexture(char const * path);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
// camera
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = SCR_WIDTH / 2.0f;
float lastY = SCR_HEIGHT / 2.0f;
bool firstMouse = true;
// timing
float deltaTime = 0.0f; // time between current frame and last frame
float lastFrame = 0.0f;
GLFWwindow* window;
int front_or_back = 1; //draw front faces first
int main()
{
STATUS status = OK;
//init project
status = init();
if(status != OK)
{
cout << "init() failed at " << __FILE__ << ":" << __LINE__ << __FUNCTION__ << endl;
return ERROR;
}
Shader ourShader("shaders/shader.vs", "shaders/shader.fs"); // you can name your shader files however you like
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
// back face
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, // bottom-right
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // bottom-left
// front face
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-right
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // top-right
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // top-left
// left face
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-left
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-left
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-right
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right
// right face
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right
0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // bottom-right
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-left
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // top-left
// bottom face
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left
0.5f, -0.5f, -0.5f, 1.0f, 1.0f, // top-left
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // bottom-left
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f, // top-right
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // bottom-right
// top face
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // top-left
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // top-right
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom-right
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // bottom-right
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // bottom-left
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f // top-left
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//define the position attribute for the shaders
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//define the texture
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
//filled or wireframe triangles
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
//glCullFace(GL_FRONT); //
glCullFace(GL_BACK);
//create texture
unsigned int texture0 = loadTexture("../images/metal.png");
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// per-frame time logic
// --------------------
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//transform and rotate by time
glm::mat4 model = glm::rotate(glm::mat4(1.0), glm::radians(0.0f), glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::rotate(model, (float)glm::radians(glfwGetTime()) * 5, glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
ourShader.use();
// set the model, view and projection matrix uniforms
ourShader.setMat4("model", model);
ourShader.setMat4("view", view);
ourShader.setMat4("projection", projection);
ourShader.setInt("texture0", 0);
ourShader.setInt("front_or_back", front_or_back);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
void showFrameRate(){
static double previousTime;
static int frameCount;
double currentTime = glfwGetTime();
double deltaMs = (currentTime - previousTime) * 1000;
frameCount++;
if ( currentTime - previousTime >= 1.0 )
{
// Display the frame count here any way you want.
std::stringstream ss;
ss << "FPS: " << frameCount;
glfwSetWindowTitle(window, ss.str().c_str());
frameCount = 0;
previousTime = currentTime;
}
}
//Init glfw, create and init window, init glew
STATUS init()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
//the following 3 lines define opengl version 4.5 and the core profile
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return ERROR;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return ERROR;
}
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
return OK;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
if(glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS){
glCullFace(GL_BACK);
front_or_back = 1;
}
if(glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS){
glCullFace(GL_FRONT);
front_or_back = 0;
}
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
// glfw: whenever the mouse moves, this callback is called
// -------------------------------------------------------
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
// glfw: whenever the mouse scroll wheel scrolls, this callback is called
// ----------------------------------------------------------------------
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(char const * path)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1){
std::cout << "GL_RED\n";
format = GL_RED;
}
else if (nrComponents == 3){
std::cout << "GL_RGB\n";
format = GL_RGB;
}
else if (nrComponents == 4){
std::cout << "GL_RGBA\n";
format = GL_RGBA;
}
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
//clamp to edge in order to prevent edge alpha value interpolated with repeated bottom
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, format == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, format == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}<file_sep>/gui/planet.h
#ifndef PLANET_H
#define PLANET_H
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
#include "camera.h"
#include "shader_class.h"
#include <glm/glm.hpp>
using glm::vec3;
using glm::mat4;
typedef struct {
vec3 position;
vec3 normal;
} VERTEX;
typedef struct {
int numNeighbours;
int neighbours[6];
int middleVertex[6];
} USED_VERTICES;
typedef struct {
vec3 position;
vec3 normal;
} NOISED_VERTEX;
typedef struct {
vec3 position;
} NORMAL_POSITION;
typedef struct {
unsigned int v1;
unsigned int v2;
unsigned int v3;
} FACE;
void processInput(int,int);
class Planet {
public:
Planet();
~Planet();
void planetDraw();
void toggleOcean(bool);
void toggleNormals(bool);
void toggleWireframe(bool);
int randomizePlanet(int, float, float);
void processInput(int,int);
void setNoiseFrequency(float);
void setNoiseAmplitude(float);
void setDetalization(int);
void setNoiseSeed(int);
private:
//matrices
mat4 model;
mat4 view;
mat4 projection;
mat4 normalMat;
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
// camera
Camera *camera;
//shaders
Shader *planetShader;
Shader *oceanShader;;
Shader *normalsShader;
// timing
float deltaTime = 0.0f; // time between current frame and last frame
float lastFrame = 0.0f;
//light position
vec3 lightPos;
//GL objects
unsigned int sphereVBO, sphereVAO, sphereEBO;
unsigned int oceanVBO, oceanVAO, oceanEBO;
unsigned int normalsVBO, normalsVAO;
//controls
bool showNormals = 0;
bool showOcean = 1;
bool showWireframe = 0;
//planet generation parameters
int detalization;
int perlinSeed;
float noiseAmplitude;
float noiseFrequency;
//These are temporary pointers for planet generations - probalby should not be here...
VERTEX *vertices;
int *normalsPerVertex; //this is needed to count number of faces each vertex involved in to average the normal
USED_VERTICES *usedVertices; //this array stores the vertices which were already split in current iteration - to prevent creating same vertex twice
NOISED_VERTEX *noisedVertices;
NORMAL_POSITION *normalsPositions;
FACE *faces;
int numVertices = 6;
int numFaces = 8;
int NUM_FACES;
int NUM_VERTICES;
void initializePlanet();
//these are helper functions
void applyNoise();
void initializeSphere();
int getMiddleVertex(int, int);
void drawPlanet();
void drawOcean();
void drawNormals();
void setupDrawParameters();
};
#endif /* PLANET_H */<file_sep>/grid/grid.cpp
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
#include <math.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "shader_class.h"
#include "utils.h"
#include "camera.h"
#include "model.h"
using namespace std;
using namespace glm;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void processInput(GLFWwindow *window);
STATUS init();
void showFrameRate();
unsigned int loadTexture(const char *path);
void draw();
// settings
const unsigned int SCR_WIDTH = 1000;
const unsigned int SCR_HEIGHT = 1000;
#define GRID_SIZE (10)
// camera
Camera camera(glm::vec3(0.0f, 0.0f, 5.0f));
float lastX = SCR_WIDTH / 2.0f;
float lastY = SCR_HEIGHT / 2.0f;
bool firstMouse = true;
// timing
float deltaTime = 0.0f; // time between current frame and last frame
float lastFrame = 0.0f;
GLFWwindow* window;
Shader *gridShader;
Shader *playerShader;
//light position
glm::vec3 lightPos(1.0f, 2.0f, 1.0f);
//player position
glm::vec3 playerPos(100.0f, 200.0f, 1.0f);
float playerSpeed = 3;
float playerAngle = M_PI_2;
struct {
vec3 position;
vec3 normal;
} gridVertices[SCR_WIDTH * SCR_HEIGHT];
struct {
unsigned int v1;
unsigned int v2;
} gridLines[SCR_WIDTH * SCR_HEIGHT] = { // note that we start from 0!
0, 1, 1, 2, 2, 3, 3, 4, //0
};
struct {
vec3 position;
vec3 normal;
} playerVertices[3] = {
{ vec3(-20.0f, -20.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f) }, //0
{ vec3(20.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f) }, //0
{ vec3(-20.0f, 20.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f) }, //0
};
struct {
unsigned int v1;
unsigned int v2;
} playerFace[3] = { // note that we start from 0!
0, 1, 2, //0
};
unsigned int gridVBO, gridVAO, gridEBO;
unsigned int playerVBO, playerVAO, playerEBO;
void initializeGrid(){
int nx = 1 + SCR_WIDTH / GRID_SIZE;
int ny = 1 + SCR_HEIGHT / GRID_SIZE;
printf("nx = %d ny = %d\n", nx, ny);
int t = 0;
for(int y = 0; y <= ny; y++){
for(int x = 0; x <= nx; x++){
gridVertices[y * nx + x].position = vec3(x * GRID_SIZE, y * GRID_SIZE, 0);
gridVertices[y * nx + x].normal = vec3(0, 0, 1);
gridLines[2*(y * nx + x)].v1 = y * nx + x;
if(x == nx-1)
gridLines[2*(y * nx + x)].v2 = y * nx + x;
else
gridLines[2*(y * nx + x)].v2 = y * nx + x + 1;
gridLines[2*(y * nx + x)+1].v1 = y * nx + x;
gridLines[2*(y * nx + x)+1].v2 = (y + 1) * nx + x;
/*
printf("%d: [%d %d] = %d %d\n", t, x,y, x*GRID_SIZE, y*GRID_SIZE);
printf("[%d] = %d----%d\n", 2*(y * ny + x), gridLines[2*(y * nx + x)].v1, gridLines[2*(y * nx + x)].v2);
printf("[%d] = %d----%d\n", 2*(y * ny + x)+1, gridLines[2*(y * nx + x)+1].v1, gridLines[2*(y * nx + x)+1].v2);*/
//t++;
}
}
}
int main()
{
STATUS status = OK;
//init project
status = init();
if(status != OK)
{
cout << "init() failed at " << __FILE__ << ":" << __LINE__ << __FUNCTION__ << endl;
return ERROR;
}
gridShader = new Shader("shaders/gridShader.vs", "shaders/gridShader.fs");
playerShader = new Shader("shaders/playerShader.vs", "shaders/playerShader.fs");
// load models
// -----------
Model ourModel("../models/nanosuit/nanosuit.obj");
initializeGrid();
glGenBuffers(1, &gridVBO);
glGenBuffers(1, &gridEBO);
glGenVertexArrays(1, &gridVAO);
glBindVertexArray(gridVAO);
glBindBuffer(GL_ARRAY_BUFFER, gridVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(gridVertices), gridVertices, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gridEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(gridLines), gridLines, GL_STATIC_DRAW);
//vertex position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glGenBuffers(1, &playerVBO);
glGenBuffers(1, &playerEBO);
glGenVertexArrays(1, &playerVAO);
glBindVertexArray(playerVAO);
glBindBuffer(GL_ARRAY_BUFFER, playerVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(playerVertices), playerVertices, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, playerEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(playerFace), playerFace, GL_STATIC_DRAW);
//vertex position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glEnable(GL_DEPTH_TEST);
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// per-frame time logic
// --------------------
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
draw();
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
showFrameRate();
}
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
void draw(){
glEnable(GL_CULL_FACE);
//filled or wireframe triangles
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//glm::mat4 lightPosTransform = glm::rotate(glm::mat4(1.0f),0.01f, glm::vec3(0.0f, -1.0f, 0.0f));
//lightPos = lightPosTransform * glm::vec4(lightPos,1.0f);
//create model, view and projection matrices for box
mat4 model = glm::mat4(1.0f);
mat4 view = camera.GetViewMatrix();
mat4 projection = glm::ortho( 0.0f, (float)SCR_WIDTH, 0.0f, (float)SCR_HEIGHT, -10.0f, 10.0f );//glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
mat4 normalMat = glm::transpose(glm::inverse(model));
// activate shader
gridShader->use();
// set the model, view and projection matrix uniforms
gridShader->setMat4("model", model);
gridShader->setMat4("view", view);
gridShader->setMat4("projection", projection);
gridShader->setVec3("playerPos", playerPos);
glBindVertexArray(gridVAO);
glDrawElements(GL_LINES, 2*2*(1 + SCR_WIDTH/GRID_SIZE) * (1 + SCR_HEIGHT/GRID_SIZE), GL_UNSIGNED_INT, 0);
playerShader->use();
model = glm::translate(model, playerPos);
model = glm::rotate(model, playerAngle, glm::vec3(0.0f, 0.0f, 1.0f));
playerShader->setMat4("model", model);
playerShader->setMat4("view", view);
playerShader->setMat4("projection", projection);
glBindVertexArray(playerVAO);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0);
}
void showFrameRate(){
static double previousTime;
static int frameCount;
double currentTime = glfwGetTime();
double deltaMs = (currentTime - previousTime) * 1000;
frameCount++;
if ( currentTime - previousTime >= 1.0 )
{
// Display the frame count here any way you want.
std::stringstream ss;
ss << "FPS: " << frameCount;
glfwSetWindowTitle(window, ss.str().c_str());
frameCount = 0;
previousTime = currentTime;
}
}
//Init glfw, create and init window, init glew
STATUS init()
{
srand(time(0));
// glfw: initialize and configure
// ------------------------------
glfwInit();
//the following 3 lines define opengl version 4.5 and the core profile
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return ERROR;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return ERROR;
}
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
return OK;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){
playerPos += playerSpeed * vec3(glm::cos(playerAngle), glm::sin(playerAngle), 0.0f);
//camera.ProcessKeyboard(FORWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){
playerPos += playerSpeed * (-vec3(glm::cos(playerAngle), glm::sin(playerAngle), 0.0f));
//camera.ProcessKeyboard(BACKWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){
playerAngle += playerSpeed * 0.01;
//camera.ProcessKeyboard(LEFT, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){
playerAngle += playerSpeed * (-0.01);
//camera.ProcessKeyboard(RIGHT, deltaTime);
}
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
// glfw: whenever the mouse moves, this callback is called
// -------------------------------------------------------
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
// glfw: whenever the mouse scroll wheel scrolls, this callback is called
// ----------------------------------------------------------------------
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.ProcessMouseScroll(yoffset);
}
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(char const * path)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}<file_sep>/09_materials/Makefile
appname := $(shell basename `pwd`).out
CXX := g++
CXXFLAGS := -std=c++11
srcfiles := $(shell find . -name "*.cpp" -not -path "./exercise/*")
objects := $(patsubst %.cpp, %.o, $(srcfiles))
LDFLAGS :=
LDLIBS := -lGLEW -lglfw -lGL -lX11 -lpthread -lXrandr
INC := -I../include/
all: $(appname)
./$(appname) || true
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS) $(INC)
%.o: %.cpp
$(CXX) -c $(CXXFLAGS) $(INC) $< -o $@
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) $(INC) -MM $^>>./.depend;
clean:
rm -f $(objects) || true
rm -f $(appname) || true
#in case we changed the base directory name - clean also all .out files
rm -f *.out || true
dist-clean: clean
rm -f *~ .depend
ex1:
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o ./exercise/ex1 exercise/ex1.cpp $(LDLIBS) $(INC)
./exercise/ex1
ex2:
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o ./exercise/ex2 exercise/ex2.cpp $(LDLIBS) $(INC)
./exercise/ex2
ex3:
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o ./exercise/ex3 exercise/ex3.cpp $(LDLIBS) $(INC)
./exercise/ex3
ex4:
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o ./exercise/ex4 exercise/ex4.cpp $(LDLIBS) $(INC)
./exercise/ex4
ex-clean:
rm ./exercise/ex1 || true
rm ./exercise/ex2 || true
rm ./exercise/ex3 || true
rm ./exercise/ex4 || true
include .depend<file_sep>/gui/planet.cpp
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
#include <math.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "shader_class.h"
#include "utils.h"
#include "camera.h"
#include "model.h"
#include "PerlinNoise.h"
#include "planet.h"
using namespace std;
using namespace glm;
void Planet::toggleNormals(bool state){
showNormals = state;
}
void Planet::toggleOcean(bool state){
showOcean = state;
}
void Planet::toggleWireframe(bool state){
showWireframe = state;
}
void Planet::setNoiseFrequency(float frequency){
noiseFrequency = frequency;
initializePlanet();
}
void Planet::setDetalization(int detalization){
this->detalization = detalization;
initializePlanet();
}
void Planet::setNoiseAmplitude(float amplitude){
noiseAmplitude = amplitude;
initializePlanet();
}
void Planet::setNoiseSeed(int seed){
perlinSeed = seed;
initializePlanet();
}
int Planet::randomizePlanet(int detalization, float frequency, float amplitude){
//update random seed
perlinSeed = rand()/10000 % 10000;
printf("perlinSeed = %d\n", perlinSeed);
//recreate planet
initializePlanet();
return perlinSeed;
}
int Planet::getMiddleVertex(int p1, int p2){
for(int i = 0; i < usedVertices[p1].numNeighbours; i++){
if(usedVertices[p1].neighbours[i] == p2){
return usedVertices[p1].middleVertex[i];
}
}
int nextNeighbour1 = usedVertices[p1].numNeighbours;
int nextNeighbour2 = usedVertices[p2].numNeighbours;
vec3 v1 = vertices[p1].position;
vec3 v2 = vertices[p2].position;
vertices[numVertices].position = vertices[numVertices].normal = normalize((v2 - v1) * 0.5f + v1);
usedVertices[p1].neighbours[nextNeighbour1] = p2;
usedVertices[p1].middleVertex[nextNeighbour1] = numVertices;
usedVertices[p1].numNeighbours++;
usedVertices[p2].neighbours[nextNeighbour2] = p1;
usedVertices[p2].middleVertex[nextNeighbour2] = numVertices;
usedVertices[p2].numNeighbours++;
return numVertices++;
}
void Planet::initializeSphere(){
numVertices = 6;
numFaces = 8;
//generate sphere vertices
for(int iteration = 0; iteration <= detalization; iteration++){
memset(usedVertices, 0, NUM_VERTICES * sizeof(USED_VERTICES));
unsigned int currentNumFaces = numFaces;
for(int face = 0; face < currentNumFaces; face++){
/* p3
/\
n6 /__\ n5
/\ /\
/__\/__\
p1 n4 p2
*/
unsigned int p1 = faces[face].v1;
unsigned int p2 = faces[face].v2;
unsigned int p3 = faces[face].v3;
vec3 v1 = vertices[p1].position;
vec3 v2 = vertices[p2].position;
vec3 v3 = vertices[p3].position;
unsigned int n4, n5, n6; // new vertices
n4 = getMiddleVertex(p1,p2);
n5 = getMiddleVertex(p2,p3);
n6 = getMiddleVertex(p3,p1);
//old big face becomes the middle triangle
faces[face].v1 = n4;
faces[face].v2 = n5;
faces[face].v3 = n6;
// 3 new faces are added
faces[numFaces].v1 = p1;
faces[numFaces].v2 = n4;
faces[numFaces].v3 = n6;
faces[numFaces + 1].v1 = n4;
faces[numFaces + 1].v2 = p2;
faces[numFaces + 1].v3 = n5;
faces[numFaces + 2].v1 = n6;
faces[numFaces + 2].v2 = n5;
faces[numFaces + 2].v3 = p3;
numFaces += 3;
}
printf("iteration: %d, numFaces = %d (0x%x), numVertices = %d (0x%x)\n", iteration, numFaces, numFaces, numVertices, numVertices);
}
printf("numVertices = %d NUM_VERTICES = %d\n", numVertices, NUM_VERTICES);
printf("max vertices = 0x%x\n", NUM_VERTICES);
printf("max faces = 0x%x\n", NUM_FACES);
}
void Planet::applyNoise(){
PerlinNoise pn(perlinSeed);
for(int v = 0; v < numVertices; v++){
vec3 pos = vertices[v].position;
float noise = 0;
float frequency = noiseFrequency;
float amplitude = noiseAmplitude;
//mountain ridge
// float ridgeNoise = amplitude*(1-(std::abs(2*(pn.noise(pos.x * frequency , pos.y * frequency , pos.z * frequency)-0.5f)))) - 0.2f;
for(int i = 0; i < 5; i++){
frequency *= 2;
amplitude *= 0.5f;
noise += amplitude * 2*((pn.noise(pos.x * frequency , pos.y * frequency , pos.z * frequency)-0.5f));
}
noisedVertices[v].position = vertices[v].position * (1 + noise);
noisedVertices[v].normal = normalize(noisedVertices[v].position);
//noisedVertices[v].normal = normalize(c1);
//make some waves in the ocean
frequency = 40.0f;
vertices[v].position = vertices[v].position + vec3(0.005f * pn.noise(pos.x * frequency , pos.y * frequency , pos.z * frequency));
normalsPositions[2 * v].position = noisedVertices[v].position;
normalsPositions[2 * v + 1].position = noisedVertices[v].position + normalize(noisedVertices[v].position)/30.0f;
}
//land normals calculation
memset(normalsPerVertex, 0, NUM_VERTICES * sizeof(int));
for(int f = 0; f < numFaces; f++){
vec3 v1 = noisedVertices[faces[f].v1].position;
vec3 v2 = noisedVertices[faces[f].v2].position;
vec3 v3 = noisedVertices[faces[f].v3].position;
noisedVertices[faces[f].v1].normal += normalize(cross(v2-v1 , v3 - v1));
normalsPerVertex[faces[f].v1]++;
noisedVertices[faces[f].v2].normal += normalize(cross(v3-v2 , v1 - v2));
normalsPerVertex[faces[f].v2]++;
noisedVertices[faces[f].v3].normal += normalize(cross(v1-v3 , v2 - v3));
normalsPerVertex[faces[f].v3]++;
}
for(int v = 0; v < numVertices; v++){
noisedVertices[v].normal /= normalsPerVertex[v];
normalsPositions[2 * v].position = noisedVertices[v].position;
normalsPositions[2 * v + 1].position = noisedVertices[v].position + noisedVertices[v].normal/30.0f;
vertices[v].normal /= normalsPerVertex[v];
}
//ocean normals calculations
memset(normalsPerVertex, 0, NUM_VERTICES * sizeof(int));
for(int f = 0; f < numFaces; f++){
vec3 v1 = vertices[faces[f].v1].position;
vec3 v2 = vertices[faces[f].v2].position;
vec3 v3 = vertices[faces[f].v3].position;
vertices[faces[f].v1].normal += normalize(cross(v2-v1 , v3 - v1));
normalsPerVertex[faces[f].v1]++;
vertices[faces[f].v2].normal += normalize(cross(v3-v2 , v1 - v2));
normalsPerVertex[faces[f].v2]++;
vertices[faces[f].v3].normal += normalize(cross(v1-v3 , v2 - v3));
normalsPerVertex[faces[f].v3]++;
}
for(int v = 0; v < numVertices; v++){
vertices[v].normal /= normalsPerVertex[v];
}
}
STATUS init()
{
srand(time(0));
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return ERROR;
}
return OK;
}
void Planet::initializePlanet()
{
STATUS status = OK;
NUM_FACES = (1<<(5+detalization*2)); //calculate expected number of faces
NUM_VERTICES = ((1<<(4+detalization*2)) + 2); //calculate expected number of vertices
//alloate all memories
faces = new FACE[NUM_FACES];// (FACE*)malloc(NUM_FACES * sizeof(FACE));
memset(faces, 0, NUM_FACES * sizeof(FACE));
faces[0] = { 0, 4, 2 }; //0
faces[1] = { 4, 1, 2 }; //1
faces[2] = { 0, 3, 4 }; //2
faces[3] = { 4, 3, 1 }; //3
faces[4] = { 0, 2, 5 }; //4
faces[5] = { 1, 5, 2 }; //5
faces[6] = { 0, 5, 3 }; //6
faces[7] = { 3, 5, 1 }; //7
vertices = new VERTEX[NUM_VERTICES]; //(VERTEX*)malloc(NUM_VERTICES * sizeof(VERTEX));
memset(vertices, 0, NUM_VERTICES * sizeof(VERTEX));
vertices[0] = { vec3(-1.0f, 0.0f, 0.0f), vec3(-1.0f, 0.0f, 0.0f) }; //0
vertices[1] = { vec3(1.0f, 0.0f, 0.0f), vec3(1.0f, 0.0f, 0.0f) }; //1
vertices[2] = { vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f) }; //2
vertices[3] = { vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, -1.0f, 0.0f) }; //3
vertices[4] = { vec3(0.0f, 0.0f, 1.0f), vec3(0.0f, 0.0f, 1.0f) }; //4
vertices[5] = { vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 0.0f, -1.0f) }; //5
normalsPerVertex = new int[NUM_VERTICES]; //(int*)malloc(NUM_VERTICES * sizeof(int));
memset(normalsPerVertex, 0, NUM_VERTICES * sizeof(int));
usedVertices = new USED_VERTICES[NUM_VERTICES];
memset(usedVertices, 0, NUM_VERTICES * sizeof(USED_VERTICES));
noisedVertices = new NOISED_VERTEX[NUM_VERTICES];
memset(noisedVertices, 0, NUM_VERTICES * sizeof(NOISED_VERTEX));
normalsPositions = new NORMAL_POSITION[ 2 * NUM_VERTICES];
memset(normalsPositions, 0, 2 * NUM_VERTICES * sizeof(NORMAL_POSITION));
initializeSphere();
applyNoise();
glGenBuffers(1, &sphereVBO);
glGenBuffers(1, &sphereEBO);
glGenVertexArrays(1, &sphereVAO);
glBindVertexArray(sphereVAO);
glBindBuffer(GL_ARRAY_BUFFER, sphereVBO);
glBufferData(GL_ARRAY_BUFFER, NUM_VERTICES * sizeof(NOISED_VERTEX), noisedVertices, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_FACES * sizeof(FACE), faces, GL_STATIC_DRAW);
//vertex position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glGenBuffers(1, &oceanVBO);
glGenBuffers(1, &oceanEBO);
glGenVertexArrays(1, &oceanVAO);
glBindVertexArray(oceanVAO);
glBindBuffer(GL_ARRAY_BUFFER, oceanVBO);
glBufferData(GL_ARRAY_BUFFER, NUM_VERTICES * sizeof(VERTEX), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oceanEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_FACES * sizeof(FACE), faces, GL_STATIC_DRAW);
//vertex position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glGenBuffers(1, &normalsVBO);
glGenVertexArrays(1, &normalsVAO);
glBindVertexArray(normalsVAO);
glBindBuffer(GL_ARRAY_BUFFER, normalsVBO);
glBufferData(GL_ARRAY_BUFFER, 2 * NUM_VERTICES * sizeof(NORMAL_POSITION), normalsPositions, GL_STATIC_DRAW);
//vertex position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//free malloced arrays
delete[] faces;
delete[] vertices;
delete[] normalsPerVertex;
delete[] usedVertices;
delete[] noisedVertices;
delete[] normalsPositions;
return;
}
void Planet::setupDrawParameters(){
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
//filled or wireframe triangles
if(showWireframe){
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
//glDisable(GL_CULL_FACE);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
void Planet::drawPlanet(){
// activate shader
planetShader->use();
planetShader->setVec3("objectColor", glm::vec3(0.4f, 0.4f, 0.4f));
planetShader->setVec3("lightColor", glm::vec3(1.0f, 1.0f, 1.0f));
planetShader->setVec3("lightPos", lightPos);
planetShader->setVec3("viewPos", camera->Position);
// set the model, view and projection matrix uniforms
planetShader->setMat4("model", model);
planetShader->setMat4("view", view);
planetShader->setMat4("projection", projection);
planetShader->setMat4("normalMat", normalMat);
glBindVertexArray(sphereVAO);
glBindBuffer(GL_ARRAY_BUFFER, sphereVBO);
//glBufferData(GL_ARRAY_BUFFER, NUM_VERTICES * sizeof(NOISED_VERTEX), noisedVertices, GL_DYNAMIC_DRAW);
// glDrawArrays(GL_TRIANGLES, 0, numTriangles);
glDrawElements(GL_TRIANGLES, NUM_FACES * sizeof(FACE), GL_UNSIGNED_INT, 0);
}
void Planet::drawOcean(){
// activate shader
oceanShader->use();
oceanShader->setVec3("lightColor", glm::vec3(1.0f, 1.0f, 1.0f));
oceanShader->setVec3("lightPos", lightPos);
oceanShader->setVec3("viewPos", camera->Position);
// set the model, view and projection matrix uniforms
oceanShader->setMat4("model", model);
oceanShader->setMat4("view", view);
oceanShader->setMat4("projection", projection);
oceanShader->setMat4("normalMat", normalMat);
oceanShader->setVec3("objectColor", glm::vec3(0.0f, 0.0f, 0.5f));
oceanShader->setFloat("time", (float)glfwGetTime()/100);
glBindVertexArray(oceanVAO);
glDrawElements(GL_TRIANGLES, NUM_FACES * sizeof(FACE), GL_UNSIGNED_INT, 0);
}
void Planet::drawNormals(){
// activate shader
normalsShader->use();
// set the model, view and projection matrix uniforms
normalsShader->setMat4("model", model);
normalsShader->setMat4("view", view);
normalsShader->setMat4("projection", projection);
normalsShader->setMat4("normalMat", normalMat);
glBindVertexArray(normalsVAO);
glDrawArrays(GL_LINES, 0, 2*numVertices);
}
void Planet::planetDraw(){
// per-frame time logic
// --------------------
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
setupDrawParameters();
glClearColor(0.7f, 0.7f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glm::mat4 lightPosTransform = glm::rotate(glm::mat4(1.0f),0.01f, glm::vec3(0.0f, -1.0f, 0.0f));
//lightPos = lightPosTransform * glm::vec4(lightPos,1.0f);
//create model, view and projection matrices
model = glm::rotate(glm::mat4(1.0f), (float)glfwGetTime()/5, glm::vec3(0.0f, 1.0f, 0.0f));
view = camera->GetViewMatrix();
projection = glm::perspective(glm::radians(camera->Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
normalMat = glm::transpose(glm::inverse(model));
drawPlanet();
if(showOcean)
drawOcean();
if(showNormals)
drawNormals();
}
void showFrameRate(){
static double previousTime;
static int frameCount;
double currentTime = glfwGetTime();
double deltaMs = (currentTime - previousTime) * 1000;
frameCount++;
if ( currentTime - previousTime >= 1.0 )
{
// Display the frame count here any way you want.
std::stringstream ss;
ss << "FPS: " << frameCount;
printf("FPS = %d\n", frameCount);
//glfwSetWindowTitle(window, ss.str().c_str());
frameCount = 0;
previousTime = currentTime;
}
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void Planet::processInput(int key, int action)
{
if (key == GLFW_KEY_W && action/* == GLFW_PRESS*/)
camera->ProcessKeyboard(FORWARD, deltaTime);
if (key == GLFW_KEY_S && action)
camera->ProcessKeyboard(BACKWARD, deltaTime);
if (key == GLFW_KEY_A && action)
camera->ProcessKeyboard(LEFT, deltaTime);
if (key == GLFW_KEY_D && action)
camera->ProcessKeyboard(RIGHT, deltaTime);
int cameraSpeed = 3.0f;
if (key == GLFW_KEY_LEFT && action)
camera->ProcessMouseMovement(-cameraSpeed, 0.0f);
if (key == GLFW_KEY_RIGHT && action)
camera->ProcessMouseMovement(cameraSpeed, 0.0f);
if (key == GLFW_KEY_UP && action)
camera->ProcessMouseMovement(0.0f, cameraSpeed);
if (key == GLFW_KEY_DOWN && action)
camera->ProcessMouseMovement(0.0f, -cameraSpeed);
}
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(char const * path)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
Planet::Planet() {
//init project
STATUS status = init();
if(status != OK)
{
cout << "init() failed at " << __FILE__ << ":" << __LINE__ << __FUNCTION__ << endl;
return;
}
planetShader = new Shader("shaders/planetShader2.vs", "shaders/planetShader2.fs"/*, "shaders/planetShader2.gs"*/);
oceanShader = new Shader("shaders/oceanShader.vs", "shaders/oceanShader.fs"/*, "shaders/planetShader2.gs"*/);
normalsShader = new Shader("shaders/normalsShader.vs", "shaders/normalsShader.fs"/*, "shaders/planetShader2.gs"*/);
camera = new Camera(glm::vec3(0.0f, 0.0f, 5.0f));
lightPos = vec3(0.0f, 0.0f, 8.0f);
perlinSeed = 1;
printf("perlinSeed = %d\n", perlinSeed);
detalization = 5;
noiseFrequency = 1.0f;
noiseAmplitude = 0.6f;
initializePlanet();
}<file_sep>/gui/example4.cpp
/*
src/example4.cpp -- C++ version of an example application that shows
how to use the OpenGL widget. For a Python implementation, see
'../python/example4.py'.
NanoGUI was developed by <NAME> <<EMAIL>>.
The widget drawing code is based on the NanoVG demo application
by <NAME>.
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE.txt file.
*/
#include "planet.h"
#include <nanogui/opengl.h>
#include <nanogui/glutil.h>
#include <nanogui/screen.h>
#include <nanogui/window.h>
#include <nanogui/layout.h>
#include <nanogui/label.h>
#include <nanogui/checkbox.h>
#include <nanogui/button.h>
#include <nanogui/toolbutton.h>
#include <nanogui/popupbutton.h>
#include <nanogui/combobox.h>
#include <nanogui/progressbar.h>
#include <nanogui/entypo.h>
#include <nanogui/messagedialog.h>
#include <nanogui/textbox.h>
#include <nanogui/slider.h>
#include <nanogui/imagepanel.h>
#include <nanogui/imageview.h>
#include <nanogui/vscrollpanel.h>
#include <nanogui/colorwheel.h>
#include <nanogui/graph.h>
#include <nanogui/tabwidget.h>
#include <nanogui/glcanvas.h>
#include <iostream>
#include <string>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::pair;
using std::to_string;
class MyGLCanvas : public nanogui::GLCanvas {
public:
MyGLCanvas(Widget *parent, Planet ** _planet) : nanogui::GLCanvas(parent) {
*_planet = planet = new Planet();
}
~MyGLCanvas() {}
virtual void drawGL() override {
planet->planetDraw();
//the widgets dotn't draw well if I dont return this back to GL_FILL
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
void toggleNormals(bool state) {
planet->toggleNormals(state);
}
void toggleOcean(bool state) {
planet->toggleOcean(state);
}
void toggleWireframe(bool state) {
planet->toggleWireframe(state);
}
int randomizePlanet(int detalization, float frequency, float amplitude) {
return planet->randomizePlanet(detalization, frequency, amplitude);
}
void setFrequency(float frequency) {
planet->setNoiseFrequency(frequency);
}
void setAmplitude(float amplitude) {
planet->setNoiseAmplitude(amplitude);
}
void setDetalization(int detalization) {
planet->setDetalization(detalization);
}
void setNoiseSeed(int seed) {
planet->setNoiseSeed(seed);
}
private:
Planet *planet;
};
class ExampleApplication : public nanogui::Screen {
public:
ExampleApplication() : nanogui::Screen(Eigen::Vector2i(1329, 889), "NanoGUI Test", false) {
using namespace nanogui;
Window *window = new Window(this, "Procedural Planets");
window->setPosition(Vector2i(0, 0));
window->setLayout(new BoxLayout(Orientation::Horizontal, Alignment::Middle, 0, 5));//new GroupLayout());
mCanvas = new MyGLCanvas(window, &planet);
mCanvas->setBackgroundColor({100, 100, 100, 255});
mCanvas->setSize({1000, 800});
//Tools widget
Widget *toolsWindow = new Window(this, "Tools");
//toolsWindow->setFixedSize(Vector2i(300,300));
toolsWindow->setPosition(Vector2i(1005, 0));
toolsWindow->setLayout(new GridLayout(Orientation::Horizontal, 1 , Alignment::Minimum, 0, 5));
new Label(toolsWindow, "Planet Parameters", "sans-bold", 20);
Widget *planetWidget = new Widget(toolsWindow);
planetWidget->setLayout(new GridLayout(Orientation::Horizontal, 2 , Alignment::Minimum, 0, 5));
/* detalization factor */
new Label(planetWidget, "Planet Detalization :", "sans");
auto intBox = new IntBox<int>(planetWidget);
intBox->setEditable(true);
intBox->setFixedSize(Vector2i(70, 20));
intBox->setValue(5);
intBox->setUnits("ui");
intBox->setDefaultValue("5");
intBox->setFontSize(16);
intBox->setFormat("[1-9][0-9]*");
intBox->setSpinnable(true);
intBox->setMinValue(0);
intBox->setValueIncrement(1);
intBox->setCallback([this](int value) { mCanvas->setDetalization(value); return true; });
/* FP frequency */
new Label(planetWidget, "Noise Frequency:", "sans");
auto frequencyTb = new FloatBox<float>(planetWidget);
frequencyTb->setEditable(true);
frequencyTb->setFixedSize(Vector2i(70, 20));
frequencyTb->setValue(1.0f);
frequencyTb->setUnits("uf");
frequencyTb->setDefaultValue("1.0");
frequencyTb->setFontSize(16);
frequencyTb->setFormat("[0-9]*\\.?[0-9]+");
frequencyTb->setSpinnable(true);
frequencyTb->setMinValue(0);
frequencyTb->setValueIncrement(0.1f);
frequencyTb->setCallback([this](float value) { mCanvas->setFrequency(value); return true; });
/* FP amplitude */
new Label(planetWidget, "Noise Amplitude:", "sans");
auto amplitudeTb = new FloatBox<float>(planetWidget);
amplitudeTb->setEditable(true);
amplitudeTb->setFixedSize(Vector2i(70, 20));
amplitudeTb->setValue(0.6f);
amplitudeTb->setUnits("uf");
amplitudeTb->setDefaultValue("0.6");
amplitudeTb->setFontSize(16);
//amplitudeTb->setFormat("[-]?[0-9]*\\.?[0-9]+");
amplitudeTb->setFormat("[0-9]*\\.?[0-9]+");
amplitudeTb->setSpinnable(true);
amplitudeTb->setMinValue(0);
amplitudeTb->setValueIncrement(0.1f);
amplitudeTb->setCallback([this](float value) { mCanvas->setAmplitude(value); return true; });
/* noise seed */
new Label(planetWidget, "Noise seed :", "sans");
auto seedIB = new IntBox<int>(planetWidget);
seedIB->setEditable(true);
seedIB->setFixedSize(Vector2i(70, 20));
seedIB->setValue(1);
seedIB->setUnits("ui");
seedIB->setDefaultValue("1");
seedIB->setFontSize(16);
seedIB->setFormat("[1-9][0-9]*");
seedIB->setCallback([this](int value) { mCanvas->setNoiseSeed(value); return true; });
Button *genPlanetBtn = new Button(toolsWindow, "RandomizePlanet");
genPlanetBtn->setCallback([this, intBox, frequencyTb, amplitudeTb, seedIB]() { int newSeed = mCanvas->randomizePlanet(intBox->value(), frequencyTb->value(), amplitudeTb->value()); seedIB->setValue(newSeed); });
new Label(toolsWindow, " ", "sans-bold", 20);
new Label(toolsWindow, "Draw Parameters", "sans-bold", 20);
Button *b0 = new Button(toolsWindow, "Show normals");
b0->setFlags(Button::ToggleButton);
b0->setChangeCallback([this](bool state) { mCanvas->toggleNormals(state); });
Button *b1 = new Button(toolsWindow, "Show ocean");
b1->setFlags(Button::ToggleButton);
b1->setPushed(true);
b1->setChangeCallback([this](bool state) { mCanvas->toggleOcean(state); });
Button *b2 = new Button(toolsWindow, "Show wireframe");
b2->setFlags(Button::ToggleButton);
b2->setChangeCallback([this](bool state) { mCanvas->toggleWireframe(state); });
performLayout();
}
virtual bool keyboardEvent(int key, int scancode, int action, int modifiers) {
if (Screen::keyboardEvent(key, scancode, action, modifiers))
return true;
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
setVisible(false);
return true;
}
switch(key){
case GLFW_KEY_W:
case GLFW_KEY_S:
case GLFW_KEY_A:
case GLFW_KEY_D:
case GLFW_KEY_LEFT:
case GLFW_KEY_RIGHT:
case GLFW_KEY_UP:
case GLFW_KEY_DOWN:
planet->processInput(key, action);
}
return false;
}
virtual void draw(NVGcontext *ctx) {
/* Draw the user interface */
Screen::draw(ctx);
}
private:
MyGLCanvas *mCanvas;
Planet *planet;
};
int main(int /* argc */, char ** /* argv */) {
try {
nanogui::init();
/* scoped variables */ {
nanogui::ref<ExampleApplication> app = new ExampleApplication();
app->drawAll();
app->setVisible(true);
nanogui::mainloop();
}
nanogui::shutdown();
} catch (const std::runtime_error &e) {
std::string error_msg = std::string("Caught a fatal error: ") + std::string(e.what());
#if defined(_WIN32)
MessageBoxA(nullptr, error_msg.c_str(), NULL, MB_ICONERROR | MB_OK);
#else
std::cerr << error_msg << endl;
#endif
return -1;
}
return 0;
}
<file_sep>/gui/demo.cpp
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
int demo()
{
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
//scene initialization
unsigned int vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
//check shader compilation errors
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
unsigned int fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
//check shader compilation errors
success;
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
//link the shaders
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
//check linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if(!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::LINKING_FAILED\n" << infoLog << std::endl;
}
//delete the shader objects after we linked them into the program
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
//use the linked shaders
glUseProgram(shaderProgram);
//define the attributes for the shaders
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f // top left
};
unsigned int indices[] = { // note that we start from 0!
0, 1, 3, // first Triangle
1, 2, 3 // second Triangle
};
unsigned int VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//filled or wireframe triangles
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
{
// render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
//draw the object
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
//glDrawArrays(GL_TRIANGLES, 0, 3);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
return 0;
}
| 634a359d166a1969ef6298e4f5bf1d8fbec4b877 | [
"Markdown",
"Makefile",
"C++",
"Shell"
] | 12 | C++ | edikar/LearnOpenGL | 5e10b1b607da5028350a5855506790a5cefee700 | e2a03313437296945c398cc5e02a055812f4cae8 |
refs/heads/master | <file_sep>import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { getCountries } from "../actions/index";
class SearchBar extends Component {
constructor(props) {
super(props)
this.state = {
selectedCountry: this.props.defaultCountry,
searchCountry: "",
placeHolder: "Search a Country",
intervalBeforeRequest: 1000,
lockRequest: false
}
}
componentWillMount() {
this.props.getCountries();
}
renderSearchBar() {
const { countries } = this.props;
if (countries) {
return (
<div>
<input
// value={this.state.selectedCountry}
onChange={(event) => this.handleChange(event)}
placeholder={this.state.placeHolder}
className="col-sm-4 input-group"
></input>
<span className="col-sm-2 input-group-btn">
<button className="btn btn-secondary"
onClick={(event)=> this.handleOnClick(event)}>Search
</button>
</span>
</div>
);
} else {
return <div>No Country found</div>;
}
}
handleChange(event) {
this.setState({ searchCountry: event.target.value })
if(!this.state.lockRequest){
this.setState({lockRequest: true})
setTimeout(function(){this.search()}.bind(this), this.state.intervalBeforeRequest)
}
}
handleOnClick(event){
this.props.callback(this.state.searchCountry)
this.search(event)
}
search(e)
{
// this.props.callback(this.state.searchCountry)
this.setState({lockRequest: false})
this.setState({ selectedCountry: e.target.value },()=>{
this.props.getMortality(this.state.selectedCountry)
});
}
render() {
return (
<div className="searchBar">
{this.renderSearchBar()}
</div>
)
}
}
const mapStateToProps = (state) => {
return { countries: state.countries };
};
function mapDispatchToProps(dispatch) {
return bindActionCreators({ getCountries }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
<file_sep>import React from 'react'
import Flag from './flag'
import { ColumnChart } from 'react-chartkick';
window.Chart = require('chart.js');
const xTitle = "Age";
const yTitle = "% Mortalité"
const MortalityListItem = ({mortality}) => {
const formatedDataMale = formatMortalityData(mortality.male)
const formatedDataFemale = formatMortalityData(mortality.female)
return (
<tr>
<td><Flag country ={mortality.country} className="flag_medium"></Flag></td>
<td className="col-md-6"><ColumnChart xtitle={xTitle} ytitle={yTitle}data={formatedDataMale} max={28}/></td>
<td className="col-md-6"><ColumnChart xtitle={xTitle} ytitle={yTitle}data={formatedDataFemale} max={28}/></td>
</tr>
)
}
function formatMortalityData(mortality){
const filteredData= mortality.filter((data) =>{
if(data.age>=131){
return false
}else{
return data
}
})
const array = filteredData.map((data) => {
return[Number((data.age).toFixed(0)), Number((data.mortality_percent).toFixed(3))]
})
return array;
}
export default MortalityListItem | 76ab73b6569b934a5af7aa1f920e35972046636c | [
"JavaScript"
] | 2 | JavaScript | jsdelivrbot/ReactStarter-Population | 80a2fa3cb67bb75b2b4e18e71c9433c5814d5e7e | 4c723c04d0ac2fa60f6e15afb4b752592ac5dea1 |
refs/heads/master | <file_sep>#ifndef __DATABASE_PERSIAN_H__
#define __DATABASE_PERSIAN_H__
#include "PersianDefine.h"
#include "IDatabase.h"
#include "QueueCondition.h"
#include <boost/thread.hpp>
#include <boost/date_time.hpp>
#include <Poco/Data/MySQL/Connector.h>
#include <Poco/Data/DataException.h>
template<typename TData>
class DatabasePersian : public IDatabase<TData>, public IPlugin
{
public:
typedef std::shared_ptr<TData> data_ptr;
typedef std::shared_ptr<QueueCondition<std::function<void (database_ptr)>> > queue_ptr;
virtual bool start() {
m_pQueue = queue_ptr(new queue_ptr::element_type);
m_Thread = boost::thread(std::bind(DatabasePersian::handleThread, m_pQueue));
return IPlugin::start();
};
virtual void stop() {
m_Thread.interrupt();
};
virtual void afterStop() {
m_Thread.timed_join(boost::posix_time::seconds(2));
};
virtual data_ptr query(boost::asio::yield_context yield, fun_type fun) {
return queryDatabase(yield, fun, m_pQueue);
};
virtual void exec(boost::asio::yield_context yield, const std::string sql) {
queryDatabase<data_ptr::element_type, database_ptr::element_type, queue_ptr::element_type>(
yield, std::bind(DatabasePersian::funSql, std::placeholders::_1, sql), m_pQueue);
};
protected:
static data_ptr funSql(database_ptr pSession, const std::string sql) {
if (!pSession)
{
return data_ptr();
}
(*pSession) << sql;
return data_ptr();
};
static void handleThread(queue_ptr pQueue) {
if (!pQueue)
{
return;
}
while (true)
{
try {
Poco::Data::MySQL::Connector::registerConnector();
// create a session
database_ptr pDatabase(new database_ptr::element_type(Poco::Data::MySQL::Connector::KEY
, "host=127.0.0.1;user=root;password=<PASSWORD>;db=sakila;compress=true;auto-reconnect=true;protocol=tcp"));
int count = 0;
(*pDatabase) << "select count(*) from city;", into(count), now;
std::cout << "database:" << boost::this_thread::get_id() << count << std::endl;
while (true)
{
auto fun = pQueue->pop();
if (!fun)
{
continue;
}
fun(pDatabase);
}
}
catch (boost::thread_interrupted&) {
break;
}
catch (Poco::Data::DataException& e) {
auto c = e.displayText();
std::cout << e.displayText() << std::endl;
}
catch (std::exception& e) {
auto c = e.what();
std::cout << e.what() << std::endl;
}
}
};
queue_ptr m_pQueue;
boost::thread m_Thread;
};
#endif
<file_sep>#ifndef __PERSIAN_DEFINE_H__
#define __PERSIAN_DEFINE_H__
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/function.hpp>
#include <functional>
#include <memory>
#include <vector>
typedef std::shared_ptr<boost::asio::io_service> ServicePtr;
typedef std::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr;
typedef std::shared_ptr<std::vector<unsigned char> > FramePtr;
typedef std::shared_ptr<boost::property_tree::ptree> TreePtr;
//////////////////////////////////////
class IPlugin {
public:
virtual bool beforeStart() { return true; };
virtual bool start() { return true; };
virtual bool afterStart() { return true; };
virtual void beforeStop() {};
virtual void stop() {};
virtual void afterStop() {};
};
typedef std::shared_ptr<IPlugin> IPluginPtr;
////////////////////////////////////
class IServerNet {
public:
virtual void setPort(const int port) = 0;
};
typedef std::shared_ptr<IServerNet> IServerNetPtr;
//////////////////////////////////////
template<typename TData>
class RequestBase {
public:
FramePtr pFrame;
std::string Route;
std::shared_ptr<TData> pData;
unsigned int Seq;
};
typedef RequestBase<TreePtr::element_type> RequestPersian;
typedef std::shared_ptr<RequestBase<TreePtr::element_type> > RequestPersianPtr;
template<typename TData>
class ResponseBase : public RequestBase<TData> {
public:
};
typedef ResponseBase<TreePtr::element_type> ResponsePersian;
typedef std::shared_ptr<ResponsePersian> ResponsePersianPtr;
/////////////////////////////////////////
template<typename TData>
class IProtocol {
public:
virtual bool encode(std::shared_ptr<RequestBase<TData> > pRequest) = 0;
virtual bool decode(std::shared_ptr<ResponseBase<TData> > pResponse) = 0;
};
///////////////////////////////////////////
template<typename TReturn, typename TDatabase, typename TQueue>
auto queryDatabase(boost::asio::yield_context yield, std::function<std::shared_ptr<TReturn>(std::shared_ptr<TDatabase>)> fun, std::shared_ptr<TQueue> pQueue) {
using db_ptr = std::shared_ptr<TDatabase>;
using completion_type = boost::asio::async_completion<boost::asio::yield_context, void(std::shared_ptr<TReturn>)>;
completion_type completion{ yield };
auto handler = completion.completion_handler;
std::function<void(db_ptr)> proxy = std::bind([handler, fun](db_ptr d) {
auto result = fun(d);
using boost::asio::asio_handler_invoke;
asio_handler_invoke(std::bind(handler, result), &handler);
}, std::placeholders::_1);
pQueue->push(proxy);
return completion.result.get();
};
/////////////////////////////////////////////
#endif // !__PERSIAN_DEFINE_H__
<file_sep>#pragma warning(disable:4996)
#include "stdafx.h"
#include "DatabasePersian.h"
<file_sep>#ifndef __SERVER_PERSIAN_H__
#define __SERVER_PERSIAN_H__
#include <map>
#include <atomic>
#include <boost/asio.hpp>
#include "PersianDefine.h"
#include "IProcessor.h"
#include "IContext.h"
#include "ContextPersian.h"
class InfoRoute {
public:
std::string Route;
SocketPtr pSocket;
boost::asio::ip::tcp::endpoint Point;
};
typedef std::shared_ptr<InfoRoute> InfoRoutePtr;
template<typename TData>
class ServerPersian : public IServerNet, public IPlugin, public IProcessor<TData>, public IContextProxy<TData>, public std::enable_shared_from_this<ServerPersian<TData> >
{
public:
typedef std::shared_ptr<TData> data_ptr;
typedef std::function<void (data_ptr)> call_seq;
typedef std::shared_ptr<boost::asio::ip::tcp::acceptor> acceptor_ptr;
typedef std::shared_ptr<ContextPersian<TData> > context_ptr;
typedef std::shared_ptr<RequestBase<TData> > request_ptr;
typedef std::shared_ptr<ResponseBase<TData> > response_ptr;
typedef std::shared_ptr<IProtocol<TData> > protocol_ptr;
#define FRAME_MAX 256
virtual bool start() {
m_bStop = false;
if (65536 < m_Port || 0 >= m_Port) {
return false;
}
try {
ServicePtr pService = m_pService;
if (!pService) {
return false;
}
boost::asio::ip::tcp::endpoint point;
if (!m_Address.empty())
{
point = boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(m_Address), m_Port);
}
else {
point = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), m_Port);
}
acceptor_ptr pAcceptor(new acceptor_ptr::element_type(*pService, point));
boost::asio::spawn(*pService, std::bind(&ServerPersian<TData>::createServer, shared_from_this(), std::placeholders::_1, pAcceptor));
}
catch (std::exception&) {
return false;
}
return true;
};
virtual void stop() {
m_bStop = true;
};
virtual bool addListen(const std::string& tag, fun_route fun) {
auto Iter = m_MapCallback.find(tag);
if (m_MapCallback.end() == Iter) {
Iter = m_MapCallback.insert(std::make_pair(tag, std::vector<fun_route>())).first;
}
Iter->second.push_back(fun);
return true;
};
virtual void setPort(const int port) {
m_Port = port;
};
virtual void setAddress(const std::string& address) {
m_Address = address;
};
virtual void setService(ServicePtr pService) {
m_pService = pService;
};
virtual void setProtocol(protocol_ptr pProtocol) {
m_pProtocol = pProtocol;
};
virtual bool write(boost::asio::yield_context yield, data_ptr pData, const std::string route, SocketPtr pSocket) {
request_ptr pRequest(new request_ptr::element_type);
pRequest->pData = pData;
if (m_pProtocol && !m_pProtocol->encode(pRequest)) {
return false;
}
boost::system::error_code ec;
pSocket->async_write_some(boost::asio::buffer(*(pRequest->pFrame), pRequest->pFrame->size()), yield[ec]);
if (ec) {
return false;
}
return true;
};
virtual bool write(boost::asio::yield_context yield, data_ptr pData, const std::string route) {
auto Iter = m_MapRoute.find(route);
if (m_MapRoute.end() == Iter || !(Iter->second->pSocket)) {
return false;
}
return write(yield, pData, route, Iter->second->pSocket);
};
virtual bool writeAndWait(boost::asio::yield_context yield, data_ptr pDataWrite, const std::string route, SocketPtr pSocket, data_ptr& pDataRead) {
request_ptr pRequest(new request_ptr::element_type);
pRequest->pData = pDataWrite;
pRequest->Seq = getSeq();
if (m_pProtocol && !m_pProtocol->encode(pRequest)) {
return false;
}
boost::system::error_code ec;
pSocket->async_write_some(boost::asio::buffer(*(pRequest->pFrame), pRequest->pFrame->size()), yield[ec]);
if (ec) {
return false;
}
pDataRead = wait<void(data_ptr), boost::asio::yield_context, data_ptr::element_type>(yield, pRequest->Seq);
return true;
};
virtual bool writeAndWait(boost::asio::yield_context yield, data_ptr pDataWrite, const std::string route, data_ptr& pDataRead) {
auto Iter = m_MapRoute.find(route);
if (m_MapRoute.end() == Iter || !(Iter->second->pSocket)) {
return false;
}
return writeAndWait(yield, pDataWrite, route, Iter->second->pSocket, pDataRead);
};
virtual bool wait(boost::asio::yield_context yield, boost::posix_time::time_duration time) {
boost::asio::deadline_timer timer(*m_pService, time);
boost::system::error_code ec;
timer.async_wait(yield[ec]);
return true;
};
protected:
virtual void readFrame(FramePtr pFrame, unsigned int count, SocketPtr pSocket) {
response_ptr pResponse(new response_ptr::element_type);
pResponse->pFrame = FramePtr(new FramePtr::element_type(pFrame->begin(), pFrame->begin() + count));
if (m_pProtocol && !m_pProtocol->decode(pResponse)) {
return;
}
auto Iter = m_MapCallback.find(pResponse->Route);
if (m_MapCallback.end() == Iter) {
return;
}
auto that = shared_from_this();
auto funs = Iter->second;
boost::asio::spawn(pSocket->get_io_service(), [pSocket, that, funs, pResponse](boost::asio::yield_context yield) {
context_ptr pContext(new context_ptr::element_type(pSocket, that, pResponse->Route, yield));
for (auto fun : funs) {
fun(pContext, pResponse->pData);
}
});
};
virtual unsigned int getSeq() {
return ++m_Seq;
};
virtual void connectServer(boost::asio::yield_context yield, InfoRoutePtr pInfo) {
FramePtr pFrame(new FramePtr::element_type);
pFrame->resize(FRAME_MAX);
while (!m_bStop) {
boost::system::error_code ec;
auto count = pInfo->pSocket->async_read_some(boost::asio::buffer(*pFrame, FRAME_MAX), yield[ec]);
if (ec) {
break;
}
response_ptr pResponse(new response_ptr::element_type);
pResponse->pFrame = FramePtr(new FramePtr::element_type(pFrame->begin(), pFrame->begin() + count));
if (m_pProtocol && !m_pProtocol->decode(pResponse)) {
continue;
}
auto Iter = m_MapCallSeq.find(pResponse->Seq);
if (m_MapCallSeq.end() == Iter) {
continue;
}
(Iter->second)(pResponse->pData);
}
};
virtual void readServer(boost::asio::yield_context yield, SocketPtr pSocket) {
FramePtr pFrame(new FramePtr::element_type);
pFrame->resize(FRAME_MAX);
while (!m_bStop) {
boost::system::error_code ec;
auto count = pSocket->async_read_some(boost::asio::buffer(*pFrame, FRAME_MAX), yield[ec]);
if (ec) {
break;
}
response_ptr pResponse(new response_ptr::element_type);
pResponse->pFrame = FramePtr(new FramePtr::element_type(pFrame->begin(), pFrame->begin() + count));
if (m_pProtocol && !m_pProtocol->decode(pResponse)) {
continue;
}
auto Iter = m_MapCallSeq.find(pResponse->Seq);
if (m_MapCallSeq.end() == Iter) {
continue;
}
(Iter->second)(pResponse->pData);
}
};
virtual void createServer(boost::asio::yield_context yield, acceptor_ptr pAcceptor) {
while (true) {
SocketPtr pSocket(new SocketPtr::element_type(pAcceptor->get_io_service()));
boost::system::error_code ec;
pAcceptor->async_accept(*pSocket, yield[ec]);
if (ec) {
std::cout << ec.message() << std::endl;
break;
}
boost::asio::spawn(pSocket->get_io_service(), std::bind(&ServerPersian<TData>::createSocket, shared_from_this(), std::placeholders::_1, pSocket));
}
};
virtual void createSocket(boost::asio::yield_context yield, SocketPtr pSocket) {
FramePtr pFrame(new FramePtr::element_type);
pFrame->resize(FRAME_MAX);
while (true) {
boost::system::error_code ec;
auto count = pSocket->async_read_some(boost::asio::buffer(*pFrame, FRAME_MAX), yield[ec]);
if (ec) {
break;
}
readFrame(pFrame, count, pSocket);
}
};
template <typename Signature, typename CompletionToken, typename TD>
auto wait(CompletionToken token, int index) {
using completion_type = boost::asio::async_completion<CompletionToken, Signature>;
completion_type completion{ token };
auto handler = completion.completion_handler;
std::function<void(std::shared_ptr<TD>)> fun = std::bind([handler](std::shared_ptr<TD> pd) {
using boost::asio::asio_handler_invoke;
asio_handler_invoke(std::bind(handler, pd), &handler);
}, std::placeholders::_1);
m_MapCallSeq.insert(std::make_pair(index, fun));
return completion.result.get();
};
std::map<std::string, std::vector<fun_route> > m_MapCallback;
std::map<std::string, InfoRoutePtr> m_MapRoute;
protocol_ptr m_pProtocol;
std::atomic_uint16_t m_Seq;
std::map<int, call_seq> m_MapCallSeq;
ServicePtr m_pService;
std::atomic_bool m_bStop;
int m_Port;
std::string m_Address;
};
#endif // !__SERVER_PERSIAN_H__
<file_sep>#ifndef __TEST_COROUTINE_H__
#define __TEST_COROUTINE_H__
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/coroutine2/all.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <string>
#include<vector>
class testCoroutine
{
public:
typedef boost::shared_ptr<boost::asio::io_service> service_ptr;
typedef boost::shared_ptr<boost::asio::ip::tcp::acceptor> acceptor_ptr;
typedef boost::shared_ptr<boost::asio::ip::tcp::socket> socket_ptr;
typedef boost::coroutines2::asymmetric_coroutine<void> coroutine_type;
typedef boost::shared_ptr<std::vector<unsigned char> > frame_ptr;
typedef boost::shared_ptr<coroutine_type::push_type> push_ptr;
typedef boost::shared_ptr<coroutine_type::pull_type> pull_ptr;
virtual bool start();
std::map<int, std::function<void(int)> > m_MapCallback;
protected:
virtual void createServer(service_ptr pService);
virtual void createClient(service_ptr pService);
template<typename Handler>
void wait(boost::asio::io_service &io, Handler & handler, int index) {
typename boost::asio::handler_type<Handler, void(int)>::type handler_(std::forward<Handler>(handler));
boost::asio::async_result<decltype(handler_)> result(handler_);
m_MapCallback.insert(std::make_pair(index, handler_));
return result.get();
};
template<typename T>
static void test(T param, int tag) {
(*param)(tag);
}
/*
int wait(boost::asio::io_service& service, boost::asio::yield_context yield, int index) {
typedef boost::asio::handler_type<decltype(yield), void(int)>::type ResultSetter;
auto result_setter(std::make_shared<ResultSetter>(yield));
boost::asio::async_result<ResultSetter> result_getter(*result_setter);
std::function<void(int)> fun = std::bind(testCoroutine::test<std::shared_ptr<ResultSetter> >, result_setter, std::placeholders::_1);
m_MapCallback.insert(std::make_pair(index, fun));
return result_getter.get();
};
*/
template <typename Signature, typename CompletionToken>
auto wait3(CompletionToken token, int index) {
using completion_type = boost::asio::async_completion<CompletionToken, Signature>;
completion_type completion{ token };
auto handler = completion.completion_handler;
std::function<void(int)> fun = std::bind([handler](int v) {
using boost::asio::asio_handler_invoke;
asio_handler_invoke(std::bind(handler, v), &handler);
}, std::placeholders::_1);
m_MapCallback.insert(std::make_pair(index, fun));
return completion.result.get();
};
acceptor_ptr m_pAcceptor;
socket_ptr m_pSocket;
service_ptr m_pService;
};
typedef boost::shared_ptr<testCoroutine> testCoroutinePtr;
#endif
<file_sep>#ifndef __IPROCESSOR_H__
#define __IPROCESSOR_H__
#include <memory>
#include <functional>
#include <string>
#include <vector>
#include "IContext.h"
#include "PersianDefine.h"
template<typename TData>
class IProcessor {
public:
typedef std::function<void(std::shared_ptr<IContext<TData> >, std::shared_ptr<TData>)> fun_route;
virtual bool addListen(const std::string& tag, fun_route fun) = 0;
};
#endif // !__IPROCESSOR_H__
<file_sep>// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "testCoroutine.h"
#include "../persian/ServerPersian.h"
#include "../persian/PersianDefine.h"
#include "../persian/DatabasePersian.cpp"
#include <Poco/Data/DataException.h>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time.hpp>
//#pragma comment (lib,"oci.lib")
using namespace Poco::Data::Keywords;
void run(ServicePtr pService) {
try {
std::cout <<"run:"<< boost::this_thread::get_id() << std::endl;
boost::asio::io_service::work work(*pService);
pService->run();
}
catch (Poco::Data::DataException& e) {
auto c = e.displayText();
std::cout << e.displayText() << std::endl;
}
catch (std::exception& e) {
auto c = e.what();
std::cout << e.what() << std::endl;
}
};
int main()
{
typedef std::shared_ptr<boost::property_tree::ptree>TreePtr;
ServicePtr pService(new ServicePtr::element_type);
typedef std::shared_ptr<ServerPersian<TreePtr::element_type> > ServerPersianPtr;
ServerPersianPtr pServerPersian(new ServerPersianPtr::element_type);
pServerPersian->setPort(1234);
pServerPersian->setService(pService);
/*
if (!pServerPersian->start() || !pServerTcp->start()) {
return -1;
}
*/
typedef std::shared_ptr<DatabasePersian<TreePtr::element_type> > DatabasePersianPtr;
DatabasePersianPtr pDatabase(new DatabasePersianPtr::element_type);
pDatabase->start();
std::cout << "main:" << boost::this_thread::get_id() << std::endl;
boost::asio::spawn(*pService, [pDatabase, pService](boost::asio::yield_context yield) {
std::cout <<"spawn:"<< boost::this_thread::get_id() << std::endl;
auto pData = pDatabase->query(yield, [](DatabasePersianPtr::element_type::database_ptr pSession) {
int count = 0;
Poco::Nullable<int> c;
(*pSession) << "select count(*) from city", into(c), now;
if (c.isNull()) {
std::cout <<boost::this_thread::get_id()<< " null" << std::endl;
}
else {
std::cout << boost::this_thread::get_id() << c.value() << std::endl;
}
TreePtr pTree(new TreePtr::element_type);
pTree->put("root.count", count);
return pTree;
});
int count = pData->get("root.count", -1);
std::cout << boost::this_thread::get_id() << " count:" << count << std::endl;
pService->post([pDatabase, pService]() {
std::cout << "post2:" << boost::this_thread::get_id() << std::endl;
boost::asio::spawn(*pService, [pDatabase] (boost::asio::yield_context yield){
std::cout << "spawn2:" << boost::this_thread::get_id() << std::endl;
auto pData = pDatabase->query(yield, [](DatabasePersianPtr::element_type::database_ptr pSession) {
std::cout << "query2:" << boost::this_thread::get_id() << std::endl;
return TreePtr();
});
std::cout << "data2:" << boost::this_thread::get_id() << std::endl;
});
});
});
boost::thread(std::bind(run, pService));
boost::this_thread::sleep(boost::posix_time::seconds(10));
pService->stop();
pDatabase->stop();
pDatabase->afterStop();
return 0;
}
<file_sep>#ifndef __QUEUE_CONDITION_H__
#define __QUEUE_CONDITION_H__
#include <memory>
#include <condition_variable>
#include <mutex>
#include <list>
#include <chrono>
template<typename T>
class QueueCondition {
public:
typedef std::shared_ptr<QueueCondition<T> > c_ptr;
QueueCondition<T>():m_bStop(false) {
};
virtual T pop() {
std::unique_lock <std::mutex> lock(m_Mutex);
while (!m_bStop && m_Queue.empty()) {
m_Condition.wait(lock);
}
if (m_bStop)
{
return T();
}
auto data = m_Queue.front();
m_Queue.pop_front();
return data;
};
virtual T popBySeconds(long time) {
std::unique_lock <std::mutex> lock(m_Mutex);
if (!m_bStop && m_Queue.empty()) {
m_Condition.wait_for(lock, std::chrono::seconds(time));
}
if (m_bStop || m_Queue.empty()) {
return T();
}
auto data = m_Queue.front();
m_Queue.pop_front();
return data;
};
virtual void push(T data) {
if (m_bStop)
{
return;
}
{
std::unique_lock<std::mutex> lock(m_Mutex);
m_Queue.push_back(data);
lock.unlock();
}
m_Condition.notify_one();
};
virtual void stop() {
m_bStop = true;
};
virtual bool isStop() {
return m_bStop;
};
protected:
std::list<T> m_Queue;
std::mutex m_Mutex;
std::condition_variable m_Condition;
std::atomic_bool m_bStop;
};
#endif // !__QUEUE_CONDITION_H__
<file_sep>#ifndef __CONTEXT_PERSIAN_H__
#define __CONTEXT_PERSIAN_H__
#include "IContext.h"
#include "PersianDefine.h"
#include <boost/asio/spawn.hpp>
template<typename TData>
class ContextPersian : public IContext<TData>
{
public:
typedef std::shared_ptr<IContextProxy<TData> > proxy_ptr;
ContextPersian(SocketPtr pSocket, proxy_ptr pProxy, std::string route, boost::asio::yield_context& yield)
:m_pSocket(pSocket), m_pProxy(pProxy), m_Route(route), m_Yield(yield)
{
};
ContextPersian(ContextPersian& context, boost::asio::yield_context& yield)
: ContextPersian(context.m_pSocket, context.m_pProxy, context.m_Route, yield)
{
};
virtual bool write(data_ptr pData) {
if (!m_pProxy) {
return false;
}
return m_pProxy->write(m_Yield, pData, m_Route, m_pSocket);
};
virtual bool writeAndWait(data_ptr pDataWrite, data_ptr& pDataRead) {
if (!m_pProxy) {
return false;
}
return m_pProxy->writeAndWait(m_Yield, pDataWrite, m_Route, m_pSocket, pDataRead);
};
virtual bool write(data_ptr pData, const std::string route) {
if (!m_pProxy) {
return false;
}
return m_pProxy->write(m_Yield, pData, route);
};
virtual bool writeAndWait(data_ptr pDataWrite, const std::string route, data_ptr& pDataRead) {
if (!m_pProxy) {
return false;
}
return m_pProxy->writeAndWait(m_Yield, pDataWrite, route, pDataRead);
};
virtual bool wait(boost::posix_time::time_duration time) {
if (!m_pProxy) {
return false;
}
return m_pProxy->wait(m_Yield, time);
};
virtual bool waitBySeconds(const long time) {
if (!m_pProxy) {
return false;
}
return m_pProxy->wait(m_Yield, boost::posix_time::seconds(time));
};
protected:
SocketPtr m_pSocket;
proxy_ptr m_pProxy;
boost::asio::yield_context m_Yield;
std::string m_Route;
};
#endif // !__CONTEXT_PERSIAN_H__
<file_sep>#ifndef __ICONTEXT_H__
#define __ICONTEXT_H__
#include <memory>
#include <string>
#include <boost/date_time.hpp>
#include <boost/asio/spawn.hpp>
#include "PersianDefine.h"
template<typename TData>
class IContextProxy {
public:
typedef std::shared_ptr<TData> data_ptr;
virtual bool write(boost::asio::yield_context yield, data_ptr pData, const std::string route, SocketPtr pSocket) = 0;
virtual bool write(boost::asio::yield_context yield, data_ptr pData, const std::string route) = 0;
virtual bool writeAndWait(boost::asio::yield_context yield, data_ptr pDataWrite, const std::string route, SocketPtr pSocket, data_ptr& pDataRead) = 0;
virtual bool writeAndWait(boost::asio::yield_context yield, data_ptr pDataWrite, const std::string route, data_ptr& pDataRead) = 0;
virtual bool wait(boost::asio::yield_context yield, boost::posix_time::time_duration time) = 0;
};
template<typename TData>
class IContext {
public:
typedef std::shared_ptr<TData> data_ptr;
virtual bool write(data_ptr pData) = 0;
virtual bool writeAndWait(data_ptr pDataWrite, data_ptr& pDataRead) = 0;
virtual bool write(data_ptr pData, const std::string route) = 0;
virtual bool writeAndWait(data_ptr pDataWrite, const std::string route, data_ptr& pDataRead) = 0;
virtual bool wait(boost::posix_time::time_duration time) = 0;
virtual bool waitBySeconds(const long time) = 0;
};
#endif // !__ICONTEXT_H__
<file_sep>========================================================================
控制台应用程序:persian 项目概述
========================================================================
应用程序向导已为您创建了此 persian 应用程序。
本文件概要介绍组成 persian 应用程序的每个文件的内容。
persian.vcxproj
这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。
persian.vcxproj.filters
这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。
persian.cpp
这是主应用程序源文件。
/////////////////////////////////////////////////////////////////////////////
其他标准文件:
StdAfx.h, StdAfx.cpp
这些文件用于生成名为 persian.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。
/////////////////////////////////////////////////////////////////////////////
其他注释:
应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。
/////////////////////////////////////////////////////////////////////////////
<file_sep>#ifndef __ILOG_H__
#define __ILOG_H__
#define LOG_ERROR() {}
#endif // !__ILOG_H__
<file_sep>#ifndef __PERSIAN_H__
#define __PERSIAN_H__
#include "IPlugin.h"
#endif // !__PERSIAN_H__
<file_sep>#ifndef __IDATABASE_H__
#define __IDATABASE_H__
#include <Poco/Data/Session.h>
#include "PersianDefine.h"
template<typename TData>
class IDatabase {
public:
typedef std::shared_ptr<Poco::Data::Session> database_ptr;
typedef std::function<std::shared_ptr<TData>(database_ptr)> fun_type;
virtual std::shared_ptr<TData> query(boost::asio::yield_context yield, fun_type fun) = 0;
virtual void exec(boost::asio::yield_context yield, const std::string sql) = 0;
};
#endif
<file_sep>#ifndef __IPLUGIN_H__
#define __IPLUGIN_H__
#include <memory>
#endif // !__IPLUGIN_H__
<file_sep>#include "stdafx.h"
#include "testCoroutine.h"
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <iostream>
#define FRAME_MAX 256
bool testCoroutine::start()
{
service_ptr pService(new boost::asio::io_service());
m_pService = pService;
pService->post(std::bind(&testCoroutine::createServer, this, pService));
pService->post(std::bind(&testCoroutine::createClient, this, pService));
std::thread([](service_ptr pService) {
boost::asio::io_service::work work(*pService);
pService->run();
}, pService).detach();
return true;
}
void testCoroutine::createServer(service_ptr pService)
{
boost::asio::spawn(*pService, [pService](boost::asio::yield_context yield) {
boost::asio::ip::tcp::endpoint point(boost::asio::ip::tcp::v4(), 1234);
acceptor_ptr pAcceptor(new acceptor_ptr::element_type(*pService, point));
while (true) {
socket_ptr pSocket(new socket_ptr::element_type(pAcceptor->get_io_service()));
boost::system::error_code ec;
pAcceptor->async_accept(*pSocket, yield[ec]);
if (ec) {
std::cout << ec.message() << std::endl;
continue;
}
boost::asio::spawn(pSocket->get_io_service(), [pSocket](boost::asio::yield_context yield2) {
auto pTmpSocket = pSocket;
frame_ptr pFrame(new frame_ptr::element_type);
pFrame->resize(FRAME_MAX);
while (true) {
boost::system::error_code ec2;
auto count = pTmpSocket->async_read_some(boost::asio::buffer(*pFrame, FRAME_MAX), yield2[ec2]);
if (ec2) {
std::cout << ec2.message() << std::endl;
break;
}
else {
std::string data((const char*)(pFrame->data()), count);
std::cout << data<<std::endl;
}
}
});
}
});
boost::asio::spawn(*pService, [pService, this](boost::asio::yield_context yield) {
boost::asio::deadline_timer timer(*pService);
timer.expires_from_now(boost::posix_time::seconds(5));
boost::system::error_code ec;
timer.async_wait(yield[ec]);
std::vector<int> keys;
for (auto keyvalue : m_MapCallback) {
keys.push_back(keyvalue.first);
}
while (!keys.empty()) {
int indexKey = (rand() % keys.size());
auto Iter = m_MapCallback.find(keys[indexKey]);
std::cout << "exe index:" << Iter->first << std::endl;
(Iter->second)(Iter->first);
keys.erase(keys.begin() + indexKey);
m_MapCallback.erase(Iter);
}
});
}
void testCoroutine::createClient(service_ptr pService)
{
static std::vector<socket_ptr> sSokcets;
for (int i = 0; i < 10; ++i) {
int index = i;
socket_ptr pSocket(new socket_ptr::element_type(*pService));
sSokcets.push_back(pSocket);
boost::asio::spawn(*pService, [pSocket, index, this](boost::asio::yield_context yield) {
boost::asio::ip::tcp::endpoint point(boost::asio::ip::address::from_string("127.0.0.1"), 1234);
boost::system::error_code ec;
pSocket->async_connect(point, yield[ec]);
if (ec) {
std::cout << ec.message() << std::endl;
return;
}
boost::format tmpFormat;
frame_ptr pFrame(new frame_ptr::element_type());
tmpFormat.parse("test Coroutine-%d") % index;
pFrame->resize(tmpFormat.str().size());
memcpy(pFrame->data(), tmpFormat.str().c_str(), tmpFormat.str().size());
pSocket->async_write_some(boost::asio::buffer(*pFrame, pFrame->size()), yield[ec]);
int back = wait3<void (int)>(yield, index);
std::cout << "exit "<<index<<" -> " << back<< std::endl;
});
}
}
| 3ace5a02241b18e69d948dadab4b25eda27b9ab8 | [
"C",
"Text",
"C++"
] | 16 | C++ | comhaqs/persian | 10c257036f31315866881420babb7fc124ab37a6 | a99bb159197d5a67926917b217cdfccfee39d480 |
refs/heads/master | <repo_name>krasilnikovivan11/ArraySumExeptions<file_sep>/mainClass.java
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class mainClass {
private static String [][] a = new String[][] {
{"1","2","3","4"},{"5","6","7","8"},
{"1","2","3","4"},{"5","6","7","8"}
};
public static void main(String[] args)throws MyArrayDataException, MyArraySizeException{
try {
int s = summ(a);
System.out.print(s);
}
catch(IllegalArgumentException e) {
Logger.getLogger(mainClass.class.getName()).log(new LogRecord(Level.WARNING,"Элемент массива не число"));
throw new MyArrayDataException(e);
}
catch(ArrayIndexOutOfBoundsException e) {
Logger.getLogger(mainClass.class.getName()).log(new LogRecord(Level.WARNING,"Массив не того размера"));
throw new MyArraySizeException(e);
}
}
public static int summ(String [][] ar) {
int sum = 0;
if(ar.length != 4 || ar[0].length != 4) throw new ArrayIndexOutOfBoundsException("the size of matrix isn't 4x4");
for(int i = 0;i<ar.length;i++) {
for(int j = 0;j<ar[0].length;j++) {
String s = ar[i][j];
if(numCheck(s)) {
sum += Integer.parseInt(s);
}
else throw new IllegalArgumentException("the value of element 'x' и 'y' isn't number x = "+i+" y = "+j);
}
}
return sum;
}
public static boolean numCheck(String str) {
try {
Integer.parseInt(str);
}
catch(NumberFormatException nfe) {
return false;
}
return true;
}
}
| 39d74925285a7e24cfc5eb34d16fd74d16071b7a | [
"Java"
] | 1 | Java | krasilnikovivan11/ArraySumExeptions | 2ab0a8555c36a4015643aa236206ff998d7996a8 | dea2e790dd8d856fa65d39d8276aa920da07a8f3 |
refs/heads/master | <file_sep>var rawData;
var UniversalGraphHeight = 400;
$('form').submit(function(event){
event.preventDefault();
///initiate call to my databse of deaths stats
$.ajax({
type: 'post',
url: "/",
data: {
state: $('select[name="state"]').val(),
gender: $('select[name="gender"]').val(),
age_group: $('select[name="age_group"]').val()
},
dataType: 'json',
success: function(responseData){
rawData = responseData;
GenPie(rawData);
},
error: function(error){
return res.json( error);
}
})
});
/////=============================================/////////
////START of GenPie: generate pie graph
//////////////////
function GenPie(rawData) {
var pieData = [];
/////filter down data to user selected demograph
rawData.forEach(function(obj, index){
if(obj.gender == $('select[name="gender"]').val() && obj.age_group == $('select[name="age_group"]').val()){
pieData.push(obj);
};
});
//////// check for existings graphs or warnings
if(document.getElementsByTagName('svg').length > 0){
var parentPie = document.getElementsByClassName("pieChart")[0];
var childPie = document.getElementsByTagName("svg")[0];
var parentHisto = document.getElementsByClassName("ageHistogram")[0];
var childHisto = document.getElementsByTagName("svg")[1];
parentPie.removeChild(childPie);
parentHisto.removeChild(childHisto);
};
if(document.getElementsByTagName("p").length > 0){
for (var ip = 0; ip < document.getElementsByTagName("p").length; ip++) {
// var childPiePar = document.getElementsByTagName("p")[0];
document.getElementsByClassName("pieChart")[0].removeChild(document.getElementsByTagName("p")[0]);
};
};
////check for data, then graph it
if (pieData.length > 0) {
pieData.sort(function(a, b) {
return b.deaths - a.deaths;
});
var topStateIcd = pieData[0];
var radius = 150;
pieDataLength = pieData.length >= 5 ? 5 : pieData.length;
pieData = pieData.slice(0, pieDataLength);
var color = d3.scale.ordinal()
.range(["#1111FF", "#2306C2", "#263F9E", "#5544BF", "#563491"]);
var graphData = pieData,
w = 350
h = UniversalGraphHeight;
var canvas = d3.select(".pieChart")
.append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(150, 150)");
var arc = d3.svg.arc()
.innerRadius(0)
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function(d) {return d.deaths});
var path = canvas.selectAll('path')
.attr("transform", "translate(20, 0)")
.data(pie(graphData))
.enter()
.append('path')
.attr('d', d3.svg.arc().innerRadius(0).outerRadius(0))
.style("opacity", 0)
.attr('fill', function(d, i) {
return color(d.data.deaths);
})
.transition()
.delay(100)
.duration(1500)
.style("opacity", 1)
.attr('d', arc);
////LEGEND
var legendRectSize = 18;
var legendSpacing = 4;
var legend = canvas.selectAll('.legend')
.data(color.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', function(d, i) {
var height = legendRectSize + legendSpacing;
var offset = height * color.domain().length / 10;
var horz = -3 * legendRectSize;
var vert = i * height - offset + 150;
return 'translate(' + (2.9 * horz) + ',' + vert + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', "black");
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.attr("fill", "#3DBE2E")
.attr("font-size", "15px")
.attr("font-weight", "bolder")
.text(function(d,i) { return graphData[i].icd.slice(7, graphData[i].icd.length) + ": " + graphData[i].deaths; });
GenHisto(rawData, topStateIcd);
} /////end of if true case for results exist
else{
d3.select(".pieChart")
.append("p")
.text("No results for this demographic");
};
}
///////
//////=============
///// GENERATE HISTOGRAM
function GenHisto(rawData, topStateIcd) {
var margin = {top: 60, right: 10, bottom: 50, left:70};
var w = 700 - margin.right - margin.left,
h = UniversalGraphHeight - margin.top - margin.bottom;
var histoData = [];
rawData.forEach(function(obj, index){
if(obj.gender == $('select[name="gender"]').val() && obj.icd == topStateIcd.icd){
histoData.push(obj);
};
});
if (histoData.length > 0) {
// define x and y scales
var xScale = d3.scale.ordinal()
.rangeRoundBands([0,w], 0, 0);
var yScale = d3.scale.linear()
.range([h, 0]); ///flip because y axis is inverted on page; larger y is down
// define x axis and y axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
// specify domains of the x and y scales
histoData.sort(function(a, b) {
return b.deaths - a.deaths;
});
yScale.domain([0, histoData[0].deaths]);
var graphData = histoData;
var age_groupSort = histoData;
//previous sorting attempts on age_group have failed. method seems to handle my strings in unpredicatble way.
/// inserting my own variable to make this work
age_groupSort.forEach(function(obj, index){
switch(obj.age_group) {
case "< 1 year":
obj.sortVal = 1;
break;
case "1-4 years":
obj.sortVal = 2;
break;
case "5-14 years":
obj.sortVal = 3;
break;
case "15-24 years":
obj.sortVal = 4;
break;
case "25-34 years":
obj.sortVal = 5;
break;
case "35-44 years":
obj.sortVal = 6;
break;
case "45-54 years":
obj.sortVal = 7;
break;
case "55-64 years":
obj.sortVal = 8;
break;
case "65-74 years":
obj.sortVal = 9;
break;
case "75-84 years":
obj.sortVal = 10;
break;
case "85+ years":
obj.sortVal = 11;
break;
}
});
age_groupSort.sort(function(a, b) {
return a.sortVal - b.sortVal;
});
xScale.domain(age_groupSort.map(function(d) { return d.age_group; }) );
histoDataLength = histoData.length == 11 ? 11 : histoData.length;
var canvas = d3.select(".ageHistogram") //select space for d3 visual
.append("svg")
.attr ({
"width": w + margin.right + margin.left,
"height": h + margin.top + margin.bottom
})
.append("g")
.attr("transform","translate(" + margin.left + "," + margin.right + ")");
var graphBars = canvas.selectAll("rect")
.data(graphData)
.enter()
.append("rect")
.attr("height", 0)
.attr("y", h)
.transition().duration(3000)
.delay( function(d,i) { return i * 200; })
// attributes can be also combined under one .attr
.attr({
"x": function(d) { return xScale(d.age_group); },
"y": function(d) { return yScale(d.deaths); },
"width": xScale.rangeBand(),
"height": function(d) { return h - yScale(d.deaths); }
})
.style("fill", function(d,i) { return 'rgb(20, 20, ' + ((d.deaths) + 10) + ')'})
.style("stroke", "black")
.style("stroke-width", 2);
canvas.selectAll("text")
.data(graphData)
.enter()
.append('text')
.text(function(d){
return d.deaths;
})
.attr({
"x": function(d){ return xScale(d.age_group) + xScale.rangeBand()/2; },
"y": function(d){ return yScale(d.deaths)+ 12; },
// "font-family": 'sans-serif',
"font-size": '18px',
"font-weight": 'bold',
"fill": '#CCC0CB',
"text-anchor": 'middle'
});
canvas.append("g") //append x axis
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis)
.selectAll("text")
.attr("dx", "-.8em")
.attr("dy", ".25em")
.attr("transform", "rotate(-60)" )
.attr("fill", "#3DBE2E")
.style("text-anchor", "end")
.attr("font-size", "12px");
var parenthIndex = topStateIcd.icd.indexOf("(");
topStateIcdShort = topStateIcd.icd.slice(parenthIndex, topStateIcd.length);
canvas.append("g") //append y axis
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("x", -h/2)
.attr("font-size", "22px")
.attr("dy", "-3em")
.attr("fill", "#3DBE2E")
.style("text-anchor", "middle")
.text("Deaths by #1 State Cause");
} else{
d3.select(".ageHistogram")
.append("p")
.text("No results for this demo");
};
}
//////////////////////
//// END OF GenHisto
/////=============================================/////////
<file_sep>//MAIN SERVER FILE
require('dotenv').config({silent: true});
var express = require('express'),
app = express(),
exphbs = require('express-handlebars'),
fs = require('fs'),
bodyParser = require('body-parser');
/////////////////
////==SET VIEW ENGINE
app.engine('hbs', exphbs({
defaultLayout: 'main',
partialsDir: __dirname + '/views/partials/',
layoutsDir: __dirname + '/views/layouts/',
extname: '.hbs'
}));
app.set('view engine', 'hbs'); //initiate view engine
app.set('views', __dirname + '/views'); //Set view directory
app.use(bodyParser.urlencoded({extended:true})); //prep body responses from DB
app.use(express.static(__dirname + '/public')); ///stactic elements directory
//////////////////////////
////==Connect database
require('./config/db');
///////////////////
////==Mount Middleware
app.use(require('./controllers/home'));
////////////////
////==START SERVER
var server = app.listen(process.env.PORT || 3000, function() {
console.log("Server listening @: " + server.address().port);
});
/////
<file_sep>// HomeController
// ==============
// Controller for the homepage.
var express = require('express'),
HomeController = express.Router(),
Stat = require(__dirname + '/../models/stat'),
fs = require("fs");
////////
var testStats = fs.readFileSync('./formattedStats.json');
testStats = JSON.parse(testStats);
////
////////=======================
HomeController.route('/all/?')
// GET /
//get all stats
.get(function(req, res) {
Stat.find(function(err, stats) { //Find ALL stats within database
res.json(stats);
})
})
// POST /
// load all stats to database
.post(function(req, res, next) {
console.log(testStats);
Stat.create(testStats, function(err, gifts) {
});
res.render('home');
})
///////delete all stats from database
.delete(function(req, res, next) {
Stat.remove({}, function(err,removed) {})
res.json("Deleted everything")
});
////=======================
HomeController.route('/?')
// POST /
// user posts form request
.post(function(req, res, next) {
var topState= [],
leadByAge = [],
userStats = [];
Stat.find({state: req.body.state}, function(error, stateMatch) {
if(error){console.log("Error: " + error);}
else{
for(var tsi = 0; tsi < stateMatch.length; tsi++) {
topState.push(stateMatch[tsi]);
};
}
res.json(topState);
}); //end of Stat.find
})//end of post
// GET /
// ------
// load main page
.get(function(req, res, next) {
res.render('home');
});
//////
module.exports = HomeController;
<file_sep>//stat MODEL
var mongoose = require('mongoose');
/////////
//Constructor function
var StatSchema = new mongoose.Schema({
state: String,
age_group: String,
gender: String,
icd: String,
deaths: Number
});
///////
module.exports = mongoose.model('Stat', StatSchema);
<file_sep># hades
personalized mortality stats
clone
run gulp
http://localhost:3000/
| a71ce2d65f07475314f8b68da4533e323641b136 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | docmidas/hades | c8cdde4713702f2b9054d5b47607dbb94a70fe2a | 9f4ad0ded9deadcd80a35ed73a27023297e619cb |
refs/heads/main | <file_sep>package exemplo.webflux.service;
import exemplo.webflux.domain.Localizacao;
import exemplo.webflux.repository.LocalizacaoRepository;
import exemplo.webflux.util.LocalizacaoCreator;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.BDDMockito;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.server.ResponseStatusException;
import reactor.blockhound.BlockHound;
import reactor.blockhound.BlockingOperationError;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
@ExtendWith(SpringExtension.class)
public class LocalizacaoServiceTest {
@InjectMocks
private LocalizacaoService localizacaoService;
@Mock
private LocalizacaoRepository localizacaoRepository;
private final Localizacao localizacao = LocalizacaoCreator.createValidLocalizacao();
@BeforeAll
public static void blockHoundSetup() {
BlockHound.install();
}
@BeforeEach
public void setup() {
BDDMockito.when(localizacaoRepository.findAll())
.thenReturn(Flux.just(localizacao));
BDDMockito.when(localizacaoRepository.findById(ArgumentMatchers.anyLong()))
.thenReturn(Mono.just(localizacao));
BDDMockito.when(localizacaoRepository.save(localizacao))
.thenReturn(Mono.just(localizacao));
BDDMockito.when(localizacaoRepository.delete(ArgumentMatchers.any(Localizacao.class)))
.thenReturn(Mono.empty());
BDDMockito.when(localizacaoRepository.save(LocalizacaoCreator.updateValidLocalizacao()))
.thenReturn(Mono.just(localizacao));
}
@Test
public void blockHoundWorks() {
try {
FutureTask<?> task = new FutureTask<>(() -> {
Thread.sleep(0);
return "";
});
Schedulers.parallel().schedule(task);
task.get(10, TimeUnit.SECONDS);
Assertions.fail("Should fail");
} catch (Exception e) {
Assertions.assertTrue(e.getCause() instanceof BlockingOperationError);
}
}
@Test
@DisplayName("Buscar todas as localizações")
public void findAll_ReturnFluxLocalizacoes_WhenSuccessful() {
StepVerifier.create(localizacaoService.findAll())
.expectSubscription()
.expectNext(localizacao)
.verifyComplete();
}
@Test
@DisplayName("Buscar uma localização Mono existente")
public void findById_ReturnMonoLocalizacao_WhenSuccessful() {
StepVerifier.create(localizacaoService.findById(1L))
.expectSubscription()
.expectNext(localizacao)
.verifyComplete();
}
@Test
@DisplayName("Buscar uma localização Mono não existente")
public void findById_ReturnMonoLocalizacao_WhenError() {
BDDMockito.when(localizacaoRepository.findById(ArgumentMatchers.anyLong()))
.thenReturn(Mono.empty());
StepVerifier.create(localizacaoService.findById(1L))
.expectSubscription()
.expectError(ResponseStatusException.class)
.verify();
}
@Test
@DisplayName("Salva uma localização")
public void save_ReturnMonoLocalizacao_WhenSuccessful() {
Localizacao localizacaoSave = LocalizacaoCreator.createValidLocalizacao();
StepVerifier.create(localizacaoService.save(localizacaoSave))
.expectSubscription()
.expectNext(localizacao)
.verifyComplete();
}
@Test
@DisplayName("Deleta uma localização")
public void delete_Localizacao_WhenSuccessful() {
StepVerifier.create(localizacaoService.delete(1L))
.expectSubscription()
.verifyComplete();
}
@Test
@DisplayName("Tenta deletar uma localização inexistente ")
public void delete_ReturnMonoError_WhenError() {
BDDMockito.when(localizacaoRepository.findById(ArgumentMatchers.anyLong()))
.thenReturn(Mono.empty());
StepVerifier.create(localizacaoService.delete(1L))
.expectSubscription()
.expectError(ResponseStatusException.class)
.verify();
}
@Test
@DisplayName("Atualiza uma localização")
public void update_ReturnMonoLocalizacao_WhenSuccessful() {
StepVerifier.create(localizacaoService.update(LocalizacaoCreator.createValidLocalizacao()))
.expectSubscription()
.verifyComplete();
}
@Test
@DisplayName("Atualiza uma localização que não existe")
public void update_ReturnMonoLocalizacao_WhenError() {
BDDMockito.when(localizacaoRepository.findById(ArgumentMatchers.anyLong()))
.thenReturn(Mono.empty());
StepVerifier.create(localizacaoService.update(LocalizacaoCreator.createValidLocalizacao()))
.expectSubscription()
.expectError(ResponseStatusException.class)
.verify();
}
}
<file_sep># spring-webflux-essentials
Modelo de Stream com Spring Boot, utilizando webFlux e MySQL
#Link para as aulas (DevDojo)
https://www.youtube.com/watch?v=-Ub0u8mMyZM&list=PL62G310vn6nH5Tgcp5q2a1xCb6CsZJAi7&index=14
#Requerimetos
Docker
- MySQL
- K6
- influxDb
- grafana
Eclipse
- Java 11
Postman
## Comandos ##
# K6 Docker
docker-compose run k6 run - < testeK6.js
#Dicas:
Grafana:
- Para configurar o Host do banco no grafana deverá ser usado como Host: host.docker.internal:8086/
- Existem dashboards customizadas para importação no site do grafana. (https://grafana.com/grafana/dashboards/2587)
<file_sep>spring.r2dbc.url=r2dbc:pool:mysql://localhost:3306/webflux
spring.r2dbc.username=root
spring.r2dbc.password=<PASSWORD>
logging.level.org.springframework.data.r2dbc=DEBUG
server.error.include-stacktrace=on_param<file_sep>package exemplo.webflux.service;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import exemplo.webflux.domain.Localizacao;
import exemplo.webflux.repository.LocalizacaoRepository;
import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
@RequiredArgsConstructor
public class LocalizacaoService {
private final LocalizacaoRepository localizacaoRepository;
public Flux<Localizacao> findAll() {
return localizacaoRepository.findAll();
}
public Mono<Localizacao> findById(Long id) {
return localizacaoRepository.findById(id).switchIfEmpty(
Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "Localizacao não encontrada")));
}
public Mono<Localizacao> save(@Valid Localizacao localizacao) {
return localizacaoRepository.save(localizacao);
}
public Mono<Void> update(Localizacao localizacao) {
return findById(localizacao.getId()).map(localFound -> localizacao.withId(localFound.getId()))
.flatMap(localizacaoRepository::save).then();
}
public Mono<Void> delete(Long id) {
return findById(id)
.flatMap(localizacaoRepository::delete);
}
}
<file_sep>package exemplo.webflux.domain;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.With;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@With
@Table("localizacao")
@Entity
public class Localizacao {
@Id
private long id;
@NotNull(message = "Longitude esta null")
private String longitude;
@NotNull(message = "Latitude esta null")
private String latitude;
}
| 55fb9ff246136ff854adb09e475dd76de60c889a | [
"Markdown",
"Java",
"INI"
] | 5 | Java | rhdesouza/spring-webflux-essentials | 894966c0cdff6e307ddaffb920dba4f088586dba | 1f262d80dd85a2b26b07afeaa5b5ce2a0cd12921 |
refs/heads/master | <repo_name>MiriamAparicio/lab-ajax-crud-characters<file_sep>/starter_code/public/javascript/APIHandler.js
'use strict';
class APIHandler {
constructor (baseUrl) {
this.BASE_URL = baseUrl;
}
getFullList () {
return axios.get(`${this.BASE_URL}/characters`)
.then((response) => {
return response.data;
})
.catch(err => {
console.log(err);
});
}
getOneRegister (id) {
return axios.get(`${this.BASE_URL}/characters/${id}`)
.then((response) => {
return response.data;
})
.catch(err => {
console.log(err);
});
}
createOneRegister (character) {
axios.post(`${this.BASE_URL}/characters/`, character)
.then((response) => {
console.log('Create SUCCESS!');
})
.catch(error => {
console.log(err);
});
}
updateOneRegister (id, character) {
axios.put(`${this.BASE_URL}/characters/${id}`, character)
.then((response) => {
console.log('Update SUCCESS!');
})
.catch(err => {
console.log(err);
});
}
deleteOneRegister (id) {
axios.delete(`${this.BASE_URL}/characters/${id}`)
.then((response) => {
console.log('Delete SUCCESS!');
})
.catch(err => {
console.log(err);
});
}
}
<file_sep>/starter_code/public/javascript/index.js
'use strict';
const charactersAPI = new APIHandler("http://localhost:8000")
$(document).ready( () => {
document.getElementById('fetch-all').onclick = function(){
let list = '';
charactersAPI.getFullList()
.then((data) => {
console.log(data);
for (let item in data) {
list += `<div class="character-info">
<div class="name">Name: ${data[item].name}</div>
<div class="occupation">Occupation: ${data[item].occupation}</div>
<div class="weapon">Weapon: ${data[item].weapon}</div>
<div class="cartoon">Is a Cartoon? ${data[item].cartoon}</div>
</div>`;
}
document.getElementsByClassName('characters-container')[0].innerHTML = list;
})
}
document.getElementById('fetch-one').onclick = function(){
const id = document.getElementsByName('character-id')[0].value;
charactersAPI.getOneRegister(id)
.then((data) => {
console.log(data);
document.getElementsByClassName('characters-container')[0].innerHTML = `<div class="character-info">
<div class="name">Name: ${data.name}</div>
<div class="occupation">Occupation: ${data.occupation}</div>
<div class="weapon">Weapon: ${data.weapon}</div>
<div class="cartoon">Is a Cartoon? ${data.cartoon}</div>
</div>`
})
}
document.getElementById('delete-one').onclick = function(){
const id = document.getElementsByName('character-id-delete')[0].value;
charactersAPI.deleteOneRegister(id);
}
document.getElementById('edit-character-form').onsubmit = function(){
event.preventDefault();
const id = document.getElementsByName('chr-id')[0].value;
const name = document.getElementsByName('name')[1].value;
const occupation = document.getElementsByName('occupation')[1].value;
const weapon = document.getElementsByName('weapon')[1].value;
const cartoon = document.getElementsByName('cartoon')[1].checked;
const character = {name, occupation, weapon, cartoon};
charactersAPI.updateOneRegister(id, character);
}
document.getElementById('new-character-form').onsubmit = function(){
event.preventDefault();
const character = {
name: document.getElementsByName('name')[0].value,
occupation: document.getElementsByName('occupation')[0].value,
weapon: document.getElementsByName('weapon')[0].value,
cartoon: document.getElementsByName('cartoon')[0].checked
};
charactersAPI.createOneRegister(character);
}
})
| f1554c287296c840034e2007642a1bfe01e5444e | [
"JavaScript"
] | 2 | JavaScript | MiriamAparicio/lab-ajax-crud-characters | c72062ec8c356ca45256b2e53bf6b3bbe7db7ee8 | 6a1fee34dee80f2f48d4d6e4ade41e519e893a56 |
refs/heads/master | <file_sep># FancyTrendView
[](https://travis-ci.org/fantasy1022/FancyTrendView)
The custom UI view including animation and typing text.
The behavior of Android APP is like Google trend web. https://trends.google.com/trends/hottrends/visualize
<file_sep>/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fantasy1022.fancytrendapp.presentation.trend;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import com.fantasy1022.fancytrendapp.common.Constant;
import com.fantasy1022.fancytrendapp.common.SPUtils;
import com.fantasy1022.fancytrendapp.presentation.base.BasePresenter;
import com.fantasy1022.fancytrendapp.data.TrendRepository;
import java.util.List;
import java.util.Locale;
import io.reactivex.Scheduler;
/**
* Created by fantasy1022 on 2017/2/7.
*/
public class FancyTrendPresenter extends BasePresenter<FancyTrendContract.View> implements FancyTrendContract.Presenter {
private final String TAG = getClass().getSimpleName();
private final Scheduler mainScheduler, ioScheduler;
private SPUtils spUtils;
private TrendRepository trendRepository;
private ArrayMap<String, List<String>> trendArrayMap;
public FancyTrendPresenter(SPUtils spUtils, TrendRepository trendRepository, Scheduler ioScheduler, Scheduler mainScheduler) {
this.trendRepository = trendRepository;
this.ioScheduler = ioScheduler;
this.mainScheduler = mainScheduler;
this.spUtils = spUtils;
}
@Override
public String getDefaultCountryCode() {
String result = spUtils.getString(Constant.SP_DEFAULT_COUNTRY_KEY, "");
if (!result.isEmpty()) {
return result;
} else {//Use system language for first time
String country = Locale.getDefault().getLanguage();
Log.d(TAG, "country:" + country);
switch (country) {
case "zh":
return "12";
case "en":
return "1";
default://TODO:map other country
return "1";
}
}
}
@Override
public void setDefaultCountryCode(String code) {//Store country code
spUtils.putString(Constant.SP_DEFAULT_COUNTRY_KEY, code);
}
@Override
public int getDefaultCountryIndex() {
int result = spUtils.getInt(Constant.SP_DEFAULT_COUNTRY_INDEX_KEY, -1);
if (result != -1) {
return result;
} else {//Use system language for first time
String country = Locale.getDefault().getLanguage();
Log.d(TAG, "country:" + country);
switch (country) {
case "zh":
return 40;
case "en":
return 45;
default://TODO:map other country
return 45;
}
}
}
@Override
public void setDefaultCountryIndex(int index) {
spUtils.putInt(Constant.SP_DEFAULT_COUNTRY_INDEX_KEY, index);
}
@Override
public int getClickBehavior() {
return spUtils.getInt(Constant.SP_DEFAULT_CLICK_BEHAVIOR_KEY, 0);
}
@Override
public void setClickBehavior(@SPUtils.ClickBehaviorItem int index) {
spUtils.putInt(Constant.SP_DEFAULT_CLICK_BEHAVIOR_KEY, index);
}
@Override
public void generateCountryCodeMapping() {
Constant.generateCountryCodeMapping();
}
@Override
public void retrieveAllTrend() {
checkViewAttached();
addSubscription(trendRepository.getAllTrend()
.doOnSubscribe(a -> getView().showLoading())
.doFinally(() -> getView().hideLoading())
.subscribeOn(ioScheduler)
.observeOn(mainScheduler)
.subscribe(trendArrayMap -> {
Log.d(TAG, "Get trend result successful");
FancyTrendPresenter.this.trendArrayMap = trendArrayMap;
getView().showTrendResult(trendArrayMap.get(getDefaultCountryCode()));
}, throwable -> {
Log.d(TAG, "Get trend result failure");
getView().showErrorScreen();
}));
}
@Override
public void retrieveSingleTrend(String countryCode, int position) {
//Use init data to find countryCode and show
getView().changeTrend(trendArrayMap.get(countryCode), position);
}
}
<file_sep>/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fantasy1022.fancytrendapp.common;
import android.support.v4.util.ArrayMap;
import java.util.Arrays;
import java.util.List;
/**
* Created by fantasy1022 on 2017/2/8.
*/
public class Constant {
public final static String GOOGLE_TREND_BASE_URL = "http://hawttrends.appspot.com";
public final static String DEFAULT_COUNTRY_CODE = "12";//Taiwan
public final static String SP_DEFAULT_COUNTRY_KEY = "SP_DEFAULT_COUNTRY_KEY";
public final static String SP_DEFAULT_COUNTRY_INDEX_KEY = "SP_DEFAULT_COUNTRY_INDEX_KEY";
public final static String SP_DEFAULT_CLICK_BEHAVIOR_KEY = "SP_DEFAULT_CLICK_BEHAVIOR_KEY";
public final static int DEFAULT_ROW_NUMBER = 3;
public final static int DEFAULT_COLUMN_NUMBER = 3;
public final static int DEFAULT_TREND_ITEM_NUMBER = DEFAULT_ROW_NUMBER * DEFAULT_COLUMN_NUMBER;
private static ArrayMap<String, String> countryMap;
public static void generateCountryCodeMapping() {
countryMap = new ArrayMap<>();//(name,code)
countryMap.put("United States", "1");
countryMap.put("India", "3");
countryMap.put("Japan", "4");
countryMap.put("Singapore", "5");
countryMap.put("Israel", "6");
countryMap.put("Australia", "8");
countryMap.put("United Kingdom", "9");
countryMap.put("Hong Kong", "10");
countryMap.put("Taiwan", "12");
countryMap.put("Canada", "13");
countryMap.put("Russia", "14");
countryMap.put("Germany", "15");
countryMap.put("France", "16");
countryMap.put("Netherlands", "17");
countryMap.put("Brazil", "18");
countryMap.put("Indonesia", "19");
countryMap.put("Mexico", "21");
countryMap.put("South Korea", "23");
countryMap.put("Turkey", "24");
countryMap.put("Philippines", "25");
countryMap.put("Spain", "26");
countryMap.put("Italy", "27");
countryMap.put("Vietnam", "28");
countryMap.put("Egypt", "29");
countryMap.put("Argentina", "30");
countryMap.put("Poland", "31");
countryMap.put("Colombia", "32");
countryMap.put("Thailand", "33");
countryMap.put("Malaysia", "34");
countryMap.put("Ukraine", "35");
countryMap.put("Saudi Arabia", "36");
countryMap.put("Kenya", "37");
countryMap.put("Chile", "38");
countryMap.put("Romania", "39");
countryMap.put("South Africa", "40");
countryMap.put("Belgium", "41");
countryMap.put("Sweden", "42");
countryMap.put("Czech Republic", "43");
countryMap.put("Austria", "44");
countryMap.put("Hungary", "45");
countryMap.put("Switzerland", "46");
countryMap.put("Portugal", "47");
countryMap.put("Greece", "48");
countryMap.put("Denmark", "49");
countryMap.put("Finland", "50");
countryMap.put("Norway", "51");
countryMap.put("Nigeria", "52");
}
public static String getCountryCode(String countryName) {
return countryMap.get(countryName);
}
public static ArrayMap<String, List<String>> generateTrendMap() {//For test and mock using
ArrayMap<String, List<String>> countryTrendMap = new ArrayMap<>();
countryTrendMap.put("1", Arrays.asList(new String[]{"Powerball", "This Is Us", "Paul George"}));
countryTrendMap.put("3", Arrays.asList(new String[]{"Exoplanet discovery", "Cricbuzz", "BMC election 2017"}));
countryTrendMap.put("4", Arrays.asList(new String[]{"愛子さま", "明日の天気", "ほのかりん"}));
countryTrendMap.put("5", Arrays.asList(new String[]{"Exoplanet discovery", "Tuas fire", "Europa League"}));
countryTrendMap.put("6", Arrays.asList(new String[]{"רשת", "יעל אלמוג", "Kim Kardashian"}));
countryTrendMap.put("8", Arrays.asList(new String[]{"penalty rates", "Bride and Prejudice", "AMD Ryzen"}));
countryTrendMap.put("9", Arrays.asList(new String[]{"Cheryl Cole", "Lottery Result", "George Michael Funeral"}));
countryTrendMap.put("10", Arrays.asList(new String[]{"发现系外行星", "Nasa", "張秀文"}));
countryTrendMap.put("12", Arrays.asList(new String[]{"羅惠美", "泰雅渡假村", "成語蕎"}));
countryTrendMap.put("13", Arrays.asList(new String[]{"Découverte D’exoplanètes", "Rockfest", "AMD Ryzen"}));
countryTrendMap.put("14", Arrays.asList(new String[]{"Алексей Петренко", "<NAME>", "Порту Ювентус"}));
countryTrendMap.put("15", Arrays.asList(new String[]{"<NAME>", "<NAME>", "Unwetterwarnung"}));
countryTrendMap.put("16", Arrays.asList(new String[]{"<NAME>", "Crif", "Saint Etienne Manchester"}));
countryTrendMap.put("17", Arrays.asList(new String[]{"VID", "Range Rover Velar", "Nicolette Kluijver"}));
countryTrendMap.put("18", Arrays.asList(new String[]{"Brit Awards 2017", "Exoplaneta descoberto", "Corinthians X Palmeiras Ao Vivo"}));
countryTrendMap.put("19", Arrays.asList(new String[]{"Liga Spanyol", "Manchester United F.c.", "Na Hye Mi"}));
countryTrendMap.put("21", Arrays.asList(new String[]{"Descubrimiento Exoplanetas", "Tigres Vs Pumas Concachampions", "Porto vs Juventus"}));
countryTrendMap.put("23", Arrays.asList(new String[]{"-행성 발견", "23 아이덴티티", "나혜미"}));
countryTrendMap.put("24", Arrays.asList(new String[]{"Ehliyet sınav sonuçları", "Diriliş Ertuğrul 79 Bölüm Fragmanı", "Fenerbahçe Krasnodar Özet"}));
countryTrendMap.put("25", Arrays.asList(new String[]{"Exoplanet discovery", "Earthquake Today", "earthquake"}));
countryTrendMap.put("26", Arrays.asList(new String[]{"Descubrimiento Exoplanetas", "Sevilla Leicester", "nueva actualización de Whatsapp"}));
countryTrendMap.put("27", Arrays.asList(new String[]{"La Porta Rossa", "Siviglia Leicester", "Aggiornamento WhatsApp"}));
countryTrendMap.put("28", Arrays.asList(new String[]{"Tuoi Thanh Xuan 2 Tap 30", "<NAME>", "Na Hye Mi"}));
countryTrendMap.put("29", Arrays.asList(new String[]{"ترتيب الدوري الاسباني", "عمر عبدالرحمن", "الدوري الاسباني"}));
countryTrendMap.put("30", Arrays.asList(new String[]{"Camila", "Descubrimiento Exoplanetas", "Atanor"}));
countryTrendMap.put("31", Arrays.asList(new String[]{"Brit Awards 2017", "Sevilla", "faworki"}));
countryTrendMap.put("32", Arrays.asList(new String[]{"Descubrimiento Exoplanetas", "Valencia vs Real Madrid", "Juventus"}));
countryTrendMap.put("33", Arrays.asList(new String[]{"สายป่าน", "วันอังคาร", "เมืองทอง"}));
countryTrendMap.put("34", Arrays.asList(new String[]{"Exoplanet discovery", "Manchester United F.c.", "La Liga"}));
countryTrendMap.put("35", Arrays.asList(new String[]{"23 Февраля Праздник", "Порту Ювентус", "Алекс<NAME>ко"}));
countryTrendMap.put("36", Arrays.asList(new String[]{"ناس", "تحديث الواتس اب", "يوفنتوس"}));
countryTrendMap.put("37", Arrays.asList(new String[]{"Juventus", "Exoplanet discovery", "Manchester United"}));
countryTrendMap.put("38", Arrays.asList(new String[]{"Lali Esposito", "Gaviota de Platino", "<NAME>"}));
countryTrendMap.put("39", Arrays.asList(new String[]{"Europa League", "HOROSCOP 23 februarie 2017", "Iohannis"}));
countryTrendMap.put("40", Arrays.asList(new String[]{"Exoplanet discovery", "Budget Speech 2017", "Cricket live scores"}));
countryTrendMap.put("41", Arrays.asList(new String[]{"aarde-achtige planeten", "<NAME>", "Juventus"}));
countryTrendMap.put("42", Arrays.asList(new String[]{"<NAME>", "<NAME>", "<NAME>"}));
countryTrendMap.put("43", Arrays.asList(new String[]{"Jawa", "AMD Ryzen", "Cssd"}));
countryTrendMap.put("44", Arrays.asList(new String[]{"<NAME>", "Weiberfastnacht", "Ho Chi Minh"}));
countryTrendMap.put("45", Arrays.asList(new String[]{"<NAME>", "Buffon", "<NAME>"}));
countryTrendMap.put("46", Arrays.asList(new String[]{"erdähnliche Planeten", "<NAME>", "Juventus"}));
countryTrendMap.put("47", Arrays.asList(new String[]{"Herrera", "Brit Awards 2017", "Liga Espanhola"}));
countryTrendMap.put("48", Arrays.asList(new String[]{"Νικοσ Γκαλησ", "Θεμησ Μανεσησ", "Κουνδουροσ"}));
countryTrendMap.put("49", Arrays.asList(new String[]{"Viaplay", "Exoplanet Discovery", "Viafree"}));
countryTrendMap.put("50", Arrays.asList(new String[]{"Kel<NAME>ok", "Temptation Island", "Saara Aalto"}));
countryTrendMap.put("51", Arrays.asList(new String[]{"Cecilia Brækhus", "Brit Awards 2017", "<NAME>"}));
countryTrendMap.put("52", Arrays.asList(new String[]{"Exoplanet discovery", "Man City vs Monaco", "Laliga"}));
return countryTrendMap;
}
}
<file_sep>/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fantasy1022.fancytrendapp.presentation.trend;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.fantasy1022.fancytrendapp.R;
import com.fantasy1022.fancytrendview.FancyTrendView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by fantasy1022 on 2017/2/17.
*/
public class FancyTrendAdapter extends RecyclerView.Adapter<FancyTrendAdapter.ItemViewHolder> {
public final String TAG = getClass().getSimpleName();
private Context context;
private ArrayList<List<String>> trendItemList;
private OnItemClickListener onItemClickListener;
private int rows;
public FancyTrendAdapter(Context context, ArrayList<List<String>> trendItemList, int rows, OnItemClickListener onItemClickListener) {
this.context = context;
this.trendItemList = trendItemList;
this.onItemClickListener = onItemClickListener;
this.rows = rows;
}
public interface OnItemClickListener {
void onItemClick(View v, String trend, int position);
}
@Override
public FancyTrendAdapter.ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_trend, parent, false);
ItemViewHolder itemViewHolder = new ItemViewHolder(view, onItemClickListener);
return itemViewHolder;
}
@Override
public void onBindViewHolder(FancyTrendAdapter.ItemViewHolder holder, int position) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int heightPixels;
if (hasNavigationBar(context)) {
heightPixels = displayMetrics.heightPixels + getNavigationBarHeight(context);
} else {
heightPixels = displayMetrics.heightPixels;
}
//Log.d(TAG, "heightPixels:" + heightPixels);
if (rows == 1) {
ViewGroup.LayoutParams params = holder.googleTrendView.getLayoutParams();
params.height = heightPixels;
holder.googleTrendView.setLayoutParams(params);
} else if (rows == 2) {
ViewGroup.LayoutParams params = holder.googleTrendView.getLayoutParams();
params.height = heightPixels / 2;
holder.googleTrendView.setLayoutParams(params);
} else if (rows == 3) {
ViewGroup.LayoutParams params = holder.googleTrendView.getLayoutParams();
params.height = heightPixels / 3;
holder.googleTrendView.setLayoutParams(params);
}
holder.googleTrendView.startAllAnimation(trendItemList.get(position));
}
@Override
public int getItemCount() {
int size = (trendItemList != null ? trendItemList.size() : 0);
return size;
}
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// @BindView(R.id.googleTrendView)
FancyTrendView googleTrendView;
private OnItemClickListener listener;
public ItemViewHolder(View itemView, OnItemClickListener listener) {
super(itemView);
googleTrendView = (FancyTrendView) itemView.findViewById(R.id.googleTrendView);
//ButterKnife.bind(this, itemView);
this.listener = listener;
googleTrendView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
listener.onItemClick(v, googleTrendView.getNowText(), getLayoutPosition());
}
}
public void updateAllList(ArrayList<List<String>> trendItemList) {
this.trendItemList = trendItemList;
notifyDataSetChanged();
}
public void updateSingleList(List<String> trendList, int position) {
Log.d(TAG, "updateSingleList position:" + position + " trendList:" + trendList);
trendItemList.set(position, trendList);
notifyItemChanged(position);
}
public void changeRowNumber(int rows) {
this.rows = rows;
notifyDataSetChanged();
}
private int getNavigationBarHeight(Context context) {
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
return (resourceId > 0) ? resources.getDimensionPixelSize(resourceId) : 0;
}
private boolean hasNavigationBar(Context context) {
Resources resources = context.getResources();
int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
return id > 0 && resources.getBoolean(id);
}
}
<file_sep>/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fantasy1022.fancytrendapp.presentation.trend;
import android.support.annotation.NonNull;
import com.fantasy1022.fancytrendapp.presentation.base.MvpView;
import com.fantasy1022.fancytrendapp.presentation.base.MvpPresenter;
import java.util.List;
/**
* Created by fantasy1022 on 2017/2/7.
*/
public interface FancyTrendContract {
interface View extends MvpView {
void showTrendResult(@NonNull List<String> trendList);
void changeTrend(@NonNull List<String> trendList, int position);
void showErrorScreen();
void showLoading();
void hideLoading();
}
interface Presenter extends MvpPresenter<View> {
void generateCountryCodeMapping();
String getDefaultCountryCode();
void setDefaultCountryCode(String code);
int getDefaultCountryIndex();
void setDefaultCountryIndex(int index);
int getClickBehavior();
void setClickBehavior(int index);
void retrieveAllTrend();
void retrieveSingleTrend(String countryCode, int position);
}
}
| a9a73217edb21a33f42a165dc449a3dbb6f77505 | [
"Markdown",
"Java"
] | 5 | Markdown | codacy-badger/FancyTrendView | 085eb060cd7cc03fadadb02478762326fda7d70b | c25549af0f76ee17da49f2739f15ef831af9d515 |
refs/heads/master | <repo_name>18371503352/sells<file_sep>/src/test/java/com/imooc/sell/LoggetTest.java
package com.imooc.sell;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class LoggetTest<Slf4j> {
private final Logger logger= LoggerFactory.getLogger(LoggetTest.class);
@Test
public void Test(){
logger.info("info");
logger.debug("debug");
logger.error("err");
}
}
| a14273cbbe137647f8658c6b24544db24b123d03 | [
"Java"
] | 1 | Java | 18371503352/sells | dd1bf1c82354ae45b1615fe1701e973eea0d373e | 38d2ab0eac5c9ee4f541b9328aec6305cd838715 |
refs/heads/master | <repo_name>NielsenPetersen/AUT-Social-App2<file_sep>/app/src/main/java/com/example/user1/socialappaut/FoodAndBarActivity.java
package com.example.user1.socialappaut;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
public class FoodAndBarActivity extends AppCompatActivity {
private ImageView ivFood;
private ImageView ivDrinks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_and_bar);
ivFood = (ImageView) findViewById(R.id.ivFood);
ivDrinks = (ImageView) findViewById(R.id.ivDrinks);
ivFood.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent foodMenu = new Intent(FoodAndBarActivity.this, FoodMenuActivity.class);
FoodAndBarActivity.this.startActivity(foodMenu);
}
});
ivDrinks.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent drinkMenu = new Intent(FoodAndBarActivity.this, DrinkItemMenuActivity.class);
FoodAndBarActivity.this.startActivity(drinkMenu);
}
});
}
}
<file_sep>/app/src/main/java/com/example/user1/socialappaut/LoginActivity.java
package com.example.user1.socialappaut;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity{
private EditText etStudentID;
private EditText etPassword;
private Button btnLogin;
private TextView tvRegisterLink;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etStudentID = (EditText) findViewById(R.id.etStudentID);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference user_table = database.getReference("User");
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String studentID = etStudentID.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
//This checks to see if both student ID and password field is empty and notifies the user.
if (TextUtils.isEmpty(studentID) && TextUtils.isEmpty(password)) {
AlertDialog.Builder build = new AlertDialog.Builder(LoginActivity.this);
build.setTitle("Invalid Details")
.setMessage("Blank Information")
.setPositiveButton("Dismiss",null)
.create()
.show();
return;
}
//This gives the progress dialog loading feature to show its processing/loading.
final ProgressDialog noteDialog = new ProgressDialog(LoginActivity.this);
noteDialog.setMessage("Checking login details...");
noteDialog.show();
user_table.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//This checks the database to see if there is a matching student ID stored, If so
if (dataSnapshot.child(etStudentID.getText().toString()).exists()) {
noteDialog.dismiss();
//This gets the users information if password is correct
Users user = dataSnapshot.child(etStudentID.getText().toString()).getValue(Users.class);
if (user.getPassword().equals(etPassword.getText().toString())) {
Toast.makeText(LoginActivity.this, "Login Successful!", Toast.LENGTH_SHORT)
.show();
Intent campusSelectionIntent = new Intent(LoginActivity.this, CampusSelectionActivity.class);
CurrentUser.currentUser = user;
startActivity(campusSelectionIntent);
finish();
} else {
Toast.makeText(LoginActivity.this, "Invalid Password", Toast.LENGTH_SHORT)
.show();
}
} else{
Toast.makeText(LoginActivity.this, "Invalid Student ID", Toast.LENGTH_SHORT)
.show();
noteDialog.dismiss();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
}
<file_sep>/app/src/main/java/com/example/user1/socialappaut/HomeScreenActivity.java
package com.example.user1.socialappaut;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class HomeScreenActivity extends AppCompatActivity{
private TextView username;
private EditText firstname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
final ImageView ivTravel = (ImageView) findViewById(R.id.ivTravel);
final ImageView ivStudentBoard = (ImageView) findViewById(R.id.ivStudentBoard);
final ImageView ivEvents = (ImageView) findViewById(R.id.ivEvents);
final ImageView ivFoodAndBar = (ImageView) findViewById(R.id.ivFoodAndBar);
ivTravel.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent travelIntent = new Intent(HomeScreenActivity.this,TravelSectionActivity.class);
HomeScreenActivity.this.startActivity(travelIntent);
}
});
ivStudentBoard.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent studentBoardIntent = new Intent(HomeScreenActivity.this,StudentBoardSectionActivity.class);
HomeScreenActivity.this.startActivity(studentBoardIntent);
}
});
ivEvents.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent eventsIntent = new Intent(HomeScreenActivity.this,EventsSectionActivity.class);
HomeScreenActivity.this.startActivity(eventsIntent);
}
});
ivFoodAndBar.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent foodAndBarIntent = new Intent(HomeScreenActivity.this,FoodAndBarActivity.class);
HomeScreenActivity.this.startActivity(foodAndBarIntent);
}
});
}
}
<file_sep>/app/src/main/java/com/example/user1/socialappaut/CurrentUser.java
package com.example.user1.socialappaut;
public class CurrentUser {
public static Users currentUser;
}
<file_sep>/app/src/main/java/com/example/user1/socialappaut/DrinkItemMenuActivity.java
package com.example.user1.socialappaut;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
public class DrinkItemMenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseDatabase database;
private DatabaseReference drinkItems;
private TextView username;
private TextView rateLabel;
private TextView itemLabel;
private TextView priceLabel;
private TextView price;
private TextView itemDescription;
private RecyclerView recycler_menu;
private RecyclerView.LayoutManager layoutManager;
private String name;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_item_menu);
//Initialise The Firebase Database Object to interact with the drink items in the database.
database = FirebaseDatabase.getInstance();
drinkItems = database.getReference("Drink_Items");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
rateLabel = (TextView) findViewById(R.id.tvRate);
itemLabel = (TextView) findViewById(R.id.tvItem);
priceLabel = (TextView) findViewById(R.id.tvPrice);
price = (TextView) findViewById(R.id.tvGetPrice);
itemDescription = (TextView)findViewById(R.id.tvGetItemDescription);
//Set the username to be displayed in the menu tab
View header = navigationView.getHeaderView(0);
username = (TextView) header.findViewById(R.id.tvFullname);
name = CurrentUser.currentUser.getFirstname()+" "+CurrentUser.currentUser.getLastname();
username.setText(name);
recycler_menu = (RecyclerView) findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
createMenu();
}
private void createMenu() {
FirebaseRecyclerAdapter<Drink_Items,MenuViewHolder> adapter = new FirebaseRecyclerAdapter<Drink_Items, MenuViewHolder>(Drink_Items.class,R.layout.menu_items,MenuViewHolder.class,drinkItems) {
@Override
protected void populateViewHolder(MenuViewHolder viewHolder, Drink_Items model, int position) {
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imgItem);
viewHolder.tvItemName.setText(model.getName());
viewHolder.tvPrice.setText(model.getPrice());
final Drink_Items clickitem = model;
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(DrinkItemMenuActivity.this,""+clickitem.getName(),Toast.LENGTH_SHORT).show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.drink_item_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id==R.id.nav_events){
Intent eventsIntent = new Intent(DrinkItemMenuActivity.this,EventsSectionActivity.class);
DrinkItemMenuActivity.this.startActivity(eventsIntent);
}else if (id==R.id.nav_food){
Intent foodAndBarIntent = new Intent(DrinkItemMenuActivity.this,FoodAndBarActivity.class);
DrinkItemMenuActivity.this.startActivity(foodAndBarIntent);
}else if(id==R.id.nav_student_board){
Intent studentBoardIntent = new Intent(DrinkItemMenuActivity.this,StudentBoardSectionActivity.class);
DrinkItemMenuActivity.this.startActivity(studentBoardIntent);
}else if(id==R.id.nav_travel){
Intent travelIntent = new Intent(DrinkItemMenuActivity.this,TravelSectionActivity.class);
DrinkItemMenuActivity.this.startActivity(travelIntent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| a0069c68912ce4ce4e37ccea8fd6a9ee36b7ad45 | [
"Java"
] | 5 | Java | NielsenPetersen/AUT-Social-App2 | 8d86ba856afc1b80b4c722cf039180c4843ab841 | 15159c95f5cc5bba9e8212545ecb6ab86e4f3557 |
refs/heads/master | <repo_name>kuroky360/angular4-exercise<file_sep>/src/app/hero.ts
/**
* Created by Kuroky360 on 7/3/17.
*/
export class Hero{
id:number;
name:string;
}<file_sep>/README.md
# angular4-exercise
Just a helloworld for ng4
| 645c823cb18d2de8698954107be5d010411e44c1 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | kuroky360/angular4-exercise | c26a2d6c69f95b1daa83bdf4cfb22029330ab6e0 | 8ef0b82c59ca381e24fa2a28d55ff82ba66ff931 |
refs/heads/master | <repo_name>djhb317/HudsonRepo<file_sep>/sdi-project2.html
<!DOCTYPE html>
<html>
<head>
<title><NAME> :: Project 3 :: Project 3</title>
<link rel="stylesheet" href="sdi.css" type="text/css" />
</head>
<body>
<header>
<h1>Project 3: <NAME></h1>
<h2>Let's buy a Super Car!</h2>
</header>
<article>
<p>A potential car buyer var "Jerry" went to a car dealer to look at (carName) === ["mercedes", "Ferrari", "Maserati"]</p>
<p>His only specifications for buying one of these vehicles is milage.</p>
<p>"Jerry" will buy one of the (carName) cars if the milesPerCar are <= 16000.
<p>The milesPerCar = [15000, 18000, 12000] and the first two vehicles have <= 16000 milesPerCar so the output is "buy now!" </p>
</article>
<footer>
<p>3/15/12,<NAME></p>
</footer>
<script type="text/javascript" src="HudsonB.js"></script>
</body>
</html><file_sep>/HudsonB.js
alert("Let's Buy A Super Car!");
//say funcion
var say = function(message) {console.log(message)}
;
var car=function(carName){
if (carName === ["Mercedes",
"Ferrari",
"Maserati"]){
say("nice car");
return true;
}else{
say("don't buy");
return false;
};
};
// miles function
var milesPerCar = [15000, 18000, 12000]
;
for (var milage = 0; milage <= milesPerCar.length; milage+=1000){
var currentCarMilage = milesPerCar[milage],
milesPerCar = milage}
;
if (milesPerCar <= 16000){
say ("buy now!")}
else{
say("Don't Buy")
};
| 6cfb222fa83b587a1ef6fa68e0576c99eaf9e671 | [
"JavaScript",
"HTML"
] | 2 | HTML | djhb317/HudsonRepo | 2b5bab17b4177efefce4a93c2b70def442d11f94 | aad9ca482b4d5467a03647be77a8cfb3c74b6f6c |
refs/heads/master | <file_sep><?php
/* @var $this gypsyk\quiz\models\renders\qone_render\QuestionOneRender */
/* @var $question \gypsyk\quiz\models\questions\QuestionOne */
?>
<table class="table table-bordered <?= $question->isUserAnswerIsCorrect() ? 'bg-success' : 'bg-danger' ?>">
<thead>
<tr>
<th><?= $question->text ?></th>
<th class="col-xs-1">Правильный</th>
<th class="col-xs-1">Ваш</th>
</tr>
</thead>
<tbody>
<?php foreach ($question->variants as $variant): ?>
<tr>
<td><?= $variant['text'] ?></td>
<td class="text-center">
<?php if($variant['is_correct']): ?>
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
<?php endif; ?>
</td>
<td class="text-center">
<?php if($variant['is_user_checked']): ?>
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table><file_sep><?php
namespace gypsyk\quiz\assets;
class QuizModuleAsset extends \yii\web\AssetBundle
{
public $sourcePath = '@vendor/gypsyk/yii2-quiz-module/assets';
public $css = [
'css/module.css',
];
public $js = [
];
public $depends = [
'yii\bootstrap\BootstrapAsset'
];
}<file_sep><?php
use yii\helpers\Html;
?>
<div data-question="3" class="g_answer_container">
<p>
Введите текстовый ответ. Учтите, что ответ будет засчитан пользователю только при полном
совпадении введенных данных.
Чтобы помочь пользователям не ошибиться, в тексте вопроса уточните в каком виде неоходимо предоставить ответ.
</p>
<div class="form-group">
<?= Html::textInput('custom', null, ['placeholder' => 'Введите правильный ответ', 'class' => 'form-control'])?>
</div>
</div><file_sep><?php
namespace gypsyk\quiz\models\questions;
use Yii;
use yii\helpers\{Json};
use gypsyk\quiz\models\AR_QuizQuestion;
class QuestionText extends \gypsyk\quiz\models\questions\AbstractQuestion
{
/**
* QuestionText constructor.
* @param AR_QuizQuestion $ar_question
*/
public function __construct(\gypsyk\quiz\models\AR_QuizQuestion $ar_question)
{
$this->renderClass = self::getRenderClass();
$jCorrectAnswers = Json::decode($ar_question->answers, false)[0];
$this->correctAnswer = $jCorrectAnswers->text;
$this->text = $ar_question->question;
$this->jsonVariants = $ar_question->answers;
}
/**
* @inheritdoc
*/
public static function getRenderClass()
{
return '\gypsyk\quiz\models\renders\qtext_render\QuestionTextRender';
}
/**
* Save user answer
*
* @param string $session_answer
*/
public function loadUserAnswer($session_answer)
{
$this->userAnswer = $session_answer;
}
/**
* @inheritdoc
*/
public function isUserAnswerIsCorrect()
{
if(!empty($this->userCorrect))
return $this->userCorrect;
if(trim(mb_strtolower($this->correctAnswer)) == trim(mb_strtolower($this->userAnswer))) {
$this->userCorrect = true;
return true;
}
$this->userCorrect = false;
return false;
}
/**
* @inheritdoc
*/
public static function saveToDb($parameters, $test_id)
{
$question = new AR_QuizQuestion();
$question->question = $parameters['question_text'];
$question->type = $parameters['question_type'];
//Prepare the right answer
$item['id'] = Yii::$app->security->generateRandomString(5);
$item['text'] = Yii::$app->request->post('custom');
$right[] = $item;
$rightId = $item['id'];
$question->answers = Json::encode($right);
$question->r_answers = Json::encode($rightId);
$question->test_id = $test_id;
return $question->save();
}
}
<file_sep><?php
namespace gypsyk\quiz\models\renders\qtext_render;
/**
* Class for rendering the view parts of QuestionText instance
*
* Class QuestionTextRender
* @package gypsyk\quiz\models\renders\qtext_render
*/
final class QuestionTextRender extends \gypsyk\quiz\models\renders\AbstractQuestionRender
{
/**
* QuestionTextRender constructor.
*/
public function __construct()
{
static::$viewFilePath = 'qtext_render/views/';
parent::__construct();
}
}<file_sep><?php
namespace gypsyk\quiz\models\renders;
use gypsyk\quiz\models\renders\Context;
/**
* Class AbstractQuestionRender
* @package gypsyk\quiz\models\renders
*/
abstract class AbstractQuestionRender extends \yii\web\View
{
/**
* @var object - object of \gypsyk\quiz\models\questions\* class
*/
public $question;
/**
* @var string - Keeps the path to renderer views
*/
public static $viewFilePath;
/**
* Load the question object to renderer
*
* @param $question - object of \gypsyk\quiz\models\questions\* class
*/
public function loadQuestion($question)
{
$this->question = $question;
}
/**
* Render the result part of question on results page
*
* @return string
*/
public function renderResult()
{
return parent::render(self::$viewFilePath . 'results', ['question' => $this->question], new Context());
}
/**
* Render the view part when testing in process
*
* @param null $variants
* @param null $sAnswer
* @return string
*/
public function renderTesting($variants = null, $sAnswer = null)
{
return parent::render(
self::$viewFilePath . 'testing',
['answers' => $variants, 'sAnswer' => $sAnswer],
new Context()
);
}
/**
* Render the view part of question on create page
*
* @param $parentViewObject - object of yii\web\View class. Needs for register scripts to correct view
* @return string
*/
public function renderCreate($parentViewObject)
{
return parent::render(self::$viewFilePath . 'create', ['parentViewObject' => $parentViewObject], new Context());
}
}<file_sep><?php
use yii\db\Migration;
/**
* Handles adding description to table `quiz_test`.
*/
class m170525_085413_add_description_column_to_quiz_test_table extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->addColumn('quiz_test', 'description', $this->string(1000));
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropColumn('quiz_test', 'description');
}
}
<file_sep><?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $sAnswer string - user answer stored in session */
?>
<table class="table">
<tr>
<td>
<?= Html::textInput(
'answer',
!empty($sAnswer) ? Html::decode($sAnswer) : null,
['class' => 'form-control']
)?>
</td>
</tr>
</table><file_sep><?php
namespace gypsyk\quiz\controllers;
use Yii;
use yii\data\ActiveDataProvider;
use gypsyk\quiz\models\{AR_QuizQuestion, Quiz, AR_QuizTest, TestSession};
use yii\web\{NotAcceptableHttpException, NotFoundHttpException, BadRequestHttpException};
/**
* Default controller for the `quiz` module
*
* Class DefaultController
* @package gypsyk\quiz\controllers
*/
class DefaultController extends \yii\web\Controller
{
/**
* Includes some necessary assets
*
* @param $view
*/
private function preparePage($view)
{
\gypsyk\quiz\assets\QuizModuleAsset::register($view); //is this a good practice?))
}
/**
* @inheritdoc
*/
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
$this->preparePage($this->getView());
return true;
}
/**
* Renders the list of tests
*
* @return string
* @throws NotFoundHttpException
*/
public function actionIndex()
{
if(!Yii::$app->controller->module->showTestListOnIndex)
throw new NotFoundHttpException('Такой страницы не существует');
$provider = new ActiveDataProvider([
'query' => AR_QuizTest::find(),
'pagination' => [
'pageSize' => Yii::$app->controller->module->testListMaxItems,
],
]);
return $this->render('index', [
'testList' => $provider->getModels(),
'pages' => $provider->getPagination()
]);
}
/**
* Page for rendering test question
*
* @param $question - index number of question
* @return string|\yii\web\Response
* @throws BadRequestHttpException
* @throws NotAcceptableHttpException
*/
public function actionTest($question)
{
$session = new TestSession($question);
if(empty($session->getVar('currentTestId'))) {
throw new BadRequestHttpException('Во время загрузки вопросов произошла ошибка. Попрубуйте зайти в тест заново');
}
if($session->checkTestIsOver()) {
throw new NotAcceptableHttpException('Доступ к тесту невозможен после его завершения');
}
$qModel = Quiz::getQuestionObjectById($session->getRealQuestionNumber($question));
$testTitle = AR_QuizTest::findOne($session->getVar('currentTestId'))->name;
if(Yii::$app->request->isPost) {
//$_POST['answer] keeps the symbolic code of users choosed variants
$session->saveUserAnswer(Yii::$app->request->post('answer'));
if(Yii::$app->request->post('save_btn')) {
$max = $session->getMaxTestQuestionNumber();
if((int)$question < $max) {
return $this->redirect(['test', 'question' => $question+1]);
} else {
return $this->refresh();
}
}
}
return $this->render('test', [
'questionText' => $qModel->getQuestionText(),
'questionRender' => $qModel->loadRender(),
'jsonVariants' => $qModel->jsonVariants,
'questionList' => $session->getVar('questionIds'),
'questionId' => $question,
'sAnswers' => $session->getVar('answers'),
'testTitle' => $testTitle
]);
}
/**
* Proxy page for init session vars
*
* @param $test_id
* @return \yii\web\Response
* @throws NotFoundHttpException
*/
public function actionEnter($test_id)
{
if(empty($test_id)) {
throw new NotFoundHttpException('Такого теста не найдено');
}
$session = new TestSession();
$session->prepareForNewTest($test_id, AR_QuizQuestion::getShuffledQuestionArray($test_id));
return $this->redirect(['test', 'question' => 1]);
}
/**
* The index page of test
*
* @param $test_id
* @return string
* @throws NotFoundHttpException
*/
public function actionTestIndex($test_id)
{
if(empty($test_id)) {
throw new NotFoundHttpException('Такого теста не найдено');
}
$testModel = AR_QuizTest::findOne($test_id);
$countQuestion = AR_QuizQuestion::count($test_id);
return $this->render('test_index', [
'testModel' => $testModel,
'countQuestion' => $countQuestion
]);
}
/**
* Page for displaying the results of testing
*
* @return string
*/
public function actionResults()
{
$session = new TestSession();
$session->markTestAsOver();
$questionList = AR_QuizQuestion::findAll(['test_id' => $session->getVar('currentTestId')]);
$quizModel = new Quiz($questionList, $session->getVar('questionIds'));
$quizModel->loadUserAnswers($session->getVar('answers'));
$quizModel->checkAnswers();
return $this->render('results', [
'quizModel' => $quizModel
]);
}
}
<file_sep><?php
use yii\helpers\{Html, Url};
/* @var $this yii\web\View */
/* @var $testModel gypsyk\quiz\models\AR_QuizTest */
/* @var $countQuestion integer */
$this->title = $testModel->name;
?>
<div class="center-block g_desc_wrapper">
<div class="panel panel-default">
<div class="panel-heading">
<?= Html::encode($testModel->name)?>
</div>
<div class="panel-body">
<p>
<?= Html::encode($testModel->description)?>
</p>
<span><?= Yii::$app->controller->module->t('app', 'Questions') ?>: <?= $countQuestion ?></span>
<?= Html::a(
Yii::$app->controller->module->t('app', 'Enter'),
Url::to(['default/enter', 'test_id' => $testModel->getPrimaryKey()]),
['class' => 'btn btn-primary pull-right']
)?>
<div class="clearfix"></div>
</div>
</div>
</div><file_sep><?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $tList array - select options (question types) */
/* @var $testModel \gypsyk\quiz\models\AR_QuizTest */
/* @var $questionList \gypsyk\quiz\models\AR_QuizQuestion[] */
/* @var $questionViews string - result of concatenation of all question renderers renderCreate() functions; */
$this->title = \Yii::$app->controller->module->t('app', 'Add question. {testName}.', [
'testName' => $testModel->name
]);
?>
<div class="row">
<div class="col-xs-6">
<?= Html::beginForm()?>
<div class="form-group">
<?= Html::label(\Yii::$app->controller->module->t('app', 'Question text'))?>
<?= Html::textarea('question_text', '', [
'class' => 'form-control',
'rows' => 7,
'placeholder' => \Yii::$app->controller->module->t('app', 'Enter the text of the question')]
)?>
</div>
<div class="form-group">
<?= Html::label(\Yii::$app->controller->module->t('app', 'Type of answer'))?>
<?= Html::dropDownList('question_type', null, $tList, [
'class' => 'form-control',
'options'=>['0' => ['disabled' => true, 'selected' => true]]
])?>
</div>
<?= \gypsyk\quiz\models\Quiz::renderQuestionCreate($this) ?>
<?= Html::submitButton(
\Yii::$app->controller->module->t('app', 'Save and add more'),
['class' => 'btn btn-success pull-right g_btn']
)?>
<?= Html::submitButton(
\Yii::$app->controller->module->t('app', 'Complete creation'),
['class' => 'btn btn-primary pull-right g_btn']
)?>
<div class="clearfix"></div>
<?= Html::endForm()?>
</div>
<div class="col-xs-6">
<h3>
<small><?= \Yii::$app->controller->module->t('app', 'Test')?>: </small>
<?= $testModel->name?>
</h3>
<ol>
<?php foreach($questionList as $question): ?>
<li><?= $question->question ?></li>
<?php endforeach; ?>
</ol>
</div>
</div>
<?php $script = <<< JS
$('select[name="question_type"]').change(function() {
g_toogle($(this).val());
});
JS;
$this->registerJs($script, yii\web\View::POS_READY); ?>
<?php $script = <<< JS
function g_toogle(value) {
$('.g_answer_container').hide();
$('div[data-question="' + value + '"]').show();
}
JS;
$this->registerJs($script, yii\web\View::POS_END); ?><file_sep><?php
namespace gypsyk\quiz\models;
use Yii;
use gypsyk\quiz\models\AR_QuizQuestionType;
/**
* This is the model class for table "quiz_question".
*
* @property integer $id
* @property integer $type
* @property string $question
* @property string $answers
* @property string $r_answers
* @property string $test_id
*
*/
class AR_QuizQuestion extends \yii\db\ActiveRecord
{
const TYPE_ONE = 'ONE';
const TYPE_MULTIPLE = 'MULTIPLE';
const TYPE_TEXT = 'TEXT';
/**
* @inheritdoc
*/
public static function tableName()
{
return 'quiz_question';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['type', 'question', 'r_answers', 'test_id'], 'required'],
[['type', 'test_id'], 'integer'],
[['question', 'answers', 'r_answers'], 'string'],
];
}
/**
* Return the AR array of questions with needed $test_id
*
* @param $test_id
* @return static[]
*/
public static function getTestQuestions($test_id)
{
return static::findAll(['test_id' => $test_id]);
}
/**
* Shuffle the test question.
* Returns array: [1 => 43, 2 => 46, ... {counter} => {db_id}]
*
* @param $test_id
* @return array
*/
public static function getShuffledQuestionArray($test_id)
{
$questionList = static::findAll(['test_id' => $test_id]);
shuffle($questionList);
//Make a normal question order to hide real ids
$i = 1;
$tempList = [];
foreach ($questionList as $question) {
$tempList[$i] = $question->getPrimaryKey();
$i++;
}
return $tempList;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getType_q()
{
return $this->hasOne(AR_QuizQuestionType::className(), ['id' => 'type']);
}
/**
* Get question type code
*
* @return mixed
*/
public function getTypeCode()
{
return $this->type_q->code;
}
/**
* Count the questions in test
*
* @param $test_id
* @return int
*/
public static function count($test_id)
{
return count(static::findAll(['test_id' => $test_id]));
}
}
<file_sep><?php
namespace gypsyk\quiz;
/**
* Quiz module class
*
* Class Module
* @package gypsyk\quiz
*/
class Module extends \yii\base\Module
{
/**
* @var bool - If true, shows the list of all test on index page
*/
public $showTestListOnIndex = true;
/**
* @var int - Test per page in indesx page
*/
public $testListMaxItems = 10;
/**
* @inheritdoc
*/
public $controllerNamespace = 'gypsyk\quiz\controllers';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->registerTranslations();
}
/**
* @inheritdoc
*/
public function registerTranslations()
{
\Yii::$app->i18n->translations['gypsyk/quiz/*'] = [
'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'en-US',
'basePath' => '@vendor/gypsyk/yii2-quiz-module/messages',
'fileMap' => [
'gypsyk/quiz/app' => 'g_app.php',
],
];
}
/**
* @inheritdoc
*/
public static function t($category, $message, $params = [], $language = null)
{
return \Yii::t('gypsyk/quiz/' . $category, $message, $params, $language);
}
}
<file_sep><?php
namespace gypsyk\quiz\models\questions;
/**
* Interface that question object must implement
*
* Interface QuestionInterface
* @package gypsyk\quiz\models\questions
*/
interface QuestionInterface
{
/**
* Return the question render class name
*
* @return mixed
*/
public static function getRenderClass();
/**
* Save the user answer info
*
* @param $session_answer
*/
public function loadUserAnswer($session_answer);
/**
* Check if user answer is correct
*
* @return bool|null
*/
public function isUserAnswerIsCorrect();
/**
* Save question info to database
*
* @param $parameters
* @param $test_id
* @return bool
*/
public static function saveToDb($parameters, $test_id);
}
<file_sep><?php
use yii\helpers\Html;
?>
<div data-question="1" class="g_answer_container">
<?= Html::label('Варианты ответа')?><br/>
<?= Html::a('<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Добавить вариант', '#', ['onclick' => 'g_add_one(event);'])?>
<table class="table">
<tr>
<td class="col-xs-11">
<div>
<?= Html::textInput('wrong_one[]', null, ['placeholder' => 'Введите вариант ответа', 'class' => 'form-control'])?>
<span class="help-block">Правильный</span>
</div>
</td>
<td>
<?= Html::checkbox('question_answers', false, ['data-control' => 'chk_one', 'onclick' => 'g_chkOneClick(this)'])?>
</td>
</tr>
<tr>
<td class="col-xs-11">
<div>
<?= Html::textInput('wrong_one[]', null, ['placeholder' => 'Введите вариант ответа', 'class' => 'form-control'])?>
<span class="help-block">Правильный</span>
</div>
</td>
<td>
<?= Html::checkbox('question_answers', false, ['data-control' => 'chk_one', 'onclick' => 'g_chkOneClick(this)'])?>
</td>
</tr>
</table>
</div>
<?php
$inputTxt_one = Html::textInput('wrong_one[]', null, ['placeholder' => 'Введите вариант ответа', 'class' => 'form-control']);
$inputChk_one = Html::checkbox('question_answers', false, ['data-control' => 'chk_one', 'onclick' => 'g_chkOneClick(this)']);
?>
<?php $script = <<< JS
function g_add_one(event) {
event.preventDefault();
var in_group = '<tr>';
in_group = in_group + '<tr>';
in_group = in_group + '<td class="col-xs-11">';
in_group = in_group + '<div>';
in_group = in_group + '$inputTxt_one';
in_group = in_group + '<span class="help-block">Правильный</span>';
in_group = in_group + '</div>';
in_group = in_group + '</td>';
in_group = in_group + '<td>';
in_group = in_group + '$inputChk_one';
in_group = in_group + '</td>';
in_group = in_group + '</tr>';
$('.g_answer_container[data-question="1"] table').prepend(in_group);
}
function g_chkOneClick(elem) {
var input = $(elem).parents('tr').find('input[type="text"]');
var other = $('input[data-control="chk_one"]').not(elem);
input.attr('name', 'right_one');
input.parent('div').toggleClass('has-success');
other.each(function() {
if($(this)[0].checked) {
$(this).prop('checked', false);
g_mark_wrong_one($(this));
}
})
}
function g_mark_wrong_one(chbx_element) {
var input = chbx_element.parents('tr').find('input[type="text"]');
input.attr('name', 'wrong_one[]');
input.parent('div').removeClass('has-success');
}
JS;
$parentViewObject->registerJs($script, yii\web\View::POS_END); ?><file_sep><?php
use yii\db\Migration;
class m170513_022454_create_quiz_question_type extends Migration
{
public function up()
{
$this->createTable('quiz_question_type', [
'id' => $this->primaryKey(),
'description' => $this->string()->notNull()->comment('Type description'),
'code' => $this->string()->notNull()->comment('Code for type identification')
]);
$this->addCommentOnTable('quiz_question_type', 'Types of questions');
$this->insert('quiz_question_type', ['description' => 'One correct answer', 'code' => 'ONE']);
$this->insert('quiz_question_type', ['description' => 'Multiple correct answers', 'code' => 'MULTIPLE']);
$this->insert('quiz_question_type', ['description' => 'Text answer', 'code' => 'TEXT']);
}
public function down()
{
$this->dropTable('quiz_question_type');
}
}
<file_sep><?php
namespace gypsyk\quiz\models\renders\qone_render;
/**
* Class for rendering the view parts of QuestionOne instance
*
* Class QuestionOneRender
* @package gypsyk\quiz\models\renders\qone_render
*/
final class QuestionOneRender extends \gypsyk\quiz\models\renders\AbstractQuestionRender
{
/**
* QuestionOneRender constructor.
*/
public function __construct()
{
static::$viewFilePath = 'qone_render/views/';
parent::__construct();
}
}
<file_sep><?php
namespace gypsyk\quiz\models\questions;
use Yii;
use yii\helpers\Html;
/**
* Main parent class for all question instances
*
* Class AbstractQuestion
* @package gypsyk\quiz\models\questions
*/
abstract class AbstractQuestion implements QuestionInterface
{
/**
* @var bool|null - Flag to mark user answer correct/not correct
*/
public $userCorrect;
/**
* @var string - Text of question
*/
public $text;
/**
* @var string|array|object - Keeps the json decoded object or just a text answer from `quiz_question`.`r_answers`
*/
public $correctAnswer;
/**
* @var string|array - Keeps the user answer for question. Can be just text (for text question) or array of codes,
* that stored in `quiz_question`.`r_answers` in 'id' property of json string
*/
public $userAnswer;
/**
* @var string - Json string form `quiz_question`.`answers` field
*/
public $jsonVariants;
/**
* @var null|array - Keeps the info about question variants of answer.
* It is an array of the following type [
* 'text' => (string)question text,
* 'is_correct' => (bool) flag to mark as correct,
* 'is_user_checked' => (bool) flag to mark id user checked this variant
* ]
*/
public $variants = null;
/**
* @var string - Keeps the class name of question render object
*/
protected $renderClass;
/**
* @var object - Instance of $this->renderClass class
*/
protected $renderer;
/**
* Get the question render object. And load question object to it.
*
* @return object
* @throws \yii\base\InvalidConfigException
*/
public function loadRender()
{
if(empty($this->renderer)) {
$this->renderer = Yii::createObject($this->renderClass);
$this->renderer->loadQuestion($this);
}
return $this->renderer;
}
/**
* Get the text of the question
*
* @return string
*/
public function getQuestionText()
{
return Html::encode($this->text);
}
}
<file_sep><?php
use yii\db\Migration;
class m170513_022427_create_quiz_test extends Migration
{
public function up()
{
$this->createTable('quiz_test', [
'id' => $this->primaryKey(),
'name' => $this->string()->notNull()->comment('Test title'),
]);
$this->addCommentOnTable('quiz_test', 'List of tests');
}
public function down()
{
$this->dropTable('quiz_test');
}
}
<file_sep><?php
namespace gypsyk\quiz\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "quiz_question_type".
*
* @property integer $id
* @property string $description
* @property string $code
*
*/
class AR_QuizQuestionType extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'quiz_question_type';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['description', 'code'], 'required'],
[['description', 'code'], 'string'],
];
}
}
<file_sep><?php
/* @var $this gypsyk\quiz\models\renders\qtext_render\QuestionTextRender */
/* @var $question \gypsyk\quiz\models\questions\QuestionText */
?>
<table class="table table-bordered <?= $question->isUserAnswerIsCorrect() ? 'bg-success' : 'bg-danger' ?>">
<thead>
<tr>
<th>Вопрос</th>
<th class="col-xs-1">Правильный</th>
<th class="col-xs-1">Ваш</th>
</tr>
</thead>
<tbody>
<tr>
<td><?= $question->text ?></td>
<td><?= $question->correctAnswer ?></td>
<td><?= $question->userAnswer ?></td>
</tr>
</tbody>
</table><file_sep><?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $testModel gypsyk\quiz\models\AR_QuizTest */
$this->title = \Yii::$app->controller->module->t('app', 'New test');
?>
<div class="row">
<div class="col-xs-6 col-xs-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<?php $form = ActiveForm::begin() ?>
<?= $form->field($testModel, 'name') ?>
<?= $form->field($testModel, 'description')->textarea(['rows' => 3]) ?>
<div class="form-group">
<div class="pull-right">
<?= Html::submitButton(
\Yii::$app->controller->module->t('app', 'Create'),
['class' => 'btn btn-primary']
) ?>
</div>
<div class="clearfix"></div>
</div>
<?php ActiveForm::end() ?>
</div>
</div>
</div>
</div>
<file_sep><?php
namespace gypsyk\quiz\controllers;
use Yii;
use yii\data\ActiveDataProvider;
use yii\web\{Controller, NotFoundHttpException};
use gypsyk\quiz\models\{Quiz, AR_QuizTest, AR_QuizQuestionType, AR_QuizQuestion};
/**
* Controller for administration
*
* Class AdminController
* @package gypsyk\quiz\controllers
*/
class AdminController extends Controller
{
/**
* Includes some necessary assets
*
* @param $view
*/
private function preparePage($view)
{
\gypsyk\quiz\assets\QuizModuleAsset::register($view); //is this a good practice?))
}
/**
* @inheritdoc
*/
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
$this->preparePage($this->getView());
return true;
}
/**
* Render the list of tests
*
* @return string
*/
public function actionIndex()
{
$provider = new ActiveDataProvider([
'query' => AR_QuizTest::find(),
'pagination' => [
'pageSize' => Yii::$app->controller->module->testListMaxItems,
],
]);
return $this->render('index', [
'testList' => $provider->getModels(),
'pages' => $provider->getPagination()
]);
}
/**
* Page for creating the test
*
* @return string|\yii\web\Response
*/
public function actionCreate()
{
$testModel = new AR_QuizTest();
if(Yii::$app->request->isPost) {
if($testModel->load(Yii::$app->request->post()) && $testModel->validate()) {
$testModel->save();
return $this->redirect(['new-question', 'test_id' => $testModel->getPrimaryKey()]);
}
}
return $this->render('create', [
'testModel' => $testModel
]);
}
/**
* Page for adding new question to test
*
* @param $test_id int - test id from database
* @return string|\yii\web\Response
* @throws NotFoundHttpException
*/
public function actionNewQuestion($test_id)
{
if(empty($test_id)) {
throw new NotFoundHttpException('Такого теста не найдено');
}
if(Yii::$app->request->isPost) {
$result = Quiz::saveQuestionToDb(Yii::$app->request->post(), $test_id);
if($result) {
return $this->refresh();
}
}
$questionList = AR_QuizQuestion::getTestQuestions($test_id);
$testModel = AR_QuizTest::findOne($test_id);
$types = AR_QuizQuestionType::find()->all();
$tList[0] = Yii::$app->controller->module->t('app', 'Select type of answer...');
foreach ($types as $type) {
$tList[$type->getPrimaryKey()] = Yii::$app->controller->module->t('app', $type->description);
}
return $this->render('new_question', [
'questionList' => $questionList,
'testModel' => $testModel,
'tList' => $tList
]);
}
}
<file_sep><?php
namespace gypsyk\quiz\models\renders\qmultiple_render;
/**
* Class for rendering the view parts of QuestionMultiple instance
*
* Class QuestionMultipleRender
* @package gypsyk\quiz\models\renders\qmultiple_render
*/
final class QuestionMultipleRender extends \gypsyk\quiz\models\renders\AbstractQuestionRender
{
/**
* QuestionMultipleRender constructor.
*/
public function __construct()
{
static::$viewFilePath = 'qmultiple_render/views/';
parent::__construct();
}
}
<file_sep><?php
namespace gypsyk\quiz\models\renders;
/**
* Context for locating the views of render object
*
* Class Context
* @package gypsyk\quiz\models\renders
*/
class Context implements \yii\base\ViewContextInterface
{
/**
* @inheritdoc
*/
public function getViewPath()
{
return __DIR__;
}
}<file_sep><?php
use yii\helpers\Html;
/* @var $answers array - Array of json decoded objects from `quiz_question`.`answers ` field */
/* @var $this yii\web\View */
/* @var $sAnswer string - user answer_id stored in session */
?>
<table class="table">
<?php foreach($answers as $answer): ?>
<tr>
<td class="col-xs-1">
<?= Html::radio(
'answer',
!empty($sAnswer) && $answer->id == $sAnswer,
[
'value' => $answer->id,
'required' => 'required'
])
?>
</td>
<td><?= Html::decode($answer->text) ?></td>
</tr>
<?php endforeach; ?>
</table><file_sep><?php
return [
'One correct answer' => 'Один правильный',
'Multiple correct answers' => 'Несколько правильных',
'Text answer' => 'Ответ текстом',
'Select type of answer...' => 'Выберите тип ответа...',
'Questions' => 'Вопросов',
'Enter' => 'Приступить',
'Answer' => 'Ответить',
'Finish testing' => 'Завершить тест',
'Are you sure you want to finish the test? You will not be able to change your answers.' => 'Вы уверены, что хотите завершить тест? Изменить ваши ответы будет невозможно.',
'Question № {questionNumber}. {testTitle}' => 'Вопрос № {questionNumber}. {testTitle}',
'Test results' => 'Результаты тестирования',
'Number of questions' => 'Всего вопросов',
'Number of correct answers' => 'Правильных ответов',
'Number of wrong answers' =>'Неправильных ответов',
'Detailing' => 'Детализация',
'Test list' => 'Список тестов',
'To test' => 'Перейти',
'Edit' => 'Редактировать',
'Create test' => 'Создать тест',
'Test name' => 'Тема теста',
'Description' => 'Описание',
'New test' => 'Новый тест',
'Create' => 'Создать',
'Question text' => 'Текст вопроса',
'Enter the text of the question' => 'Введите текст вопроса',
'Type of answer' => 'Тип ответа',
'Add question. {testName}.' => 'Добавить вопрос. {testName}.',
'Test' => 'Тест',
'Save and add more' => 'Сохранить и добавить еще',
'Complete creation' => 'Завершить создание'
];
<file_sep><?php
namespace gypsyk\quiz\models\questions;
use Yii;
use yii\helpers\{Json, ArrayHelper};
use gypsyk\quiz\models\AR_QuizQuestion;
/**
* Class for representing question that have multiple correct answers
*
* Class QuestionMultiple
* @package gypsyk\quiz\models\questions
*/
class QuestionMultiple extends \gypsyk\quiz\models\questions\AbstractQuestion
{
/**
* QuestionMultiple constructor.
* @param AR_QuizQuestion $ar_question
*/
public function __construct(\gypsyk\quiz\models\AR_QuizQuestion $ar_question)
{
$this->renderClass = self::getRenderClass();
$jcorrectAnswer = Json::decode($ar_question->r_answers, false);
$this->correctAnswer = $jcorrectAnswer;
$this->text = $ar_question->question;
$this->jsonVariants = $ar_question->answers;
foreach (Json::decode($ar_question->answers, false) as $jVariant) {
$isCorrect = in_array($jVariant->id, $jcorrectAnswer) ? true : false;
$this->variants[$jVariant->id] = [
'text' => $jVariant->text,
'is_correct' => $isCorrect,
'is_user_checked' => false
];
}
}
/**
* @inheritdoc
*/
public static function getRenderClass()
{
return '\gypsyk\quiz\models\renders\qmultiple_render\QuestionMultipleRender';
}
/**
* Mark a variant as user checked and save the user answer
*
* @param array $session_answer
*/
public function loadUserAnswer($session_answer)
{
foreach ($session_answer as $answer) {
$this->variants[$answer]['is_user_checked'] = true;
}
$this->userAnswer = $session_answer;
}
/**
* @inheritdoc
*/
public function isUserAnswerIsCorrect()
{
if(!empty($this->userCorrect))
return $this->userCorrect;
if($this->correctAnswer == $this->userAnswer) {
$this->userCorrect = true;
return true;
}
$this->userCorrect = false;
return false;
}
/**
* @inheritdoc
*/
public static function saveToDb($parameters, $test_id)
{
$question = new AR_QuizQuestion();
$question->question = $parameters['question_text'];
$question->type = $parameters['question_type'];
foreach (Yii::$app->request->post('wrong_many') as $wrongMany) {
$item['id'] = Yii::$app->security->generateRandomString(5);
$item['text'] = $wrongMany;
$wrong[] = $item;
}
foreach (Yii::$app->request->post('right_many') as $rightMany) {
$item['id'] = Yii::$app->security->generateRandomString(5);
$item['text'] = $rightMany;
$right[] = $item;
$rightIds[] = $item['id'];
}
$all = ArrayHelper::merge($wrong, $right);
$question->answers = Json::encode($all);
$question->r_answers = Json::encode($rightIds);
$question->test_id = $test_id;
return $question->save();
}
}
<file_sep><?php
use yii\db\Migration;
class m170513_022510_create_quiz_question extends Migration
{
public function up()
{
$this->createTable('quiz_question', [
'id' => $this->primaryKey(),
'test_id' => $this->integer()->notNull()->comment('Test id'),
'type' => $this->integer()->notNull()->comment('Question type'),
'question' => $this->text()->notNull()->comment('Question text'),
'answers' => 'JSON' . ' DEFAULT NULL COMMENT "Variants of answers"',
'r_answers' => 'JSON' . ' NOT NULL COMMENT "Right answer(-s)"'
]);
$this->addCommentOnTable('quiz_question', 'List of tests questions');
//Foreign key for test table
$this->createIndex('idx-quiz_question-test_id', 'quiz_question', 'test_id');
$this->addForeignKey('fk-quiz_question-test_id', 'quiz_question', 'test_id', 'quiz_test', 'id', 'CASCADE', 'CASCADE');
//Foreign key for question-type table
$this->createIndex('idx-quiz_question-type', 'quiz_question', 'type');
$this->addForeignKey('fk-quiz_question-type', 'quiz_question', 'type', 'quiz_question_type', 'id', 'CASCADE', 'CASCADE');
}
public function down()
{
$this->dropForeignKey('fk-quiz_question-test_id', 'quiz_question');
$this->dropIndex('idx-quiz_question-test_id', 'quiz_question');
$this->dropForeignKey('fk-quiz_question-type', 'quiz_question');
$this->dropIndex('idx-quiz_question-type', 'quiz_question');
$this->dropTable('quiz_question');
}
}
<file_sep><?php
use yii\helpers\{Html, Url, Json};
/* @var $this yii\web\View */
/* @var $questionText string */
/* @var $questionRender object - object of \gypsyk\quiz\models\renders\* class */
/* @var $testTitle string */
/* @var $questionList array - question numbers map */
/* @var $questionId integer - number of question in current test session */
/* @var $jsonVariants string - Json string from `quiz_question`.`answers` field */
/* @var $sAnswers array - Array of user answers stored in session */
$this->title = \Yii::$app->controller->module->t('app', 'Question № {questionNumber}. {testTitle}', [
'questionNumber' => $questionId,
'testTitle' => $testTitle
]);
?>
<p>
<?= Html::decode($questionText)?>
</p>
<?= Html::beginForm()?>
<?= $questionRender->renderTesting(Json::decode($jsonVariants, false), $sAnswers[$questionId] ?? null) ?>
<?= Html::submitButton(
\Yii::$app->controller->module->t('app', 'Answer'),
['class' => 'btn btn-success', 'name' => 'save_btn', 'value' => '1']
)?>
<?= Html::a(
\Yii::$app->controller->module->t('app', 'Finish testing'),
Url::to(['results']),
['class' => 'btn btn-danger', 'id'=>'g_end_test_btn']
)?>
<?= Html::endForm()?>
<ul class="pagination">
<?php foreach($questionList as $key => $value): ?>
<li class="<?= $questionId == $key ? 'active' : ''?>">
<a href="<?= Url::to(['test', 'question' => $key]) ?>">
<?=$key?>
<?php if(!empty($sAnswers[$key])): ?>
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
<?php endif; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php
$confirmMessage = \Yii::$app->controller->module->t('app', 'Are you sure you want to finish the test? You will not be able to change your answers.');
?>
<?php $script = <<< JS
$('#g_end_test_btn').click(function(event) {
var href = this.href;
event.preventDefault();
var isOver = confirm("$confirmMessage");
if(isOver)
window.location = href;
})
JS;
$this->registerJs($script, yii\web\View::POS_READY); ?>
<file_sep><?php
namespace gypsyk\quiz\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* Class TestSession for keeping the current user answers and other current test session data
* @package gypsyk\quiz\models
*/
class TestSession
{
/**
* @var mixed|\yii\web\Session
*/
private $session;
/**
* @var null - question number parameter from url
*/
private $qSessionNumber;
/**
* TestSession constructor.
* @param null $current_question_session_number
*/
public function __construct($current_question_session_number = null)
{
$this->session = Yii::$app->session;
if(!$this->session->isActive)
$this->session->open();
if(!empty($current_question_session_number))
$this->qSessionNumber = $current_question_session_number;
}
/**
* Return value of session variable
*
* @param $var_name
* @return mixed
*/
public function getVar($var_name)
{
return $this->session[$var_name];
}
/**
* Get database question number
*
* @param $q_number
* @return mixed
*/
public function getRealQuestionNumber($q_number)
{
return $this->session['questionIds'][$q_number];
}
/**
* Check of test is over (User pressed end button)
*
* @return bool
*/
public function checkTestIsOver()
{
if(!empty($this->session['isResults'])) {
if($this->session['isResults'])
return true;
}
return false;
}
/**
* Save user answer to session
*
* @param $post_answer
*/
public function saveUserAnswer($post_answer)
{
//If the answer has already been given
if(array_key_exists($this->qSessionNumber, $this->session['answers'])) {
$answersTemp = $this->session['answers'];
$answersTemp[$this->qSessionNumber] = $post_answer;
$this->session['answers'] = $answersTemp;
} else {
$this->session['answers'] = ArrayHelper::merge(
$this->session['answers'],
[$this->qSessionNumber => $post_answer]
);
}
}
/**
* Get max question number in question list
*
* @return mixed
*/
public function getMaxTestQuestionNumber()
{
return max(array_keys($this->session['questionIds']));
}
/**
* Prepare session array for new test
*
* @param $test_id
* @param $question_map
*/
public function prepareForNewTest($test_id, $question_map)
{
$this->session->remove('currentTestId');
$this->session->remove('questionIds');
$this->session->remove('answers');
$this->session->remove('isResults');
$this->session['currentTestId'] = $test_id;
$this->session['questionIds'] = $question_map;
$this->session['answers'] = [];
}
/**
* Mark test as over
*/
public function markTestAsOver()
{
$this->session['isResults'] = true;
}
}
<file_sep><?php
namespace gypsyk\quiz\models;
use Yii;
use gypsyk\quiz\models\AR_QuizQuestion;
use gypsyk\quiz\models\helpers\QuestionsTypeMapper;
/**
* Class for working with test data
*
* Class Quiz
* @package gypsyk\quiz\models
*/
class Quiz
{
/**
* @var array - Array of instances \gypsyk\quiz\models\questions\*
*/
public $questions;
/**
* @var array - Array for mapping question numbers. Example: [1 => 43, 2 => 46, ... {counter} => {db_id}]
*/
public $idsMap;
/**
* @var array - Keeps statistic info. Array keys are: maxPoints, points, rightAnswersCount, wrongAnswersCount
*/
public $statistics;
/**
* @var integer - Test id from database
*/
public $testId;
/**
* Quiz constructor.
* @param $ar_questions array
* @param $id_map array
*/
public function __construct($ar_questions, $id_map)
{
$this->idsMap = $id_map;
$classMap = new QuestionsTypeMapper();
foreach($ar_questions as $question) {
$sessionQuestionNumber = array_search($question->getPrimaryKey(), $id_map);
$this->questions[$sessionQuestionNumber] = Yii::createObject(
$classMap->getQuestionClassByTypeName($question->type_q->code),
[$question]
);
}
}
/**
* Load user answers
*
* @param $session_answers
*/
public function loadUserAnswers($session_answers)
{
foreach ($session_answers as $key => $value) {
$this->questions[$key]->loadUserAnswer($value);
}
}
/**
* Check all user answers
*
* @return mixed
*/
public function checkAnswers()
{
$maxPoints = count($this->questions);
$points = $maxPoints;
$rightAnswersCount = 0;
$wrongAnswersCount = 0;
foreach ($this->questions as $question) {
if(!$question->isUserAnswerIsCorrect()) {
$wrongAnswersCount++;
$points--;
} else {
$rightAnswersCount++;
}
}
$this->statistics['maxPoints'] = $maxPoints;
$this->statistics['points'] = $points;
$this->statistics['rightAnswersCount'] = $rightAnswersCount;
$this->statistics['wrongAnswersCount'] = $wrongAnswersCount;
}
/**
* Save the question to database
*
* @param $parameters
* @param $test_id
* @return mixed
*/
public static function saveQuestionToDb($parameters, $test_id)
{
$qClass = (new QuestionsTypeMapper())->getQuestionClassByTypeId($parameters['question_type']);
return forward_static_call([$qClass, 'saveToDb'], $parameters, $test_id);
}
/**
* Create and return question object
*
* @param $id
* @return bool|object
* @throws \yii\base\InvalidConfigException
*/
public static function getQuestionObjectById($id)
{
$questionModel = AR_QuizQuestion::findOne($id);
if(empty($questionModel))
return false;
$qClass = (new QuestionsTypeMapper())->getQuestionClassByTypeName($questionModel->getTypeCode());
return Yii::createObject($qClass, [$questionModel]);
}
/**
* Return the render part contains question create form
*
* @param $viewObject
* @return string
* @throws \yii\base\InvalidConfigException
*/
public static function renderQuestionCreate($viewObject)
{
$questionClassesList = QuestionsTypeMapper::getAllClasses();
$renderResult = '';
foreach ($questionClassesList as $questionClass) {
$render = Yii::createObject($questionClass::getRenderClass());
$renderResult .= $render->renderCreate($viewObject);
}
return $renderResult;
}
}
<file_sep><?php
use yii\widgets\LinkPager;
use yii\helpers\{Html, Url};
/* @var $this yii\web\View */
/* @var $testList gypsyk\quiz\models\AR_QuizTest[] */
/* @var $pages integer */
$this->title = \Yii::$app->controller->module->t('app', 'Test list');
?>
<h2><?= \Yii::$app->controller->module->t('app', 'Test list') ?></h2>
<div class="g_test_list_table_wrapper">
<table class="table table-striped">
<?php foreach($testList as $item): ?>
<tr>
<td>
<?= $item->name ?>
</td>
<td align="right">
<?= Html::a(
\Yii::$app->controller->module->t('app', 'To test'),
Url::to(['test-index', 'test_id' => $item['id']]),
['class' => 'btn btn-primary btn-small']
)?>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?= LinkPager::widget(['pagination' => $pages]); ?><file_sep><?php
use yii\helpers\Html;
?>
<div data-question="2" class="g_answer_container">
<?= Html::label('Варианты ответа')?><br/>
<?= Html::a('<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Добавить вариант', '#', ['onclick' => 'g_add_many(event);'])?>
<table class="table">
<tr>
<td class="col-xs-11">
<div>
<?= Html::textInput('wrong_many[]', null, ['placeholder' => 'Введите вариант ответа', 'class' => 'form-control'])?>
<span class="help-block">Правильный</span>
</div>
</td>
<td>
<?= Html::checkbox('question_answers', false, ['data-control' => 'chk_many', 'onclick' => 'g_chkManyClick(this)'])?>
</td>
</tr>
<tr>
<td class="col-xs-11">
<div>
<?= Html::textInput('wrong_many[]', null, ['placeholder' => 'Введите вариант ответа', 'class' => 'form-control'])?>
<span class="help-block">Правильный</span>
</div>
</td>
<td>
<?= Html::checkbox('question_answers', false, ['data-control' => 'chk_many', 'onclick' => 'g_chkManyClick(this)'])?>
</td>
</tr>
</table>
</div>
<?php
$inputTxt_many = Html::textInput('wrong_many[]', null, ['placeholder' => 'Введите вариант ответа', 'class' => 'form-control']);
$inputChk_many = Html::checkbox('question_answers', false, ['data-control' => 'chk_many', 'onclick' => 'g_chkManyClick(this)']);
?>
<?php $script = <<< JS
function g_add_many() {
event.preventDefault();
var in_group = '<tr>';
in_group = in_group + '<tr>';
in_group = in_group + '<td class="col-xs-11">';
in_group = in_group + '<div>';
in_group = in_group + '$inputTxt_many';
in_group = in_group + '<span class="help-block">Правильный</span>';
in_group = in_group + '</div>';
in_group = in_group + '</td>';
in_group = in_group + '<td>';
in_group = in_group + '$inputChk_many';
in_group = in_group + '</td>';
in_group = in_group + '</tr>';
$('.g_answer_container[data-question="2"] table').prepend(in_group);
}
function g_chkManyClick(elem) {
var input = $(elem).parents('tr').find('input[type="text"]');
var other = $('input[data-control="chk_many"]').not(elem);
input.attr('name', 'right_many[]');
input.parent('div').toggleClass('has-success');
}
JS;
$parentViewObject->registerJs($script, yii\web\View::POS_END); ?>
<file_sep><?php
namespace gypsyk\quiz\models\helpers;
use gypsyk\quiz\models\AR_QuizQuestionType;
/**
* Class for mapping question class name and code of type
*
* Class QuestionsTypeMapper
* @package gypsyk\quiz\models\helpers
*/
class QuestionsTypeMapper
{
/**
* Array to store map info
*/
private $map;
public function __construct()
{
$this->map['ONE'] = '\gypsyk\quiz\models\questions\QuestionOne';
$this->map['MULTIPLE'] = '\gypsyk\quiz\models\questions\QuestionMultiple';
$this->map['TEXT'] = '\gypsyk\quiz\models\questions\QuestionText';
}
/**
* Get question class name by its code name
*
* @param $type_name
* @return bool
*/
public function getQuestionClassByTypeName($type_name)
{
if(!array_key_exists($type_name, $this->map))
return false;
return $this->map[$type_name];
}
/**
* Get question class name by its codes database id
*
* @param $type_id
* @return bool
*/
public function getQuestionClassByTypeId($type_id)
{
$arType = AR_QuizQuestionType::findOne($type_id);
if(empty($arType))
return false;
return $this->map[$arType->code];
}
/**
* Get all question classes list
*
* @return array
*/
public static function getAllClasses()
{
$classes = new static();
return array_values($classes->map);
}
}<file_sep><?php
/* @var $this yii\web\View */
/* @var $quizModel gypsyk\quiz\models\Quiz */
$this->title = \Yii::$app->controller->module->t('app', 'Test results');
?>
<h1><?= \Yii::$app->controller->module->t('app', 'Test results') ?></h1>
<p>
<?= \Yii::$app->controller->module->t('app', 'Number of questions')?>:
<?= $quizModel->statistics['maxPoints'] ?>
</p>
<p>
<?= \Yii::$app->controller->module->t('app', 'Number of correct answers')?>:
<?= $quizModel->statistics['rightAnswersCount'] ?>
</p>
<p>
<?= \Yii::$app->controller->module->t('app', 'Number of wrong answers')?>:
<?= $quizModel->statistics['wrongAnswersCount'] ?>
</p>
<h2><?= \Yii::$app->controller->module->t('app', 'Detailing') ?></h2>
<?php foreach ($quizModel->questions as $question): ?>
<?= $question->loadRender()->renderResult($this) ?>
<hr>
<?php endforeach; ?><file_sep><?php
namespace gypsyk\quiz\models\questions;
use Yii;
use yii\helpers\{Json, ArrayHelper};
use gypsyk\quiz\models\AR_QuizQuestion;
/**
* Class that representing the question that have only one correct answer
*
* Class QuestionOne
* @package gypsyk\quiz\models\questions
*/
class QuestionOne extends \gypsyk\quiz\models\questions\AbstractQuestion
{
/**
* QuestionOne constructor.
* @param AR_QuizQuestion $ar_question
*/
public function __construct(\gypsyk\quiz\models\AR_QuizQuestion $ar_question)
{
$this->renderClass = self::getRenderClass();
$jCorrectAnswer = Json::decode($ar_question->r_answers, false);
$this->correctAnswer = $jCorrectAnswer;
$this->text = $ar_question->question;
$this->jsonVariants = $ar_question->answers;
foreach (Json::decode($ar_question->answers, false) as $jVariant) {
$isCorrect = ($jCorrectAnswer == $jVariant->id) ? true : false;
$this->variants[$jVariant->id] = [
'text' => $jVariant->text,
'is_correct' => $isCorrect,
'is_user_checked' => false
];
}
}
/**
* @inheritdoc
*/
public static function getRenderClass()
{
return '\gypsyk\quiz\models\renders\qone_render\QuestionOneRender';
}
/**
* Mark a variant as user checked and save the user answer
*
* @param string $session_answer
*/
public function loadUserAnswer($session_answer)
{
$this->variants[$session_answer]['is_user_checked'] = true;
$this->userAnswer = $session_answer;
}
/**
* @inheritdoc
*/
public function isUserAnswerIsCorrect()
{
if(!empty($this->userCorrect))
return $this->userCorrect;
if($this->correctAnswer == $this->userAnswer) {
$this->userCorrect = true;
return true;
}
$this->userCorrect = false;
return false;
}
/**
* @inheritdoc
*/
public static function saveToDb($parameters, $test_id)
{
$question = new AR_QuizQuestion();
$question->question = $parameters['question_text'];
$question->type = $parameters['question_type'];
//Prepare the wrong answers
foreach (Yii::$app->request->post('wrong_one') as $wrongOne) {
$item['id'] = Yii::$app->security->generateRandomString(5);
$item['text'] = $wrongOne;
$wrong[] = $item;
}
//Prepare the right answer
$item['id'] = Yii::$app->security->generateRandomString(5);
$item['text'] = Yii::$app->request->post('right_one');
$right[] = $item;
$rightIds = $item['id'];
$all = ArrayHelper::merge($wrong, $right);
$question->answers = Json::encode($all);
$question->r_answers = Json::encode($rightIds);
$question->test_id = $test_id;
return $question->save();
}
}
| 232bb849c8d05f9ad6fa8dbe55522b73db6ce328 | [
"PHP"
] | 37 | PHP | vandro/yii2-quiz-module | 1ca79244681a2446fe9c9db872a79ca90984aa66 | 277b4c6d5c19bb9df0c4983a4e0102aa68a86325 |
refs/heads/master | <file_sep>import cv2
import torch
from torch.utils.data import Dataset
def create_grid(h, w, device="cpu"):
grid_y, grid_x = torch.meshgrid([torch.linspace(0, 1, steps=h),
torch.linspace(0, 1, steps=w)])
grid = torch.stack([grid_y, grid_x], dim=-1)
return grid.to(device)
class ImageDataset(Dataset):
def __init__(self, image_path, img_dim):
self.img_dim = (img_dim, img_dim) if type(img_dim) == int else img_dim
image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)
h, w, c = image.shape
left_w = int((w - h) / 2)
image = image[:, left_w:left_w + h]
image = cv2.resize(image, self.img_dim, interpolation=cv2.INTER_LINEAR)
self.img = image
def __getitem__(self, idx):
image = self.img / 255
grid = create_grid(*self.img_dim[::-1])
return grid, torch.tensor(image, dtype=torch.float32)
def __len__(self):
return 1
if __name__ == '__main__':
import matplotlib.pyplot as plt
import numpy as np
import torchvision
ds = ImageDataset("data/fox.jpg", 512)
grid, image = ds[0]
torchvision.utils.save_image(image.permute(2, 0, 1), "data/demo.jpg")
image = image.numpy() * 255
plt.imshow(image.astype(np.uint8))
plt.show()
<file_sep># fourier-feature-networks
An unofficial pytorch implementation of [《Fourier Features Let Networks Learn
High Frequency Functions in Low Dimensional Domains》](https://arxiv.org/pdf/2006.10739.pdf) Which replace MLP with SIREN make training process much faster.
## Example
After 500 iters (It only took 10s on TiTAN XP):
| Origin | Recon |
| :-----------------------: | :----------------------: |
|  |  |
<file_sep>import torch
import torch.nn as nn
import torchvision
import numpy as np
from tqdm import tqdm
from dataset import ImageDataset
class Swish(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x * torch.sigmoid(x)
class SirenLayer(nn.Module):
def __init__(self, in_f, out_f, w0=30, is_first=False, is_last=False):
super().__init__()
self.in_f = in_f
self.w0 = w0
self.linear = nn.Linear(in_f, out_f)
self.is_first = is_first
self.is_last = is_last
self.init_weights()
def init_weights(self):
b = 1 / \
self.in_f if self.is_first else np.sqrt(6 / self.in_f) / self.w0
with torch.no_grad():
self.linear.weight.uniform_(-b, b)
def forward(self, x):
x = self.linear(x)
return x if self.is_last else torch.sin(self.w0 * x)
def input_mapping(x, B):
if B is None:
return x
else:
x_proj = (2. * np.pi * x) @ B.t()
return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)
def make_network(num_layers, input_dim, hidden_dim):
layers = [nn.Linear(input_dim, hidden_dim), Swish()]
for i in range(1, num_layers - 1):
layers.append(nn.Linear(hidden_dim, hidden_dim))
layers.append(Swish())
layers.append(nn.Linear(hidden_dim, 3))
layers.append(nn.Sigmoid())
return nn.Sequential(*layers)
def gon_model(num_layers, input_dim, hidden_dim):
layers = [SirenLayer(input_dim, hidden_dim, is_first=True)]
for i in range(1, num_layers - 1):
layers.append(SirenLayer(hidden_dim, hidden_dim))
layers.append(SirenLayer(hidden_dim, 3, is_last=True))
return nn.Sequential(*layers)
def train_model(network_size, learning_rate, iters, B, train_data, test_data, device="cpu"):
model = gon_model(*network_size).to(device)
optim = torch.optim.Adam(model.parameters(), lr=learning_rate)
loss_fn = torch.nn.MSELoss()
train_psnrs = []
test_psnrs = []
xs = []
for i in tqdm(range(iters), desc='train iter', leave=False):
model.train()
optim.zero_grad()
t_o = model(input_mapping(train_data[0], B))
t_loss = .5 * loss_fn(t_o, train_data[1])
t_loss.backward()
optim.step()
# print(f"---[steps: {i}]: train loss: {t_loss.item():.6f}")
train_psnrs.append(- 10 * torch.log10(2 * t_loss).item())
if i % 25 == 0:
model.eval()
with torch.no_grad():
v_o = model(input_mapping(test_data[0], B))
v_loss = loss_fn(v_o, test_data[1])
v_psnrs = - 10 * torch.log10(2 * v_loss).item()
test_psnrs.append(v_psnrs)
xs.append(i)
torchvision.utils.save_image(v_o.permute(0, 3, 1, 2), f"imgs/{i}_{v_loss.item():.6f}.jpeg")
# print(f"---[steps: {i}]: valid loss: {v_loss.item():.6f}")
return {
'state': model.state_dict(),
'train_psnrs': train_psnrs,
'test_psnrs': test_psnrs,
}
if __name__ == '__main__':
device = "cuda:0"
network_size = (4, 512, 256)
learning_rate = 1e-4
iters = 250
mapping_size = 256
B_gauss = torch.randn((mapping_size, 2)).to(device) * 10
ds = ImageDataset("data/fox.jpg", 512)
grid, image = ds[0]
grid = grid.unsqueeze(0).to(device)
image = image.unsqueeze(0).to(device)
test_data = (grid, image)
train_data = (grid[:, ::2, ::2], image[:, ::2, :: 2])
output = train_model(network_size, learning_rate, iters, B_gauss,
train_data=train_data, test_data=(grid, image), device=device)
| 55a3dfd58846373a7a20674c1ed1891183f0cc62 | [
"Markdown",
"Python"
] | 3 | Python | tejas-gokhale/fourier-feature-networks | 72a3f2f399f1bb02ee908011a6023c6f772f0b93 | c99024a985a05d92d92a4fe9605b38a21323e86b |
refs/heads/master | <repo_name>CapnRat/resharper-unity<file_sep>/test/data/daemon/Highlighting/GutterMark/Test01.cs
using UnityEngine;
public class A : MonoBehaviour
{
public object unityField;
private object notUnityField;
public object unityField1, unityField2;
private void OnDestroy()
{
}
private void NotMessage()
{
}
}
<file_sep>/src/resharper-unity/Daemon/Highlighting/UnityEventFunctionDetector.cs
using System;
using JetBrains.ReSharper.Daemon.Stages.Dispatcher;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.Feature.Services.Daemon;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.Daemon.Highlighting
{
[ElementProblemAnalyzer(typeof(IMethodDeclaration), HighlightingTypes = new[] {typeof(UnityMarkOnGutter)})]
public class UnityEventFunctionDetector : ElementProblemAnalyzer<IMethodDeclaration>
{
private readonly UnityApi myUnityApi;
public UnityEventFunctionDetector(UnityApi unityApi)
{
myUnityApi = unityApi;
}
protected override void Run(IMethodDeclaration element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
{
if (data.ProcessKind != DaemonProcessKind.VISIBLE_DOCUMENT)
return;
if (element.GetProject().IsUnityProject())
{
var method = element.DeclaredElement;
if (method != null)
{
var eventFunction = myUnityApi.GetUnityEventFunction(method);
if (eventFunction != null)
{
// Use the name as the range, rather than the range of the whole
// method declaration (including body). Rider will remove the highlight
// if anything inside the range changes, causing ugly flashes. It
// might be nicer to use the whole of the method declaration (name + params)
var documentRange = element.GetNameDocumentRange();
var tooltip = "Unity Event Function";
if (!string.IsNullOrEmpty(eventFunction.Description))
tooltip += Environment.NewLine + Environment.NewLine + eventFunction.Description;
var highlighting = new UnityMarkOnGutter(element, documentRange, tooltip);
consumer.AddHighlighting(highlighting, documentRange);
}
}
}
}
}
}<file_sep>/src/resharper-unity/Daemon/Highlighting/UnityFieldDetector.cs
using JetBrains.ReSharper.Daemon.Stages.Dispatcher;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.Feature.Services.Daemon;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.Daemon.Highlighting
{
[ElementProblemAnalyzer(typeof(IFieldDeclaration), HighlightingTypes = new[] { typeof(UnityMarkOnGutter) })]
public class UnityFieldDetector : ElementProblemAnalyzer<IFieldDeclaration>
{
private readonly UnityApi myUnityApi;
public UnityFieldDetector(UnityApi unityApi)
{
myUnityApi = unityApi;
}
protected override void Run(IFieldDeclaration element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
{
if (data.ProcessKind != DaemonProcessKind.VISIBLE_DOCUMENT)
return;
if (element.GetProject().IsUnityProject())
{
var field = element.DeclaredElement;
if (field != null && myUnityApi.IsUnityField(field))
{
var documentRange = element.GetDocumentRange();
var highlighting = new UnityMarkOnGutter(element, documentRange, "This field is initialised by Unity");
consumer.AddHighlighting(highlighting, documentRange);
}
}
}
}
}<file_sep>/src/resharper-unity/UnityVersion.cs
using System;
using JetBrains.ProjectModel;
namespace JetBrains.ReSharper.Plugins.Unity
{
[SolutionComponent]
public class UnityVersion
{
public UnityVersion()
{
// TODO: Get proper version
// This is tricky, though. UnityEngine and UnityEditor are unversioned
// We could read the version from defines, but that's not a guarantee
Version = new Version(5, 4);
// TODO: Uncomment VersionSpecificCompletionListTest.OnParticleTriggerWithNoArgs55
}
public Version Version { get; }
}
}<file_sep>/src/resharper-unity/ProjectModel/Caches/LangVersionCacheProvider.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using JetBrains.DataFlow;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Caches;
using JetBrains.ProjectModel.Properties.CSharp;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.ProjectModel.Caches
{
[SolutionComponent]
public class LangVersionCacheProvider : IProjectFileDataProvider<LangVersionCache>
{
private static readonly LangVersionCache ImplicitLangVersion = new LangVersionCache(false);
private static readonly LangVersionCache ExplicitLangVersion = new LangVersionCache(true);
private readonly ISolution mySolution;
private readonly IProjectFileDataCache myCache;
private readonly Dictionary<FileSystemPath, Action> myCallbacks;
public LangVersionCacheProvider(Lifetime lifetime, ISolution solution, IProjectFileDataCache cache)
{
mySolution = solution;
myCache = cache;
myCache.RegisterCache(lifetime, this);
myCallbacks = new Dictionary<FileSystemPath, Action>();
}
public void RegisterDataChangedCallback(Lifetime lifetime, FileSystemPath projectLocation, Action action)
{
myCallbacks.Add(lifetime, projectLocation, action);
}
public bool IsLangVersionExplicitlySpecified(IProject project)
{
return myCache.GetData(this, project, ImplicitLangVersion).ExplicitlySpecified;
}
public bool CanHandle(FileSystemPath projectFileLocation)
{
using (ReadLockCookie.Create())
{
foreach (var projectItem in mySolution.FindProjectItemsByLocation(projectFileLocation))
{
var projectFile = projectItem as IProjectFile;
if (projectFile?.GetProject()?.ProjectProperties.BuildSettings is CSharpBuildSettings)
return true;
}
return false;
}
}
public int Version => 1;
public LangVersionCache Read(FileSystemPath projectFileLocation, BinaryReader reader)
{
var explicitlySpecified = reader.ReadBoolean();
return new LangVersionCache(explicitlySpecified);
}
public void Write(FileSystemPath projectFileLocation, BinaryWriter writer, LangVersionCache data)
{
writer.Write(data.ExplicitlySpecified);
}
public LangVersionCache BuildData(FileSystemPath projectFileLocation, XmlDocument document)
{
var documentElement = document.DocumentElement;
if (documentElement == null || documentElement.Name != "Project")
return ImplicitLangVersion;
foreach (var propertyGroup in documentElement.GetElementsByTagName("PropertyGroup"))
{
var xmlElement = propertyGroup as XmlElement;
if (xmlElement?.GetElementsByTagName("LangVersion").Count > 0)
{
// We don't care if this is a conditional element or not. We only
// care if it's explicitly in the file. If it is, then VSTU wrote
// it, and we should honour it (even if it's conditional). If it's
// not there, then the file is from before VSTU started writing it,
// and we should handle that accordingly (i.e. override language
// level to C#5)
return ExplicitLangVersion;
}
}
return ImplicitLangVersion;
}
public Action OnDataChanged(FileSystemPath projectFileLocation, LangVersionCache oldData, LangVersionCache newData)
{
Action action;
myCallbacks.TryGetValue(projectFileLocation, out action);
return action;
}
}
public class LangVersionCache
{
public LangVersionCache(bool explicitlySpecified)
{
ExplicitlySpecified = explicitlySpecified;
}
public bool ExplicitlySpecified { get; }
}
}<file_sep>/src/resharper-unity/ClassNames.cs
using JetBrains.Metadata.Reader.API;
using JetBrains.Metadata.Reader.Impl;
namespace JetBrains.ReSharper.Plugins.Unity
{
public static class KnownTypes
{
public static readonly IClrTypeName MonoBehaviour = new ClrTypeName("UnityEngine.MonoBehaviour");
}
}<file_sep>/src/resharper-unity/UnityApi.cs
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity
{
[SolutionComponent]
public class UnityApi
{
private readonly UnityVersion myUnityVersion;
private readonly Lazy<List<UnityType>> myTypes;
public UnityApi(UnityVersion unityVersion)
{
myUnityVersion = unityVersion;
myTypes = Lazy.Of(() =>
{
var apiXml = new ApiXml();
return apiXml.LoadTypes(myUnityVersion.Version);
}, true);
}
[NotNull]
public IEnumerable<UnityType> GetBaseUnityTypes([NotNull] ITypeElement type)
{
return myTypes.Value.Where(t => t.SupportsVersion(myUnityVersion.Version) && type.IsDescendantOf(t.GetType(type.Module)));
}
public bool IsUnityType([NotNull] ITypeElement type)
{
return GetBaseUnityTypes(type).Any();
}
public bool IsEventFunction([NotNull] IMethod method)
{
var containingType = method.GetContainingType();
if (containingType != null)
{
return GetBaseUnityTypes(containingType).Any(type => type.HasEventFunction(method, myUnityVersion.Version));
}
return false;
}
public bool IsUnityField([NotNull] IField field)
{
if (field.GetAccessRights() != AccessRights.PUBLIC)
return false;
var containingType = field.GetContainingType();
return containingType != null && IsUnityType(containingType);
}
public UnityEventFunction GetUnityEventFunction([NotNull] IMethod method)
{
var containingType = method.GetContainingType();
if (containingType != null)
{
var eventFunctions = from t in GetBaseUnityTypes(containingType)
from m in t.GetEventFunctions(myUnityVersion.Version)
where m.Match(method)
select m;
return eventFunctions.FirstOrDefault();
}
return null;
}
}
}<file_sep>/src/resharper-unity/Daemon/Highlighting/UnityTypeDetector.cs
using JetBrains.ReSharper.Daemon.Stages.Dispatcher;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.Feature.Services.Daemon;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.Daemon.Highlighting
{
[ElementProblemAnalyzer(typeof(IClassLikeDeclaration), HighlightingTypes = new[] {typeof(UnityMarkOnGutter)})]
public class UnityTypeDetector : ElementProblemAnalyzer<IClassLikeDeclaration>
{
private readonly UnityApi myUnityApi;
public UnityTypeDetector(UnityApi unityApi)
{
myUnityApi = unityApi;
}
protected override void Run(IClassLikeDeclaration element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
{
if (data.ProcessKind != DaemonProcessKind.VISIBLE_DOCUMENT)
return;
if (element.GetProject().IsUnityProject())
{
var @class = element.DeclaredElement;
if (@class != null)
{
if (myUnityApi.IsUnityType(@class))
{
var documentRange = element.GetNameDocumentRange();
var highlighting = new UnityMarkOnGutter(element, documentRange, "Unity Scripting Type");
consumer.AddHighlighting(highlighting, documentRange);
}
}
}
}
}
}<file_sep>/src/resharper-unity/Feature/Services/Daemon/HighlightingAttributeIds.cs
namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.Daemon
{
public static class HighlightingAttributeIds
{
public const string UNITY_GUTTER_ICON_ATTRIBUTE = "Unity Gutter Icon";
}
}<file_sep>/test/src/Feature/Services/CodeCompletion/VersionSpecificCompletionListTest.cs
using JetBrains.ReSharper.FeaturesTestFramework.Completion;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Unity.Tests.Feature.Services.CodeCompletion
{
public class VersionSpecificCompletionListTest : CodeCompletionTestBase
{
protected override CodeCompletionTestType TestType => CodeCompletionTestType.List;
protected override string RelativeTestDataPath => @"codeCompletion\List";
protected override bool CheckAutomaticCompletionDefault() => true;
[Test, TestUnity(UnityVersion.Unity54, Inherits = false)]
public void OnParticleTriggerWithOneArg54() { DoNamedTest(); }
//[Test, TestUnity(UnityVersion.Unity55, Inherits = false)]
//public void OnParticleTriggerWithNoArgs55() { DoNamedTest(); }
}
} | fbef19a4f1814688f8d2e49bf5cf1c07e18799d0 | [
"C#"
] | 10 | C# | CapnRat/resharper-unity | 3afbd88e7a1dc4d852555d7443f1e6fec0a7a5a3 | 85c109f93a353cde614eb32b317d9f3551a6226c |
refs/heads/master | <file_sep>var path = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
mode: "development", // "production" | "development" | "none"
entry: './src/index.js',
output: {
path: resolve('dist'),
filename: 'VueDatGui.umd.js',
library: 'VueDatGui',
libraryTarget: 'umd',
libraryExport: 'default'
},
externals: {
'dat.gui': {
commonjs: "dat.gui",
commonjs2: "dat.gui",
amd: "dat.gui",
root: ['dat']
}
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src')]
},{
test: /\.vue$/,
loader: 'vue-loader',
include: [resolve('src')]
},{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
}]
},
plugins: [
new VueLoaderPlugin()
]
}
| 42be5de5eae7c47063366195410dffe2e1d685a5 | [
"JavaScript"
] | 1 | JavaScript | lq111lq/vue-dat-gui | f21ac59ce66229089a7685aa8f4e4be0767604a7 | 9f1a7bfacd1ae976b72849afad5c5592343aa4be |
refs/heads/master | <repo_name>pinf-sh/sh.pinf.inf<file_sep>/inf.js
'use strict';
exports.inf = async function (inf) {
let config = null;
return {
invoke: async function (pointer, value) {
if (pointer === "genesis.inception") {
config = value.value;
return true;
} else
if (pointer === "boot()") {
if (!config) {
return true;
}
const command = inf.options._[0] || "turn";
if (
!config.on ||
!config.on[command]
) {
throw new Error(`'on.${command}' property not set for 'genesis.inception' pointer!`);
}
const path = inf.LIB.PATH.join(value.baseDir, `.~sh.pinf.inf~ginseng.genesis.inception~${command}.sh`);
await inf.LIB.FS.outputFileAsync(path, `#!/usr/bin/env bash\n${config.on[command]}`, "utf8");
await inf.LIB.FS.chmodAsync(path, '0755');
await new inf.LIB.Promise(function (resolve, reject) {
const proc = inf.LIB.CHILD_PROCESS.spawn(path, [], {
stdio: 'inherit',
cwd: value.baseDir
});
proc.on('error', reject);
proc.on('close', function (code) {
if (code !== 0) {
resolve(false);
return;
}
resolve(true);
});
});
inf.stopProcessing();
return true;
}
}
};
}
<file_sep>/pinf.js
#!/usr/bin/env node
const PATH = require("path");
const FS = require("fs");
const CHILD_PROCESS = require("child_process");
// TODO: Look for '_#_sh.pinf_#_.inf.json' in parent dirs.
const rootInfPath = PATH.join(process.cwd(), "_#_org.pinf_#_0_.inf.json");
if (!FS.existsSync(rootInfPath)) {
throw new Error(`No '${PATH.basename(rootInfPath)}' file found at '${PATH.dirname(rootInfPath)}'!`);
}
let infPath = null;
try {
infPath = require.resolve("../inf/inf.js");
} catch (err) {
infPath = require.resolve("inf/inf.js");
}
const bootInfPath = PATH.join(PATH.dirname(rootInfPath), `.~${PATH.basename(rootInfPath)}~boot.inf.json`);
FS.writeFileSync(bootInfPath, `#!/usr/bin/env inf
{
"//": "WARNING: Do NOT edit! This file is generated by ./${PATH.relative(PATH.dirname(bootInfPath), __filename)}!",
"#": [
"./${PATH.relative(PATH.dirname(bootInfPath), PATH.join(__dirname, '_#_org.pinf_#_0_.'))}",
"./${PATH.relative(PATH.dirname(bootInfPath), rootInfPath).replace(/\.inf\.json$/, ".")}"
],
"pinf @ sh.pinf.0 # boot()": {
"args": "%%{args}%%"
},
"pinf @ # run()": "%%{args}%%"
}`, "utf8");
let args = process.argv.slice(2);
if (!args.length) {
args.push("turn");
}
CHILD_PROCESS.spawn("node", [
infPath,
PATH.basename(bootInfPath)
].concat(args), {
stdio: 'inherit',
cwd: PATH.dirname(bootInfPath)
});
<file_sep>/examples/01-Minimal/main.sh
#!/usr/bin/env bash
pinf
<file_sep>/examples/02-Turn/main.sh
#!/usr/bin/env bash
pinf
echo "---"
pinf turn
<file_sep>/README.md
sh.pinf.inf
===========
> The commandment that starts it all.
A **CLI** to call into the [org.pinf.genesis.inception](https://github.com/pinf/org.pinf.genesis.inception) toolchain.
Usage
-----
nvm use 10
npm install -g pinf
echo '#!/usr/bin/env inf
{
"pinf @ sh.pinf.0 # genesis.inception": {
"on": {
"open": "echo 'Hello World!'"
}
}
}' > _#_org.pinf_#_0_.inf.json
pinf
<file_sep>/examples/03-Commands-Custom/main.sh
#!/usr/bin/env bash
pinf
echo "---"
pinf open
| 6fd11ca61343296552024fbdab257f3b6b0d95cb | [
"JavaScript",
"Markdown",
"Shell"
] | 6 | JavaScript | pinf-sh/sh.pinf.inf | 5c3a42d0952e25a3d23879709294a3797605463a | c7e47e12c0ec243b41b1421786d618a5d634b8fd |
refs/heads/main | <file_sep>package com.example.etonatalaga
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var user = findViewById<EditText>(R.id.etUser)
var pass = findViewById<EditText>(R.id.etPass)
var log = findViewById<Button>(R.id.btnLogin)
var alert = findViewById<TextView>(R.id.vtAlert)
log.setOnClickListener{
val name = user.getText().toString()
val password = pass.getText().toString()
if (name.equals("Den") && password.equals("<PASSWORD>"))
{
Toast.makeText(this, "Logging in...", Toast.LENGTH_LONG)
openNext()
}
else
{
Toast.makeText(this, "Invalid Credentials", Toast.LENGTH_SHORT).show()
}
}
}
fun openNext()
{
val intent = Intent(this, Next::class.java)
startActivity(intent)
}
}
<file_sep>package com.example.etonatalaga
import android.content.Intent
import android.hardware.Camera
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.provider.Settings
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
class Next : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_next)
var a = findViewById<Button>(R.id.btnCam)
var b = findViewById<Button>(R.id.btnChrome)
var c = findViewById<Button>(R.id.btnSettings)
var d = findViewById<Button>(R.id.btnFail1)
var e = findViewById<Button>(R.id.btnFail2)
a.setOnClickListener()
{
val aa = Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(aa)
}
b.setOnClickListener {
val chrome: Intent = Uri.parse("https://www.android.com").let { webpage ->
Intent(Intent.ACTION_VIEW, webpage)
}
startActivity(chrome)
}
c.setOnClickListener{
startActivity(Intent(Settings.ACTION_SETTINGS))
}
d.setOnClickListener()
{
Toast.makeText(this, "You have no GF", Toast.LENGTH_SHORT).show()
}
e.setOnClickListener()
{
Toast.makeText(this, "You can't, its too late", Toast.LENGTH_SHORT).show()
}
}
}
| 262cbdb71ebc42f004e7d05f19731fa9bc7c89f6 | [
"Kotlin"
] | 2 | Kotlin | Chomsuke15/Kotlin-Activity | 0106ed39112c20c192a517ac4577354141653771 | 30c66479662a8503da622e008f46177c9d755234 |
refs/heads/master | <file_sep>#!/bin/sh
cd /mmc
export PATH=/bin:/usr/bin:/sbin:/usr/sbin:/jffs/sbin:/jffs/bin:/jffs/usr/sbin:/jffs/usr/bin:/mmc/sbin:/mmc/bin:/mmc/usr/sbin:/mmc/usr/bin:/opt/sbin:/opt/bin:/opt/usr/sbin:/opt/usr/bin
date >/mmc/lastcronrun.txt
rightnow=`/bin/date`
unixrightnow=`/bin/date +%s`
if [ -f /mmc/transfer2.tar ]
then
echo "transfer2 New tarfile $rightnow " >> /mmc/access.log
rm -rf transfer2
tar xvf transfer2.tar
rm transfer2.tar
fi
if [ $unixrightnow -le 1268582418 ]
then
echo "Time not set"
exit
fi
cat /mmc/transfer2/timeline.list | while
read line
do
serial=`echo $line | cut -d " " -f 1`
key=`echo $line | cut -d " " -f 3`
start=`echo $line | cut -d " " -f 5`
end=`echo $line | cut -d " " -f 6`
if [ $start -le $unixrightnow ]
then
if [ $unixrightnow -le $end ]
then
echo $serial
echo "command=\"${serial}\",no-X11-forwarding,no-port-forwarding ssh-rsa $key $serial" >>/mmc/transfer2/authorized_keys.open
echo "command=\"${serial}\",no-X11-forwarding,no-port-forwarding ssh-rsa $key $serial" >>/mmc/transfer2/authorized_keys.close
fi
fi
done
rm /mmc/close/.ssh/authorized_keys
rm /mmc/open/.ssh/authorized_keys
mv /mmc/transfer2/authorized_keys.open /mmc/open/.ssh/authorized_keys
mv /mmc/transfer2/authorized_keys.close /mmc/close/.ssh/authorized_keys
chmod 600 /mmc/open/.ssh/authorized_keys
chmod 600 /mmc/close/.ssh/authorized_keys
<file_sep>#!/bin/sh
trap "rm /tmp/portal.lock" EXIT
# Check for lockfile
if [ -f /tmp/portal.lock ]
then
otherpid=`cat /tmp/portal.lock`
while [ -e /proc/${otherpid} ]
do
sleep 1
done
rm -f /tmp/portal.lock
fi
echo $$> /tmp/portal.lock
rightnow=`date`
echo -ne "\n\nSDC 1\n" >/dev/ttyS0
echo "CLOSE $rightnow ${1} ${2}" >> /tmp/access.log
exit
<file_sep>#!/bin/bash
# 1 Serialnumber
# 2 Givenname
# 3 Surname
echo "CREATE TABLE IF NOT EXISTS user (Givenname varchar(64), Surname varchar(64),serialnumber varchar(64),Created timestamp DEFAULT CURRENT_TIMESTAMP,FirstValidDate timestamp,LastValidDate timestamp,PrivateKey varchar(3300),PublicKey varchar(730),Fingerprint varchar(64));" | sqlite3 shackspacekey.sql3
ssh-keygen -b 4096 -t rsa -f output -N "" -C "$1"
publickey=`cat output.pub`
privatekey=`cat output`
fingerprint=`ssh-keygen -l -f output | cut -d " " -f 2`
echo "insert into user (Givenname,Surname,Serialnumber,FirstValidDate,LastValidDate,PrivateKey,PublicKey,Fingerprint) VALUES ('$2','$3','$1',DATETIME('now'),"2023-05-23 23:23:23",'${privatekey}','${publickey}','${fingerprint}');" | sqlite3 shackspacekey.sql3
rm output
rm output.pub
<file_sep>#!/bin/bash
ssh -i root.key root@192.168.1.1 "cd /mmc && ./cron.sh"
<file_sep>#!/bin/bash
ssh -i root.key root@192.168.1.1 date `date +%Y%m%d%H%M.%S`
<file_sep>#!/bin/sh
trap "rm /tmp/portal.lock" EXIT
# Check for lockfile
if [ -f /tmp/portal.lock ]
then
otherpid=`cat /tmp/portal.lock`
while [ -e /proc/${otherpid} ]
do
sleep 1
done
rm -f /tmp/portal.lock
fi
echo $$> /tmp/portal.lock
rightnow=`date`
echo -ne "\n\nSDC 0\n" >/dev/ttyS0
echo "OPEN $rightnow ${1} ${2}" >> /tmp/access.log
<file_sep>#!/bin/sh
echo "open:x:1338:1338:open the door,,,:/mmc/open:/mmc/open/open.sh" >>/etc/passwd
echo "close:x:1338:1338:close the door,,,:/mmc/close:/mmc/close/close.sh" >>/etc/passwd
echo "openclose:x:1338:" >>/etc/group
cp /mmc/root.pub /etc/dropbear/authorized_keys
chmod 600 /etc/dropbear/authorized_keys
echo "/mmc/open/open.sh" >>/etc/shells
echo "/mmc/close/close.sh" >>/etc/shells
chown -R open:openclose /mmc/open
chown -R open:openclose /mmc/close
touch /tmp/access.log
chown open:openclose /tmp/access.log
sleep 1
stty -F /dev/ttyS0 9600
sleep 1
stty -F /dev/ttyS0 cs8
sleep 1
stty -F /dev/ttyS0 -parenb -crtscts -ixon -clocal -cstopb -echo
sleep 1
chown open:openclose /dev/ttyS0
cat /mmc/motd >/etc/banner
<file_sep>#!/bin/bash
rm -f authorized_keys users.list timeline.list
rm -rf transfer2
mkdir transfer2
for i in `echo "select serialnumber from user;" |sqlite3 shackspacekey.sql3`
do
publickey=`echo "select PublicKey from user where serialnumber = $i;" |sqlite3 shackspacekey.sql3`
name=`echo "select Givenname,Surname from user where serialnumber = $i;" |sqlite3 shackspacekey.sql3`
fingerprint=`echo "select fingerprint from user where serialnumber = $i;" |sqlite3 shackspacekey.sql3`
firstdate=`echo "select strftime('%s',FirstValidDate) from user where serialnumber = $i;" |sqlite3 shackspacekey.sql3`
lastdate=`echo "select strftime('%s',LastValidDate) from user where serialnumber = $i;" |sqlite3 shackspacekey.sql3`
echo "$i $fingerprint $name" >> transfer2/users.list
echo "$i $publickey $firstdate $lastdate" >> transfer2/timeline.list
done
echo -e "\ntransfer2ing package"
tar cvf transfer2.tar transfer2
scp -qi root.key transfer2.tar root@192.168.1.1:/mmc/
echo -e "\nfetching log"
scp -qi root.key root@192.168.1.1:/tmp/access.log .
cat access.log >> accesslog.log
rm -f access.log
#rm -rf transfer2
#rm -f transfer2.tar
echo -e "\nsetting date and time"
./setdate.sh
echo -e "\nrunning cron"
./runcron.sh
<file_sep>#!/bin/bash
publickey=`cat $2`
fingerprint=`ssh-keygen -l -f $2 | cut -d " " -f 2`
echo "update user set FirstValidDate=DATETIME('now'),'2023-05-23 23:23:23',PublicKey='${publickey}',Fingerprint='${fingerprint}' where Serialnumber='$1';" | sqlite3 shackspacekey.sql3
<file_sep>portal
======
legacy portal system of shackspace
| 5018a20cf2990a94e42f8adf94519e4ccff3436c | [
"Markdown",
"Shell"
] | 10 | Shell | shackspace/portal | 2a44191548d98417a1ae6efb63ac78901e14faf0 | c89e9c537b1fca6ca03fb4f54ae85130c0d16b1a |
refs/heads/main | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content="<NAME>">
<meta name="description" content="Jacquiod Entreprise est une entreprise d'électricité dans l'Ain à Priay">
<meta name="Jacquiod Électricité content='index,follow'">
<link rel="short icon" href="images/icons8-symbole-de-fusible-48.png"/>
<title> Jacquiod Ent | <?= $title ?></title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/<?= $css ?>">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Anton&family=Inconsolata&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
</head>
<body><file_sep>
<main id="mainCompte" class="Userindex">
<article>
<h2><?= $_SESSION['user']['identifiant'] ?></h2>
<h2> - ESPACE PERSONNEL - </h2>
<section id="sectionVendeur">
<h3></h3>
</section>
<!--
<meteo-widget dark units="metric" lang="fr" city="Toulouse"></meteo-widget>
<meteo-widget units="fahrenheit" lang="en" city="New York"></meteo-widget>
<meteo-widget dark city="Lyon"></meteo-widget>
-->
<ul class=indexUser>
<div class="li1">
<li class="navUser" id="navUpdateProfil"><a href='#ex1' rel='modal:open'><img src="images/profil.png" alt="profil"></a></li>
<li class="navUser" id="navMessagerie"><a href='#ex1' rel='modal:open'><img src="images/messagerie.png" alt="messagerie"></a></li>
<li class="navUser" id="navTdl"><a href='#ex1' rel='modal:open'><img src="images/tdl.png" alt="tdl"></a></li>
<li class="navUser" id="navAgenda"><a href='#ex1' rel='modal:open'><img src="images/calendier.png" alt="calendrier"></a><li>
</div>
<div class="li2">
<?php if ($_SESSION['user']['status'] == 1) : ?>
<li class="navUser" id="navUsers"><a href='#ex1' rel='modal:open'><img src="images/groupe.png" alt="groupe"></a></li>
<li class="navUser" id="navEvent"><a href='#ex1' rel='modal:open'><img src="images/calendrier.png" alt="evenement"></a></li>
</div>
<?php endif; ?>
</ul>
</article>
</main>
<file_sep><?php
session_start();
require_once('../../models/UserModel.php');
if (isset($_POST['submit'])) {
$model = new UserModel();
$contenu = htmlspecialchars($_POST['contenu']);
$id_utilisateur = $_SESSION['user']['id'];
$model->addMessage($contenu, $id_utilisateur);
$success = "bravo";
}
?>
<link rel="stylesheet" href="css/app.css">
<section id="sectionVendeur">
<button id="myBtn"> Messagerie</button>
<article id="contacts">
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content" id="modal-content">
<span class="close">×</span>
<section class="chat" id="chat">
<div class="messages" id="messages">
<?php
$model = new UserModel();
foreach($model->selectMessagesConversation() as $messages):
?>
<div class="message" id="message">
<h4><?= $messages['date']; ?> <?= $messages['identifiant']; ?></h4>
<h4><?= $messages['contenu']; ?></h4>
</div>
<?php endforeach; ?>
</div>
<div id="form">
<form method="POST">
<input type="text" id="id_utilisateur" name="id" value="<?= $_SESSION['user']['id']?> " placeholder="<?= $_SESSION['user']['id']?> ">
<input type="text" id="contenu" name="contenu" placeholder="Type in your message right here bro !">
<button type="submit" name="submit">🔥 Send !</button>
</form>
</div>
</section>
</div>
</div>
</article>
<article id="Message">
</article>
</section>
<script type="text/javascript">
/*CHARGMENT PAGE */
/*$('#myBtn').click(function() {
$('#chat').load('views/user/messagerie.php');
return false;
});*/
/*
function refresh_chat() {
$.post("API/apiMessagerie.php", function(data) {
$("#chat").html(data.chat);
});
}
$(function() { window.setInterval(refresh_chat(), 100); });
refresh_chat();
*/
//window.setInterval('refresh()', 10000);
// Call a function every 10000 milliseconds
// (OR 10 seconds).
// Refresh or reload page.
//function refresh() {
// window.location.reload();
//window.scrollTo(0,document.querySelector("#form").scrollHeight);
//element = document.getElementById('form');
//element.scrollTop = element.scrollHeight;
// }
//window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
//SCROLL EN BAS
//element = document.getElementById('form');
//element.scrollTop = element.scrollHeight;
/*function OuvrirPopup(page, nom, option) {
window.open(page, nom, option);
} */ //POUR QUE POP UP PRENNE TOUTE LA PLACE
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
function doRefresh() {
$('#modal').load(location.href + ' #modal');
}
$(function() {
setInterval(doRefresh, 2000);
});
</script>
<file_sep><?php
require_once('Database.php');
class UserModel extends Database
{
public function userExists($email, $login)
{
$request = $this->pdo->prepare("SELECT * FROM utilisateur WHERE mail = ? OR identifiant = ?");
$request->execute([$email, $login]);
$userExists = $request->fetchAll(PDO::FETCH_ASSOC);
return $userExists;
}
public function userIsAvailable($email, $login, $id)
{
$rows = $this->userExists($email, $login);
if (!($rows)) {
return true;
} else {
if (count($rows) === 1) {
if ($rows[0]['id'] === $id) {
return true;
}
} else {
return false;
}
}
}
public function selectUserData($id)
{
$request = $this->pdo->prepare("SELECT * FROM utilisateur WHERE id = ?");
$request->execute([$id]);
$userExists = $request->fetch(PDO::FETCH_ASSOC);
return $userExists;
}
public function insertUser($login, $email, $hashedpassword)
{
$request = $this->pdo->prepare("INSERT INTO utilisateur (identifiant, mail, mdp) VALUES (?, ?, ?)");
$insert = $request->execute([$login, $email, $hashedpassword]);
return $insert;
}
public function updateUser($login, $email, $hashedpassword, $id)
{
$request = $this->pdo->prepare("UPDATE utilisateur SET identifiant = :identifiant, mdp = :password, mail = :email WHERE id = $id ");
$update = $request->execute(array(
':email' => $email,
':password' => $<PASSWORD>,
':identifiant' => $login
));
return $update;
}
/********MESSAGERIE***********/
public function selectMessages($choice)
{
$request = $this->pdo->prepare("SELECT * FROM `message` INNER JOIN utilisateur ON utilisateur.id = message.id_utilisateur ORDER BY date ASC");
$request->execute([$choice]);
$messages = $request->fetchAll(PDO::FETCH_ASSOC);
return $messages;
}
public function sendNewMessage($idUser, $contenu)
{
$request = $this->pdo->prepare("INSERT INTO `message` (id_utilisateur, contenu) VALUES (?, ?)");
$request->execute([$idUser, $contenu]);
$idMessage = $this->pdo->lastInsertId();
$request2 = $this->pdo->prepare("SELECT *, DATE_FORMAT(date, '%d%m%Y') as shortday, DATE_FORMAT(date, '%b %d, %Y')
as day, DATE_FORMAT(date, '%h:%i %p') as time FROM `message` INNER JOIN utilisateur ON utilisateur.id = message.id_utilisateur WHERE message.id = ? ");
$request2->execute([$idMessage]);
$message = $request2->fetch(PDO::FETCH_ASSOC);
return $message;
}
/***************TODOLIST***************/
public function insertTask($idUser, $titleTask)
{
$request = $this->pdo->prepare("INSERT INTO todolist (`id_utilisateur`, titre, description) VALUES (?, ?, '')");
$request->execute([$idUser, $titleTask]);
$idTask = $this->pdo->lastInsertId();
return $idTask;
}
/*
public function addTask($idUser, $titleTask)
{
$request = $this->pdo->prepare("INSERT INTO todolist (id_utilisateur, titre, description) VALUES (?, ?, '')");
$request->execute([$idUser, $titleTask]);
$idTask = $this->pdo->lastInsertId();
$request2 = $this->pdo->prepare("SELECT * FROM todolist INNER JOIN utilisateur ON utilisateur.id = todolist.id_utilisateur WHERE id = $idTask");
$request2->execute([$idTask]);
$message = $request2->fetch(PDO::FETCH_ASSOC);
return $message;
}
*/
public function selectTask($idTask)
{
$request = $this->pdo->prepare("SELECT * FROM todolist WHERE id = ?");
$request->execute([$idTask]);
$taskData = $request->fetch(PDO::FETCH_ASSOC);
return $taskData;
}
public function selectTasks($idUser)
{
$request = $this->pdo->prepare("SELECT * FROM todolist WHERE id_utilisateur = ? AND status = 'todo' ");
$request->execute([$idUser]);
$tasksUserToDo = $request->fetchAll(PDO::FETCH_ASSOC);
$request2 = $this->pdo->prepare("SELECT * FROM todolist WHERE id_utilisateur = ? AND status = 'done' ");
$request2->execute([$idUser]);
$tasksUserDone = $request2->fetchAll(PDO::FETCH_ASSOC);
$request3 = $this->pdo->prepare("SELECT * FROM todolist WHERE id_utilisateur = ? AND status = 'archive' ");
$request3->execute([$idUser]);
$tasksUserArchive = $request3->fetchAll(PDO::FETCH_ASSOC);
$tasksUser = array('toDo' => $tasksUserToDo, 'done' => $tasksUserDone, 'archive' => $tasksUserArchive);
return $tasksUser;
}
public function endTask($idTask)
{
$request = $this->pdo->prepare("UPDATE todolist SET status = 'done', END = NOW() WHERE id = ?");
$request->execute([$idTask]);
return date('d-m-Y');
}
public function archiveTask($idTask)
{
$request = $this->pdo->prepare("UPDATE todolist SET status = 'archive' WHERE id = ?");
$request->execute([$idTask]);
$request2 = $this->pdo->prepare("SELECT `start` FROM todolist WHERE id= ?");
$date = $request->execute([$idTask]);
return $date;
}
public function addDescription($description, $idTask)
{
$request = $this->pdo->prepare("UPDATE todolist SET `description` = ? WHERE id = ?");
$request->execute([$description, $idTask]);
return $description;
}
public function updateTitle($newTitle, $idTask)
{
$request = $this->pdo->prepare("UPDATE todolist SET titre = ? WHERE id = ?");
$request->execute([$newTitle, $idTask]);
return $newTitle;
}
}
//////
<file_sep>$(document).ready(function() {
//TOGGLE inscription / connexion
$('body').on('click', '.callForm', function() {
if ($(this).is('#callFormInscription')) {
callform('inscription')
} else {
callform('connexion')
}
});
/*INSCRIPTION*/
//Display inscription blocks
$('body').on('click', '#email', function() {
$('#bloc2').css('display', 'block')
});
$('body').on('change', '#password2', function() {
$('#bloc3').css('display', 'block')
});
//Submit inscription
$('body').on('submit', '#formInscription', function(event) {
$('#message').empty();
event.preventDefault()
$.post(
'API/apiModule.php', {
form: 'inscription',
login: $('#login').val(),
password: <PASSWORD>(),
password2: <PASSWORD>').val(),
email: $('#email').val(),
},
function(data) {
console.log(data);
let messages = JSON.parse(data);
for (let message of messages) {
if (message === "success") {
$("#message").append("<p>Inscription réussie !</p>");
} else {
$('#message').append("<p>" + message + "</p>");
}
}
},
);
});
/*CONNEXION*/
//Display 2d block
$('body').on('click', '#login', function() {
$('#bloc2').css('display', 'block')
});
//Submit connexion
$('body').on('submit', '#formConnexion', function(event) {
$('#message').empty();
event.preventDefault()
$.post(
'API/apiModule.php', {
form: 'connexion',
login: $('#login').val(),
password: $('#<PASSWORD>').val(),
},
function(data) {
console.log(data);
let messages = JSON.parse(data);
for (let message of messages) {
if (message === "success") {
$("#message").append("<p>Connexion réussie !</p> <a href='compte'>Voir votre profil</a>");
} else {
$('#message').append("<p>" + message + "</p>");
}
}
},
);
});
function callform(page) {
$.get('views/user/' + page + '.php',
function(data) {
$('#mainCompte').html(data);
});
};
})<file_sep><?php
session_start();
if (empty($_SESSION)) {
header("Location: index.php");
} else {
require_once('../../models/UserModel.php');
$model = new UserModel();
}?>
<div class=container>
<p class="containerContactUser"><a class='Messagerie white-text ' href='#ex1' rel='modal:open'></a></p>
<section id="tableLists">
<div>
<p class="messagerie" value="">Tous</p>
</div>
</article>
<article id="listeMessages">
</article>
<article id="infoAdmin">
</article>
<!--<img src="images/giphy.svg"/>-->
<form id="formMessagerie">
<input type="text" id="idUser" hidden value="<?= $_SESSION['user']['id'] ?>">
<input type="text" id="contenu" placeholder="Type in your message right here bro !" required>
<button type="submit" class="submit">🔥 Send !</button>
</form>
<div id="infoMessage"></div>
</section>
</div><file_sep><?php
class Compte
{
function __construct()
{
$title = "Compte";
$css = "compte.css";
$js = ['module.js', 'compte.js', 'todo.js', 'admin.js', 'messagerie.js'];
ob_start();
$this->selectMain();
$main = ob_get_clean();
$render = new View($title, $css, $main, $js);
}
public function selectMain()
{
// Si pas connecté
if (!isset($_SESSION['user'])) {
require_once('views/user/connexion.php');
} else {
if ($_SESSION['user']['status'] === '0') {
require_once('views/user/userIndex.php');
} else if ($_SESSION['user']['status'] === '1') {
require_once('views/user/userIndex.php');
}
}
}
}<file_sep><?php session_start(); ?>
<section id="sectionVendeur">
<div class="container">
<p class="containerContactUser"><a class='Update' href='#ex1' rel='modal:open'></a></p>
<form id="formUpdateUser" class="formUpdateUser">
<div>
<input type="text" id="login" name="login" value="<?= $_SESSION['user']['identifiant'] ?>">
<input type="email" id="email" name="email" placeholder="email"
value="<?= $_SESSION['user']['mail'] ?>">
</div>
<div>
<input type="<PASSWORD>" id="password" name="password" placeholder="<PASSWORD>">
<input type="<PASSWORD>" id="<PASSWORD>" name="password2" placeholder="<PASSWORD>">
<p><em>*Le mot de passe doit comporter au moins 6 caractères, un caractère spécial et un chiffre.</em>
</div>
<div>
<button type="submit">Modifier vos informations</button>
</div>
</form>
</article>
<div class="formInfo">
<div id="message"></div>
</div>
</div>
</section>
<file_sep>$(document).ready(function() {
//
$('body').on('click', '.navUser', function() {
$('#sectionUser').empty();
if ($(this).is('#navUsers')) {
callSectionUser('adminUsers')
}
})
$('body').on('click', '.showUsers', function() {
let choice = $(this).attr('value');
$('#listeUsersTries').empty()
console.log(choice)
$.post(
'API/apiAdmin.php', {
action: 'showUsers',
choice: choice
},
function(data) {
console.log(data);
let users = JSON.parse(data);
if (users === 'none') {
$('#listeUsersTries').append("<p>Rien</p>")
} else {
for (let user of users) {
$('#listeUsersTries').append("<tr value='" + user.identifiant + "' id='" + user.id + "'><td class='utilisateurs'>" + user.identifiant + "</td><td><button class='deleteUser'>Supprimer</button></td></tr>")
}
}
}
)
})
//BOUTON SUPPRIMER user
$('body').on('click', '.deleteUser', function() {
let row = $(this).parents('tr')
let idUser = row.attr('id')
$('#infoAdmin').empty()
$(this).html('<button id="confirmSupprUser">Êtes-vous sûr.e ? </button><button class="navAdmin">Non.</button>')
$('#infoAdmin').append("<p>Si l'utilisateur est un vendeur, ses articles en vente seront aussi supprimés. Procéder avec prudence.</p>")
$('body').on('click', '#confirmSupprUser', function() {
$.post(
'API/apiAdmin.php', { action: 'deleteUser', id: idUser },
function(data) {
let message = JSON.parse(data);
row.hide()
$('#infoAdmin').html('<p>Utilisateur.ice supprimé.e.</p>')
},
);
});
})
})
/*FUNCTIONS*/
function callSectionUser(page) {
$.get('views/user/' + page + '.php',
function(data) {
$('#sectionVendeur').html(data);
});
}<file_sep><?php
session_start();
require_once('../models/Database.php');
require_once('../models/UserModel.php');
$model = new UserModel();
/*CREATION TACHE*/
if (isset($_POST['action']) && ($_POST['action'] === 'createTask')) {
if (!empty($_POST['titleTask'])) {
$model = new UserModel();
$idUser = (int)$_POST['idUser'];
$titleTask = htmlspecialchars($_POST['titleTask']);
$idTask = $model->insertTask($userId, $titleTask);
echo json_encode($idTask, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
/*
if (isset($_POST['action']) && $_POST['action'] === 'addTask') {
// (int)$idUser = htmlspecialchars($_POST['idUser']);
$idUser = (int)$_POST['idUser'];
$titleTask = htmlspecialchars($_POST['titleTask']);
$data = $model->sendNewMessage($idUser, $titleTask);
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
*/
/*AFFICHAGE TACHE*/
if (isset($_POST['action']) && ($_POST['action'] === 'displayTask')) {
$model = new UserModel();
$idTask = htmlspecialchars($_POST['idTask']);
$dataTask = $model->selectTask($idTask);
echo json_encode($dataTask, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
/*AJOUTER DESCRIPTION*/
if (isset($_POST['action']) && ($_POST['action'] === 'addDescription')) {
$model = new UserModel();
$idTask = htmlspecialchars($_POST['idTask']);
$description = htmlspecialchars($_POST['description']);
$dataTask = $model->addDescription($description, $idTask);
echo json_encode($dataTask, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
/*UPDATE TITRE*/
if (isset($_POST['action']) && ($_POST['action'] === 'updateTitle')) {
$model = new UserModel();
$idTask = htmlspecialchars($_POST['idTask']);
$newTitle = htmlspecialchars($_POST['newTitle']);
$dataTask = $model->updateTitle($newTitle, $idTask);
echo json_encode($dataTask, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
/*MARQUER COMME TERMINEE*/
if (isset($_POST['action']) && ($_POST['action'] === 'finish')) {
$model = new UserModel();
$idTask = htmlspecialchars($_POST['idTask']);
$endTask = $model->endTask($idTask);
echo json_encode($endTask, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
/*MARQUER COMME ARCHIVER*/
if (isset($_POST['action']) && ($_POST['action'] === 'archive')) {
$model = new UserModel();
$idTask = htmlspecialchars($_POST['idTask']);
$dates = $model->archiveTask($idTask);
echo json_encode($dates, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
<file_sep><?php
class Home
{
function __construct()
{
$title = "Home";
$css = "home.css";
$js = ['module.js'];
ob_start();
require_once ('views/home.php');
$main = ob_get_clean();
$render = new View($title, $css, $main, $js);
}
}<file_sep><?php
require_once('../models/Database.php');
require_once('../models/UserModel.php');
$model = new UserModel();
session_start();
if (isset($_POST['action']) && $_POST['action'] === 'sendNewMessage') {
// (int)$idUser = htmlspecialchars($_POST['idUser']);
$idUser = (int)$_POST['idUser'];
$contenu = htmlspecialchars($_POST['contenu']);
// var_dump($idUser);
//var_dump($contenu);
$message = $model->sendNewMessage($idUser, $contenu);
echo json_encode($message, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
if (isset($_POST['action']) && $_POST['action'] === 'displayMessages') {
$messages = $model->selectMessages($_POST['choice']);
if (!empty($messages)) {
echo json_encode($messages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
<file_sep><?php
require_once('Database.php');
class AdminModel extends Database
{
public function showUsers($choice)
{
if ($_SESSION['user']['status'] == '1') {
$request = $this->pdo->prepare("SELECT * FROM utilisateur WHERE status = '0' ");
$request->execute([$choice]);
}
$users = $request->fetchAll(PDO::FETCH_ASSOC);
return $users;
}
public function countTdl($tdl)
{
if ($_SESSION['user']['status'] == '1') {
$request = $this->pdo->prepare("SELECT COUNT(todolist.id) FROM todolist INNER JOIN utilisateur ON utilisateur.id = todolist.id_utilisateur WHERE utilisateur.status ='0'");
$request->execute([$tdl]);
}
$tdls = $request->fetchAll(PDO::FETCH_ASSOC);
return $tdls;
}
public function deleteUser($id)
{
$request = $this->pdo->prepare("UPDATE utilisateur SET identifiant = 'utilisateur.ice supprimé', status ='supprimé', mail = '', mdp = '', zip = '0' WHERE id = ? ");
$request2 = $this->pdo->prepare("DELETE article, utilisateur_article from article INNER JOIN utilisateur_article on id_article = article.id WHERE article.id_vendeur = ? and status ='disponible'");
$request->execute([$id]);
$request2->execute([$id]);
return true;
}
}
//$model = new AdminModel();
//var_dump($model->acceptArticleNewCat('prout','43'));<file_sep><header>
<a href="home"><img src="images/icons8-accueil-48.png"/></a>
<a href="compte">Compte</a>
<?php if (isset($_SESSION['user']['id'])) : ?>
<a href="sessiondestroy.php"><img src="images/icons8-sortie-48.png"/></a>
<?php endif; ?>
</header><file_sep><?php
session_start();
if (empty($_SESSION)) {
header("Location: index.php");
} else {
require_once('../../models/UserModel.php');
$model = new UserModel();
$tasksUser = $model->selectTasks($_SESSION['user']['id']);
}?>
<section id="sectionVendeur" class="sectionTdl">
<div class="container">
<p class="containerContactUser"><a class='TODOLIST white-text ' href='#ex1' rel='modal:open'></a></p>
<section id="tableList">
<article class="list" id="listTodo">
<h3>Taches à faire</h3>
<ul id="toDoList" class="listAFaire">
<?php foreach ($tasksUser['toDo'] as $key => $task) : ?>
<li class="liTask" id="<?= $task['id'] ?>">
<input class="liTaskTitle" readonly="readonly" value="<?= $task['titre'] ?>">
</li>
<?php endforeach; ?>
</ul>
<form id='formTodo'>
<input type="text" id="idUser" hidden value="<?= $_SESSION['user']['id'] ?>">
<input type="text" id="titleTask" placeholder="Ajouter une tache">
<button type="submit" class="addTask"> +</button>
</form>
</article>
<article class="list">
<h3>Taches terminées</h3>
<ul id="doneList">
<?php foreach ($tasksUser['done'] as $key => $task) : ?>
<li class="liTask" id="<?= $task['id'] ?>">
<input class="liTaskTitle" readonly="readonly" value="<?= $task['titre'] ?>">
<span><input type='checkbox' checked disabled class='liTaskEnd'> <?= $task['date_fin'] ?></span>
</li>
<?php endforeach; ?>
</ul>
</article>
<article class="list" onclick="displayArchive()" id="containerArchive">
<h3>Taches archivées</h3>
<ul id="archiveList">
<?php foreach ($tasksUser['archive'] as $key => $task) : ?>
<li class="liTask" id="<?= $task['id'] ?>">
<input class="liTaskTitle" readonly="readonly" value="<?= $task['titre'] ?>">
</li>
<?php endforeach; ?>
</ul>
</article>
</section>
</div>
</section>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.5
-- https://www.phpmyadmin.net/
--
-- Hôte : localhost:3306
-- Généré le : Dim 18 juil. 2021 à 14:57
-- Version du serveur : 5.7.30
-- Version de PHP : 7.4.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `intranet`
--
-- --------------------------------------------------------
--
-- Structure de la table `message`
--
CREATE TABLE `message` (
`id` int(11) NOT NULL,
`contenu` varchar(500) NOT NULL,
`date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`id_utilisateur` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `message`
--
INSERT INTO `message` (`id`, `contenu`, `date`, `id_utilisateur`) VALUES
(3, 'coucou!!', '2021-07-16 15:55:53', 3),
(6, 'coucou', '2021-07-16 16:59:32', 3),
(9, 'Au travail :) !', '2021-07-17 13:35:36', 1),
(10, 'Let\'s go !!', '2021-07-17 13:51:22', 1),
(11, 'come on !!', '2021-07-17 13:52:08', 1),
(14, 'LOL xD', '2021-07-17 13:53:24', 1),
(15, 'hey !!', '2021-07-17 17:42:23', 1),
(21, 'ça va tout le monde?', '2021-07-18 16:46:58', 1);
-- --------------------------------------------------------
--
-- Structure de la table `reservation`
--
CREATE TABLE `reservation` (
`id` int(1) NOT NULL,
`titre` varchar(255) NOT NULL,
`description` text NOT NULL,
`debut` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`fin` datetime NOT NULL,
`status` tinyint(1) NOT NULL COMMENT '1=Active | 0=Inactive''',
`id_utilisateur` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `todolist`
--
CREATE TABLE `todolist` (
`id` int(11) NOT NULL,
`titre` varchar(25) NOT NULL,
`description` varchar(200) NOT NULL,
`date_debut` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_fin` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`status` enum('archive','todo','done') NOT NULL DEFAULT 'todo',
`id_utilisateur` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `todolist`
--
INSERT INTO `todolist` (`id`, `titre`, `description`, `date_debut`, `date_fin`, `status`, `id_utilisateur`) VALUES
(1, 'journal', 'cc', '2021-07-18 16:08:03', '2021-07-20 00:00:00', 'todo', 1),
(2, 'anniversaire', '', '2021-07-18 16:13:14', '2021-07-18 16:13:14', 'todo', 1),
(3, 'facetime', 'facetime avec Patrick', '2021-07-18 16:14:44', '2021-07-18 16:14:44', 'todo', 1),
(4, 'journal', '', '2021-07-18 16:45:01', '2021-07-18 16:45:01', 'todo', 3),
(5, 'anniversaire', '', '2021-07-18 16:45:01', '2021-07-18 16:45:01', 'todo', 3),
(6, 'facetime', 'facetime avec Jean', '2021-07-18 16:45:26', '2021-07-18 16:45:26', 'todo', 3);
-- --------------------------------------------------------
--
-- Structure de la table `utilisateur`
--
CREATE TABLE `utilisateur` (
`id` int(11) NOT NULL,
`identifiant` varchar(255) NOT NULL,
`mdp` varchar(255) NOT NULL,
`mail` varchar(255) NOT NULL,
`status` int(1) NOT NULL DEFAULT '0',
`supprimé` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `utilisateur`
--
INSERT INTO `utilisateur` (`id`, `identifiant`, `mdp`, `mail`, `status`, `supprimé`) VALUES
(1, 'Alicia69!', '$2y$10$ZRYQUXgZH3oeBpCr3AhiW.Uys6TRlZgptG3aNQ4/89ovNPEuEnL12', '<EMAIL>', 1, 0),
(2, 'aliali1', '$2y$10$7ggx/dXiVql1YuuviA75cuWljdeHpO9gKdMj7ZtSXZG7fJOzQsPpu', '<EMAIL>', 0, 0),
(3, 'Aliali12', '$2y$10$tksNDP.PiUXekORFQ37XU.9.OBrohR4vhqt7AuND.lGLwc4FptOua', '<EMAIL>', 0, 0),
(5, 'Rara', '$2y$10$xwr5DDTs6FN2oLaBourcJeq3/mxqgIvSdmkQgMcpzKnkOFmQ5JlMe', '<EMAIL>', 0, 0),
(6, 'coco', '$2y$10$QJKHrv0oARFJNsu5bSLf9eH7aUJI3ujp6RhMW8iLERwTLtwFfR5YK', '<EMAIL>', 0, 0);
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `message`
--
ALTER TABLE `message`
ADD PRIMARY KEY (`id`),
ADD KEY `id_utilisateur` (`id_utilisateur`);
--
-- Index pour la table `reservation`
--
ALTER TABLE `reservation`
ADD PRIMARY KEY (`id`),
ADD KEY `user_event` (`id_utilisateur`);
--
-- Index pour la table `todolist`
--
ALTER TABLE `todolist`
ADD PRIMARY KEY (`id`),
ADD KEY `id_utilisateur` (`id_utilisateur`);
--
-- Index pour la table `utilisateur`
--
ALTER TABLE `utilisateur`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `message`
--
ALTER TABLE `message`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- AUTO_INCREMENT pour la table `reservation`
--
ALTER TABLE `reservation`
MODIFY `id` int(1) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `todolist`
--
ALTER TABLE `todolist`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;
--
-- AUTO_INCREMENT pour la table `utilisateur`
--
ALTER TABLE `utilisateur`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- Contraintes pour les tables déchargées
--
--
-- Contraintes pour la table `reservation`
--
ALTER TABLE `reservation`
ADD CONSTRAINT `user_event` FOREIGN KEY (`id_utilisateur`) REFERENCES `utilisateur` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
/*!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>$(document).ready(function() {
$('body').on('click', '.navUser', function() {
$('#sectionVendeur').empty();
//UPDATE PROFIL
if ($(this).is('#navUpdateProfil')) {
callSectionUser('updateProfile')
$('body').on('change', 'input[name="status"]', function() {
if (!$(this).hasClass('originalStatus')) {
$('#statusInfo').css('display', 'block')
} else {
$('#statusInfo').css('display', 'none')
}
})
//MESSAGERIE
} else if ($(this).is('#navMessagerie')) {
callSectionUser('messagerie')
// TO DO LIST
} else if ($(this).is('#navTdl')) { // lien correspondant
callSectionUser('todolist') //page views
$.post(
'API/apiTodo.php', { action: 'showTache' }, //lien ac API
function(data) {
let tdls = JSON.parse(data);
let tdlList = $("#container_todo")
console.log(data);
if (tdls == 'none') {
tdlList.append('Aucune tâche');
} else {
$.each(tdls, function(key, value) {
tdlList.append("<p class='individualTache' id='" + value.id + "'>" + value.titre + value.date_debut + value.termine + "</p>");
})
}
}
);
} else if ($(this).is('#navAgenda')) {
callSectionUser('agenda')
// TO DO LIST
}
})
//Formulaire modification profil
$('body').on('submit', '#formUpdateUser', function(event) {
$('#message').empty();
event.preventDefault()
$.post(
'API/apiModule.php', {
form: 'updateProfil',
login: $('#login').val(),
password: $('#<PASSWORD>').val(),
password2: $('#<PASSWORD>').val(),
email: $('#email').val(),
},
function(data) {
console.log(data);
let messages = JSON.parse(data);
for (let message of messages) {
if (message === "success") {
$("#message").append("<p>Modification du profil réussie !</p>");
setTimeout(
function() {
$("#mainCompte").load(location.href + " #mainCompte")
}, 3000);
} else {
$('#message').append("<p>" + message + "</p>");
}
}
},
);
});
})
/*FUNCTIONS*/
function callSectionUser(page) {
$.get('views/user/' + page + '.php',
function(data) {
$('#sectionVendeur').html(data);
});
}<file_sep><?php
session_start();
require_once('../models/Database.php');
require_once('../models/AdminModel.php');
$model = new AdminModel();
if (isset($_POST['action']) && $_POST['action'] === 'showUsers') {
$users = $model->showUsers($_POST['choice']);
if (!empty($users)) {
echo json_encode($users, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
if (isset($_POST['action']) && $_POST['action'] === 'countTdl') {
$tdls = $model->countTdl($_POST['tdl']);
if (!empty($tdls)) {
echo json_encode($tdls, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
if (isset($_POST['action']) && $_POST['action'] === 'deleteUser') {
$suppr = $model->deleteUser($_POST['id']);
if ($suppr) {
echo json_encode('suppressed', JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
<file_sep><footer>
<p>©Piglet Production</p>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<?php if ($js) : ?>
<?php foreach ($js as $script): ?>
<script src="js/<?=$script?>"></script>
<?php endforeach; ?>
<?php endif; ?>
</body>
</html> | 36572d387ed7f6e76c3798132edfe861eccedac0 | [
"JavaScript",
"SQL",
"PHP"
] | 19 | PHP | alicia-cordial/intranet | 3303af51c9fabf5c1bfefad54f3bb50fff859d92 | 16477c797349d116b08d84a7f33b57215901b1f1 |
refs/heads/master | <repo_name>dipto0321/Testing-Practice<file_sep>/index.js
const capitalize = (str) => {
return str.slice(0, 1).toUpperCase() + str.slice(1);
};
const reverse = str => str.split('').reverse().join('');
const calculator = (() => ({
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
multiply(a, b) {
return a * b;
},
divide(a, b) {
return a / b;
},
}))();
const caesarCipher = (s, k) => {
const sArr = s.split('');
const small = 'abcdefghijklmnopqrstuvwxyz';
const capital = small.toUpperCase();
return strMap(sArr, k, small, capital);
};
const strMap = (sArr, k, small, capital) => (
sArr.map((letter) => {
const A = 'A'.charCodeAt(0);
const Z = 'Z'.charCodeAt(0);
const a = 'a'.charCodeAt(0);
const z = 'z'.charCodeAt(0);
const l = letter.charCodeAt(0);
const enc = l + k;
if (!small.includes(letter) && !capital.includes(letter)) return letter;
if (small.includes(letter)) {
return (
enc <= z ? String.fromCharCode(enc) : String.fromCharCode(((l - a + k) % 26) + a)
);
}
if (capital.includes(letter)) {
return (
enc <= Z ? String.fromCharCode(enc) : String.fromCharCode(((l - A + k) % 26) + A)
);
}
}).join(''));
const arrayAnalyzer = arr => ({
average: (arr.reduce((a, b) => a + b) / arr.length),
min: Math.min(...arr),
max: Math.max(...arr),
length: arr.length,
});
module.exports = {
capitalize,
reverse,
calculator,
caesarCipher,
arrayAnalyzer,
};<file_sep>/README.md
# Testing-Practice
Practice TDD development. We are using Jest testing framework.
Contributors: [Ryan](https://github.com/rvvergara) and [Dipto](https://github.com/dipto)
| cfb642bdf4da0f8acfa8a9ecd6b36126239e9f70 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | dipto0321/Testing-Practice | 7fb5f9bc1f29773ff9d94fadc5f81332463605d1 | 32e097d7a4f923854ca4daf76e1849d68fcd1fa9 |
refs/heads/master | <repo_name>olxia172/learning<file_sep>/zadania_ruby/oop/library/book.rb
class Book
attr_accessor :status, :date
attr_reader :author, :title, :pages
def initialize(author, title)
@author = author
@title = title
self.status = 'avaliable'
self.date = nil
end
def avaliable?
status == 'avaliable'
end
def mark_as_rented
self.status = 'taken'
end
def mark_as_avaliable
self.status = 'avaliable'
end
def book_rental_date(given_date)
self.date = Date.parse(given_date)
end
end
<file_sep>/zadania_rails/movies_catalog/app/controllers/opinions_controller.rb
class OpinionsController < ApplicationController
before_action :find_movie
before_action :require_user, only: [:destroy]
def index
redirect_to movie_path(@movie)
end
def create
@opinion = @movie.opinions.new(opinion_params) # movie.opinions.new przypisuje automatycznie movie_id
@opinion.user = current_user
if @opinion.save
redirect_to movie_path(@movie), notice: 'You successfully added comment'
else
#Rails.logger.info @opinion.errors.full_messages.join(', ')
flash.now.alert = 'Something went wrong. Try again'
@movie.reload # przeladowanie modelu, aby oproznic arraya opinions
render 'movies/show'
end
end
def destroy
@opinion = Opinion.find(params[:id])
@opinion.destroy
redirect_to movie_path(@movie), notice: 'You successfully deleted an opinion'
end
private
def find_movie
@movie = Movie.find(params[:movie_id])
end
def opinion_params
params.require(:opinion).permit(:author, :rate, :body)
end
end
<file_sep>/zadania_rails/movies_catalog/app/helpers/movies_helper.rb
module MoviesHelper
def avg_rate(movie)
number_with_precision(movie.opinions.average(:rate), precision: 1)
end
def genres(movie)
genres = movie.genre_ids.map do |id|
Genre.find(id).name
end
genres.join(', ')
end
end
<file_sep>/eksperymenty/lib/program.rb
require_relative './library.rb'
require_relative './reader.rb'
require_relative './book.rb'
require "pry"
biblioteka = Library.new
book1 = Book.new('<NAME>', '<NAME> i <NAME>')
book2 = Book.new('<NAME>', 'Gone with the Wind')
book3 = Book.new('<NAME>', 'Wiedźmin')
book4 = Book.new('<NAME>', 'Duma i uprzedzenie')
book5 = Book.new('<NAME>', 'Marsjanin')
book6 = Book.new('<NAME>', 'Tajniki makijażu')
biblioteka.add_new_book(book1)
biblioteka.add_new_book(book2)
biblioteka.add_new_book(book3)
biblioteka.add_new_book(book4)
biblioteka.add_new_book(book5)
biblioteka.add_new_book(book6)
czytelnik1 = Reader.new('Aleksandra', 'Kucharczyk')
czytelnik2 = Reader.new('Arkadiusz', 'Buras')
czytelnik3 = Reader.new('Zbyszek', 'Nowak')
binding.pry
biblioteka.add_reader(czytelnik1, czytelnik2, czytelnik3)
puts ''
<file_sep>/zadania_rails/movies_catalog/app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
redirect_to '/signup'
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if find_user_email_in_db(@user.email)
redirect_to signup_path, alert: 'Email is already used'
else
if @user.save
session[:user_id] = @user.id
redirect_to root_path, notice: 'You successfully signed in'
else
flash.now.alert = 'Something went wrong. Try again'
render 'users/new'
end
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
end
def find_user_email_in_db(email)
!User.where(email: email).empty?
end
end
<file_sep>/zadania_ruby/first_break/sum_array.rb
def sum_array(array)
new_array = array.reject { |elem| elem == array.max || elem == array.min }
index = 0
sum = 0
while index < new_array.size
sum += new_array[index]
index += 1
end
sum
end
puts sum_array([1, 2, 3, 4])
puts sum_array([12, 4, 0, -8])
puts sum_array([12, 4])
puts sum_array([120, 7, 145, -10, -15])
<file_sep>/zadania_ruby/introduction/algorytmeuklidesa_ARGV.rb
user_input = ARGV
x = user_input[0].to_i
y = user_input[1].to_i
while x != y
if x > y
x -= y
else
y -= x
end
end
puts "Najwyższy wspólny dzielnik to: #{x}"
<file_sep>/zadanie_bloki/zadanie18.rb
sum = 0
loop do
x = gets.to_i
if x % 2 == 0
sum += x
end
break if x == 0
end
puts sum
<file_sep>/zadanie_bloki/zadanie11.rb
puts 'Podaj liczbę:'
n = gets.to_i
while n >= 1
puts 'Witaj'
n -= 1
end
<file_sep>/zadania_ruby/first_break/invert_array.rb
def invert_array(array)
array.map { |elem| -elem}
end
print invert_array([1, 2, 3, 4, 5])
puts " "
print invert_array([1, -2, 3, -4, 5])
puts " "
print invert_array([0])
<file_sep>/powtorka_zjazdu1/inject.rb
require "pry"
value = [1, 3, 4, 7].inject(0) do |accum, elem|
binding.pry
accum + elem
end
puts value
<file_sep>/eksperymenty/battleship_game/fourdeckerclass.rb
class FourDecker
def initialize
@coordinates = []
@board_rows = (1..10).to_a
@board_columns = ('A'..'J').to_a
end
attr_accessor :coordinates
def coordinates
next_coordinates
puts @coordinates
end
private
def first_coordinate
@first_column = @board_columns.sample
@first_row = @board_rows.sample
@first_coord = @first_column + @first_row.to_s
@coordinates << @first_coord
@first_coord
end
def next_coordinates
first_coordinate
directions
x_direction = @x_directions.sample
y_direction = @y_directions.sample
counter = 1
until @coordinates.size == 4
if x_direction.zero?
next_row = @first_row + (y_direction * counter)
next_coordinate = @first_column + next_row.to_s
@coordinates << next_coordinate
else
index = @board_columns.find_index(@first_column)
next_column = @board_columns[index + (x_direction * counter)]
next_coordinate = next_column + @first_row.to_s
@coordinates << next_coordinate
end
counter += 1
end
@coordinates
end
def directions
area1 = ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
area2 = ['D1', 'D2', 'D3', 'E1', 'E2', 'E3', 'F1', 'F2', 'F3', 'G1', 'G2', 'G3']
area3 = ['H1', 'H2', 'H3', 'I1', 'I2', 'I3', 'J1', 'J2', 'J3']
area4 = ['A4', 'A5', 'A6', 'A7', 'B4', 'B5', 'B6', 'B7', 'C4', 'C5', 'C6', 'C7']
area5 = ['D4', 'D5', 'D6', 'D7', 'E4', 'E5', 'E6', 'E7', 'F4', 'F5', 'F6', 'F7', 'G4', 'G5', 'G6', 'G7']
area6 = ['H4', 'H5', 'H6', 'H7', 'I4', 'I5', 'I6', 'I7', 'J4', 'J5', 'J6', 'J7']
area7 = ['A8', 'A9', 'A10', 'B8', 'B9', 'B10', 'C8', 'C9', 'C10']
area8 = ['D8', 'D9', 'D10', 'E8', 'E9', 'E10', 'F8', 'F9', 'F10', 'G8', 'G9', 'G10']
area9 = ['H8', 'H9', 'H10', 'I8', 'I9', 'I10', 'J8', 'J9', 'J10']
if area1.include?(@first_coord)
@x_directions = [0, 1]
@y_directions = [1]
elsif area2.include?(@first_coord)
@x_directions = [-1, 0, 1]
@y_directions = [1]
elsif area3.include?(@first_coord)
@x_directions = [-1, 0]
@y_directions = [1]
elsif area4.include?(@first_coord)
@x_directions = [0, 1]
@y_directions = [-1, 1]
elsif area5.include?(@first_coord)
@x_directions = [-1, 0, 1]
@y_directions = [-1, 1]
elsif area6.include?(@first_coord)
@x_directions = [-1, 0]
@y_directions = [-1, 1]
elsif area7.include?(@first_coord)
@x_directions = [1, 0]
@y_directions = [-1]
elsif area8.include?(@first_coord)
@x_directions = [-1, 0, 1]
@y_directions = [-1]
elsif area9.include?(@first_coord)
@x_directions = [-1, 0]
@y_directions = [-1]
end
end
end
<file_sep>/zadania_ruby/oop/sieve_e.rb
user_input = ARGV
start = user_input.first.to_i
finish = user_input.last.to_i
if finish < start
puts 'ERROR! Enter a smaller number first and then a larger one.'
end
naturals = (2..finish).to_a
index = 0
while index < naturals.length
prime = naturals[index]
naturals.reject! { |num| num % prime == 0 && num > prime }
index += 1
end
naturals.reject! { |num| num < start }
n = naturals.join(", ")
print "Prime numbers: #{n}\n"
<file_sep>/zadania_ruby/first_break/accum.rb
def accum(text)
index = 0
accum = []
while index < text.size
element = text[index] * (index + 1)
element.capitalize!
accum << element
index += 1
end
accum.join('-')
end
puts accum('ola')
puts accum('abCd')
<file_sep>/eksperymenty/lib/library.rb
require_relative "./book.rb"
require_relative "./reader.rb"
class Library
attr_accessor :all_books_in_library
attr_reader :readers
def initialize
self.all_books_in_library = []
@readers = []
end
def show_book_list
all_books_in_library.each do |book|
print book.author + "\t" + book.title + "\t" + 'status: ' + book.status + "\n"
end
end
def add_new_book(book)
all_books_in_library << book
end
def add_reader(reader)
generate_card_number(reader)
@readers << reader
end
def generate_card_number(reader)
letters = ('A'..'Z').to_a
numbers = (0..9).to_a
reader.card_number = letters.sample(3).join + numbers.sample(5).join
end
end
<file_sep>/zadania_rails/movies_catalog/config/routes.rb
Rails.application.routes.draw do
root 'main#index'
resources :movies do
resources :opinions, only: [:create, :destroy, :index]
resources :reviews
end
get 'signup' => 'users#new'
resources :users
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :genres, only: [:index, :show]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
<file_sep>/zadanie_bloki/zadanie4.rb
puts 'Podaj ilość $: '
x = gets.to_f
puts 'Podaj kurs: '
y = gets.to_f
k = x * y
puts "Koszt w zł wynosi: #{k}"
<file_sep>/postgresql/tasks.sql
# 1. Wyświetl nazwy wszystkich produktów dostępnych w sklepie.
SELECT name FROM products;
# 2. Wyświetl nazwy oraz ceny wszystkich produktów dostępnych w sklepie.
SELECT name, price FROM products;
# 3. Wyświetl nazwy wszystkich produktów których cena jest mniejsza lub równa 200.
SELECT name FROM products WHERE price <= 200;
# 4. Wyświetl wszystkie produkty, których cena zawiera się w przedziale 60..120.
SELECT * FROM products WHERE price BETWEEN 60 AND 120;
# 5. Wyświetl nazwy oraz ceny w groszach wszystkich produktów dostępnych w sklepie (ceny powinny zostać pomnożone przez 100).
SELECT name, price*100 AS price_gr FROM products;
# 6. Oblicz średnią cenę z wszystkich produktów.
SELECT AVG(price) FROM products;
# 7. Oblicz średnią cenę z wszystkich produktów, które zostały wyprodukowane przez producenta o id 2.
SELECT AVG(price) FROM products WHERE manufacturer_id = 2;
# 8. Oblicz ilość produktów, których cena jest większa bądź równa 180.
SELECT COUNT(*) FROM products WHERE price >= 180;
# 9. Wyświetl nazwy i ceny produktów, których cena jest większa bądź równa 180. Wyniki posortuj po cenie (malejąco) oraz po nazwie (rosnąco).
SELECT name, price FROM products WHERE price >= 180 ORDER BY price DESC, name;
# 10. Wyświetl wszystkie dane o produktach oraz odpowiadających im producentach.
SELECT *
FROM products
INNER JOIN manufacturers ON manufacturer_id = manufacturers.id;
# 11. Wyświetl nazwę, cenę oraz nazwę producenta wszystkich produktów dostępnych w sklepie.
SELECT products.name, products.price, manufacturers.name
FROM products
INNER JOIN manufacturers ON manufacturer_id = manufacturers.id;
# 12. Wyświetl średnią cenę produktów dla każdego producenta oraz jego id.
SELECT manufacturer_id, AVG(price) FROM products GROUP BY manufacturer_id;
# 13. Wyświetl średnią cenę produktów dla każdego producenta oraz jego nazwę.
SELECT manufacturers.name, AVG(price)
FROM manufacturers
INNER JOIN products ON manufacturer_id = manufacturers.id
GROUP BY manufacturers.id;
# 14. Wyświetl nazwy producentów których produkty mają średnią cenę większą bądź równą 150.
SELECT manufacturers.name, AVG(price)
FROM manufacturers
INNER JOIN products ON manufacturer_id = manufacturers.id
GROUP BY manufacturers.id
HAVING AVG(price) >= 180;
# 15. Wyświetl nazwę oraz cenę najtańszego produktu w sklepie.
SELECT name, price FROM products ORDER BY price LIMIT 1;
# 16. Wyświetl nazwę każdego producenta wraz z nazwą oraz ceną najdroższego produktu tego producenta.
SELECT DISTINCT ON (products.manufacturer_id) manufacturers.name, products.name, products.price
FROM products
INNER JOIN manufacturers ON manufacturers.id = manufacturer_id
WHERE products.id IN (SELECT id FROM products ORDER BY manufacturer_id, price DESC);
# 17. Wyświetl nazwy producentów, dla których sklep nie posiada produktów.
SELECT manufacturers.name
FROM manufacturers
LEFT OUTER JOIN products ON manufacturer_id = manufacturers.id
WHERE manufacturer_id is NULL;
# 18. Dodaj nowy produkt przypisany do producenta o id 2 z danymi: Loudspeakers, 70.
INSERT INTO products (name, price, manufacturer_id) VALUES ('Loudspeakers', 70, 2);
# 19. Zaktualizuj nazwę produktu o id 8 na Laser Printer.
UPDATE products SET name = 'Laser Printer' WHERE id = 8;
# 20. Zaktualizuj ceny wszystkich produktów o rabat 10%.
UPDATE products SET price = price * 0.9;
# 21. Obniż o 10% cenę wszystkich produktów droższych od 120.
UPDATE products SET price = price * 0.9 WHERE price > 120;
<file_sep>/eksperymenty/battleship_game/onedeckerclass.rb
class OneDecker
def initialize
@coordinates = []
@board_rows = (1..10).to_a
@board_columns = ('A'..'J').to_a
end
attr_accessor :coordinates
def coordinates
first_coordinate
puts @coordinates
end
private
def first_coordinate
@first_column = @board_columns.sample
@first_row = @board_rows.sample
@first_coord = @first_column + @first_row.to_s
@coordinates << @first_coord
@coordinates
end
end
statek = OneDecker.new
statek.coordinates
<file_sep>/zadanie_bloki/zadanie5.rb
dystans = gets.to_f
zuzycie_paliwa = (dystans * 6.5) / 100
koszt = zuzycie_paliwa * 4.3
puts "Zużycie paliwa na podany dystans to: #{zuzycie_paliwa}, a koszt: #{koszt}"
<file_sep>/zadania_rails/movies_catalog/app/validators/user_validator.rb
class UserValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, "must be your email" unless
value == current_user.email
end
end
<file_sep>/zadania_ruby/first_break/queue_time.rb
def queue_time(clients_queue, num_of_cash_registers)
time = 0
cash_registers = []
cash_registers_index = 0
while cash_registers_index < num_of_cash_registers
cash_registers << clients_queue.shift
cash_registers_index += 1
end
until cash_registers.empty?
until cash_registers.include?(0)
cash_registers.map! { |elem| elem - 1}
time += 1
end
cash_registers.reject! { |elem| elem == 0 }
unless clients_queue.empty?
cash_registers << clients_queue.shift
end
end
time
end
puts queue_time([5, 3, 4], 1)
puts queue_time([10, 2, 3, 3], 2)
puts queue_time([2, 3, 10], 2)
puts queue_time([7, 4, 5, 8, 2, 4], 3)
puts queue_time([7, 4, 5, 8, 2, 4], 4)
<file_sep>/zadania_ruby/introduction/multiplication.rb
print " "*5
liczba = 0
while liczba < 10
liczba += 1
print "%-5d" % liczba
end
puts ' '
print ' ' + '---- '*10
mnoznik = 0
while mnoznik < 10
mnoznik +=1
print "\n" + "%-3d" % mnoznik + "| "
liczba = 0
while liczba < 10
liczba += 1
wynik = mnoznik * liczba
print "%-5d" % wynik
end
end
puts ' '
<file_sep>/zadania_ruby/introduction/kalkulator.rb
# operacje
ADDITION = 1
SUBTRACTION = 2
MULTIPLICATION = 3
DIVISION = 4
QUIT = 5
puts 'Choose operation:'
puts ' 1. Add numbers'
puts ' 2. Subtract numbers'
puts ' 3. Multiply numbers'
puts ' 4. Divide numbers'
puts ' 5. Quit'
def popros_o_int(prosba)
print prosba
return gets.to_i
end
loop do
wybrana_operacja = popros_o_int('What is your choice? ')
break if wybrana_operacja == QUIT
first_number = popros_o_int('Enter first number: ')
second_number = popros_o_int('Enter second number: ')
case wybrana_operacja
when ADDITION
outcome = first_number + second_number
znak = '+'
when SUBTRACTION
outcome = first_number - second_number
znak = '-'
when MULTIPLICATION
outcome = first_number * second_number
znak = '*'
when DIVISION
if second_number.zero?
puts 'Do not divide by 0!'
next
else
outcome = first_number / second_number
znak = '/'
end
end
puts "#{first_number} #{znak} #{second_number} = #{outcome}"
end
puts 'Bye, bye'
<file_sep>/eksperymenty/zad_rails/my_to_do_list/app/controllers/jobs_controller.rb
class JobsController < ApplicationController
def index
end
def new
@job = Job.new
end
def create
@job = Job.new(params.require(:job).permit(:title))
end
end
<file_sep>/zadania_ruby/first_break/battleship_game/shipsonboard.rb
require_relative "./ship_type/onedecker.rb"
require_relative "./ship_type/twodecker.rb"
require_relative "./ship_type/threedecker.rb"
require_relative "./ship_type/fourdecker.rb"
require_relative "./board.rb"
class ShipsOnBoard
attr_reader :board, :ships, :all_ships_coordinates
def initialize
@board = Board.new
@ships = []
@all_ships_coordinates = []
run
end
def run
1.times { add_fourdecker }
2.times { add_threedecker }
3.times { add_twodecker }
4.times { add_onedecker }
find_all_ships_coordinates
return @board
end
def add_onedecker
ship = OneDecker.new(@board)
add_ship(ship)
end
def add_twodecker
while true
ship = TwoDecker.new(@board)
break if add_ship(ship)
end
end
def add_threedecker
while true
ship = ThreeDecker.new(@board)
break if add_ship(ship)
end
end
def add_fourdecker
while true
ship = FourDecker.new(@board)
break if add_ship(ship)
end
end
def add_ship(ship)
adding_ship = true
adding_ship = false unless @board.are_fields_empty?(ship.coordinates)
ship.coordinates.each do |elem|
unless @board.neighbouring_fields_empty?(elem)
adding_ship = false
end
end
if adding_ship
@board.fill(ship.coordinates)
@ships << ship
return true
else
return false
end
end
def find_all_ships_coordinates
index = 0
while index < @ships.size
ship_coordinates = @ships[index].coordinates
ship_coordinates.each { |coord| @all_ships_coordinates << coord }
index += 1
end
@all_ships_coordinates
end
end
<file_sep>/zadanie_bloki/zadanie3.rb
miesiac = gets.to_i
miesiace_po_31_dni = [1, 3, 5, 7, 8, 10, 12]
if miesiac == 2
puts "Miesiąc ma 28 dni"
elsif miesiace_po_31_dni.include?(miesiac) #należy do zbioru 1, 3, 5, 7, 8, 10, 12
puts "Miesiąc ma 31 dni"
else
puts "Miesiąc ma 30 dni"
end
<file_sep>/zadania_ruby/oop/calculator.rb
class Calculator
attr_reader :name, :history, :memory, :result
def initialize(name)
@name = name
@history = []
@result = nil
@memory = 0
end
def set_memory
@memory = @result
end
def clear
@result = 0
@memory = 0
add_to_history('clear')
end
def add(number)
@result = memory + number
set_memory
add_to_history('add', number)
end
def subtract(number)
@result = memory - number
set_memory
add_to_history('subtract', number)
end
def multiply(number)
@result = memory * number
set_memory
add_to_history('multiply', number)
end
def divide(number)
@result = memory / number
set_memory
add_to_history('divide', number)
end
def change_sign
@result = -@result
add_to_history('change_sign')
end
def add_to_history(method, number = nil)
action = {
method: method,
number: number,
result: result
}
@history << action
end
def print_history
puts 'History:'
@history.each do |action|
print "#{action[:method]} #{action[:number]} (result: #{action[:result]})\n"
end
end
end
calculator = Calculator.new('CASIO')
puts calculator.name # prints CASIO
calculator.add(2)
calculator.add(3)
puts calculator.result # prints 5
calculator.add(10)
puts calculator.result # prints 15
calculator.clear # set result to 0
puts calculator.result # prints 0
calculator.subtract(20)
puts calculator.result # prints -20
calculator.multiply(3)
puts calculator.result # prints -60
calculator.divide(4)
puts calculator.result # prints -15
calculator.change_sign
puts calculator.result # prints 15
calculator.print_history # prints entire history
<file_sep>/zadania_ruby/first_break/battleship_game/ship_type/onedecker.rb
require_relative "../board.rb"
require "pry"
class OneDecker
def initialize(board)
@coordinates = []
@neighbours = []
@board = board
generate_coordinates
end
attr_reader :coordinates, :neighbours
private
def generate_coordinates
@coordinates << @board.sample_coordinate
find_neighbours(@coordinates[0])
end
def find_neighbours(coordinates)
row_index, column_index = find_coordinate_index(coordinates)
i = -1
while i <= 1
index1 = row_index - 1
index2 = column_index + i
if in_bounds(index1, index2)
coord = @board.columns[index2] + @board.rows[index1].to_s
neighbours << coord
end
index1 = row_index
index2 = column_index + i
if in_bounds(index1, index2)
coord = @board.columns[index2] + @board.rows[index1].to_s
neighbours << coord
end
index1 = row_index + 1
index2 = column_index + i
if in_bounds(index1, index2)
coord = @board.columns[index2] + @board.rows[index1].to_s
neighbours << coord
end
i += 1
end
@neighbours = neighbours.reject { |elem| elem == @coordinates[0] }
end
def find_coordinate_index(coordinate) # coordinate jest to "A1"
column_index = @board.columns.find_index(coordinate[0])
if coordinate.length == 2
positions = 1
else
positions = 1..2
end
row_index = @board.rows.find_index(coordinate[positions].to_i)
[row_index, column_index]
end
def in_bounds(index1, index2)
if (index1 >= 0 && index1 <= 9) && (index2 >= 0 && index2 <= 9)
true
end
end
end
<file_sep>/zadanie_bloki/zadanie20.rb
sum = 0
x = gets.to_i
until x == 0
reszta = x % 10
sum += reszta
x = (x - reszta) / 10
end
puts sum
<file_sep>/zadania_rails/movies_catalog/db/migrate/20180108211550_remove_types_column_from_movies.rb
class RemoveTypesColumnFromMovies < ActiveRecord::Migration[5.1]
def change
remove_column(:movies, :types)
end
end
<file_sep>/zadania_ruby/first_break/hamming_distance.rb
def hamming_distance(string1, string2)
return unless string1.size == string2.size
distance = 0
index = 0
while index < string1.size
distance += 1 unless string1[index] == string2[index]
index += 1
end
distance
end
puts hamming_distance('1234', '1235').inspect
puts hamming_distance('GAGCCT', 'CATCGT').inspect
puts hamming_distance('1234', '12345').inspect
puts hamming_distance('123', 'foobar').inspect
<file_sep>/zadania_ruby/introduction/choinka.rb
def draw_level(padding, start, stop)
start.step(stop, 2) do |i|
print ' ' * padding
print ' ' * ((stop - i) / 2)
print '*' * i
print "\n"
end
end
draw_level(3, 1, 7)
draw_level(1, 3, 11)
draw_level(6, 1, 1)
<file_sep>/zadania_ruby/oop/library/program.rb
require_relative './library.rb'
require_relative './reader.rb'
require_relative './book.rb'
require "pry"
biblioteka = Library.new
book1 = Book.new('<NAME>', '<NAME> i <NAME>')
book2 = Book.new('<NAME>', 'Przeminęło z wiatrem')
book3 = Book.new('<NAME>', 'Wiedźmin')
book4 = Book.new('<NAME>', 'Duma i uprzedzenie')
book5 = Book.new('<NAME>', 'Marsjanin')
book6 = Book.new('<NAME>', 'Tajniki makijażu')
biblioteka.add_new_book(book1)
biblioteka.add_new_book(book2)
biblioteka.add_new_book(book3)
biblioteka.add_new_book(book4)
biblioteka.add_new_book(book5)
biblioteka.add_new_book(book6)
#binding.pry
czytelnik1 = Reader.new('Aleksandra', 'Kucharczyk')
czytelnik2 = Reader.new('Arkadiusz', 'Buras')
czytelnik3 = Reader.new('Zbyszek', 'Nowak')
#mam_ksiazke = biblioteka.find('Wiedźmin')
#czytelnik1.rent_book(mam_ksiazke)
biblioteka.add_reader(czytelnik1)
biblioteka.add_reader(czytelnik2)
biblioteka.add_reader(czytelnik3)
begin
biblioteka.rent_book_to_reader('tytul ksiazki', 'imie', 'nazwisko', '2017-05-01')
rescue Exception => error
puts error
end
biblioteka.rent_book_to_reader('Wiedźmin', 'Aleksandra', 'Kucharczyk', '2017-02-03')
puts ''
<file_sep>/zadania_rails/movies_catalog/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
def current_user
@current_user ||= User.where(id: session[:user_id]).first if session[:user_id]
end
def require_user
redirect_to login_path, alert: 'You have to be logged in' unless current_user
end
def require_admin
redirect_to root_path, alert: 'You are not an admin' unless current_user.admin?
end
end
<file_sep>/zadania_rails/movies_catalog/app/controllers/reviews_controller.rb
class ReviewsController < ApplicationController
before_action :find_movie
before_action :find_review, only: [:edit, :update, :destroy]
before_action :require_user
def index
redirect_to movie_path(@movie)
end
def new
@review = Review.new
end
def create
@review = @movie.reviews.new(review_params)
@review.user = current_user
if @review.save
redirect_to movie_path(@movie), notice: 'You successfully add a review!'
else
flash.now.alert = 'Something went wrong. Try again'
render 'reviews/new'
end
end
def edit
end
def update
if @review.update(review_params)
redirect_to movie_path(@review.movie), notice: 'You successfully updated this review'
else
flash.now.alert = 'Something went wrong. Try again'
render 'edit'
end
end
def destroy
@review.destroy
redirect_to movie_path(@movie), notice: 'You successfully deleted a review'
end
private
def find_movie
@movie = Movie.find(params[:movie_id])
end
def find_review
@review = Review.find(params[:id])
end
def review_params
params.require(:review).permit(:rate, :body)
end
end
<file_sep>/zadania_rails/movies_catalog/db/migrate/20180103143905_add_review_to_movie.rb
class AddReviewToMovie < ActiveRecord::Migration[5.1]
def change
add_reference :reviews, :movie
add_foreign_key :reviews, :movies
end
end
<file_sep>/zadania_ruby/first_break/sneak/gameplay.rb
# zaladowanie ekranu
# wybieranie akcji: graj, najlepsze wyniki, autorzy, koniec
# granie
require_relative './screen.rb'
require 'curses'
class Gameplay
def initialize
Curses.init_screen
begin
Curses.crmode
Curses.noecho
Curses.stdscr.keypad(true)
Curses.nonl
ensure
Curses.close_screen
end
game
end
def game
x, y = 1, 11
begin
Curses.timeout = 0
dx, dy = 1, 0
while true
key = Curses.getch
if key == Curses::Key::RIGHT
dx, dy = 1, 0
elsif key == Curses::Key::LEFT
dx, dy = -1, 0
elsif key == Curses::Key::UP
dx, dy = 0, -1
elsif key == Curses::Key::DOWN
dx, dy = 0, 1
elsif key == 'q'
break
end
x += dx
y += dy
Curses.clear
Curses.setpos(y, x)
Curses.addch('@')
Curses.setpos(0, 0)
Curses.refresh
sleep 0.2
end
ensure
Curses.close_screen
end
end
end
wunsz = Gameplay.new
<file_sep>/eksperymenty/znajdz_index.rb
#value = gets.to_i
#array = [7, 2, 4, 2, 1, 5, 6]
#print array
#puts ' '
def find_index(array, value)
#if array.include?(value)
index = 0
while index < array.size
if array[index] == value
return index
end
index += 1
end
return 'not found'
#else
# puts 'not found'
#end
end
puts find_index([1, 2, 3, 4, 5], 3)
puts find_index([5, 8, 6, 2, 2, 10], 2)
puts find_index([10, 20, 30], 100)
puts find_index([], 0)
<file_sep>/zadania_ruby/first_break/battleship_game/gameplay.rb
require_relative './shipsonboard.rb'
require_relative './gamers_choice.rb'
class Gameplay < Board
include GamersChoice
attr_reader :board
def initialize
super
@board = ShipsOnBoard.new
end
def gameplay
board_for_gamer
if finished_game?
end_game
end
gamer_input = gamer_choice
checking_gamer_choice(gamer_input)
puts "\e[H\e[2J"
end
private
def board_for_gamer
print frame
print create_headline
rows
end
def frame
'+---' * 11 + "+\n"
end
def create_headline
headline_names = @columns + [' ']
headline_names.sort!
headline = '| '
index = 0
while index < headline_names.size
a = "#{headline_names[index]} "
b = '| '
headline << (a + b)
index += 1
end
headline << "\n"
headline
end
def rows
row_index = 0
while row_index < @rows.size
print frame
column_index = 0
row = [@rows[row_index].to_s]
while column_index < @columns.size
value_on_board = @board.board.board[row_index][column_index]
row << field_output(value_on_board)
column_index += 1
end
print '|'
row.each { |elem| print elem.center(3) + '|' }
print "\n"
row_index += 1
end
print frame
end
def field_output(value)
if value == @field_options[:empty_unselected_field]
@field = ' '
elsif value == @field_options[:filled_unselected_field]
@field = ' '
elsif value == @field_options[:empty_selected_field]
@field = '*'
elsif value == @field_options[:filled_selected_field]
@field = 'X'
end
@field
end
#rysowanie planszy z ShipsOnBoard
#użytkownik podaje nr pola
#przetworzenie akcji z Board
#czy koniec gry? Tak -> wygrałeś
#jeśli nie, wróć do linii 2
end
gra = Gameplay.new
gra.gameplay
<file_sep>/eksperymenty/yield_test.rb
def each_element(array)
index = 0
while index < array.size
element = array[index]
yield element
index += 1
end
end
each_element(['Arek', 'Ola', 'Himen']) { |opp| puts opp}
<file_sep>/zadania_rails/movies_catalog/app/controllers/movies_controller.rb
class MoviesController < ApplicationController
before_action :find_movie, only: [:show, :edit, :update, :destroy]
before_action :require_user, only: [:new, :create, :edit, :update, :destroy] # metoda z application_controller
before_action :require_admin, only: [:edit, :update, :destroy] # metoda z application_controller
def index
@movies = Movie.all.order(created_at: :desc)
@movies = Movie.where("title like :searched_title", searched_title: "%#{params[:search].capitalize!}%") if params[:search].present?
end
def new
@movie = Movie.new
end
def create
@movie = current_user.movies.new(movie_params)
if @movie.save
redirect_to movie_path(@movie), notice: 'You successfully added new movie'
else
#Rails.logger.info @movie.errors.full_messages.join(', ')
flash.now.alert = 'Something went wrong. Try again'
render 'new'
end
end
def show
@opinion = Opinion.new
end
def edit
end
def update
if @movie.update(movie_params)
redirect_to movie_path(@movie), notice: 'You successfully updated this movie'
else
#Rails.logger.info @movie.errors.full_messages.join(', ')
flash.now.alert = 'Something went wrong. Try again'
render 'edit'
end
end
def destroy
@movie.destroy
redirect_to movies_path, notice: 'You successfully deleted a movie'
end
private
def find_movie
@movie = Movie.find(params[:id])
end
def movie_params
params.require(:movie).permit(:title, :release_date, :length, :description, :director, :writer, :country, :image, :youtube_url, genre_ids: [])
end
end
<file_sep>/zadania_rails/movies_catalog/db/migrate/20171230192403_add_user_to_movie.rb
class AddUserToMovie < ActiveRecord::Migration[5.1]
def change
add_reference :movies, :user
add_foreign_key :movies, :users, column: :user_id
end
end
<file_sep>/zadania_ruby/first_break/to_roman.rb
def to_roman(number)
if (number / 1000) > 0
m = 0
until number < 1000
m += 1
number -= 1000
end
tysiace = 'M' * m
end
if (number / 100) > 0
c = 0
until number < 100
c += 1
number -= 100
end
if c < 4
setki = 'C' * c
elsif c == 4
setki = 'CD'
elsif c > 4 && c < 9
setki = 'D' + 'C' * (c - 5)
elsif c == 9
setki = 'XM'
end
end
if (number / 10) > 0
x = 0
until number < 10
x += 1
number -= 10
end
if x < 4
dziesiatki = 'X' * x
elsif x == 4
dziesiatki = 'XL'
elsif x > 4 && x < 9
dziesiatki = 'L' + 'X' * (x - 5)
elsif x == 9
dziesiatki = 'XC'
end
end
if (number / 1) > 0
i = 0
until number.zero?
i += 1
number -= 1
end
if i < 4
jednosci = 'I' * i
elsif i == 4
jednosci = 'IV'
elsif i > 4 && i < 9
jednosci = 'V' + 'I' * (i - 5)
elsif i == 9
jednosci = 'IX'
end
end
print tysiace
print setki
print dziesiatki
print jednosci
end
puts to_roman(3)
puts to_roman(23)
puts to_roman(623)
puts to_roman(2623)
puts to_roman(3000)
puts to_roman(200)
puts to_roman(10)
<file_sep>/zadania_ruby/first_break/palindrome.rb
def palindrome?(sentence)
letters = []
sentence.downcase.each_char { |chr| letters << chr }
letters.reject! { |elem| elem == ' ' }
if letters == letters.reverse
true
else
false
end
end
puts palindrome?('Kobyła ma mały bok')
puts palindrome?('A to kanapa pana Kota')
puts palindrome?('kajak')
puts palindrome?('kajak i wiosło')
<file_sep>/zadania_ruby/first_break/animals.rb
class Animals
def give_sound
end
end
class Dog < Animals
def give_sound
puts 'Hau! Hau!'
end
end
class Cat < Animals
def give_sound
puts 'Miau! Miau!'
end
end
class Duck < Animals
def give_sound
puts 'Qua! Qua!'
end
end
class Goose < Animals
def give_sound
puts 'Duck! Duck!'
end
end
class Farm
def initialize(animals_array)
@animals_array = animals_array
end
def give_sound
@animals_array.each { |animal| animal.give_sound }
end
end
farm = Farm.new([Dog.new, Cat.new])
farm.give_sound
farm2 = Farm.new([Duck.new, Cat.new, Goose.new, Duck.new, Dog.new])
farm2.give_sound
<file_sep>/zadania_ruby/first_break/highest_number.rb
def highest_number(numbers)
num_array = []
numbers.to_s.each_char { |chr| num_array << chr.to_i }
sorted = []
loop do
max_num = num_array.max
sorted << max_num
max_num_index = num_array.find_index(max_num)
num_array.delete_at(max_num_index)
break if num_array.empty?
end
sorted.join.to_i
end
print highest_number(123456)
puts " "
print highest_number(1464)
puts " "
<file_sep>/zadania_ruby/introduction/PESEL_ARGV.rb
input_array = ARGV
pesel = input_array.join.to_i
def pesel_valid?(pesel)
p = pesel.digits.reverse
sum = (p[0].to_i + p[4].to_i + p[8].to_i) * 9 + (p[1].to_i + p[5].to_i + p[9].to_i) * 7 + (p[2].to_i + p[6].to_i) * 3 + p[3].to_i + p[7].to_i
return sum % 10 == p.last
end
def what_sex(pesel)
p = pesel.digits.reverse
if (p[9].to_i % 2).zero?
sex = 'kobieta'
else
sex = 'meżczyzna'
end
puts " - płeć: #{sex}"
end
def what_birth_date(pesel)
p = pesel.digits.reverse
if p[2].to_i < 2
month = "#{p[2]}#{p[3]}"
else
month = "#{(p[2].to_i * 10 - 10)}#{p[3]}"
end
if p[2].to_i < 2
year = 1900 + p[0].to_i * 10 + p[1].to_i
else
year = 2000 + (p[0].to_i * 10 - 10) + p[1].to_i
end
puts " - data urodzenia: #{p[4]}#{p[5]}-#{month}-#{year}"
end
if pesel_valid?(pesel)
puts "PESEL o numerze #{pesel} jest prawidłowy."
puts 'Informacje o numerze PESEL:'
what_sex(pesel)
what_birth_date(pesel)
else
puts "PESEL o numerze #{pesel} jest nieprawidłowy."
end
<file_sep>/zadania_ruby/introduction/suma_liczb2.rb
number = gets.to_i
suma_liczb_parzystych = (2..number).step(2).sum(0)
puts suma_liczb_parzystych
<file_sep>/zadania_ruby/introduction/fib2.rb
liczba = gets.to_i
def fib(n)
a, b = 0, 1
puts a
puts b
i = 0
while i < n - 2
wynik = a + b
puts wynik
a = b
b = wynik
i += 1
end
end
fib(liczba)
<file_sep>/zadanie_bloki/zadanie2.rb
x = gets.to_i
sek = x * 24 * 60 * 60
puts "Ilość sekund w #{x} dni wynosi: #{sek}"
<file_sep>/zadanie_bloki/zadanie19.rb
puts 'Podaj liczbę:'
n = gets.to_i
if n < 1
puts 'Liczba musi być > 0'
else
i = 1
sum = i**2
while i < n
i += 1
sum += i**2
end
end
puts sum
<file_sep>/zadania_ruby/first_break/battleship_game/board.rb
class Board
def initialize
@columns = ('A'..'J').to_a
@rows = (1..10).to_a
@field_options = {
empty_unselected_field: 0,
empty_selected_field: 1,
filled_unselected_field: 2,
filled_selected_field: 3
}
create_board
end
attr_reader :board, :coordinates, :columns, :rows
def create_board
@board = Array.new(10) { Array.new(10, @field_options[:empty_unselected_field])}
end
def sample_coordinate
first_column = @columns.sample
first_row = @rows.sample
first_coord = first_column + first_row.to_s
if are_fields_empty?(first_coord) && neighbouring_fields_empty?(first_coord)
return first_coord
else
sample_coordinate
end
end
def find_coordinate_value(coordinate) # coordinate jest to "A1"
row_index, column_index = find_coordinate_index(coordinate)
@board[row_index][column_index]
end
def find_coordinate_index(coordinate) # coordinate jest to "A1"
column_index = @columns.find_index(coordinate[0])
if coordinate.length == 2
positions = 1
else
positions = 1..2
end
row_index = @rows.find_index(coordinate[positions].to_i)
[row_index, column_index]
end
def neighbouring_fields_empty?(coord)
neighbours_coord = []
row_index, column_index = find_coordinate_index(coord)
i = -1
while i <= 1
index1 = row_index - 1
index2 = column_index + i
if in_bounds(index1, index2)
coord = @columns[index2] + @rows[index1].to_s
neighbours_coord << coord
end
index1 = row_index
index2 = column_index + i
if in_bounds(index1, index2)
coord = @columns[index2] + @rows[index1].to_s
neighbours_coord << coord
end
index1 = row_index + 1
index2 = column_index + i
if in_bounds(index1, index2)
coord = @columns[index2] + @rows[index1].to_s
neighbours_coord << coord
end
i += 1
end
empty = true
i = 0
while i < neighbours_coord.size
empty = false unless are_fields_empty?(neighbours_coord[i])
i += 1
end
return empty
end
def in_bounds(index1, index2)
if (index1 >= 0 && index1 <= 9) && (index2 >= 0 && index2 <= 9)
true
end
end
def are_fields_empty?(coordinates)
if coordinates.class == String
return true if find_coordinate_value(coordinates).zero?
elsif coordinates.class == Array
empty = true
i = 0
while i < coordinates.size
empty = false unless find_coordinate_value(coordinates[i])
i += 1
end
return empty
end
end
def fill(coordinates)
coordinates.each do |coordinate|
row_index, column_index = find_coordinate_index(coordinate)
@board[row_index][column_index] = @field_options[:filled_unselected_field]
end
end
end
<file_sep>/zadania_ruby/introduction/znajdz_index2.rb
value = gets.to_i
array = [1, 2, 3, 4, 5, 5, 4]
def find_index(array, value)
if array.include?(value)
puts array.index(value)
else
puts 'not found'
end
end
find_index(array, value)
<file_sep>/zadania_ruby/introduction/fib.rb
n = gets.to_i
def fib(n)
a, b = 0, 1
i = 1
puts a
puts b
loop do
wynik = a + b
puts wynik
a = b
b = wynik
i += 1
break if i == n - 1
end
end
fib(n)
<file_sep>/zadania_ruby/first_break/vowel_count.rb
VOWELS = ["a", "e", "i", "o", "u", "y"]
def vowel_count(word)
word.downcase!
counter = 0
word.each_char do |letter|
if VOWELS.include?(letter)
counter += 1
end
end
return counter
end
puts vowel_count('Aleksandra')
<file_sep>/zadania_ruby/introduction/guessinggame.rb
num = rand(100)
loop do
input = gets.to_i
if input < num
puts 'więcej'
else
puts 'mniej'
end
break if input == num
end
puts "Udało się: #{num}"
<file_sep>/zadanie_bloki/zadanie6.rb
puts 'Podaj liczbę całkowitą a'
a = gets.to_i
puts 'Podaj liczbę całkowitą b'
b = gets.to_i
roznica = a - b
suma = a + b
if roznica == suma
puts 'Suma jest równa różnicy'
elsif suma > roznica
puts 'Suma jest większa od różnicy'
else
puts 'Suma jest mniejsza od różnicy'
end
<file_sep>/zadania_ruby/oop/quick_sort.rb
require "pry"
class QuickSort
attr_accessor :to_sort, :right, :left
def initialize(user_input)
@to_sort = []
@user_input = user_input
array_to_sort
@right = @to_sort.size - 1
@left = 0
end
def array_to_sort
@user_input.each { |elem| @to_sort << elem.to_i }
@to_sort
end
def sort!
quick_sort(@to_sort, @left, @right)
end
private
def quick_sort(to_sort, left, right)
i = (left + right) / 2
pivot = to_sort[i]
to_sort[i], to_sort[right] = to_sort[right], to_sort[i]
j = i = left
while i < right
if to_sort[i] < pivot
to_sort[i], to_sort[j] = to_sort[j], to_sort[i]
j += 1
end
i += 1
end
to_sort[right], to_sort[j] = to_sort[j], pivot
to_sort = quick_sort(to_sort, left, j - 1) if left < j - 1
to_sort = quick_sort(to_sort, j + 1, right) if j + 1 < right
to_sort
end
end
sortowanie = QuickSort.new(ARGV)
puts sortowanie.sort!
<file_sep>/zadania_ruby/first_break/avg_array.rb
def equal_sizes_arrays?(array)
sizes_array = array.map { |elem| elem.size }
sizes_array.uniq!
return sizes_array.size == 1
end
def avg_array(*main_array)
raise 'Sizes of arrays are not the same' unless equal_sizes_arrays?(main_array)
index = 0
result_array = []
while index < main_array[0].size
main_index = 0
sum = 0
while main_index < main_array.size
elem = main_array[main_index][index]
sum += elem
main_index += 1
end
result = sum / main_array.size.to_f
result_array << result
index += 1
end
result_array
end
print avg_array([1, 3, 5], [3, 5, 7])
print avg_array([1, 5, 3, 22], [12, 22, 13, 5], [5, 12, 24, 5], [14, 40, 5, 17])
<file_sep>/zadania_ruby/oop/products.rb
require "csv"
class Products
def initialize
@products = []
load_products
end
def load_products
if @products == []
CSV.foreach('products.csv', headers: true) do |row|
@products << parse_line(row)
end
end
@products
end
def find(product)
@products.each do |row|
if row[:name] == product
result = "#{row[:name]} #{row[:price]}#{row[:currency]}"
return result
end
end
result
end
def find_cheaper_products(price)
@products.find_all do |row|
row[:price].to_f < price.to_f
end.each do |row|
puts "#{row[:name]} #{row[:price]}#{row[:currency]}\n"
end
end
def find_more_expensive_products(price)
@products.find_all do |row|
if row[:price].to_f > price.to_f
puts "#{row[:name]} #{row[:price]}#{row[:currency]}"
end
end
end
def convert_prices_to_currency(exchange_rate, currency, file_name)
new_headers = ['Product', "Price(#{currency})", 'Weight(kg)']
CSV.open("./#{file_name}", 'w') do |csv|
csv << new_headers
@products.each do |row|
new_price = row[:price].to_f / exchange_rate.to_f
csv << [row[:name], new_price.round(2), row[:weight]]
end
end
end
private
def parse_line(row)
price_header = price_header(row)
{
name: row['Product'],
price: row[price_header],
weight: row['Weight(kg)'],
currency: price_header[6..-2]
}
end
def price_header(row)
row.headers.select do |header|
header[0..4] == 'Price'
end.first
end
end
products = Products.new
products.load_products
case ARGV[0]
when '-f'
puts products.find(ARGV[1])
when '-lt'
products.find_cheaper_products(ARGV[1])
when '-gt'
puts products.find_more_expensive_products(ARGV[1])
when '-c'
products.convert_prices_to_currency(ARGV[1], ARGV[2], ARGV[3])
end
<file_sep>/zadania_ruby/introduction/suma_liczb3.rb
number = gets.to_i
ilosc_liczb_parzystych = number / 2
suma_liczb_parzystych = (2 + (ilosc_liczb_parzystych - 1)) * ilosc_liczb_parzystych
puts suma_liczb_parzystych
<file_sep>/zadania_ruby/first_break/initials.rb
def initials(name_surname)
words = name_surname.split(/(\s|-)/) # regexp rubular.com
words.reject! { |word| word == " " || word == "-"}
letters = words.map { |word| word[0] }
letters.join.upcase
end
puts initials('<NAME>')
puts initials('<NAME>')
puts initials('<NAME>')
<file_sep>/zadania_ruby/oop/sieve_e_oop.rb
class Sieve
def initialize(start, finish)
@start = start
@finish = finish
@naturals = []
if finish < start
puts 'ERROR! Enter a smaller number first and then a larger one.'
end
end
def result
n = @naturals.join(", ")
print "Prime numbers: #{n}\n"
end
def prime_num
@naturals = (2..@finish).to_a
index = 0
while index < @naturals.length
prime = @naturals[index]
@naturals.reject! { |num| num % prime == 0 && num > prime }
index += 1
end
@naturals.reject! { |num| num < @start }
@naturals
end
end
user_input = ARGV
start = user_input.first.to_i
finish = user_input.last.to_i
calculation1 = Sieve.new(start, finish)
calculation1.prime_num
calculation1.result
<file_sep>/eksperymenty/rysowanie_planszy.rb
#require "pry"
@columns = ('A'..'J').to_a
@rows = (1..10).to_a
def board_for_gamer
print frame
print create_headline
rows
end
def frame
'+---' * 11 + "+\n"
end
def create_headline
headline_names = @columns + [' ']
headline_names.sort!
headline = '| '
index = 0
while index < headline_names.size
a = "#{headline_names[index]} "
b = '| '
headline << (a + b)
index += 1
end
headline << "\n"
headline
end
def rows
field = ' '
index = 0
while index < @rows.size
print frame
row = [@rows[index].to_s] + [field] * 10
print '|'
row.each { |elem| print elem.center(3) + '|'}
print "\n"
index += 1
end
print frame
end
board_for_gamer
<file_sep>/zadanie_bloki/zadanie16.rb
puts 'Podaj liczbę:'
n = gets.to_i
if n < 1
puts 'Liczba musi być > 0'
else
i = 1
j = -n
while i <= n
puts i
puts j
i += 1
j = -n + (i - 1)
end
end
<file_sep>/zadania_ruby/oop/figures.rb
class Figures
def result
area
perimeter
puts ''
end
def area(area, unit)
puts "Pole wynosi: #{area}#{unit}2"
end
def perimeter(perimeter, unit)
puts "Obwód wynosi: #{perimeter}#{unit}"
end
private
def string_to_array(input)
value_in_array = []
units = ['m', 'c', 'k']
input.each_char { |char| value_in_array << char unless units.include?(char) }
value_in_array
end
def take_value(input)
string_to_array(input).join.to_f
end
def value_precision(input)
value_in_array = string_to_array(input)
if value_in_array.include?('.')
i = 0
until value_in_array[i] == '.'
value_in_array.delete_at(i)
end
counter = 0
value_in_array.each { |elem| counter += 1 unless elem == '.' }
return counter
else
return 0
end
end
def take_unit(input)
final_unit = []
units = ['m', 'c', 'k']
input.each_char do |char|
final_unit << char if units.include?(char)
end
final_unit.join
end
end
class Circle < Figures
def initialize(radius)
@radius = take_value(radius)
@unit = take_unit(radius)
@precision = value_precision(radius)
end
def area
area = (3.14 * (@radius**2)).round(@precision)
super(area, @unit)
end
def perimeter
perimeter = (2 * 3.14 * @radius).round(@precision)
super(perimeter, @unit)
end
end
class Trapeze < Figures
def initialize(a, b, h)
@a = take_value(a)
@b = take_value(b)
@h = take_value(h)
@unit = take_unit(a)
@precision = value_precision(a)
end
def area
area = (@h * ((@a + @b) / 2.0)).round(@precision)
super(area, @unit)
end
def perimeter
perimeter = (@a + @b + 2 * c).round(@precision)
super(perimeter, @unit)
end
private
def c
d = (@b - @a) / 2.0
Math.sqrt(@h * @h + d * d)
end
end
class Rectangle < Trapeze
def initialize(a, b)
super(b, b, a)
end
end
class Square < Rectangle
def initialize(a)
super(a, a)
end
end
puts 'Circles:'
Circle.new('5cm').result
Circle.new('2.25cm').result
Circle.new('100m').result
Circle.new('2.25cm').result
puts 'Rectangles:'
Rectangle.new('5cm', '2cm').result
Rectangle.new('3.33cm', '4.20cm').result
Rectangle.new('124m', '33m').result
Rectangle.new('1.2km', '2.2km').result
puts 'Squares:'
Square.new('3cm').result
Square.new('4.45').result
Square.new('12m').result
Square.new('3.66km').result
puts 'Trapezes:'
Trapeze.new('2.34cm', '6.66cm', '2cm').result
Trapeze.new('113m', '33m', '16m').result
<file_sep>/zadania_rails/movies_catalog/app/models/review.rb
class Review < ApplicationRecord
validates :rate, presence: true, numericality: true, range: true
validates :body, presence: true, length: { minimum: 250 }
belongs_to :movie
belongs_to :user
end
<file_sep>/eksperymenty/sieve_of_eratosthenes.rb
user_input = ARGV
num1 = user_input.first.to_i
num2 = user_input.last.to_i
def range_numbers(num1, num2)
index = 0
if num1 <= 1
array = [2]
num1 = 2
else
array = [num1]
end
while array[index] < num2
num1 += 1
array << num1
index += 1
end
return array
end
def elimination(num)
i = 0
divisors = [2, 3, 5, 7]
if divisors.include?(num)
return false
else
while i < divisors.size
result = num % divisors[i]
if result.zero?
return true
else
i += 1
end
end
end
end
def sieve(num1, num2)
if num1 > num2
puts 'ERROR! Enter a smaller number first and then a larger one.'
else
numbers = range_numbers(num1, num2)
elimination = numbers.delete_if { |num| elimination(num) }
prime_numbers = elimination.join(", ")
print "Prime numbers: #{prime_numbers}\n"
end
end
sieve(num1, num2)
<file_sep>/zadania_ruby/first_break/consecutives_sum.rb
def consecutives_sum(numbers)
result = []
until numbers.empty?
index = 0
storage = []
if numbers[index] == numbers[index + 1]
while numbers[index] == numbers[index + 1]
storage << numbers.shift
end
storage << numbers.shift
accum = storage.inject(0) { |accum, elem| accum + elem }
result << accum
else
result << numbers.shift
end
end
result
end
print consecutives_sum([1, 4, 4, 4, 0, 4, 3, 3, 1])
print consecutives_sum([1, 1, 7, 7, 3])
print consecutives_sum([-5, -5, 7, 7, 12, 0])
<file_sep>/zadania_ruby/first_break/highest_number2.rb
def highest_number(numbers)
num_array = []
numbers.to_s.each_char { |chr| num_array << chr.to_i }
sorted = num_array.sort { |x, y| y <=> x}
sorted.join.to_i
end
print highest_number(123456)
puts " "
print highest_number(1464)
puts " "
print highest_number(165023)
puts " "
<file_sep>/zadania_ruby/oop/library/library.rb
require_relative "./book.rb"
require_relative "./reader.rb"
class Library
attr_reader :readers
def initialize
@all_books_in_library = []
@readers = []
end
def show_book_list
@all_books_in_library.each do |book|
print book.author + "\t" + book.title + "\t" + 'status: ' + book.status + "\n"
end
end
def add_new_book(book)
@all_books_in_library << book
end
def add_reader(reader)
generate_card_number(reader)
@readers << reader
end
def generate_card_number(reader)
letters = ('A'..'Z').to_a
numbers = (0..9).to_a
reader.card_number = letters.sample(5).join + numbers.sample(5).join
end
def find_book(title_or_author)
@all_books_in_library.find do |book|
book.title.downcase == title_or_author.downcase || book.author.downcase == title_or_author.downcase
end
end
def find_reader(first_name, last_name)
@readers.find do |reader|
reader.name == first_name && reader.surname == last_name
end
end
def rent_book_to_reader(title_or_author, first_name, last_name, date)
book = find_book(title_or_author)
reader = find_reader(first_name, last_name)
if book.nil?
raise 'Nie ma takiej książki' # TODO: dodac przekazywanie title_or_author
end
if reader.nil?
raise 'Nie ma takiego użytkownika' # TODO: dodac przekazywanie reader
end
reader.rent_book(book, date)
end
end
<file_sep>/zadania_ruby/first_break/backspaces_in_string.rb
def backspaces(text)
elements = []
text.each_char { |chr| elements << chr }
while elements.include?('#')
index = elements.find_index('#')
elements.delete_at(index)
elements.delete_at(index - 1) if index - 1 >= 0
end
elements.join
end
puts backspaces('a#bc#d')
puts backspaces('abc#d##c')
puts backspaces('abc##d######c')
puts backspaces('')
puts backspaces('a##bcd')
<file_sep>/zadanie_bloki/zadanie15.rb
puts 'Podaj liczbę:'
n = gets.to_i
if n < 1
puts 'Liczba musi być > 0'
else
i = 1
while i <= n
puts i
puts -i
i += 1
end
end
<file_sep>/zadania_ruby/first_break/middle.rb
def middle(word)
position = word.length / 2
if (word.length % 2).zero?
return word[position, position + 1]
else
return word[position]
end
end
puts middle('word')
puts middle('bla')
puts middle('tesTing')
<file_sep>/zadania_ruby/first_break/word_count.rb
def word_count(sentence)
sentence.downcase!
words = sentence.split
result = {}
words.each do |elem|
if result.include?(elem)
result[elem] += 1
else
result[elem] = 1
end
end
result
end
print word_count('foo Foo bar bar Bar')
print word_count('Losowy ciąg znaków ciąg')
<file_sep>/zadania_rails/movies_catalog/db/migrate/20180103144245_add_user_to_review.rb
class AddUserToReview < ActiveRecord::Migration[5.1]
def change
add_reference :reviews, :user
add_foreign_key :reviews, :users
end
end
<file_sep>/zadania_rails/movies_catalog/app/models/opinion.rb
class Opinion < ApplicationRecord
validates :author, presence: true, length: { minimum: 3, maximum: 30 }, unless: :have_user?
validates :rate, presence: true, numericality: true, range: true
validates :body, presence: true, length: { minimum: 5, maximum: 500 }
belongs_to :movie
belongs_to :user, optional: true
def have_user?
!user.nil?
end
end
<file_sep>/zadanie_bloki/zadanie21.rb
n = gets.to_i
i = 1
wynik = 1
while i < n
i += 1
wynik *= i
end
puts wynik
<file_sep>/zadania_ruby/first_break/battleship_game/gamers_choice.rb
module GamersChoice
def gamer_choice
puts 'What is your choice?'
choice = gets.chomp.upcase
unless choice_invalid?(choice)
@choice_row, @choice_column = find_coordinate_index(choice)
@choice_value = find_coordinate_value(choice)
checking_gamer_choice(choice)
end
end
def find_coordinate_value(coordinate) # coordinate jest to "A1"
row_index, column_index = find_coordinate_index(coordinate)
@board.board.board[row_index][column_index]
end
def find_coordinate_index(coordinate) # coordinate jest to "A1"
column_index = @board.board.columns.find_index(coordinate[0])
if coordinate.size == 2
positions = 1
else
positions = 1..2
end
row_index = @board.board.rows.find_index(coordinate[positions].to_i)
[row_index, column_index]
end
def checking_gamer_choice(gamer_choice)
choice_value = find_coordinate_value(gamer_choice)
if missed?(choice_value)
@board.board.board[@choice_row][@choice_column] = @field_options[:empty_selected_field]
puts 'You missed. Try again!'
elsif hit?(choice_value)
@board.board.board[@choice_row][@choice_column] = @field_options[:filled_selected_field]
puts 'Hit!'
ship_sunk?(gamer_choice)
else
puts 'This field is already filled. Try again'
end
gameplay
end
def choice_invalid?(choice)
if choice.empty? || choice.nil?
puts 'Try again'
gamer_choice
elsif choice.length > 3
puts 'Try again'
gamer_choice
end
end
def missed?(value)
if value == @field_options[:empty_unselected_field]
true
end
end
def hit?(value)
if value == @field_options[:filled_unselected_field]
true
end
end
def ship_sunk?(coordinate)
ship = find_ship_with_coordinate(coordinate)
if ship.class == OneDecker
one_decker_sunk(ship)
else
more_decker_sunk(ship)
end
end
def find_ship_with_coordinate(coordinate)
index = 0
ship = nil
while index < @board.ships.size
ship_coordinates = @board.ships[index].coordinates
ship = @board.ships[index] if ship_coordinates.include?(coordinate)
index += 1
end
ship
end
def one_decker_sunk(ship)
puts 'Hit and sunk!'
ship.neighbours.each do |coord|
row_index, column_index = find_coordinate_index(coord)
@board.board.board[row_index][column_index] = @field_options[:empty_selected_field]
end
end
def more_decker_sunk(ship)
hit_fields = []
ship.coordinates.each do |coord|
row_index, column_index = find_coordinate_index(coord)
if @board.board.board[row_index][column_index] == @field_options[:filled_selected_field]
hit_fields << coord
end
end
if ship.coordinates == hit_fields
puts 'Hit and sunk!'
ship.neighbours.each do |coord|
row_index, column_index = find_coordinate_index(coord)
@board.board.board[row_index][column_index] = @field_options[:empty_selected_field]
end
end
end
def finished_game?
hit_fields = []
@board.all_ships_coordinates.each do |coord|
row_index, column_index = find_coordinate_index(coord)
if @board.board.board[row_index][column_index] == @field_options[:filled_selected_field]
hit_fields << coord
end
end
if @board.all_ships_coordinates == hit_fields
puts 'You win!!! Congratulations!'
true
end
end
def end_game
exit
end
end
<file_sep>/zadania_ruby/first_break/common_elements.rb
def common_elements(array1, array2)
index = 0
common_elements = []
while index < array1.size
if array2.include?(array1[index])
common_elements << array1[index] unless common_elements.include?(array1[index])
end
index += 1
end
common_elements
end
print common_elements([1, 2, 3, 4, 5], [4, 5, 6])
print common_elements(['cat', 1227, 'apple', 0], ['apple', 'cat', 1227, 4])
print common_elements(['cat', 1227, 1227, 'apple', 0], [1227, 'apple', 'cat', 1227, 4])
<file_sep>/zadanie_bloki/zadanie9.rb
puts 'Podaj dwie liczby:'
a = gets.to_i
b = gets.to_i
if a < b
puts 'Ciąg jest rosnący'
else
puts 'Ciąg nie jest rosnący'
end
<file_sep>/zadania_rails/movies_catalog/db/migrate/20171230192631_add_opinions_to_movie.rb
class AddOpinionsToMovie < ActiveRecord::Migration[5.1]
def change
add_reference :opinions, :movie
add_foreign_key :opinions, :movies
end
end
<file_sep>/zadania_rails/movies_catalog/app/helpers/application_helper.rb
module ApplicationHelper
def errors_msg(object, field_name)
@errors = object.errors.messages[field_name]
end
end
<file_sep>/zadanie_bloki/zadanie7.rb
puts 'Podaj liczbę całkowitą a'
a = gets.to_i
puts 'Podaj liczbę całkowitą b'
b = gets.to_i
puts ' '
if a >= b
puts a
else
puts b
end
<file_sep>/zadania_ruby/introduction/suma_liczb.rb
number = gets.to_i
i = 0
suma_liczb_parzystych = 0
while i < number
i += 1
if i % 2 == 0
suma_liczb_parzystych += i
end
end
puts suma_liczb_parzystych
<file_sep>/zadania_rails/movies_catalog/db/migrate/20171230193132_add_user_to_opinion.rb
class AddUserToOpinion < ActiveRecord::Migration[5.1]
def change
add_reference :opinions, :user
add_foreign_key :opinions, :users
end
end
<file_sep>/zadanie_bloki/zadanie14.rb
puts 'Podaj liczbę:'
n = gets.to_i
if n < 2
puts 'Liczba musi być > 1'
else
i = 2
while i <= n
puts i
i += 2
end
end
<file_sep>/zadania_rails/movies_catalog/db/migrate/20180102195630_remove_constrains_from_opinions.rb
class RemoveConstrainsFromOpinions < ActiveRecord::Migration[5.1]
def change
change_column_null(:opinions, :author, true )
end
end
<file_sep>/zadania_ruby/first_break/sneak/screen.rb
require 'curses'
class Screen
SCREEN_HIGHT = Curses.lines
SCREEN_WIDTH = Curses.cols
def initialize
Curses.init_screen
begin
Curses.crmode
Curses.noecho
Curses.stdscr.keypad(true)
Curses.nonl
header_window
action_window
ensure
Curses.close_screen
end
end
def header_window
header = Curses::Window.new(10, SCREEN_WIDTH, 0, 0)
header.box('#', '#')
header.refresh
end
def action_window
action = Curses::Window.new(30, SCREEN_WIDTH, 10, 0)
action.box('#', '#')
action.refresh
action.getch
end
end
<file_sep>/zadanie_bloki/zadanie17.rb
sum = 0
loop do
x = gets.to_i
sum += x
break if x == 0
end
puts sum
<file_sep>/zadania_rails/movies_catalog/app/models/user.rb
class User < ApplicationRecord
has_secure_password
validates :first_name, presence: true
validates :email, presence: true, email: true
validates :password, presence: true, confirmation: true, length: { minimum: 5 }
has_many :opinions
has_many :reviews
has_many :movies
def admin?
self.admin == true
end
def author?(review)
self.id == review.user_id
end
end
<file_sep>/zadania_ruby/first_break/leap_year.rb
def leap_year?(year)
if ((year % 4).zero? && year % 100 != 0) || (year % 400).zero?
true
else
false
end
end
puts leap_year?(2004).inspect
puts leap_year?(2000).inspect
puts leap_year?(2100).inspect
<file_sep>/zadanie_bloki/zadanie1.rb
a = gets.to_i
obwod = 4 * a
pole = a * a
puts "Obwód kwadratu wynosi: #{obwod}"
puts "Pole kwadratu wynosi: #{pole}"
<file_sep>/zadania_ruby/first_break/battleship_game/ship_type/twodecker.rb
require_relative './directions.rb'
require_relative './allcoordinates.rb'
require_relative '../board.rb'
class TwoDecker
include AllCoordinates
attr_reader :coordinates, :neighbours
def initialize(board)
@coordinates = []
@neighbours = []
@board = board
generate_coordinates
end
def generate_coordinates
all_coordinates
find_neighbours(@coordinates)
end
def all_coordinates
first_coord = @board.sample_coordinate
@coordinates << first_coord
first_row, first_column = find_coordinate_index(first_coord)
directions = Directions.new(first_coord)
x_direction = directions.x.sample
y_direction = directions.y.sample if x_direction.zero?
if x_direction.zero?
next_row = @board.rows[first_row + y_direction]
next_coordinate = @board.columns[first_column] + next_row.to_s
@coordinates << next_coordinate
else
next_column = @board.columns[first_column + x_direction]
next_coordinate = next_column + @board.rows[first_row].to_s
@coordinates << next_coordinate
end
return @coordinates
end
end
<file_sep>/zadania_ruby/introduction/algorytmeuklidesa.rb
puts "Pierwsza liczba"
x = gets.to_i
puts "Druga liczba"
y = gets.to_i
while x != y
if x > y
x -= y
else
y -= x
end
end
puts "Najwyższy wspólny dzielnik to: #{x}"
<file_sep>/zadanie_bloki/zadanie10.rb
puts 'Podaj trzy liczby:'
a = gets.to_i
b = gets.to_i
c = gets.to_i
if a < b && b < c
puts 'Ciąg jest rosnący'
else
puts 'Ciąg nie jest rosnący'
end
<file_sep>/zadania_rails/movies_catalog/app/validators/range_validator.rb
class RangeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, "must be in range 1 - 10" unless
(1..10).include?(value)
end
end
<file_sep>/zadania_ruby/first_break/leap_years.rb
def leap_year?(year)
if ((year % 4).zero? && year % 100 != 0) || (year % 400).zero?
true
else
false
end
end
def leap_years(years)
result = []
years.each do |year|
if leap_year?(year)
result << year
end
end
result
end
puts leap_years([2011, 2012, 2015, 2016, 2018])
puts leap_years((2000..2100).to_a)
<file_sep>/zadanie_bloki/zadanie16a.rb
puts 'Podaj liczbę:'
n = gets.to_i
puts "\n"
if n < 1
puts 'Liczba musi być > 0'
else
i = 0
while i < n
j = -n + i
i += 1
puts i
puts j
end
end
<file_sep>/zadania_ruby/first_break/multiples.rb
def multiples(n)
numbers = (0..n).to_a
index = 0
sum = 0
while index < numbers.size
if (numbers[index] % 3).zero? || (numbers[index] % 5).zero?
sum += numbers[index]
end
index += 1
end
sum
end
puts multiples(10)
puts multiples(20)
<file_sep>/zadania_ruby/oop/bubble_sort.rb
class BubbleSort
def initialize(user_input)
@numbers = user_input
end
def sort
iteration = 1
while iteration < @numbers.size
index = 0
while index < @numbers.size - 1
if @numbers[index].to_i > @numbers[index + 1].to_i
@numbers[index], @numbers[index + 1] = @numbers[index + 1], @numbers[index]
end
index += 1
end
iteration += 1
end
@numbers.join(" ")
end
end
numbers = BubbleSort.new(ARGV)
print numbers.sort
<file_sep>/zadanie_bloki/zadanie12.rb
puts 'Podaj liczbę:'
x = gets.to_i
if x % 2 == 0
puts 'Liczba jest parzysta'
else
puts 'Liczba jest nieparzysta'
end
<file_sep>/eksperymenty/argv.rb
require "pry"
binding.pry
user_input = ARGV
puts user_input
<file_sep>/zadania_rails/movies_catalog/app/models/movie.rb
class Movie < ApplicationRecord
validates :title, presence: true
validates :release_date, presence: true
validates :length, presence: true
validates :description, presence: true, length: { in: 2..500 }
validates :director, presence: true
validates :writer, presence: true
validates :country, presence: true
mount_uploader :image, ImageUploader
belongs_to :user
has_many :opinions, dependent: :destroy
has_many :reviews, dependent: :destroy
has_and_belongs_to_many :genres
def youtube_url=(new_url)
self.youtube_id = YoutubeID.from(new_url)
end
def youtube_url
if youtube_id
"https://www.youtube.com/watch?v=#{youtube_id}"
end
end
end
<file_sep>/zadania_ruby/first_break/rps.rb
ROCK = 'rock'
PAPER = 'paper'
SCISSORS = 'scissors'
def rps(gamer1_choice, gamer2_choice)
if gamer1_choice == gamer2_choice
puts 'Remis'
elsif gamer1_choice == ROCK && gamer2_choice == PAPER
puts 'Gracz 2 wygywa'
elsif gamer1_choice == ROCK && gamer2_choice == SCISSORS
puts 'Gracz 1 wygrywa'
elsif gamer1_choice == PAPER && gamer2_choice == ROCK
puts 'Gracz 1 wygrywa'
elsif gamer1_choice == PAPER && gamer2_choice == SCISSORS
puts 'Gracz 2 wygrywa'
elsif gamer1_choice == SCISSORS && gamer2_choice == ROCK
puts 'Gracz 2 wygrywa'
elsif gamer1_choice == SCISSORS && gamer2_choice == PAPER
puts 'Gracz 1 wygrywa'
end
end
rps('rock', 'scissors')
rps('paper', 'rock')
<file_sep>/zadania_ruby/first_break/pangram.rb
POLISH_ALPHABET = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "w", "y", "z", "ó", "ą", "ć", "ę", "ł", "ń", "ś", "ź", "ż"]
PUNCTUACTION_MARKS = ['.', ',', ':', ';', ' ', '!', '?']
def pangram?(sentence)
sentence_array = []
sentence.downcase!.each_char do |chr|
sentence_array << chr unless sentence_array.include?(chr)
end
sentence_array.reject! { |elem| PUNCTUACTION_MARKS.include?(elem)}
sorted = sentence_array.sort
if sorted == POLISH_ALPHABET
'true'
else
'false'
end
end
puts pangram?('Dość błazeństw, żrą mój pęk luźnych fig')
puts pangram?('Losowy ciąg znaków')
puts pangram?('Pójdźże, kiń tę chmurność w głąb flaszy!')
<file_sep>/zadanie_bloki/zadanie22.rb
u = false #czy wystąpiła liczba ujemna
d = false #czy wystąpiła liczba dodatnia
loop do
x = gets.to_i
if x < 0
u = true
elsif x > 0
d = true
end
break if x == 0
end
if u == true
puts 'Wystąpiła liczba ujemna'
end
if d == true
puts 'Wystąpiła liczba dodatnia'
end
<file_sep>/zadania_ruby/first_break/complementary_DNA.rb
BASES = {
"A" => "G",
"G" => "A",
"C" => "T",
"T" => "C"
}
def complementary_base(base)
BASES[base] || '?'
end
def complementary_dna(dna)
dna.chars.map { |base| complementary_base(base) }.join
end
puts complementary_dna('ATTA')
puts complementary_dna('GCCTTAAATAGC')
puts complementary_dna('ssssssssss')
<file_sep>/zadanie_bloki/zadanie8.rb
puts 'Podaj trzy liczby:'
a = gets.to_i
b = gets.to_i
c = gets.to_i
max = a
if max < b
max = b
end
if max < c
max = c
end
puts ' '
puts max
<file_sep>/zadania_ruby/introduction/foldr.rb
def foldr(start_accumulator, array)
index = 0
array = array.reverse
accumulator = start_accumulator
while index < array.size
element = array[index]
accumulator = yield(accumulator, element)
index += 1
end
puts accumulator
end
foldr(0, [3, 4, 65, 9]) { |accumulator, element| element - accumulator }
<file_sep>/postgresql/create_database.sql
CREATE DATABASE computer_store;
CREATE TABLE manufacturers (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL ,
price REAL NOT NULL ,
manufacturer_id INTEGER NOT NULL,
FOREIGN KEY (manufacturer_id) REFERENCES manufacturers(id)
);
INSERT INTO manufacturers (name) VALUES ('Sony');
INSERT INTO manufacturers (name) VALUES ('Creative Labs');
INSERT INTO manufacturers (name) VALUES ('Hewlett-Packard');
INSERT INTO manufacturers (name) VALUES ('Iomega');
INSERT INTO manufacturers (name) VALUES ('Fujitsu');
INSERT INTO manufacturers (name) VALUES ('Winchester');
INSERT INTO manufacturers (name) VALUES ('Apple');
INSERT INTO products (name, price, manufacturer_id) VALUES ('Hard drive', 240, 5);
INSERT INTO products (name, price, manufacturer_id) VALUES ('Memory', 120, 6);
INSERT INTO products (name, price, manufacturer_id) VALUES ('ZIP drive', 150, 4);
INSERT INTO products (name, price, manufacturer_id) VALUES ('Floppy disk', 5, 6);
INSERT INTO products (name, price, manufacturer_id) VALUES ('Monitor', 240, 1);
INSERT INTO products (name, price, manufacturer_id) VALUES ('DVD drive', 180, 2);
INSERT INTO products (name, price, manufacturer_id) VALUES ('CD drive', 90, 2);
INSERT INTO products (name, price, manufacturer_id) VALUES ('Printer', 270, 3);
INSERT INTO products (name, price, manufacturer_id) VALUES ('Toner cartridge', 66, 3);
INSERT INTO products (name, price, manufacturer_id) VALUES ('DVD burner', 180, 2);
<file_sep>/eksperymenty/lib/reader.rb
require_relative "./book.rb"
require_relative "./library.rb"
class Reader
attr_accessor :card_number, :rented
def initialize(name, surname)
@name = name
@surname = surname
@history = []
self.rented = []
self.card_number = nil
end
def rent_book(library, title_or_author, date)
book_to_rent = library.all_books_in_library.find do |book|
(book.title.downcase || book.author.downcase) == title_or_author.downcase
end
if book_to_rent.avaliable?
book_to_rent.mark_as_rented
book_to_rent.book_rental_date(date)
rented << book_to_rent
else
throw 'Książka jest już wypożyczona'
end
end
def return_book(title_or_author, date)
book_to_return = rented.find do |book|
(book.title.downcase || book.author.downcase) == title_or_author.downcase
end
if book_to_return
to_history(book_to_return, date)
book_to_return.mark_as_avaliable
rented.reject! { |rented_book| rented_book == book_to_return }
else
throw 'Nie masz wypożyczonej takiej książki'
end
end
def list_of_rented_books
rented.each do |book|
print book.author + "\t" + book.title + "\t" + 'wypożyczona od: ' + book.date.to_s + "\n"
end
end
def to_history(book, date)
book = rented.find { |elem| elem == book }
time = (Date.parse(date) - book.date).to_i
book_to_history = {
title: book.title,
author: book.author,
how_long_rented: time
}
@history << book_to_history
end
def show_history
@history.each do |book|
print book[:author] + "\t" + book[:title] + "\t" + 'wypożyczona przez: ' + book[:how_long_rented].to_s + "dni\n"
end
end
end
<file_sep>/powtorka_zjazdu1/schematblokowy.rb
a = gets.to_i
b = gets.to_i
counter = 0
result = 1
while counter < b
counter += 1
result *= a
end
puts result
<file_sep>/zadania_rails/movies_catalog/app/helpers/sessions_helper.rb
module SessionsHelper
def user_guest?
current_user.nil?
end
def user_logged_in?
current_user
end
def user_admin?
user_logged_in? && current_user.admin?
end
def user_author?(review)
user_logged_in? && current_user.author?(review)
end
end
<file_sep>/zadanie_bloki/zadanie23.rb
sum_d = 0 #suma liczb dodatnich
sum_u = 0 #suma liczb ujemnych
loop do
x = gets.to_i
if x < 0
sum_u += x
elsif x > 0
sum_d += x
end
break if x == 0
end
puts "Suma liczb dodatnich wynosi: #{sum_d}"
puts "Suma liczb ujemnych wynosi: #{sum_u}"
<file_sep>/eksperymenty/znajdz_index3.rb
def find_index(array, value)
array.each_with_index do |elem, index|
if elem == value
return index
end
end
return 'not found'
end
puts find_index([1, 2, 3, 4, 5], 3)
puts find_index([5, 8, 6, 2, 2, 10], 2)
puts find_index([10, 20, 30], 100)
puts find_index([], 0)
<file_sep>/zadania_rails/movies_catalog/app/helpers/opinions_helper.rb
module OpinionsHelper
def opinion_author(opinion)
if opinion.user
opinion.user.email
else
opinion.author
end
end
end
<file_sep>/zadania_rails/movies_catalog/db/migrate/20180108203013_create_genre_movies_join_table.rb
class CreateGenreMoviesJoinTable < ActiveRecord::Migration[5.1]
def change
create_join_table :genres, :movies
end
end
<file_sep>/zadania_ruby/first_break/battleship_game/ship_type/allcoordinates.rb
module AllCoordinates
def find_coordinate_index(coordinate) # coordinate jest to "A1"
column_index = @board.columns.find_index(coordinate[0])
if coordinate.length == 2
positions = 1
else
positions = 1..2
end
row_index = @board.rows.find_index(coordinate[positions].to_i)
[row_index, column_index]
end
def find_neighbours(coordinates)
coordinates.each do |coord|
neighbours_for_one_coord(coord)
end
@neighbours = neighbours.uniq!.reject { |elem| @coordinates.include?(elem) }
end
def neighbours_for_one_coord(coord)
row_index, column_index = find_coordinate_index(coord)
i = -1
while i <= 1
index1 = row_index - 1
index2 = column_index + i
if in_bounds(index1, index2)
coord = @board.columns[index2] + @board.rows[index1].to_s
neighbours << coord
end
index1 = row_index
index2 = column_index + i
if in_bounds(index1, index2)
coord = @board.columns[index2] + @board.rows[index1].to_s
neighbours << coord
end
index1 = row_index + 1
index2 = column_index + i
if in_bounds(index1, index2)
coord = @board.columns[index2] + @board.rows[index1].to_s
neighbours << coord
end
i += 1
end
end
def in_bounds(index1, index2)
if (index1 >= 0 && index1 <= 9) && (index2 >= 0 && index2 <= 9)
true
end
end
end
| 9688f86d6c7de1f9875dc9da7e5f2e25c2dd9ad3 | [
"SQL",
"Ruby"
] | 120 | Ruby | olxia172/learning | b6569c0790c2384c910e7a0ee0f2f79d065f82e0 | 7c6a8925dbf8b3534d6a887d605111cbfc60d3ed |
refs/heads/master | <file_sep>// This is the main.js file. Import global CSS and scripts here.
// The Client API can be used here. Learn more: gridsome.org/docs/client-api
import "element-ui/lib/theme-chalk/index.css"
import util from "./utils/util"
import Vue from "vue"
import ElementUI from "element-ui"
import App from "./App.vue"
Vue.use(ElementUI)
Vue.prototype.$util = util
export default function(Vue, { router, head, isClient }) {
Vue.component("App", App)
}
| 1e3dd7d5d9dc30df5ebf2d03efa8cbfdd156120e | [
"JavaScript"
] | 1 | JavaScript | lichtcui/gridsome-blog | 8d3b5c85e86f285d6f39db2f98785ed2fc06e9a2 | 3cf03d162acec2bca5a026a0f3cd973bda4c7da7 |
refs/heads/master | <repo_name>cindyward1/cindys_airbnb<file_sep>/spec/models/rental_spec.rb
require "spec_helper"
describe Rental do
it { should belong_to :landlord }
it { should have_many :reservations }
it { should have_many :renters }
it { should have_many :comments }
it { should validate_presence_of :city }
it { should validate_presence_of :state }
it { should validate_presence_of :base_rate }
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
concern :opinions_about do
resources :comments
end
resources :rentals, concerns: :opinions_about
resources :reservations
devise_for :users
devise_scope :user do
root to: "devise/sessions#new"
end
devise_scope :landlord do
get '/landlord', to: 'rentals#new', as: 'landlord_root'
end
devise_scope :renter do
get '/renter', to: 'reservations#new', as: 'renter_root'
end
resources :users, only: [], concerns: :opinions_about
end
<file_sep>/db/migrate/20140929183854_add_has_photo_to_rentals.rb
class AddHasPhotoToRentals < ActiveRecord::Migration
def change
add_column :rentals, :has_photo, :boolean, default: false
end
end
<file_sep>/app/models/reservation.rb
class Reservation < ActiveRecord::Base
belongs_to :renter, foreign_key: :user_id
belongs_to :rental
validates :start_date, presence: true
validates :end_date, presence: true
end
<file_sep>/db/migrate/20140925172754_create_rentals.rb
class CreateRentals < ActiveRecord::Migration
def change
create_table :rentals do |t|
t.integer :user_id
t.string :rental_type
t.string :city
t.string :state
t.integer :number_bedrooms
t.integer :number_beds
t.integer :number_bathrooms
t.integer :max_number_guests
t.float :base_rate
t.float :extra_guest_rate
t.integer :minimum_days_stay
t.float :rating
t.integer :number_ratings
t.string :cancellation_policy
t.string :description
t.string :amenities_list
t.string :the_photo_file_name
t.string :the_photo_content_type
t.integer :the_photo_file_size
t.datetime :the_photo_updated_at
t.timestamps
end
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments, as: :opinions_about
validates :username, presence: true, uniqueness: true, case_sensitive: false,
length: { minimum: 8, maximum: 32 }
validates :email, presence: true, length: { minimum: 5, maximum: 50 }
validates_format_of :email, with: /^.+@.+\..+$/, on: :create, :multiline => true
validates :date_joined, presence: true
scope :landlords, -> { where(type: 'Landlord') }
scope :renters, -> { where(type: 'Renter') }
def landlord?
self.type == "Landlord"
end
def renter?
self.type == "Renter"
end
end
<file_sep>/spec/models/comment_spec.rb
require "spec_helper"
describe Comment do
it { should belong_to :opinions_about }
it { should validate_presence_of :comment_text}
end
<file_sep>/db/migrate/20140926232559_remove_fields_from_rentals.rb
class RemoveFieldsFromRentals < ActiveRecord::Migration
def change
remove_column :rentals, :cancellation_policy
remove_column :rentals, :amenities_list
end
end
<file_sep>/config/initializers/haml.rb
Haml::Template.options[:escape_html] = true
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'rails'
gem 'pg'
gem 'bootstrap-sass'
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
gem 'jquery-rails'
gem 'turbolinks'
gem 'autoprefixer-rails'
gem 'devise'
gem 'paperclip'
gem 'kaminari'
gem 'aws-sdk'
gem 'haml'
group :development do
gem 'better_errors'
gem 'binding_of_caller'
gem 'quiet_assets'
gem 'letter_opener'
gem 'pry'
end
group :test, :development do
gem 'rspec-rails'
gem 'launchy'
end
group :test do
gem 'shoulda-matchers'
gem 'capybara'
gem 'factory_girl'
gem 'database_cleaner'
gem 'poltergeist'
end
group :production do
gem 'rails_12factor'
gem 'rest-client'
end
<file_sep>/README.md
cindys_airbnb
====================
# README for the Airbnb Clone application written in Rails with AJAX
* Author: <NAME> <<EMAIL>>
* Date created: September 23, 2014
* Last modification date: September 28, 2014
* Created for: Epicodus, Summer 2014 session
## Included; written by author:
* ./README.md (this file)
* ./Gemfile (list of gems to be installed by bundler; please see below for more information)
* ./Gemfile.lock (list of gems and versions actually installed by bundler; please see below for more information)
* ./LICENSE.md (using the "Unlicense" template)
* ./Rakefile (configuration information used by 'rake' utility)
* ./app/assets/images/logo.png (downloaded from Web then customized)
* ./app/assets/stylesheets/application.css.scss (modified by author)
* ./app/controllers/application\_controller.rb (modified by author)
* ./app/controllers/users\_controller.rb
* ./app/models/landlord.rb (the Ruby implementation of the Landlord model, child of User model)
* ./app/views/layouts/\_errors.html.erb (error partial form)
* ./app/views/layouts/application.html.erb (modified by author)
* ./app/views/recipe\_users/\_form1.html.erb (shared partial form)
* ./config/routes.rb (the Rails routes for user action requests)
* ./db/config.yml (database configuration file showing the names of the development and test databases)
* ./db/schema.rb (database schema)
* ./db/migrate/*.rb (database migrations, which show the development of the database step-by-step. These are stored in the database as an additional table. The names are preceded by time stamps so they vary)
* ./spec/features/landlord\_spec.rb (the test spec for the Landlord class)
* ./spec/models/landlord\_spec.rb (the test spec for the Landlord portion of the application)
## Requirements for execution:
* This application can be run in production mode over the World Wide Web from [Heroku](https://www.heroku.com/) at http://cindys-airbnb.herokuapp.com . It uses a Mailgun sandbox server to send emails confirming registration and reservation to users.
* If you wish to run the application on your local computer in development mode, it requires the following:
* [The Ruby language interpreter](https://www.ruby-lang.org/en/downloads/) must be installed. Please use version 2.1.2
* [git](http://github.com/) must be installed. You will need to enter the following at a terminal application prompt **$: git clone http://github.com/cindyward1/cindys\_airbnb , which will create a cindys\_airbnb directory with app, bin, config, db, lib, log, public, spec, tmp, and vendor directories
* [Homebrew](http://brew.sh/) is a package installer for Apple computers. To install homebrew, enter the following at a terminal application prompt **$: ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"**
* [PostgreSQL](http://http://www.postgresql.org/) is a SQL database package. To install PostgreSQL on an Apple computer, enter the following at a terminal application prompt **$: brew install postgres** . To configure PostgreSQL, enter the following commands at a terminal application prompt $:
* **$: echo "export PGDATA=/usr/local/var/postgres" >> ~/.bash\_profile**
* **$: echo "export PGHOST=/tmp" >> ~/.bash\_profile**
* **$: source ~/.bash\_profile**
* To start the PostgreSQL server, enter the following at a terminal application prompt **$: postgres** . It is necessary to leave the window open for the server to continue to run. To create a database with the user's login name, enter the following at a teriminal application prompt **$: createdb $USER**
* [Bundler](http://bundler.io) tracks and installs the exact gems and versions that are needed. To install Bundler, enter the following at a terminal application prompt **$: gem install bundler**
* [PhantomJS](http://phantomjs.org/) is a headless WebKit scriptable with a JavaScript API. This is used for testing but is not available as a Ruby gem. To install it, enter the following at a terminal application prompt **$: brew install phantomjs**
* The following gems from http://rubygems.org will be automatically installed by entering the following at a terminal application prompt **$: bundle install**
* [rails](https://rubygems.org/gems/rails) is a full-stack web framework. Please use Rails 4.1.5
* [pg](https://rubygems.org/gems/pg) implements the Ruby interface to the PostgreSQL database
* [bootstrap-sass](https://rubygems.org/gems/bootstrap-sass) implements the Ruby interface to Bootstrap (a popular HTML, CSS, and JS framework)
* [sass-rails](https://rubygems.org/gems/sass-rails) is the SASS adapter for the Rails asset pipeline
* [uglifier](https://rubygems.org/gems/uglifier) wraps UglifyJS (a JavaScript parser, mangler/compressor and beautifier toolkit) so it is accessible in Ruby
* [coffee-rails](https://rubygems.org/gems/coffee-rails) is the CoffeeScript adapter for the Rails asset pipeline
* [jquery-rails](https://rubygems.org/gems/jquery-rails) provides jQuery and the jQuery-ujs driver for Rails
* [turbolinks](https://rubygems.org/gems/turbolinks) makes following links in a Web application faster
* [autoprefixer-rails](https://rubygems.org/gems/autoprefixer-rails) parses CSS and adds vendor prefixes to CSS rules using values from the 'Can I Use' Web site
* [devise](https://rubygems.org/gems/devise) provides a flexible authentication solution for Rails with Warden (middleware that provides authentication for applications using Rack. (Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby.)
* [paperclip](https://rubygems.org/gems/paperclip) provides easy upload management for ActiveRecord
* [kaminari](https://rubygems.org/gems/kaminari) is a "Scope & Engine" based, clean, powerful, agnostic, customizable and sophisticated paginator for Rails
* (development configuration only) [better\_errors](https://rubygems.org/gems/better\_errors) provides a better error page for Rails and other Rack apps. Includes source code inspection, a live REPL and local/instance variable inspection for all stack frames
* (development configuration only) [binding\_of\_caller](https://rubygems.org/gems/binding\_of\_caller) retrieve the binding of a method's caller; can also retrieve bindings even further up the stack
* (development configuration only) [quiet\_assets](https://rubygems.org/gems/quiet\_assets) turns off Rails asset pipeline log
* (development configuration only) [letter\_opener](https://rubygems.org/gems/letter_opener) opens a preview of a "sent" email in the browser instead of actually sending it
* (development and test configurations only) [rspec-rails](https://rubygems.org/gems/rspec-rails) implements RSpec for Rails
* (test configuration only) [shoulda-matchers](http://robots.thoughtbot.com/shoulda-matchers-2-6-0) "makes tests easy on the fingers and eyes" by simplifying the expression of rspec test conditions to be met
* (test configuration only) [capybara](https://rubygems.org/gems/capybara) is an integration testing tool for rack based web applications. It simulates how a user would interact with a website
* (test configuration only) [launchy](https://rubygems.org/gems/launchy) is a helper class for launching cross-platform applications in a "fire and forget" manner
* (test configuation only) [factory_girl](https://rubygems.org/gems/factory_girl) provides a framework and DSL for defining and using factories, which allows more flexible, less error-prone testing
* (test configuation only) [database_cleaner](https://rubygems.org/gems/database_cleaner) provides strategies for cleaning databases and is used to ensure a clean state for testing
* (test configuation only) [poltergeist](https://rubygems.org/gems/poltergeist) is a driver for Capybara that allows running tests on the headless WebKit browser provided by PhantomJS
* (production configuration only) [rails\_12factor](https://rubygems.org/gems/rails\_12factor) runs Rails the 12factor way (allowing the application to be run at the same time by multiple Web users)
* (production configuration only) [rest-client](https://rubygems.org/gems/rest-client) is a simple HTTP and REST client for Ruby
* To create the database, cd to (clone location)/cindys\_airbnb and enter the following at a terminal application prompt **$: rake db:create** followed by **$: rake db:schema:load**
* To run the application takes several steps:
* You must start the Rails server for the application to function at all. cd to (clone location)/cindys\_airbnb and enter the following at a terminal application prompt **$: rails server . This window must stay open the entire time the application is running; it can be minimized.
* After the Rails server is running, run the Chrome Web browser and enter **localhost:3000** in the Web address field. This should bring up the login screen. To create a new user, follow the "Register with Cindy's Airbnb" link near the bottom of the Web page.
* You can also test a non-interactive version of the methods against their test cases found in (clone location)/cindys\_airbnb/spec/\*.rb using rspec (see gem reference above). Please use version 3.1.1. If you wish to do this, you must first cd to (clone location)/cindys\_airbnb and enter the following at a terminal application **$: rake db:test:prepare** . This will prepare the test version of the database for use. Then to run rspec, cd to (clone location)/cindys\_airbnb and enter the following string at a terminal application **$: rspec** (This command will automatically execute any .rb file it finds in ./spec/.)
* Please note that this repository has only been tested with [Google Chrome browser](http://www.google.com/intl/en/chrome/browser) version 36.0.1985.125 on an iMac running [Apple](http://www.apple.com) OS X version 10.9.4 (Mavericks). Execution on any other computing platform, browser or operating system is at the user's risk.
## Description:
This Ruby application implements a graphical user interface to a rental management application. The user interface is divided into two parts depending on the user type: the actions a landlord performs to list and maintain the listings of rental properties, and the actions a renter performs to select and reserve rental properties.
### User stories for the landlord:
* As a landlord, I want to be able to create a uniquely named, secure landlord account and have my registration confirmed via email.
* As a landlord, I want to list my rentals including rental description, address, rental rate, and miscellaneous amenities. I then want to be able to maintain or delete my listing.
* As a landlord, I want to optionally be able to upload a photo of each rental.
* As a landlord, I want to keep track of the YTD and future reservations for my rentals.
* As a landlord, I want to receive an email message when each rental is reserved by a renter.
* As a landlord, I want to be able to rate and make comments about renters.
* As a landlord, I want to be able to see the ratings and comments of others about renters who have or have had reservations for my rentals.
### User stories for the renter:
* As a renter, I want to be able to create a secure renter account and have my registration confirmed via email.
* As a renter, I want to see all rentals available in a city, including rates, addresses, and photos (if available). The display needs to have pagination so I can keep track of the rentals I've seen
* As a renter, I want to see all rentals available in a city for a given time period.
* As a renter, I want to see all rentals available in a city within a range of rental rates.
* As a renter, I want to be able to reserve a rental for a specific period of time and receive an email confirmation of the reservation. I also want to be able to cancel any reservation and receive an email confirmation of the cancellation. If the reservation period has already begun, I want to be able to cancel the remainder of the reservation without having to pay.
* As a renter, I want to be able to rate and make comments about landlords and properties.
* As a renter, I want to be able to see the ratings and comments of others about all landlords and properties so I can make better decisions about the rentals I reserve.
### Constraints and conditions:
* If a user wishes to be both a landlord and a renter, they must have 2 different user names (user names are unique for all users, whether landlords or renters). This is a constraint because I used single-table inheritance rather than a more flexible mechanism to distinguish between the two types of users.
* There is no direct way to adjust the rate by season; the landlord would have to manually adjust the rate.
##Thanks:
* To the staff at Epicodus for providing such a wonderful boot camp class with a tremendous internship opportunity at the end! It's been a lot of hard work but totally worth it :)
<file_sep>/app/controllers/rentals_controller.rb
class RentalsController < ApplicationController
def new
@rental = Rental.new
end
def create
@rental = Rental.new(params[:rental_params])
@rental.city = params[:rental][:city]
@rental.state = params[:rental][:state]
@rental.base_rate = params[:rental][:base_rate]
@rental.user_id = current_user.id
if params[:rental][:has_photo]
@rental.has_photo = true
@rental.the_photo = params[:rental][:the_photo]
end
@rental.set_default_fields(params[:rental])
if @rental.save
flash[:notice] = "The rental has been saved"
redirect_to rental_path(@rental.id )
else
render "new"
end
end
def show
@rental = Rental.find(params[:id])
end
def index
if current_user.landlord?
@rentals = Rental.where(:user_id => current_user.id).order(state: :asc, city: :asc)
else
@rentals = Rentals.all.order(state: :asc, city: :asc)
end
end
def edit
@rental = Rental.find(params[:id])
if current_user.id != @rental.user_id
redirect_to rental_path(@rental)
end
end
def update
@rental = Rental.find(params[:id])
if current_user.id != @rental.user_id
flash[:alert] = "You may only edit your own rentals"
redirect_to rental_path(@rental)
elsif !params[:rental].nil?
if @rental.update(:rental_params)
flash[:notice] = "The rental has been updated"
redirect_to landlord_return_to_path
else
render 'edit'
end
else
flash[:notice] = "Nothing was updated"
redirect_to landlord_return_to_path
end
end
def destroy
@rental = Rental.find(params[:id])
if current_user.id != @rental.user_id
flash[:alert] = "You may only delete your own rentals"
redirect_to rental_path(@rental)
else
@rental.destroy
flash[:notice] = "The rental was deleted"
redirect_to landlord_return_to_path
end
end
end
<file_sep>/spec/models/reservation_spec.rb
require "spec_helper"
describe Reservation do
it { should belong_to :renter }
it { should belong_to :rental }
it { should validate_presence_of :start_date }
it { should validate_presence_of :end_date }
end
<file_sep>/app/models/rental.rb
class Rental < ActiveRecord::Base
belongs_to :landlord, foreign_key: :user_id
has_many :reservations
has_many :renters, through: :reservations
has_many :comments, as: :opinions_about
validates :city, presence: true
validates :state, presence: true
validates :base_rate, presence: true
has_attached_file :the_photo, :styles => { :small => "100x100>", :original => "400x400>>" }
validates_attachment :the_photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
def set_default_fields(rental_hash)
if rental_hash[:rental_type].nil?
self.rental_type = "shared"
else
self.rental_type = rental_hash[:rental_type]
end
if rental_hash[:number_bedrooms].nil?
self.number_bedrooms = 1
else
self.number_bedrooms = rental_hash[:number_bedrooms]
end
if rental_hash[:number_beds].nil?
self.number_beds = 1
else
self.number_beds = rental_hash[:number_beds]
end
if rental_hash[:number_bathrooms].nil?
self.number_bathrooms = 0
else
self.number_bathrooms = rental_hash[:number_bathrooms]
end
if rental_hash[:max_number_guests].nil?
self.max_number_guests = 1
else
self.max_number_guests = rental_hash[:max_number_guests]
end
if rental_hash[:extra_guest_rate].nil?
self.extra_guest_rate = 0
else
self.extra_guest_rate = rental_hash[:extra_guest_rate]
end
if rental_hash[:minimum_days_stay].nil?
self.minimum_days_stay = 1
else
self.minimum_days_stay = rental_hash[:minimum_days_stay]
end
if rental_hash[:description].nil?
self.description = ""
else
self.description = rental_hash[:description]
end
self
end
private
def rental_params
params.require(:rental).permit(:rental_type, :city, :state, :number_bedrooms, :number_beds,
:number_bathrooms, :max_number_guests, :base_rate,
:extra_guest_rate, :minimum_days_stay, :description,
:has_photo, :the_photo)
end
end
<file_sep>/spec/models/renter_spec.rb
require "spec_helper"
describe Renter do
it { should have_many :reservations }
it { should have_many :rentals }
end
<file_sep>/app/models/renter.rb
class Renter < User
has_many :reservations, foreign_key: :user_id
has_many :rentals, through: :reservations
end
<file_sep>/app/models/landlord.rb
class Landlord < User
has_many :rentals, foreign_key: :user_id
has_many :reservations, through: :rentals
end
<file_sep>/spec/models/landlord_spec.rb
require "spec_helper"
describe Landlord do
it { should have_many :rentals }
it { should have_many :reservations }
end
<file_sep>/db/migrate/20140925165132_add_rating_to_users.rb
class AddRatingToUsers < ActiveRecord::Migration
def change
add_column :users, :rating, :float
add_column :users, :number_ratings, :integer
end
end
<file_sep>/spec/models/user_spec.rb
require "spec_helper"
describe User do
it { should have_many :comments }
it { should validate_presence_of :username}
it { should validate_uniqueness_of :username }
it { should ensure_length_of(:username).is_at_least(8) }
it { should ensure_length_of(:username).is_at_most(32) }
it { should validate_presence_of :email }
it { should allow_value("<EMAIL>").for(:email) }
it { should_not allow_value("foo").for(:email) }
it { should ensure_length_of(:email).is_at_least(5) }
it { should ensure_length_of(:email).is_at_most(50) }
it { should validate_presence_of :date_joined }
end
<file_sep>/app/assets/javascripts/rentals.js
$(function () {
$('#upload').hide();
$('#has-photo input[type=checkbox]').click(function () {
if ($(this).prop("checked") == true) {
$('#upload').show();
} else {
$('#upload').hide();
};
});
});
| d32326cdc219dbb14f33cdedd4bdec0fd54382a4 | [
"Markdown",
"JavaScript",
"Ruby"
] | 21 | Ruby | cindyward1/cindys_airbnb | 95515e784f53ce473174f196d11f904cae58aad3 | d44e8fb6d8d42884bde1cf3fda982cd6a0164e7d |
refs/heads/master | <file_sep>import logging
from django.db.models import CASCADE, PROTECT, SET_NULL
from mptt.fields import TreeOneToOneField
from river.models import TransitionApprovalMeta, Workflow
from river.models.transition import Transition
try:
from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError:
from django.contrib.contenttypes.generic import GenericForeignKey
from django.db import models
from django.utils.translation import ugettext_lazy as _
from river.models.base_model import BaseModel
from river.models.managers.transitionapproval import TransitionApprovalManager
from river.config import app_config
PENDING = "pending"
APPROVED = "approved"
JUMPED = "jumped"
CANCELLED = "cancelled"
STATUSES = [
(PENDING, _('Pending')),
(APPROVED, _('Approved')),
(CANCELLED, _('Cancelled')),
(JUMPED, _('Jumped')),
]
LOGGER = logging.getLogger(__name__)
class TransitionApproval(BaseModel):
class Meta:
app_label = 'river'
verbose_name = _("Transition Approval")
verbose_name_plural = _("Transition Approvals")
objects = TransitionApprovalManager()
content_type = models.ForeignKey(app_config.CONTENT_TYPE_CLASS, verbose_name=_('Content Type'), on_delete=CASCADE)
object_id = models.CharField(max_length=50, verbose_name=_('Related Object'))
workflow_object = GenericForeignKey('content_type', 'object_id')
meta = models.ForeignKey(TransitionApprovalMeta, verbose_name=_('Meta'), related_name="transition_approvals", null=True, blank=True, on_delete=SET_NULL)
workflow = models.ForeignKey(Workflow, verbose_name=_("Workflow"), related_name='transition_approvals', on_delete=PROTECT)
transition = models.ForeignKey(Transition, verbose_name=_("Transition"), related_name='transition_approvals', on_delete=PROTECT)
transactioner = models.ForeignKey(app_config.USER_CLASS, verbose_name=_('Transactioner'), null=True, blank=True, on_delete=SET_NULL)
transaction_date = models.DateTimeField(null=True, blank=True)
status = models.CharField(_('Status'), choices=STATUSES, max_length=100, default=PENDING)
permissions = models.ManyToManyField(app_config.PERMISSION_CLASS, verbose_name=_('Permissions'))
groups = models.ManyToManyField(app_config.GROUP_CLASS, verbose_name=_('Groups'))
priority = models.IntegerField(default=0, verbose_name=_('Priority'))
previous = TreeOneToOneField("self", verbose_name=_('Previous Transition'), related_name="next_transition", null=True, blank=True, on_delete=CASCADE)
@property
def peers(self):
return TransitionApproval.objects.filter(
workflow_object=self.workflow_object,
workflow=self.workflow,
transition=self.transition,
).exclude(pk=self.pk)
<file_sep>from datetime import datetime
from behave import given, when, then
from hamcrest import assert_that, has_length, is_
@given('a permission with name {name:w}')
def permission(context, name):
from river.models.factories import PermissionObjectFactory
PermissionObjectFactory(name=name)
@given('a group with name "{name:ws}"')
def group(context, name):
from river.models.factories import GroupObjectFactory
GroupObjectFactory(name=name)
@given('a user with name {name:w} with permission "{permission_name:ws}"')
def user_with_permission(context, name, permission_name):
from django.contrib.auth.models import Permission
from river.models.factories import UserObjectFactory
permission = Permission.objects.get(name=permission_name)
UserObjectFactory(username=name, user_permissions=[permission])
@given('a user with name {name:w} with group "{group_name:ws}"')
def user_with_group(context, name, group_name):
from django.contrib.auth.models import Group
from river.models.factories import UserObjectFactory
group = Group.objects.get(name=group_name)
UserObjectFactory(username=name, groups=[group])
@given('a state with label "{state_label:ws}"')
def state_with_label(context, state_label):
from river.models.factories import StateObjectFactory
StateObjectFactory(label=state_label)
@given('a workflow with an identifier "{identifier:ws}" and initial state "{initial_state_label:ws}"')
def workflow(context, identifier, initial_state_label):
from django.contrib.contenttypes.models import ContentType
from river.tests.models import BasicTestModel
from river.models import State
from river.models.factories import WorkflowFactory
content_type = ContentType.objects.get_for_model(BasicTestModel)
initial_state = State.objects.get(label=initial_state_label)
workflow = WorkflowFactory(initial_state=initial_state, content_type=content_type, field_name="my_field")
workflows = getattr(context, "workflows", {})
workflows[identifier] = workflow
context.workflows = workflows
@given('a transition "{source_state_label:ws}" -> "{destination_state_label:ws}" in "{workflow_identifier:ws}"')
def transition(context, source_state_label, destination_state_label, workflow_identifier):
from river.models import State
from river.models.factories import TransitionMetaFactory
workflow = getattr(context, "workflows", {})[workflow_identifier]
source_state = State.objects.get(label=source_state_label)
destination_state = State.objects.get(label=destination_state_label)
transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=source_state,
destination_state=destination_state,
)
identifier = source_state_label + destination_state_label
transitions = getattr(context, "transitions", {})
transitions[identifier] = transition
context.transitions = transitions
@given('an authorization rule for the transition "{source_state_label:ws}" -> "{destination_state_label:ws}" with permission "{permission_name:ws}" and priority {priority:d}')
def authorization_rule_with_permission(context, source_state_label, destination_state_label, permission_name, priority):
from django.contrib.auth.models import Permission
from river.models.factories import TransitionApprovalMetaFactory
permission = Permission.objects.get(name=permission_name)
transition_identifier = source_state_label + destination_state_label
transition_meta = getattr(context, "transitions", {})[transition_identifier]
TransitionApprovalMetaFactory.create(
workflow=transition_meta.workflow,
transition_meta=transition_meta,
priority=priority,
permissions=[permission]
)
@given('an authorization rule for the transition "{source_state_label:ws}" -> "{destination_state_label:ws}" with group "{group_name:ws}" and priority {priority:d}')
def authorization_rule_with_group(context, source_state_label, destination_state_label, group_name, priority):
authorization_rule_with_groups(context, source_state_label, destination_state_label, [group_name], priority)
@given('an authorization rule for the transition "{source_state_label:ws}" -> "{destination_state_label:ws}" with groups "{group_names:list}" and priority {priority:d}')
def authorization_rule_with_groups(context, source_state_label, destination_state_label, group_names, priority):
from django.contrib.auth.models import Group
from river.models.factories import TransitionApprovalMetaFactory
transition_identifier = source_state_label + destination_state_label
transition_meta = getattr(context, "transitions", {})[transition_identifier]
transition_approval_meta = TransitionApprovalMetaFactory.create(
workflow=transition_meta.workflow,
transition_meta=transition_meta,
priority=priority,
)
transition_approval_meta.groups.set(Group.objects.filter(name__in=group_names))
@given('a workflow object with identifier "{identifier:ws}"')
def workflow_object(context, identifier):
from river.tests.models.factories import BasicTestModelObjectFactory
workflow_object = BasicTestModelObjectFactory().model
workflow_objects = getattr(context, "workflow_objects", {})
workflow_objects[identifier] = workflow_object
context.workflow_objects = workflow_objects
@given('"{workflow_object_identifier:ws}" is jumped on state "{state_label:ws}"')
def jump_workflow_object(context, workflow_object_identifier, state_label):
from river.models import State
state = State.objects.get(label=state_label)
workflow_object = getattr(context, "workflow_objects", {})[workflow_object_identifier]
workflow_object.river.my_field.jump_to(state)
@given('{number:d} workflow objects')
def many_workflow_object(context, number):
from river.tests.models.factories import BasicTestModelObjectFactory
BasicTestModelObjectFactory.create_batch(250)
@when('available approvals are fetched with user {username:w}')
def fetched_approvals(context, username):
from django.contrib.auth.models import User
from river.tests.models import BasicTestModel
user = User.objects.get(username=username)
context.before = datetime.now()
context.result = BasicTestModel.river.my_field.get_on_approval_objects(as_user=user)
context.after = datetime.now()
@when('get current state of "{workflow_object_identifier:ws}"')
def get_current_state(context, workflow_object_identifier):
workflow_object = getattr(context, "workflow_objects", {})[workflow_object_identifier]
from river.tests.models import BasicTestModel
workflow_object = BasicTestModel.objects.get(pk=workflow_object.pk)
context.current_state = workflow_object.my_field
@when('"{workflow_object_identifier:ws}" is attempted to be approved by {username:w}')
def approve_by(context, workflow_object_identifier, username):
from django.contrib.auth.models import User
workflow_object = getattr(context, "workflow_objects", {})[workflow_object_identifier]
user = User.objects.get(username=username)
workflow_object.river.my_field.approve(as_user=user)
@then('return {number:d} items')
def check_output_count(context, number):
assert_that(context.result, has_length(number))
@then('return current state as "{state_name:ws}"')
def check_current_state(context, state_name):
assert_that(context.current_state.label, is_(state_name))
<file_sep>from datetime import datetime, timedelta
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from hamcrest import assert_that, equal_to, has_item, all_of, has_property, less_than, has_items, has_length
from river.models import TransitionApproval
from river.models.factories import PermissionObjectFactory, UserObjectFactory, StateObjectFactory, TransitionApprovalMetaFactory, GroupObjectFactory, \
WorkflowFactory, TransitionMetaFactory
from river.tests.models import BasicTestModel
from river.tests.models.factories import BasicTestModelObjectFactory
# noinspection PyMethodMayBeStatic,DuplicatedCode
class ClassApiTest(TestCase):
def __init__(self, *args, **kwargs):
super(ClassApiTest, self).__init__(*args, **kwargs)
self.content_type = ContentType.objects.get_for_model(BasicTestModel)
def test_shouldReturnNoApprovalWhenUserIsUnAuthorized(self):
unauthorized_user = UserObjectFactory()
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
authorized_permission = PermissionObjectFactory()
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
BasicTestModelObjectFactory()
available_approvals = BasicTestModel.river.my_field.get_available_approvals(as_user=unauthorized_user)
assert_that(available_approvals, has_length(0))
def test_shouldReturnAnApprovalWhenUserIsAuthorizedWithAPermission(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
available_approvals = BasicTestModel.river.my_field.get_available_approvals(as_user=authorized_user)
assert_that(available_approvals, has_length(1))
assert_that(list(available_approvals), has_item(
all_of(
has_property("workflow_object", workflow_object.model),
has_property("workflow", workflow),
has_property("transition", transition_meta.transitions.first())
)
))
def test_shouldReturnAnApprovalWhenUserIsAuthorizedWithAUserGroup(self):
authorized_user_group = GroupObjectFactory()
authorized_user = UserObjectFactory(groups=[authorized_user_group])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
approval_meta = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0
)
approval_meta.groups.add(authorized_user_group)
workflow_object = BasicTestModelObjectFactory()
available_approvals = BasicTestModel.river.my_field.get_available_approvals(as_user=authorized_user)
assert_that(available_approvals, has_length(1))
assert_that(list(available_approvals), has_item(
all_of(
has_property("workflow_object", workflow_object.model),
has_property("workflow", workflow),
has_property("transition", transition_meta.transitions.first())
)
))
def test_shouldReturnAnApprovalWhenUserIsAuthorizedAsTransactioner(self):
authorized_user = UserObjectFactory()
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0
)
workflow_object = BasicTestModelObjectFactory()
TransitionApproval.objects.filter(workflow_object=workflow_object.model).update(transactioner=authorized_user)
available_approvals = BasicTestModel.river.my_field.get_available_approvals(as_user=authorized_user)
assert_that(available_approvals, has_length(1))
assert_that(list(available_approvals), has_item(
all_of(
has_property("workflow_object", workflow_object.model),
has_property("workflow", workflow),
has_property("transition", transition_meta.transitions.first())
)
))
def test__shouldReturnApprovalsOnTimeWhenTooManyWorkflowObject(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
self.objects = BasicTestModelObjectFactory.create_batch(250)
before = datetime.now()
BasicTestModel.river.my_field.get_on_approval_objects(as_user=authorized_user)
after = datetime.now()
assert_that(after - before, less_than(timedelta(milliseconds=200)))
print("Time taken %s" % str(after - before))
def test_shouldAssesInitialStateProperly(self):
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0
)
assert_that(BasicTestModel.river.my_field.initial_state, equal_to(state1))
def test_shouldAssesFinalStateProperlyWhenThereIsOnlyOne(self):
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0
)
assert_that(BasicTestModel.river.my_field.final_states, has_length(1))
assert_that(list(BasicTestModel.river.my_field.final_states), has_item(state2))
def test_shouldAssesFinalStateProperlyWhenThereAreMultiple(self):
state1 = StateObjectFactory(label="state1")
state21 = StateObjectFactory(label="state21")
state22 = StateObjectFactory(label="state22")
state31 = StateObjectFactory(label="state31")
state32 = StateObjectFactory(label="state32")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state21,
)
transition_meta2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state22,
)
transition_meta3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state31,
)
transition_meta4 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state32,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta1,
priority=0
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta2,
priority=0
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta3,
priority=0
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta4,
priority=0
)
assert_that(BasicTestModel.river.my_field.final_states, has_length(4))
assert_that(list(BasicTestModel.river.my_field.final_states), has_items(state21, state22, state31, state32))
<file_sep>WITH approvals_with_min_priority (workflow_id, transition_id, object_id, min_priority) AS
(
SELECT workflow_id,
transition_id,
object_id,
min(priority) as min_priority
FROM river.dbo.river_transitionapproval
WHERE workflow_id = '%(workflow_id)s'
AND status = 'PENDING'
group by workflow_id, transition_id, object_id
),
authorized_approvals(id, workflow_id, transition_id, source_state_id, object_id, priority) AS
(
SELECT ta.id,
ta.workflow_id,
ta.transition_id,
t.source_state_id,
ta.object_id,
ta.priority
FROM river.dbo.river_transitionapproval ta
INNER JOIN river.dbo.river_transition t on t.id = ta.transition_id
LEFT JOIN river.dbo.river_transitionapproval_permissions tap on tap.transitionapproval_id = ta.id
LEFT JOIN river.dbo.river_transitionapproval_groups tag on tag.transitionapproval_id = ta.id
WHERE ta.workflow_id = '%(workflow_id)s'
AND ta.status = 'PENDING'
AND (ta.transactioner_id is null or ta.transactioner_id = '%(transactioner_id)s')
AND (tap.id is null or tap.permission_id in ('%(permission_ids)s'))
AND (tag.id is null or tag.group_id in ('%(group_ids)s'))
),
approvals_with_max_priority (id, object_id, source_state_id) AS
(
SELECT aa.id, aa.object_id, aa.source_state_id
FROM approvals_with_min_priority awmp
INNER JOIN authorized_approvals aa
ON (
aa.workflow_id = awmp.workflow_id
AND aa.transition_id = awmp.transition_id
AND aa.object_id = awmp.object_id
)
WHERE awmp.min_priority = aa.priority
)
SELECT awmp.id
FROM approvals_with_max_priority awmp
INNER JOIN '%(workflow_object_table)s' wot
ON (
wot.'%(object_pk_name)s' = awmp.object_id
AND awmp.source_state_id = wot.'%(field_name)s'_id
)
<file_sep>from uuid import uuid4
from .base import *
DB_HOST = os.environ['POSTGRES_HOST']
DB_PORT = os.environ['POSTGRES_5432_TCP_PORT']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'river',
'USER': 'river',
'PASSWORD': '<PASSWORD>',
'HOST': DB_HOST,
'PORT': DB_PORT,
'TEST': {
'NAME': 'river' + str(uuid4()),
},
}
}
INSTALLED_APPS += (
'river.tests',
)
if django.get_version() >= '1.9.0':
MIGRATION_MODULES = DisableMigrations()
<file_sep>from django.contrib import auth
from django.db.models import Min, CharField, Q, F
from django.db.models.functions import Cast
from django_cte import With
from river.driver.river_driver import RiverDriver
from river.models import TransitionApproval, PENDING
class OrmDriver(RiverDriver):
def get_available_approvals(self, as_user):
those_with_max_priority = With(
TransitionApproval.objects.filter(
workflow=self.workflow, status=PENDING
).values(
'workflow', 'object_id', 'transition'
).annotate(min_priority=Min('priority'))
)
workflow_objects = With(
self.wokflow_object_class.objects.all(),
name="workflow_object"
)
approvals_with_max_priority = those_with_max_priority.join(
self._authorized_approvals(as_user),
workflow_id=those_with_max_priority.col.workflow_id,
object_id=those_with_max_priority.col.object_id,
transition_id=those_with_max_priority.col.transition_id,
).with_cte(
those_with_max_priority
).annotate(
object_id_as_str=Cast('object_id', CharField(max_length=200)),
min_priority=those_with_max_priority.col.min_priority
).filter(min_priority=F("priority"))
return workflow_objects.join(
approvals_with_max_priority, object_id_as_str=Cast(workflow_objects.col.pk, CharField(max_length=200))
).with_cte(
workflow_objects
).filter(transition__source_state=getattr(workflow_objects.col, self.field_name + "_id"))
def _authorized_approvals(self, as_user):
group_q = Q()
for g in as_user.groups.all():
group_q = group_q | Q(groups__in=[g])
permissions = []
for backend in auth.get_backends():
if hasattr(backend, "get_all_permissions"):
permissions.extend(backend.get_all_permissions(as_user))
permission_q = Q()
for p in permissions:
label, codename = p.split('.')
permission_q = permission_q | Q(permissions__content_type__app_label=label,
permissions__codename=codename)
return TransitionApproval.objects.filter(
Q(workflow=self.workflow, status=PENDING) &
(
(Q(transactioner__isnull=True) | Q(transactioner=as_user)) &
(Q(permissions__isnull=True) | permission_q) &
(Q(groups__isnull=True) | group_q)
)
)
<file_sep>from river.models.managers.rivermanager import RiverManager
class StateManager(RiverManager):
def get_by_natural_key(self, slug):
return self.get(slug=slug)
<file_sep>from django.contrib.contenttypes.models import ContentType
from hamcrest import equal_to, assert_that, none, has_entry, all_of, has_key, has_length, is_not
from river.models import TransitionApproval
from river.models.factories import PermissionObjectFactory, UserObjectFactory, StateObjectFactory, WorkflowFactory, TransitionApprovalMetaFactory, \
TransitionMetaFactory
from river.models.hook import BEFORE
from river.tests.hooking.base_hooking_test import BaseHookingTest
from river.tests.models import BasicTestModel
from river.tests.models.factories import BasicTestModelObjectFactory
# noinspection DuplicatedCode
class ApprovedHooking(BaseHookingTest):
def test_shouldInvokeCallbackThatIsRegisteredWithInstanceWhenAnApprovingHappens(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
content_type = ContentType.objects.get_for_model(BasicTestModel)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
meta1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=1,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
self.hook_pre_approve(workflow, meta1, workflow_object=workflow_object.model)
assert_that(self.get_output(), none())
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state1))
output = self.get_output()
assert_that(output, has_length(1))
assert_that(output[0], has_key("hook"))
assert_that(output[0]["hook"], has_entry("type", "on-approved"))
assert_that(output[0]["hook"], has_entry("when", BEFORE))
assert_that(output[0]["hook"], has_entry(
"payload",
all_of(
has_entry(equal_to("workflow_object"), equal_to(workflow_object.model)),
has_entry(equal_to("transition_approval"), equal_to(meta1.transition_approvals.filter(priority=0).first()))
)
))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state2))
output = self.get_output()
assert_that(output, has_length(1))
assert_that(output[0], has_key("hook"))
assert_that(output[0]["hook"], has_entry("type", "on-approved"))
assert_that(output[0]["hook"], has_entry("when", BEFORE))
assert_that(output[0]["hook"], has_entry(
"payload",
all_of(
has_entry(equal_to("workflow_object"), equal_to(workflow_object.model)),
has_entry(equal_to("transition_approval"), equal_to(meta1.transition_approvals.filter(priority=0).first()))
)
))
def test_shouldInvokeCallbackThatIsRegisteredWithoutInstanceWhenAnApprovingHappens(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
content_type = ContentType.objects.get_for_model(BasicTestModel)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
meta1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=1,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
self.hook_pre_approve(workflow, meta1)
assert_that(self.get_output(), none())
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state1))
output = self.get_output()
assert_that(output, has_length(1))
assert_that(output[0], has_key("hook"))
assert_that(output[0]["hook"], has_entry("type", "on-approved"))
assert_that(output[0]["hook"], has_entry("when", BEFORE))
assert_that(output[0]["hook"], has_entry(
"payload",
all_of(
has_entry(equal_to("workflow_object"), equal_to(workflow_object.model)),
has_entry(equal_to("transition_approval"), equal_to(meta1.transition_approvals.filter(priority=0).first()))
)
))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state2))
output = self.get_output()
assert_that(output, has_length(1))
assert_that(output[0], has_key("hook"))
assert_that(output[0]["hook"], has_entry("type", "on-approved"))
assert_that(output[0]["hook"], has_entry("when", BEFORE))
assert_that(output[0]["hook"], has_entry(
"payload",
all_of(
has_entry(equal_to("workflow_object"), equal_to(workflow_object.model)),
has_entry(equal_to("transition_approval"), equal_to(meta1.transition_approvals.filter(priority=0).first()))
)
))
def test_shouldInvokeCallbackForTheOnlyGivenApproval(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
content_type = ContentType.objects.get_for_model(BasicTestModel)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state3,
destination_state=state1,
)
meta1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
workflow_object.model.river.my_field.approve(as_user=authorized_user)
workflow_object.model.river.my_field.approve(as_user=authorized_user)
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(TransitionApproval.objects.filter(meta=meta1), has_length(2))
first_approval = TransitionApproval.objects.filter(meta=meta1, transition__iteration=0).first()
assert_that(first_approval, is_not(none()))
self.hook_pre_approve(workflow, meta1, transition_approval=first_approval)
output = self.get_output()
assert_that(output, none())
workflow_object.model.river.my_field.approve(as_user=authorized_user)
output = self.get_output()
assert_that(output, none())
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-03-16 11:46
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.CreateModel(
name='Function',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('name', models.CharField(max_length=200, unique=True, verbose_name='Function Name')),
('body', models.TextField(max_length=100000, verbose_name='Function Body')),
('version', models.IntegerField(default=0, verbose_name='Function Version')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='OnApprovedHook',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('object_id', models.CharField(blank=True, max_length=200, null=True)),
('hook_type', models.CharField(choices=[(b'BEFORE', 'Before'), (b'AFTER', 'After')], max_length=50, verbose_name='When?')),
('callback_function', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='river_onapprovedhook_hooks', to='river.Function', verbose_name='Function')),
('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='contenttypes.ContentType')),
],
),
migrations.CreateModel(
name='OnCompleteHook',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('object_id', models.CharField(blank=True, max_length=200, null=True)),
('hook_type', models.CharField(choices=[(b'BEFORE', 'Before'), (b'AFTER', 'After')], max_length=50, verbose_name='When?')),
('callback_function', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='river_oncompletehook_hooks', to='river.Function', verbose_name='Function')),
('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='contenttypes.ContentType')),
],
),
migrations.CreateModel(
name='OnTransitHook',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('object_id', models.CharField(blank=True, max_length=200, null=True)),
('hook_type', models.CharField(choices=[(b'BEFORE', 'Before'), (b'AFTER', 'After')], max_length=50, verbose_name='When?')),
('callback_function', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='river_ontransithook_hooks', to='river.Function', verbose_name='Function')),
('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='contenttypes.ContentType')),
],
),
migrations.CreateModel(
name='State',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('slug', models.SlugField(blank=True, null=True, unique=True)),
('label', models.CharField(max_length=50)),
('description', models.CharField(blank=True, max_length=200, null=True, verbose_name='Description')),
],
options={
'verbose_name': 'State',
'verbose_name_plural': 'States',
},
),
migrations.CreateModel(
name='Transition',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('object_id', models.CharField(max_length=50, verbose_name='Related Object')),
('status', models.CharField(choices=[(b'pending', 'Pending'), (b'cancelled', 'Cancelled'), (b'done', 'Done'), (b'jumped', 'Jumped')], default=b'pending', max_length=100, verbose_name='Status')),
('iteration', models.IntegerField(default=0, verbose_name='Priority')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType', verbose_name='Content Type')),
('destination_state', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_as_destination', to='river.State', verbose_name='Destination State')),
],
options={
'verbose_name': 'Transition',
'verbose_name_plural': 'Transitions',
},
),
migrations.CreateModel(
name='TransitionApproval',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('object_id', models.CharField(max_length=50, verbose_name='Related Object')),
('transaction_date', models.DateTimeField(blank=True, null=True)),
('status', models.CharField(choices=[(b'pending', 'Pending'), (b'approved', 'Approved'), (b'cancelled', 'Cancelled'), (b'jumped', 'Jumped')], default=b'pending', max_length=100, verbose_name='Status')),
('priority', models.IntegerField(default=0, verbose_name='Priority')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType', verbose_name='Content Type')),
('groups', models.ManyToManyField(to='auth.Group', verbose_name='Groups')),
],
options={
'verbose_name': 'Transition Approval',
'verbose_name_plural': 'Transition Approvals',
},
),
migrations.CreateModel(
name='TransitionApprovalMeta',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('priority', models.IntegerField(default=0, null=True, verbose_name='Priority')),
('groups', models.ManyToManyField(blank=True, to='auth.Group', verbose_name='Groups')),
('parents', models.ManyToManyField(blank=True, db_index=True, related_name='children', to='river.TransitionApprovalMeta', verbose_name='parents')),
('permissions', models.ManyToManyField(blank=True, to='auth.Permission', verbose_name='Permissions')),
],
options={
'verbose_name': 'Transition Approval Meta',
'verbose_name_plural': 'Transition Approval Meta',
},
),
migrations.CreateModel(
name='TransitionMeta',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('destination_state', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_meta_as_destination', to='river.State', verbose_name='Destination State')),
('source_state', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_meta_as_source', to='river.State', verbose_name='Source State')),
],
options={
'verbose_name': 'Transition Meta',
'verbose_name_plural': 'Transition Meta',
},
),
migrations.CreateModel(
name='Workflow',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date Created')),
('date_updated', models.DateTimeField(auto_now=True, null=True, verbose_name='Date Updated')),
('field_name', models.CharField(max_length=200, verbose_name='Field Name')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.ContentType', verbose_name='Content Type')),
('initial_state', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='workflow_this_set_as_initial_state', to='river.State', verbose_name='Initial State')),
],
options={
'verbose_name': 'Workflow',
'verbose_name_plural': 'Workflows',
},
),
migrations.AddField(
model_name='transitionmeta',
name='workflow',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_metas', to='river.Workflow', verbose_name='Workflow'),
),
migrations.AddField(
model_name='transitionapprovalmeta',
name='transition_meta',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_approval_meta', to='river.TransitionMeta', verbose_name='Transition Meta'),
),
migrations.AddField(
model_name='transitionapprovalmeta',
name='workflow',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_approval_metas', to='river.Workflow', verbose_name='Workflow'),
),
migrations.AddField(
model_name='transitionapproval',
name='meta',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transition_approvals', to='river.TransitionApprovalMeta', verbose_name='Meta'),
),
migrations.AddField(
model_name='transitionapproval',
name='permissions',
field=models.ManyToManyField(to='auth.Permission', verbose_name='Permissions'),
),
migrations.AddField(
model_name='transitionapproval',
name='previous',
field=mptt.fields.TreeOneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='next_transition', to='river.TransitionApproval', verbose_name='Previous Transition'),
),
migrations.AddField(
model_name='transitionapproval',
name='transactioner',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='Transactioner'),
),
migrations.AddField(
model_name='transitionapproval',
name='transition',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_approvals', to='river.Transition', verbose_name='Transition'),
),
migrations.AddField(
model_name='transitionapproval',
name='workflow',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_approvals', to='river.Workflow', verbose_name='Workflow'),
),
migrations.AddField(
model_name='transition',
name='meta',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transitions', to='river.TransitionMeta', verbose_name='Meta'),
),
migrations.AddField(
model_name='transition',
name='source_state',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transition_as_source', to='river.State', verbose_name='Source State'),
),
migrations.AddField(
model_name='transition',
name='workflow',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transitions', to='river.Workflow', verbose_name='Workflow'),
),
migrations.AddField(
model_name='ontransithook',
name='transition',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='on_transit_hooks', to='river.Transition', verbose_name='Transition'),
),
migrations.AddField(
model_name='ontransithook',
name='transition_meta',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='on_transit_hooks', to='river.TransitionMeta', verbose_name='Transition Meta'),
),
migrations.AddField(
model_name='ontransithook',
name='workflow',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='river_ontransithook_hooks', to='river.Workflow', verbose_name='Workflow'),
),
migrations.AddField(
model_name='oncompletehook',
name='workflow',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='river_oncompletehook_hooks', to='river.Workflow', verbose_name='Workflow'),
),
migrations.AddField(
model_name='onapprovedhook',
name='transition_approval',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='on_approved_hooks', to='river.TransitionApproval', verbose_name='Transition Approval'),
),
migrations.AddField(
model_name='onapprovedhook',
name='transition_approval_meta',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='on_approved_hooks', to='river.TransitionApprovalMeta', verbose_name='Transition Approval Meta'),
),
migrations.AddField(
model_name='onapprovedhook',
name='workflow',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='river_onapprovedhook_hooks', to='river.Workflow', verbose_name='Workflow'),
),
migrations.AlterUniqueTogether(
name='workflow',
unique_together=set([('content_type', 'field_name')]),
),
migrations.AlterUniqueTogether(
name='transitionmeta',
unique_together=set([('workflow', 'source_state', 'destination_state')]),
),
migrations.AlterUniqueTogether(
name='transitionapprovalmeta',
unique_together=set([('workflow', 'transition_meta', 'priority')]),
),
migrations.AlterUniqueTogether(
name='ontransithook',
unique_together=set([('callback_function', 'workflow', 'transition_meta', 'content_type', 'object_id', 'transition')]),
),
migrations.AlterUniqueTogether(
name='oncompletehook',
unique_together=set([('callback_function', 'workflow', 'content_type', 'object_id')]),
),
migrations.AlterUniqueTogether(
name='onapprovedhook',
unique_together=set([('callback_function', 'workflow', 'transition_approval_meta', 'content_type', 'object_id', 'transition_approval')]),
),
]
<file_sep>import os
from os.path import dirname
import six
from django.db import connection
from django.contrib.auth.models import Permission
from river.driver.river_driver import RiverDriver
from river.models import TransitionApproval
class MsSqlDriver(RiverDriver):
def __init__(self, *args, **kwargs):
super(MsSqlDriver, self).__init__(*args, **kwargs)
with open(os.path.join(dirname(dirname(__file__)), "sql", "mssql", "get_available_approvals.sql")) as f:
self.available_approvals_sql_template = f.read().replace("river.dbo.", "")
self.cursor = connection.cursor()
def get_available_approvals(self, as_user):
with connection.cursor() as cursor:
cursor.execute(self._clean_sql % {
"workflow_id": self.workflow.pk,
"transactioner_id": as_user.pk,
"field_name": self.field_name,
"permission_ids": self._permission_ids_str(as_user),
"group_ids": self._group_ids_str(as_user),
"workflow_object_table": self.wokflow_object_class._meta.db_table,
"object_pk_name": self.wokflow_object_class._meta.pk.name
})
return TransitionApproval.objects.filter(pk__in=[row[0] for row in cursor.fetchall()])
@staticmethod
def _permission_ids_str(as_user):
permissions = as_user.user_permissions.all() | Permission.objects.filter(group__user=as_user)
return ",".join(list(six.moves.map(str, permissions.values_list("pk", flat=True))) or ["-1"])
@staticmethod
def _group_ids_str(as_user):
return ",".join(list(six.moves.map(str, as_user.groups.all().values_list("pk", flat=True))) or ["-1"])
@property
def _clean_sql(self):
return self.available_approvals_sql_template \
.replace("'%(workflow_id)s'", "%(workflow_id)s") \
.replace("'%(transactioner_id)s'", "%(transactioner_id)s") \
.replace("'%(field_name)s'", "%(field_name)s") \
.replace("'%(permission_ids)s'", "%(permission_ids)s") \
.replace("'%(group_ids)s'", "%(group_ids)s") \
.replace("'%(workflow_object_table)s'", "%(workflow_object_table)s") \
.replace("'%(object_pk_name)s'", "%(object_pk_name)s")
<file_sep>.. _admin-guide:
Administration
==============
Since ``django-river`` keeps all the data needed in a database, those should be pre-created before your first model
object is created. Otherwise **your app will crash first time you create a model object.** Here are all needed models
that you need to provide. ``django-river`` will register an Administration for those model for you. All you need to do
is to provide them by using their Django admin pages.
.. toctree::
:maxdepth: 2
state
transition_meta
transition_approval_meta
<file_sep>.. _migration_31_to_32:
3.1.X to 3.2.X
==============
``django-river`` started to support **Microsoft SQL Server 17 and 19** after version 3.2.0 but the previous migrations didn't get along with it. We needed to reset all
the migrations to have fresh start. If you have already migrated to version `3.1.X` all you need to do is to pull your migrations back to the beginning.
.. code:: bash
python manage.py migrate --fake river zero
python manage.py migrate --fake river
<file_sep>from river.models.managers.rivermanager import RiverManager
class WorkflowManager(RiverManager):
def get_by_natural_key(self, content_type, field_name):
return self.get(content_type=content_type, field_name=field_name)
<file_sep>from __future__ import unicode_literals
from django.db import models, transaction
from django.db.models import PROTECT
from django.db.models.signals import post_save, pre_delete
from django.utils.translation import ugettext_lazy as _
from river.config import app_config
from river.models import Workflow
from river.models.base_model import BaseModel
from river.models.managers.transitionmetada import TransitionApprovalMetadataManager
from river.models.transitionmeta import TransitionMeta
class TransitionApprovalMeta(BaseModel):
class Meta:
app_label = 'river'
verbose_name = _("Transition Approval Meta")
verbose_name_plural = _("Transition Approval Meta")
unique_together = [('workflow', 'transition_meta', 'priority')]
objects = TransitionApprovalMetadataManager()
workflow = models.ForeignKey(Workflow, verbose_name=_("Workflow"), related_name='transition_approval_metas', on_delete=PROTECT)
transition_meta = models.ForeignKey(TransitionMeta, verbose_name=_("Transition Meta"), related_name='transition_approval_meta', on_delete=PROTECT)
permissions = models.ManyToManyField(app_config.PERMISSION_CLASS, verbose_name=_('Permissions'), blank=True)
groups = models.ManyToManyField(app_config.GROUP_CLASS, verbose_name=_('Groups'), blank=True)
priority = models.IntegerField(default=0, verbose_name=_('Priority'), null=True)
parents = models.ManyToManyField('self', verbose_name='parents', related_name='children', symmetrical=False, db_index=True, blank=True)
def __str__(self):
return 'Transition: %s,Permissions: %s, Groups: %s, Order: %s' % (
self.transition_meta,
','.join(self.permissions.values_list('name', flat=True)),
','.join(self.groups.values_list('name', flat=True)), self.priority)
def post_save_model(sender, instance, *args, **kwargs):
parents = TransitionApprovalMeta.objects \
.filter(workflow=instance.workflow, transition_meta__destination_state=instance.transition_meta.source_state) \
.exclude(pk__in=instance.parents.values_list('pk', flat=True)) \
.exclude(pk=instance.pk)
children = TransitionApprovalMeta.objects \
.filter(workflow=instance.workflow, transition_meta__source_state=instance.transition_meta.destination_state) \
.exclude(parents__in=[instance.pk]) \
.exclude(pk=instance.pk)
instance = TransitionApprovalMeta.objects.get(pk=instance.pk)
if parents:
instance.parents.add(*parents)
for child in children:
child.parents.add(instance)
@transaction.atomic
def pre_delete_model(sender, instance, *args, **kwargs):
from river.models.transitionapproval import PENDING
instance.transition_approvals.filter(status=PENDING).delete()
post_save.connect(post_save_model, sender=TransitionApprovalMeta)
pre_delete.connect(pre_delete_model, sender=TransitionApprovalMeta)
<file_sep>
from django.db.models import QuerySet
from django.db.models.manager import BaseManager
from river.config import app_config
class RiverQuerySet(QuerySet):
def first(self):
if app_config.IS_MSSQL:
return next(iter(self), None)
else:
return super(RiverQuerySet, self).first()
class RiverManager(BaseManager.from_queryset(RiverQuerySet)):
pass
<file_sep>from river.models.managers.rivermanager import RiverManager
class TransitionApprovalMetadataManager(RiverManager):
def get_by_natural_key(self, workflow, source_state, destination_state, priority):
return self.get(workflow=workflow, source_state=source_state, destination_state=destination_state, priority=priority)
<file_sep>from __future__ import unicode_literals
from django.db import models
from django.db.models import PROTECT
from django.utils.translation import ugettext_lazy as _
from river.models import State, Workflow
from river.models.base_model import BaseModel
class TransitionMeta(BaseModel):
class Meta:
app_label = 'river'
verbose_name = _("Transition Meta")
verbose_name_plural = _("Transition Meta")
unique_together = [('workflow', 'source_state', 'destination_state')]
workflow = models.ForeignKey(Workflow, verbose_name=_("Workflow"), related_name='transition_metas', on_delete=PROTECT)
source_state = models.ForeignKey(State, verbose_name=_("Source State"), related_name='transition_meta_as_source', on_delete=PROTECT)
destination_state = models.ForeignKey(State, verbose_name=_("Destination State"), related_name='transition_meta_as_destination', on_delete=PROTECT)
def __str__(self):
return 'Field Name:%s, %s -> %s' % (
self.workflow,
self.source_state,
self.destination_state
)
<file_sep>.. _getting-started:
Getting Started
===============
1. Install and enable it
.. code:: bash
pip install django-river
.. code:: python
INSTALLED_APPS=[
...
river
...
]
2. Create your first state machine in your model and migrate your db
.. code:: python
from django.db import models
from river.models.fields.state import StateField
class MyModel(models.Model):
my_state_field = StateField()
3. Create all your ``states`` on the admin page
4. Create a ``workflow`` with your model ( ``MyModel`` - ``my_state_field`` ) information on the admin page
5. Create your ``transition metadata`` within the workflow created earlier, source and destination states
6. Create your ``transition approval metadata`` within the workflow created earlier and authorization rules along with their priority on the admin page
7. Enjoy your ``django-river`` journey.
.. code-block:: python
my_model=MyModel.objects.get(....)
my_model.river.my_state_field.approve(as_user=transactioner_user)
my_model.river.my_state_field.approve(as_user=transactioner_user, next_state=State.objects.get(label='re-opened'))
# and much more. Check the documentation
.. note::
Whenever a model object is saved, it's state field will be initialized with the
state is given at step-4 above by ``django-river``.<file_sep>import logging
from django.db.models import CASCADE, PROTECT
from river.models import State, Workflow, TransitionMeta
try:
from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError:
from django.contrib.contenttypes.generic import GenericForeignKey
from django.db import models
from django.utils.translation import ugettext_lazy as _
from river.models.base_model import BaseModel
from river.models.managers.transitionapproval import TransitionApprovalManager
from river.config import app_config
PENDING = "pending"
CANCELLED = "cancelled"
JUMPED = "jumped"
DONE = "done"
STATUSES = [
(PENDING, _('Pending')),
(CANCELLED, _('Cancelled')),
(DONE, _('Done')),
(JUMPED, _('Jumped')),
]
LOGGER = logging.getLogger(__name__)
class Transition(BaseModel):
class Meta:
app_label = 'river'
verbose_name = _("Transition")
verbose_name_plural = _("Transitions")
objects = TransitionApprovalManager()
content_type = models.ForeignKey(app_config.CONTENT_TYPE_CLASS, verbose_name=_('Content Type'), on_delete=CASCADE)
object_id = models.CharField(max_length=50, verbose_name=_('Related Object'))
workflow_object = GenericForeignKey('content_type', 'object_id')
meta = models.ForeignKey(TransitionMeta, verbose_name=_('Meta'), related_name="transitions", on_delete=PROTECT)
workflow = models.ForeignKey(Workflow, verbose_name=_("Workflow"), related_name='transitions', on_delete=PROTECT)
source_state = models.ForeignKey(State, verbose_name=_("Source State"), related_name='transition_as_source', on_delete=PROTECT)
destination_state = models.ForeignKey(State, verbose_name=_("Destination State"), related_name='transition_as_destination', on_delete=PROTECT)
status = models.CharField(_('Status'), choices=STATUSES, max_length=100, default=PENDING)
iteration = models.IntegerField(default=0, verbose_name=_('Priority'))
@property
def next_transitions(self):
return Transition.objects.filter(
workflow=self.workflow,
workflow_object=self.workflow_object,
source_state=self.destination_state,
iteration=self.iteration + 1
)
@property
def peers(self):
return Transition.objects.filter(
workflow=self.workflow,
workflow_object=self.workflow_object,
source_state=self.source_state,
iteration=self.iteration
).exclude(pk=self.pk)
<file_sep>import logging
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import PROTECT
from django.utils.translation import ugettext_lazy as _
from river.models import Workflow, GenericForeignKey, BaseModel
from river.models.function import Function
BEFORE = "BEFORE"
AFTER = "AFTER"
HOOK_TYPES = [
(BEFORE, _('Before')),
(AFTER, _('After')),
]
LOGGER = logging.getLogger(__name__)
class Hook(BaseModel):
class Meta:
abstract = True
callback_function = models.ForeignKey(Function, verbose_name=_("Function"), related_name='%(app_label)s_%(class)s_hooks', on_delete=PROTECT)
workflow = models.ForeignKey(Workflow, verbose_name=_("Workflow"), related_name='%(app_label)s_%(class)s_hooks', on_delete=PROTECT)
content_type = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.SET_NULL)
object_id = models.CharField(max_length=200, blank=True, null=True)
workflow_object = GenericForeignKey('content_type', 'object_id')
hook_type = models.CharField(_('When?'), choices=HOOK_TYPES, max_length=50)
def execute(self, context):
try:
self.callback_function.get()(context)
except Exception as e:
LOGGER.exception(e)
<file_sep>from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
}
INSTALLED_APPS += (
'river.tests',
)
if django.get_version() >= '1.9.0':
MIGRATION_MODULES = DisableMigrations()
<file_sep>from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from django.db import connection
class RiverConfig(object):
prefix = 'RIVER'
def __init__(self):
self.cached_settings = None
@property
def settings(self):
if self.cached_settings:
return self.cached_settings
else:
from django.conf import settings
allowed_configurations = {
'CONTENT_TYPE_CLASS': ContentType,
'USER_CLASS': settings.AUTH_USER_MODEL,
'PERMISSION_CLASS': Permission,
'GROUP_CLASS': Group,
'INJECT_MODEL_ADMIN': False
}
river_settings = {}
for key, default in allowed_configurations.items():
river_settings[key] = getattr(settings, self.get_with_prefix(key), default)
river_settings['IS_MSSQL'] = connection.vendor == 'microsoft'
self.cached_settings = river_settings
return self.cached_settings
def get_with_prefix(self, config):
return '%s_%s' % (self.prefix, config)
def __getattr__(self, item):
if item in self.settings:
return self.settings[item]
else:
raise AttributeError(item)
app_config = RiverConfig()
<file_sep>.. |Re Open Case| image:: https://cloud.githubusercontent.com/assets/1279644/9653471/3c9dfcfa-522c-11e5-85cb-f90a4f184201.png
.. |Closed Without Re Open Case| image:: https://cloud.githubusercontent.com/assets/1279644/9624970/88c0ddaa-515a-11e5-8f65-d1e35e945976.png
.. |Closed With Re Open Case| image:: https://cloud.githubusercontent.com/assets/1279644/9624968/88b5f278-515a-11e5-996b-b62d6e224357.png
Overview
========
Main goal of developing this framework is **to be able to edit any workflow item on the fly.** This means, all elements in workflow like states, transitions, user authorizations(permission), group authorization are editable. To do this, all data about the workflow item is persisted into DB. **Hence, they can be changed without touching the code and re-deploying your application.**
There is ordering aprovments for a transition functionality in ``django-river``. It also provides skipping specific transition of a specific objects.
**Playground**: There is a fake jira example repository as a playground of django-river. https://github.com/javrasya/fakejira
Requirements
------------
* Python (``2.7``, ``3.4``, ``3.5``, ``3.6``)
* Django (``1.11``, ``2.0``, ``2.1``, ``2.2``, ``3.0``)
* ``Django`` >= 2.0 is supported for ``Python`` >= 3.5
Supported (Tested) Databases:
-----------------------------
+------------+--------+---------+
| PostgreSQL | Tested | Support |
+------------+--------+---------+
| 9 | ✅ | ✅ |
+------------+--------+---------+
| 10 | ✅ | ✅ |
+------------+--------+---------+
| 11 | ✅ | ✅ |
+------------+--------+---------+
| 12 | ✅ | ✅ |
+------------+--------+---------+
+------------+--------+---------+
| MySQL | Tested | Support |
+------------+--------+---------+
| 5.6 | ✅ | ❌ |
+------------+--------+---------+
| 5.7 | ✅ | ❌ |
+------------+--------+---------+
| 8.0 | ✅ | ✅ |
+------------+--------+---------+
+------------+--------+---------+
| MSSQL | Tested | Support |
+------------+--------+---------+
| 19 | ✅ | ✅ |
+------------+--------+---------+
| 17 | ✅ | ✅ |
+------------+--------+---------+
Example Scenarios
-----------------
Simple Issue Tracking System
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Re-Open case
""""""""""""
|Re Open Case|
Closed without Re-Open case
"""""""""""""""""""""""""""
|Closed Without Re Open Case|
Closed with Re-Open case
""""""""""""""""""""""""
|Closed With Re Open Case| <file_sep>import factory
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from factory import DjangoModelFactory
from river.models import Workflow, TransitionMeta
from river.models.state import State
from river.models.transitionapprovalmeta import TransitionApprovalMeta
class ContentTypeObjectFactory(DjangoModelFactory):
class Meta:
model = ContentType
model = factory.Sequence(lambda n: 'ect_model_%s' % n)
class UserObjectFactory(factory.DjangoModelFactory):
class Meta:
model = get_user_model()
username = factory.Sequence(lambda n: 'User_%s' % n)
@factory.post_generation
def user_permissions(self, create, extracted, **kwargs):
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of groups were passed in, use them
for permission in extracted:
self.user_permissions.add(permission)
@factory.post_generation
def groups(self, create, extracted, **kwargs):
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of groups were passed in, use them
for group in extracted:
self.groups.add(group)
class GroupObjectFactory(factory.DjangoModelFactory):
class Meta:
model = 'auth.Group'
name = factory.Sequence(lambda n: 'Group_%s' % n)
@factory.post_generation
def permissions(self, create, extracted, **kwargs):
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of groups were passed in, use them
for permission in extracted:
self.permissions.add(permission)
class PermissionObjectFactory(factory.DjangoModelFactory):
class Meta:
model = 'auth.Permission'
name = factory.Sequence(lambda n: 'Permission_%s' % n)
codename = factory.Sequence(lambda n: 'Codename_%s' % n)
content_type = factory.SubFactory(ContentTypeObjectFactory)
class StateObjectFactory(DjangoModelFactory):
class Meta:
model = State
label = factory.Sequence(lambda n: 's%s' % n)
description = factory.Sequence(lambda n: 'desc_%s' % n)
class WorkflowFactory(DjangoModelFactory):
class Meta:
model = Workflow
content_type = factory.SubFactory(ContentTypeObjectFactory)
initial_state = factory.SubFactory(StateObjectFactory)
class TransitionMetaFactory(DjangoModelFactory):
class Meta:
model = TransitionMeta
source_state = factory.SubFactory(StateObjectFactory)
destination_state = factory.SubFactory(StateObjectFactory)
workflow = factory.SubFactory(WorkflowFactory)
@factory.post_generation
def permissions(self, create, extracted, **kwargs):
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of groups were passed in, use them
for permission in extracted:
self.permissions.add(permission)
class TransitionApprovalMetaFactory(DjangoModelFactory):
class Meta:
model = TransitionApprovalMeta
transition_meta = factory.SubFactory(TransitionMetaFactory)
workflow = factory.SubFactory(WorkflowFactory)
@factory.post_generation
def permissions(self, create, extracted, **kwargs):
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of groups were passed in, use them
for permission in extracted:
self.permissions.add(permission)
<file_sep>[run]
omit =
river/admin/*
river/tests/*
river/migrations/*
settings/*
*/__init__*
.tox/*
setup.py
test_settings.py
test_urls.py
manage.py<file_sep>from django.contrib.contenttypes.models import ContentType
from river.driver.mssql_driver import MsSqlDriver
from river.driver.orm_driver import OrmDriver
from river.models import State, TransitionApprovalMeta, Workflow, app_config
class ClassWorkflowObject(object):
def __init__(self, wokflow_object_class, field_name):
self.wokflow_object_class = wokflow_object_class
self.field_name = field_name
self.workflow = Workflow.objects.filter(field_name=self.field_name, content_type=self._content_type).first()
self._cached_river_driver = None
@property
def _river_driver(self):
if self._cached_river_driver:
return self._cached_river_driver
else:
if app_config.IS_MSSQL:
self._cached_river_driver = MsSqlDriver(self.workflow, self.wokflow_object_class, self.field_name)
else:
self._cached_river_driver = OrmDriver(self.workflow, self.wokflow_object_class, self.field_name)
return self._cached_river_driver
def get_on_approval_objects(self, as_user):
approvals = self.get_available_approvals(as_user)
object_ids = list(approvals.values_list('object_id', flat=True))
return self.wokflow_object_class.objects.filter(pk__in=object_ids)
def get_available_approvals(self, as_user):
return self._river_driver.get_available_approvals(as_user)
@property
def initial_state(self):
workflow = Workflow.objects.filter(content_type=self._content_type, field_name=self.field_name).first()
return workflow.initial_state if workflow else None
@property
def final_states(self):
final_approvals = TransitionApprovalMeta.objects.filter(workflow=self.workflow, children__isnull=True)
return State.objects.filter(pk__in=final_approvals.values_list("transition_meta__destination_state", flat=True))
@property
def _content_type(self):
return ContentType.objects.get_for_model(self.wokflow_object_class)
<file_sep>from hamcrest import all_of, has_property
from hamcrest.core.base_matcher import BaseMatcher
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
def has_permission(name, match):
return HasPermissions(name, wrap_matcher(match))
def has_transition(source_state, destination_state, iteration=None):
return HasTransition(source_state, destination_state, iteration=iteration)
class HasPermissions(BaseMatcher):
def __init__(self, permission_property_name, value_matcher):
self.permission_property_name = permission_property_name
self.value_matcher = value_matcher
def describe_to(self, description):
description.append_text("an object with a permission'") \
.append_text(self.permission_property_name) \
.append_text("' matching ") \
.append_description_of(self.value_matcher)
def _matches(self, item):
if item is None:
return False
if not hasattr(item, self.permission_property_name):
return False
permission_field = getattr(item, self.permission_property_name)
return self.value_matcher.matches(permission_field.all())
class HasTransition(BaseMatcher):
def __init__(self, source_state, destination_state, iteration=None):
self.source_state = source_state
self.destination_state = destination_state
self.iteration = iteration
conditions = [
has_property("source_state", source_state),
has_property("destination_state", destination_state)
]
if iteration:
conditions.append(has_property("iteration", iteration))
self.value_matcher = all_of(*conditions)
def describe_to(self, description):
description.append_text("an object with a transition (%s -> %s) (%s)'" % (self.source_state, self.destination_state, self.iteration)) \
.append_text("' matching ") \
.append_description_of(self.value_matcher)
def _matches(self, item):
if item is None:
return False
return self.value_matcher.matches(getattr(item, "transition"))
<file_sep>.. _state-administration:
State Administration
====================
+-------------+--------------+----------+--------------+-----------------------------+
| Field | Default | Optional | Format | Description |
+=============+==============+==========+==============+=============================+
| label | NaN | False | String (\w+) | A name for the state |
+-------------+--------------+----------+--------------+-----------------------------+
| description | Empty string | True | String (\w+) | A description for the state |
+-------------+--------------+----------+--------------+-----------------------------+
.. toctree::
:maxdepth: 2
<file_sep>from .base_model import *
from .state import *
from .workflow import *
from .transitionmeta import *
from .transitionapprovalmeta import *
from .transition import *
from .transitionapproval import *
from .function import *
from .on_approved_hook import *
from .on_transit_hook import *
from .on_complete_hook import *
<file_sep>from abc import abstractmethod
class RiverDriver(object):
def __init__(self, workflow, wokflow_object_class, field_name):
self.workflow = workflow
self.wokflow_object_class = wokflow_object_class
self.field_name = field_name
self._cached_workflow = None
@abstractmethod
def get_available_approvals(self, as_user):
raise NotImplementedError()
<file_sep>from behave import given, when
from features.steps.basic_steps import workflow_object
@given('a bug "{description:ws}" identifier "{identifier:ws}"')
def issue(context, description, identifier):
workflow_object(context, identifier)
def _approve(context, workflow_object_identifier, username, next_state):
from django.contrib.auth.models import User
from river.models import State
workflow_object = getattr(context, "workflow_objects", {})[workflow_object_identifier]
user = User.objects.get(username=username)
workflow_object.river.my_field.approve(as_user=user, next_state=State.objects.get(label=next_state))
@when('"{workflow_object_identifier:ws}" is attempted to be closed by {username:w}')
def close_issue(context, workflow_object_identifier, username):
_approve(context, workflow_object_identifier, username, "Closed")
@when('"{workflow_object_identifier:ws}" is attempted to be re-opened by {username:w}')
def re_open_issue(context, workflow_object_identifier, username):
_approve(context, workflow_object_identifier, username, "Re-Opened")
<file_sep>.. _migration_2_to_3:
2.X.X to 3.0.0
==============
``django-river`` v3.0.0 comes with quite number of migrations, but the good news is that even though those are hard to determine kind of migrations, it comes with the required migrations
out of the box. All you need to do is to run;
.. code:: bash
python manage.py migrate river
<file_sep>from django.contrib.contenttypes.models import ContentType
from django.db.models import QuerySet
from django.test import TestCase
from hamcrest import assert_that, has_property, is_, instance_of
from river.core.classworkflowobject import ClassWorkflowObject
from river.core.instanceworkflowobject import InstanceWorkflowObject
from river.core.riverobject import RiverObject
from river.models import State
from river.models.factories import StateObjectFactory, TransitionApprovalMetaFactory, WorkflowFactory, TransitionMetaFactory
from river.tests.models import BasicTestModel
# noinspection PyMethodMayBeStatic
class StateFieldTest(TestCase):
def test_shouldInjectTheField(self): # pylint: disable=no-self-use
assert_that(BasicTestModel, has_property('river', is_(instance_of(RiverObject))))
assert_that(BasicTestModel.river, has_property('my_field', is_(instance_of(ClassWorkflowObject))))
content_type = ContentType.objects.get_for_model(BasicTestModel)
state1 = StateObjectFactory.create(label="state1")
state2 = StateObjectFactory.create(label="state2")
workflow = WorkflowFactory(content_type=content_type, field_name="my_field", initial_state=state1)
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0
)
test_model = BasicTestModel.objects.create()
assert_that(test_model, has_property('river', is_(instance_of(RiverObject))))
assert_that(test_model.river, has_property('my_field', is_(instance_of(InstanceWorkflowObject))))
assert_that(BasicTestModel.river.my_field, has_property('initial_state', is_(instance_of(State))))
assert_that(BasicTestModel.river.my_field, has_property('final_states', is_(instance_of(QuerySet))))
assert_that(test_model.river.my_field, has_property('approve', has_property("__call__")))
assert_that(test_model.river.my_field, has_property('on_initial_state', is_(instance_of(bool))))
assert_that(test_model.river.my_field, has_property('on_final_state', is_(instance_of(bool))))
<file_sep>.. _class_api_guide:
Class API
=========
This page will be covering the class level API. It is all the function that you can access through your model class
like in the example below;
>>> MyModel.river.my_state_field.<function>(*args)
get_on_approval_objects
-----------------------
This is the function that helps you to fetch all model objects waitig for a users approval.
>>> my_model_objects == MyModel.river.my_state_field.get_on_approval_objects(as_user=team_leader)
True
+---------+--------+---------+----------+---------------+----------------------------------------+
| | Type | Default | Optional | Format | Description |
+=========+========+=========+==========+===============+========================================+
| as_user | input | NaN | False | Django User | | A user to find all the model objects |
| | | | | | | waiting for a user's approvals |
+---------+--------+---------+----------+---------------+----------------------------------------+
| | Output | | | List<MyModel> | | List of available my model objects |
+---------+--------+---------+----------+---------------+----------------------------------------+
initial_state
-------------
This is a property that is the initial state in the workflow
>>> State.objects.get(label="open") == MyModel.river.my_state_field.initial_state
True
+--------+--------+-----------------------------------+
| Type | Format | Description |
+========+========+===================================+
| Output | State | The initial state in the workflow |
+--------+--------+-----------------------------------+
final_states
-------------
This is a property that is the list of final state in the workflow
>>> State.objects.filter(Q(label="closed") | Q(label="cancelled")) == MyModel.river.my_state_field.final_states
True
+--------+-------------+------------------------------------------+
| Type | Format | Description |
+========+=============+==========================================+
| Output | List<State> | List of the final states in the workflow |
+--------+-------------+------------------------------------------+
.. toctree::
:maxdepth: 2<file_sep>from django.contrib import admin
from django.contrib.admin import ModelAdmin
from river.tests.models import BasicTestModel
class BasicTestModelAdmin(ModelAdmin):
pass
admin.site.register(BasicTestModel, BasicTestModelAdmin)
<file_sep>from django.db import models
from django.db.models import PROTECT
from django.utils.translation import ugettext_lazy as _
from river.config import app_config
from river.models import BaseModel, State
from river.models.managers.workflowmetada import WorkflowManager
class Workflow(BaseModel):
class Meta:
app_label = 'river'
verbose_name = _("Workflow")
verbose_name_plural = _("Workflows")
unique_together = [("content_type", "field_name")]
objects = WorkflowManager()
content_type = models.ForeignKey(app_config.CONTENT_TYPE_CLASS, verbose_name=_('Content Type'), on_delete=PROTECT)
field_name = models.CharField(_("Field Name"), max_length=200)
initial_state = models.ForeignKey(State, verbose_name=_("Initial State"), related_name='workflow_this_set_as_initial_state', on_delete=PROTECT)
def natural_key(self):
return self.content_type, self.field_name
def __str__(self):
return "%s.%s" % (self.content_type.model, self.field_name)
<file_sep>django-mptt==0.9.1
factory-boy==2.11.1
mock==2.0.0
pyhamcrest==1.9.0
django-cte==1.1.4
django-codemirror2==0.2
behave-django==1.3.0<file_sep>from django_cte import CTEManager
from river.config import app_config
from river.models.managers.rivermanager import RiverManager
class TransitionApprovalManager(RiverManager if app_config.IS_MSSQL else CTEManager):
def __init__(self, *args, **kwargs):
super(TransitionApprovalManager, self).__init__(*args, **kwargs)
def filter(self, *args, **kwarg):
workflow_object = kwarg.pop('workflow_object', None)
if workflow_object:
kwarg['content_type'] = app_config.CONTENT_TYPE_CLASS.objects.get_for_model(workflow_object)
kwarg['object_id'] = workflow_object.pk
return super(TransitionApprovalManager, self).filter(*args, **kwarg)
def update_or_create(self, *args, **kwarg):
workflow_object = kwarg.pop('workflow_object', None)
if workflow_object:
kwarg['content_type'] = app_config.CONTENT_TYPE_CLASS.objects.get_for_model(workflow_object)
kwarg['object_id'] = workflow_object.pk
return super(TransitionApprovalManager, self).update_or_create(*args, **kwarg)
<file_sep>from __future__ import unicode_literals
from django.db import models
from django.db.models.signals import pre_save
from django.template.defaultfilters import slugify
try:
from django.utils.encoding import python_2_unicode_compatible
except ImportError:
from six import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from river.models.base_model import BaseModel
from river.models.managers.state import StateManager
@python_2_unicode_compatible
class State(BaseModel):
class Meta:
app_label = 'river'
verbose_name = _("State")
verbose_name_plural = _("States")
objects = StateManager()
slug = models.SlugField(unique=True, null=True, blank=True)
label = models.CharField(max_length=50)
description = models.CharField(_("Description"), max_length=200, null=True, blank=True)
def __str__(self):
return self.label
def natural_key(self):
return self.slug,
def details(self):
detail = super(State, self).details()
detail.update(
{
'label': self.label,
'description': self.description
}
)
return detail
def on_pre_save(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = slugify(instance.label)
else:
instance.slug = slugify(instance.slug)
pre_save.connect(on_pre_save, State)
<file_sep>.. _hooking_guide:
Hook it Up
==========
The hookings in ``django-river`` can be created both specifically for a workflow object or for a whole workflow. ``django-river`` comes with some model objects and admin interfaces which you can use
to create the hooks.
* To create one for whole workflow regardless of what the workflow object is, go to
* ``/admin/river/onapprovedhook/`` to hook up to an approval
* ``/admin/river/ontransithook/`` to hook up to a transition
* ``/admin/river/oncompletehook/`` to hook up to the completion of the workflow
* To create one for a specific workflow object you should use the admin interface for the workflow object itself. One amazing feature of ``django-river`` is now that
it creates a default admin interface with the hookings for your workflow model class. If you have already defined one, ``django-river`` enriches your already defined
admin with the hooking section. It is default disabled. To enable it just define ``RIVER_INJECT_MODEL_ADMIN`` to be ``True`` in the ``settings.py``.
**Note:** They can programmatically be created as well since they are model objects. If it is needed to be at workflow level, just don't provide the workflow object column. If it is needed
to be for a specific workflow object then provide it.
Here are the list of hook models;
* OnApprovedHook
* OnTransitHook
* OnCompleteHook
<file_sep>from river.tests.models import BasicTestModel, ModelWithTwoStateFields
class BasicTestModelObjectFactory(object):
def __init__(self):
self.model = BasicTestModel.objects.create(test_field="")
@staticmethod
def create_batch(size):
for i in range(size):
BasicTestModel.objects.create(test_field=i)
return BasicTestModel.objects.all()
class ModelWithTwoStateFieldsObjectFactory(object):
def __init__(self):
self.model = ModelWithTwoStateFields.objects.create()
@staticmethod
def create_batch(size):
for i in range(size):
ModelWithTwoStateFields.objects.create()
return ModelWithTwoStateFields.objects.all()
<file_sep>.. _migration_guide:
Migration Guide
=============
.. toctree::
:maxdepth: 2
migration_2_to_3
migration_31_to_32
hooking
<file_sep>from django.contrib.contenttypes.models import ContentType
from hamcrest import assert_that, equal_to, has_entry, none, has_key, has_length
from river.models.factories import PermissionObjectFactory, StateObjectFactory, WorkflowFactory, TransitionApprovalMetaFactory, UserObjectFactory, TransitionMetaFactory
from river.models.hook import AFTER
from river.tests.hooking.base_hooking_test import BaseHookingTest
from river.tests.models import BasicTestModel
from river.tests.models.factories import BasicTestModelObjectFactory
# noinspection DuplicatedCode
class CompletedHookingTest(BaseHookingTest):
def test_shouldInvokeCallbackThatIsRegisteredWithInstanceWhenFlowIsComplete(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
content_type = ContentType.objects.get_for_model(BasicTestModel)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
self.hook_post_complete(workflow, workflow_object=workflow_object.model)
assert_that(self.get_output(), none())
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state2))
assert_that(self.get_output(), none())
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state3))
output = self.get_output()
assert_that(output, has_length(1))
assert_that(output[0], has_key("hook"))
assert_that(output[0]["hook"], has_entry("type", "on-complete"))
assert_that(output[0]["hook"], has_entry("when", AFTER))
assert_that(output[0]["hook"], has_entry(
"payload",
has_entry(equal_to("workflow_object"), equal_to(workflow_object.model))
))
def test_shouldInvokeCallbackThatIsRegisteredWithoutInstanceWhenFlowIsComplete(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
content_type = ContentType.objects.get_for_model(BasicTestModel)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
self.hook_post_complete(workflow)
assert_that(self.get_output(), none())
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state2))
assert_that(self.get_output(), none())
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state3))
output = self.get_output()
assert_that(output, has_length(1))
assert_that(output[0], has_key("hook"))
assert_that(output[0]["hook"], has_entry("type", "on-complete"))
assert_that(output[0]["hook"], has_entry("when", AFTER))
assert_that(output[0]["hook"], has_entry(
"payload",
has_entry(equal_to("workflow_object"), equal_to(workflow_object.model))
))
<file_sep>.. _change_logs:
Change Logs
===========
3.2.0 (Stable):
---------------
* **Improvement** - # 140_ 141_: Support Microsoft SQL Server 17 and 19
.. _140: https://github.com/javrasya/django-river/issues/140
.. _141: https://github.com/javrasya/django-river/issues/141
3.1.4
-----
* **Bug** - # 137_: Fix a bug with jumping to a state
.. _137: https://github.com/javrasya/django-river/issues/137
3.1.3:
------
* **Improvement** - # 135_: Support Django 3.0
.. _135: https://github.com/javrasya/django-river/issues/135
3.1.2:
------
* **Improvement** - # 133_: Support MySQL 8.0
.. _133: https://github.com/javrasya/django-river/issues/133
3.1.1
-----
* **Bug** - # 128_: Available approvals are not found properly when primary key is string
* **Bug** - # 129_: Models with string typed primary keys violates integer field in the hooks
.. _128: https://github.com/javrasya/django-river/issues/128
.. _129: https://github.com/javrasya/django-river/issues/129
3.1.0
-----
* **Imrovement** - # 123_: Jump to a specific future state of a workflow object
* **Bug** - # 124_: Include some BDD tests for the users to understand the usages easier.
.. _123: https://github.com/javrasya/django-river/issues/123
.. _124: https://github.com/javrasya/django-river/issues/124
3.0.0
-----
* **Bug** - # 106_: It crashes when saving a workflow object when there is no workflow definition for a state field
* **Bug** - # 107_: next_approvals api of the instance is broken
* **Bug** - # 112_: Next approval after it cycles doesn't break the workflow anymore. Multiple cycles are working just fine.
* **Improvement** - # 108_: Status column of transition approvals are now kept as string in the DB instead of number to maintain readability and avoid mistakenly changed ordinals.
* **Improvement** - # 109_: Cancel all other peer approvals that are with different branching state.
* **Improvement** - # 110_: Introduce an iteration to keep track of the order of the transitions even the cycling ones. This comes with a migration that will assess the iteration of all of your existing approvals so far. According to the tests, 250 workflow objects that have 5 approvals each will take ~1 minutes with the slowest django `v1.11`.
* **Improvement** - # 111_: Cancel all approvals that are not part of the possible future instead of only impossible the peers when something approved and re-create the whole rest of the pipeline when it cycles
* **Improvement** - # 105_: More dynamic and better way for hooks.On the fly function and hook creations, update or delete are also supported now. It also comes with useful admin interfaces for hooks and functions. This is a huge improvement for callback lovers :-)
* **Improvement** - # 113_: Support defining an approval hook with a specific approval.
* **Improvement** - # 114_: Support defining a transition hook with a specific iteration.
* **Drop** - # 115_: Drop skipping and disabling approvals to cut the unnecessary complexity.
* **Improvement** - # 116_: Allow creating transitions without any approvals. A new TransitionMeta and Transition models are introduced to keep transition information even though there is no transition approval yet.
.. _105: https://github.com/javrasya/django-river/issues/105
.. _106: https://github.com/javrasya/django-river/issues/106
.. _107: https://github.com/javrasya/django-river/issues/107
.. _108: https://github.com/javrasya/django-river/issues/108
.. _109: https://github.com/javrasya/django-river/issues/109
.. _110: https://github.com/javrasya/django-river/issues/110
.. _111: https://github.com/javrasya/django-river/issues/110
.. _112: https://github.com/javrasya/django-river/issues/112
.. _113: https://github.com/javrasya/django-river/issues/113
.. _114: https://github.com/javrasya/django-river/issues/114
.. _115: https://github.com/javrasya/django-river/issues/115
.. _116: https://github.com/javrasya/django-river/issues/116
2.0.0
-----
* **Improvement** - [ # 90_,# 36_ ]: Finding available approvals has been speeded up ~x400 times at scale
* **Improvement** - # 92_ : It is mandatory to provide initial state by the system user to avoid confusion and possible mistakes
* **Improvement** - # 93_ : Tests are revisited, separated, simplified and easy to maintain right now
* **Improvement** - # 94_ : Support class level hooking. Meaning that, a hook can be registered for all the objects through the class api
* **Bug** - # 91_ : Callbacks get removed when the related workflow object is deleted
* **Improvement** - Whole ``django-river`` source code is revisited and simplified
* **Improvement** - Support ``Django v2.2``
* **Deprecation** - ``Django v1.7``, ``v1.8``, ``v1.9`` and ``v1.10`` supports have been dropped
.. _36: https://github.com/javrasya/django-river/issues/36
.. _90: https://github.com/javrasya/django-river/issues/90
.. _91: https://github.com/javrasya/django-river/issues/91
.. _92: https://github.com/javrasya/django-river/issues/92
.. _93: https://github.com/javrasya/django-river/issues/93
.. _94: https://github.com/javrasya/django-river/issues/94
1.0.2
-----
* **Bug** - # 77_ : Migrations for the models that have state field is no longer kept getting recreated.
* **Bug** - It is crashing when there is no workflow in the workspace.
.. _77: https://github.com/javrasya/django-river/issues/77
1.0.1
-----
* **Bug** - # 74_ : Fields that have no transition approval meta are now logged correctly.
* **Bug** - ``django`` version is now fixed to 2.1 for coverage in the build to make the build pass
.. _74: https://github.com/javrasya/django-river/issues/74
1.0.0
-----
``django-river`` is finally having it's first major version bump. In this version, all code and the APIs are revisited
and are much easier to understand how it works and much easier to use it now. In some places even more performant.
There are also more documentation with this version. Stay tuned :-)
* **Improvement** - Support ``Django2.1``
* **Improvement** - Support multiple state fields in a model
* **Improvement** - Make the API very easy and useful by accessing everything via model objects and model classes
* **Improvement** - Simplify the concepts
* **Improvement** - Migrate ProceedingMeta and Transition into TransitionApprovalMeta for simplification
* **Improvement** - Rename Proceeding as TransitionApproval
* **Improvement** - Document transition and on-complete hooks
* **Improvement** - Document transition and on-complete hooks
* **Improvement** - Imrove documents in general
* **Improvement** - Minor improvements on admin pages
* **Improvement** - Some performance improvements
0.10.0
------
* # 39_ - **Improvement** - Django has dropped support for pypy-3. So, It should be dropped from django itself too.
* **Remove** - ``pypy`` support has been dropped
* **Remove** - ``Python3.3`` support has been dropped
* **Improvement** - ``Django2.0`` support with ``Python3.5`` and ``Python3.6`` is provided
.. _39: https://github.com/javrasya/django-river/issues/39
0.9.0
-----
* # 30_ - **Bug** - Missing migration file which is ``0007`` because of ``Python2.7`` can not detect it.
* # 31_ - **Improvement** - unicode issue for Python3.
* # 33_ - **Bug** - Automatically injecting workflow manager was causing the models not have default ``objects`` one. So, automatic injection support has been dropped. If anyone want to use it, it can be used explicitly.
* # 35_ - **Bug** - This is huge change in django-river. Multiple state field each model support is dropped completely and so many APIs have been changed. Check documentations and apply changes.
.. _30: https://github.com/javrasya/django-river/pull/30
.. _31: https://github.com/javrasya/django-river/pull/30
.. _33: https://github.com/javrasya/django-river/pull/33
.. _35: https://github.com/javrasya/django-river/pull/35
0.8.2
-----
* **Bug** - Features providing multiple state field in a model was causing a problem. When there are multiple state field, injected attributes in model class are owerriten. This feature is also unpractical. So, it is dropped to fix the bug.
* **Improvement** - Initial video tutorial which is Simple jira example is added into the documentations. Also repository link of fakejira project which is created in the video tutorial is added into the docs.
* **Improvement** - No proceeding meta parent input is required by user. It is set automatically by django-river now. The field is removed from ProceedingMeta admin interface too.
0.8.1
-----
* **Bug** - ProceedingMeta form was causing a problem on migrations. Accessing content type before migrations was the problem. This is fixed by defining choices in init function instead of in field
0.8.0
-----
* **Deprecation** - ProceedingTrack is removed. ProceedingTracks were being used to keep any transaction track to handle even circular one. This was a workaround. So, it can be handled with Proceeding now by cloning them if there is circle. ProceedingTracks was just causing confusion. To fix this, ProceedingTrack model and its functions are removed from django-river.
* **Improvement** - Circular scenario test is added.
* **Improvement** - Admins of the workflow components such as State, Transition and ProceedingMeta are registered automatically now. Issue #14 is fixed.
0.7.0
-----
* **Improvement** - Python version 3.5 support is added. (not for Django1.7)
* **Improvement** - Django version 1.9 support is added. (not for Python3.3 and PyPy3)
0.6.2
-----
* **Bug** - Migration ``0002`` and ``0003`` were not working properly for postgresql (maybe oracle). For these databases, data can not be fixed. Because, django migrates each in a transactional block and schema migration and data migration can not be done in a transactional block. To fix this, data fixing and schema fixing are seperated.
* **Improvement** - Timeline section is added into documentation.
* **Improvement** - State slug field is set as slug version of its label if it is not given on saving.
0.6.1
-----
* **Bug** - After ``content_type`` and ``field`` are moved into ``ProceedingMeta`` model from ``Transition`` model in version ``0.6.0``, finding initial and final states was failing. This is fixed.
* **Bug** - ``0002`` migrations was trying to set default slug field of State model. There was a unique problem. It is fixed. ``0002`` can be migrated now.
* **Improvement** - The way of finding initial and final states is changed. ProceedingMeta now has parent-child tree structure to present state machine. This tree structure is used to define the way. This requires to migrate ``0003``. This migration will build the tree of your existed ProceedingMeta data.
0.6.0
-----
* **Improvement** - ``content_type`` and ``field`` are moved into ``ProceedingMeta`` model from ``Transition`` model. This requires to migrate ``0002``. This migrations will move value of the fields from ``Transition`` to ``ProceedingMeta``.
* **Improvement** - Slug field is added in ``State``. It is unique field to describe state. This requires to migrate ``0002``. This migration will set the field as slug version of ``label`` field value. (Re Opened -> re-opened)
* **Improvement** - ``State`` model now has ``natural_key`` as ``slug`` field.
* **Improvement** - ``Transition`` model now has ``natural_key`` as (``source_state_slug`` , ``destination_state_slug``) fields
* **Improvement** - ``ProceedingMeta`` model now has ``natural_key`` as (``content_type``, ``field``, ``transition``, ``order``) fields
* **Improvement** - Changelog is added into documentation.
0.5.3
-----
* **Bug** - Authorization was not working properly when the user has irrelevant permissions and groups. This is fixed.
* **Improvement** - User permissions are now retreived from registered authentication backends instead of ``user.user_permissions``
0.5.2
-----
* **Improvement** - Removed unnecessary models.
* **Improvement** - Migrations are added
* **Bug** - ``content_type__0002`` migrations cause failing for ``django1.7``. Dependency is removed
* **Bug** - ``DatabaseHandlerBacked`` was trying to access database on django setup. This cause ``no table in db`` error for some django commands. This was happening; because there is no db created before some commands are executed; like ``makemigrations``, ``migrate``.
0.5.1
-----
* **Improvement** - Example scenario diagrams are added into documentation.
* **Bug** - Migrations was failing because of injected ``ProceedingTrack`` relation. Relation is not injected anymore. But property ``proceeing_track`` remains. It still returns current one.
<file_sep>class RiverException(Exception):
code = None
def __init__(self, error_code, *args, **kwargs):
super(RiverException, self).__init__(*args, **kwargs)
self.code = error_code
<file_sep>Authorization
=============
``django-river`` provides system users an ability to configure the authorizations at three level. Those are permissions, user group or a specific user at any step. If the
user is not authorized, they are not entitled to see and approve those approvals. These three authorization mechanisms are also not blocking each other. An authorized user
by any of them is entitled to see and approve the approvals.
Permission Based Authorization
""""""""""""""""""""""""""""""
Multiple permission can be specified on the `transition approval metadata` admin page and ``django-river`` will allow only the users who have the given permission.
Given multiple permissions are issued in ``OR`` fashion meaning that it is enough to have one of the given permissions to be authorized for the user. This can be
configurable on the admin page provided by `django-river`
User Group Based Authorization
""""""""""""""""""""""""""""""
Multiple user group can be specified on the `transition approval metadata` admin page and ``django-river`` will allow only the users who are in the given user groups.
Like permission based authorization, given multiple user groups are issued in ``OR`` fashion meaning that it is enough to be in one of the given user groups to be
authorized for the user.This can be configurable on the admin page provided by `django-river`
User Based Authorization
""""""""""""""""""""""""
Only one specific user can be assigned and no matter what permissions the user has or what user groups the user is in, the user will be authorized. Unlike the other
methods, ``django-river`` doesn't provide an admin interface for that. But this can be handled within the repositories that is using `django-river`. The way how to do
this is basically setting the ``transactioner`` column of the related ``TransitionApproval`` object as the user who is wanted to be authorized on this approval either
programmatically or through a third party admin page on this model.
<file_sep>from time import sleep
from uuid import uuid4
import pyodbc
from .base import *
DB_DRIVER = 'ODBC Driver 17 for SQL Server'
DB_HOST = os.environ['MCR_MICROSOFT_COM_MSSQL_SERVER_HOST']
DB_PORT = os.environ['MCR_MICROSOFT_COM_MSSQL_SERVER_1433_TCP']
DB_USER = 'sa'
DB_PASSWORD = '<PASSWORD>'
sleep(10)
db_connection = pyodbc.connect(f"DRIVER={DB_DRIVER};SERVER={DB_HOST},{DB_PORT};DATABASE=master;UID={DB_USER};PWD={DB_PASSWORD}", autocommit=True)
cursor = db_connection.cursor()
cursor.execute(
"""
If(db_id(N'river') IS NULL)
BEGIN
CREATE DATABASE river
END;
""")
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'river',
'USER': DB_USER,
'PASSWORD': <PASSWORD>,
'HOST': DB_HOST,
'PORT': DB_PORT,
'TEST': {
'NAME': 'river' + str(uuid4()),
},
'OPTIONS': {
'driver': DB_DRIVER
},
}
}
INSTALLED_APPS += (
'river.tests',
)
if django.get_version() >= '1.9.0':
MIGRATION_MODULES = DisableMigrations()
<file_sep>class ErrorCode(object):
NO_AVAILABLE_INITIAL_STATE = 1
NO_AVAILABLE_FINAL_STATE = 2
MULTIPLE_INITIAL_STATE = 3
NO_AVAILABLE_NEXT_STATE_FOR_USER = 4
INVALID_NEXT_STATE_FOR_USER = 5
NEXT_STATE_IS_REQUIRED = 6
MULTIPLE_STATE_FIELDS = 7
NO_STATE_FIELD = 8
ALREADY_SKIPPED = 9
STATE_IS_NOT_AVAILABLE_TO_BE_JUMPED = 10
<file_sep>import inspect
import re
from django.db import models
from django.db.models.signals import pre_save
from django.utils.translation import ugettext_lazy as _
from river.models import BaseModel
loaded_functions = {}
class Function(BaseModel):
name = models.CharField(verbose_name=_("Function Name"), max_length=200, unique=True, null=False, blank=False)
body = models.TextField(verbose_name=_("Function Body"), max_length=100000, null=False, blank=False)
version = models.IntegerField(verbose_name=_("Function Version"), default=0)
def __str__(self):
return "%s - %s" % (self.name, "v%s" % self.version)
def get(self):
func = loaded_functions.get(self.name, None)
if not func or func["version"] != self.version:
func = {"function": self._load(), "version": self.version}
loaded_functions[self.pk] = func
return func["function"]
def _load(self):
func_body = "def _wrapper(context):\n"
for line in self.body.split("\n"):
func_body += "\t" + line + "\n"
func_body += "\thandle(context)\n"
exec(func_body)
return eval("_wrapper")
def on_pre_save(sender, instance, *args, **kwargs):
instance.version += 1
pre_save.connect(on_pre_save, Function)
def _normalize_callback(callback):
callback_str = inspect.getsource(callback).replace("def %s(" % callback.__name__, "def handle(")
space_size = callback_str.index('def handle(')
return re.sub(r'^\s{%s}' % space_size, '', inspect.getsource(callback).replace("def %s(" % callback.__name__, "def handle("))
def create_function(callback):
return Function.objects.get_or_create(
name=callback.__module__ + "." + callback.__name__,
body=_normalize_callback(callback)
)[0]
<file_sep>from uuid import uuid4
from .base import *
DB_HOST = os.environ['MYSQL_HOST']
DB_PORT = os.environ['MYSQL_3306_TCP_PORT']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'river',
'USER': 'root',
'PASSWORD': '<PASSWORD>',
'HOST': DB_HOST,
'PORT': DB_PORT,
'TEST': {
'NAME': 'river' + str(uuid4()),
},
}
}
INSTALLED_APPS += (
'river.tests',
)
if django.get_version() >= '1.9.0':
MIGRATION_MODULES = DisableMigrations()
<file_sep>from uuid import uuid4
from django.db import models
from river.models.fields.state import StateField
class BasicTestModel(models.Model):
test_field = models.CharField(max_length=50, null=True, blank=True)
my_field = StateField()
class BasicTestModelWithoutAdmin(models.Model):
test_field = models.CharField(max_length=50, null=True, blank=True)
my_field = StateField()
class ModelWithoutStateField(models.Model):
test_field = models.CharField(max_length=50, null=True, blank=True)
class ModelForSlowCase1(models.Model):
status = StateField()
class ModelForSlowCase2(models.Model):
status = StateField()
class ModelWithTwoStateFields(models.Model):
status1 = StateField()
status2 = StateField()
class ModelWithStringPrimaryKey(models.Model):
custom_pk = models.CharField(max_length=200, primary_key=True, default=uuid4())
status = StateField()
<file_sep>import os
import django
from behave import register_type
from django.core import management
os.environ["DJANGO_SETTINGS_MODULE"] = "settings.with_sqlite3"
def before_all(context):
django.setup()
def before_scenario(context, scenario):
management.call_command('flush', interactive=False)
def parse_string_with_whitespace(text):
return text
def parse_list(text):
return [better_item.strip() for item in text.split(" or ") for better_item in item.split(" and ")]
# -- REGISTER: User-defined type converter (parse_type).
register_type(ws=parse_string_with_whitespace)
register_type(list=parse_list)
<file_sep>from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from hamcrest import assert_that, equal_to, has_item, has_property, raises, calling, has_length, is_not, all_of, none, has_items
from river.models import TransitionApproval, PENDING, CANCELLED, APPROVED, Transition, JUMPED
from river.models.factories import UserObjectFactory, StateObjectFactory, TransitionApprovalMetaFactory, PermissionObjectFactory, WorkflowFactory, \
TransitionMetaFactory
from river.tests.matchers import has_permission, has_transition
from river.tests.models import BasicTestModel, ModelWithTwoStateFields, ModelWithStringPrimaryKey
from river.tests.models.factories import BasicTestModelObjectFactory, ModelWithTwoStateFieldsObjectFactory
from river.utils.exceptions import RiverException
# noinspection PyMethodMayBeStatic,DuplicatedCode
class InstanceApiTest(TestCase):
def __init__(self, *args, **kwargs):
super(InstanceApiTest, self).__init__(*args, **kwargs)
self.content_type = ContentType.objects.get_for_model(BasicTestModel)
def test_shouldNotReturnOtherObjectsApprovalsForTheAuthorizedUser(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
workflow_object1 = BasicTestModelObjectFactory()
workflow_object2 = BasicTestModelObjectFactory()
available_approvals = workflow_object1.model.river.my_field.get_available_approvals(as_user=authorized_user)
assert_that(available_approvals, has_length(1))
assert_that(list(available_approvals), has_item(
has_property("workflow_object", workflow_object1.model)
))
assert_that(list(available_approvals), has_item(
is_not(has_property("workflow_object", workflow_object2.model))
))
def test_shouldNotAllowUnauthorizedUserToProceedToNextState(self):
unauthorized_user = UserObjectFactory()
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
authorized_permission = PermissionObjectFactory()
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(
calling(workflow_object.model.river.my_field.approve).with_args(as_user=unauthorized_user),
raises(RiverException, "There is no available approval for the user")
)
def test_shouldAllowAuthorizedUserToProceedToNextState(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state2))
def test_shouldNotLetUserWhosePriorityComesLaterApproveProceed(self):
manager_permission = PermissionObjectFactory()
team_leader_permission = PermissionObjectFactory()
manager = UserObjectFactory(user_permissions=[manager_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=1,
permissions=[manager_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[team_leader_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(
calling(workflow_object.model.river.my_field.approve).with_args(as_user=manager),
raises(RiverException, "There is no available approval for the user")
)
def test_shouldNotTransitToNextStateWhenThereAreMultipleApprovalsToBeApproved(self):
manager_permission = PermissionObjectFactory()
team_leader_permission = PermissionObjectFactory()
team_leader = UserObjectFactory(user_permissions=[team_leader_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=1,
permissions=[manager_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[team_leader_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(team_leader)
assert_that(workflow_object.model.my_field, equal_to(state1))
def test_shouldTransitToNextStateWhenAppTheApprovalsAreApprovedBeApproved(self):
manager_permission = PermissionObjectFactory()
team_leader_permission = PermissionObjectFactory()
manager = UserObjectFactory(user_permissions=[manager_permission])
team_leader = UserObjectFactory(user_permissions=[team_leader_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=1,
permissions=[manager_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[team_leader_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(team_leader)
assert_that(workflow_object.model.my_field, equal_to(state1))
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(manager)
assert_that(workflow_object.model.my_field, equal_to(state2))
def test_shouldDictatePassingNextStateWhenThereAreMultiple(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(
calling(workflow_object.model.river.my_field.approve).with_args(as_user=authorized_user),
raises(RiverException, "State must be given when there are multiple states for destination")
)
def test_shouldTransitToTheGivenNextStateWhenThereAreMultipleNextStates(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=state3)
assert_that(workflow_object.model.my_field, equal_to(state3))
def test_shouldNotAcceptANextStateWhichIsNotAmongPossibleNextStates(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
invalid_state = StateObjectFactory(label="state4")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(
calling(workflow_object.model.river.my_field.approve).with_args(as_user=authorized_user, next_state=invalid_state),
raises(RiverException,
"Invalid state is given\(%s\). Valid states is\(are\) (%s|%s)" % (
invalid_state.label,
",".join([state2.label, state3.label]),
",".join([state3.label, state2.label]))
)
)
def test_shouldAllowCyclicTransitions(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
cycle_state_1 = StateObjectFactory(label="cycle_state_1")
cycle_state_2 = StateObjectFactory(label="cycle_state_2")
cycle_state_3 = StateObjectFactory(label="cycle_state_3")
off_the_cycle_state = StateObjectFactory(label="off_the_cycle_state")
final_state = StateObjectFactory(label="final_state")
workflow = WorkflowFactory(initial_state=cycle_state_1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_1,
destination_state=cycle_state_2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_2,
destination_state=cycle_state_3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_3,
destination_state=cycle_state_1,
)
transition_meta_4 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_3,
destination_state=off_the_cycle_state,
)
transition_meta_5 = TransitionMetaFactory.create(
workflow=workflow,
source_state=off_the_cycle_state,
destination_state=final_state,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_4,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_5,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_2))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_3))
transitions = Transition.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(transitions, has_length(5))
approvals = TransitionApproval.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(approvals, has_length(5))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_1, cycle_state_2, iteration=0),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_2, cycle_state_3, iteration=1),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, cycle_state_1, iteration=2),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, off_the_cycle_state, iteration=2),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(off_the_cycle_state, final_state, iteration=3),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=cycle_state_1)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
transitions = Transition.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(transitions, has_length(10))
approvals = TransitionApproval.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(approvals, has_length(10))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_1, cycle_state_2, iteration=0),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_2, cycle_state_3, iteration=1),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, cycle_state_1, iteration=2),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, off_the_cycle_state, iteration=2),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", CANCELLED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(off_the_cycle_state, final_state, iteration=3),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", CANCELLED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_1, cycle_state_2, iteration=3),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_2, cycle_state_3, iteration=4),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, cycle_state_1, iteration=5),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, off_the_cycle_state, iteration=5),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(off_the_cycle_state, final_state, iteration=6),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
def test_shouldHandleSecondCycleProperly(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
cycle_state_1 = StateObjectFactory(label="cycle_state_1")
cycle_state_2 = StateObjectFactory(label="cycle_state_2")
cycle_state_3 = StateObjectFactory(label="cycle_state_3")
off_the_cycle_state = StateObjectFactory(label="off_the_cycle_state")
final_state = StateObjectFactory(label="final_state")
workflow = WorkflowFactory(initial_state=cycle_state_1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_1,
destination_state=cycle_state_2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_2,
destination_state=cycle_state_3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_3,
destination_state=cycle_state_1,
)
transition_meta_4 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_3,
destination_state=off_the_cycle_state,
)
transition_meta_5 = TransitionMetaFactory.create(
workflow=workflow,
source_state=off_the_cycle_state,
destination_state=final_state,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_4,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_5,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_2))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_3))
transitions = Transition.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(transitions, has_length(5))
approvals = TransitionApproval.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(approvals, has_length(5))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_1, cycle_state_2, iteration=0),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_2, cycle_state_3, iteration=1),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, cycle_state_1, iteration=2),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, off_the_cycle_state, iteration=2),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(off_the_cycle_state, final_state, iteration=3),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=cycle_state_1)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_2))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_3))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=cycle_state_1)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
approvals = TransitionApproval.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(approvals, has_length(15))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_1, cycle_state_2, iteration=0),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_2, cycle_state_3, iteration=1),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, cycle_state_1, iteration=2),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, off_the_cycle_state, iteration=2),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", CANCELLED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(off_the_cycle_state, final_state, iteration=3),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", CANCELLED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_1, cycle_state_2, iteration=3),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_2, cycle_state_3, iteration=4),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, cycle_state_1, iteration=5),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", APPROVED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, off_the_cycle_state, iteration=5),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", CANCELLED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(off_the_cycle_state, final_state, iteration=6),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", CANCELLED),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_1, cycle_state_2, iteration=6),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_2, cycle_state_3, iteration=7),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, cycle_state_1, iteration=8),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(cycle_state_3, off_the_cycle_state, iteration=8),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
assert_that(approvals, has_item(
all_of(
has_transition(off_the_cycle_state, final_state, iteration=9),
has_permission("permissions", has_length(1)),
has_permission("permissions", has_item(authorized_permission)),
has_property("status", PENDING),
)
))
def test__shouldHandleUndefinedSecondWorkflowCase(self):
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
content_type = ContentType.objects.get_for_model(ModelWithTwoStateFields)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="status1")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
)
workflow_object = ModelWithTwoStateFieldsObjectFactory()
assert_that(workflow_object.model.status1, equal_to(state1))
assert_that(workflow_object.model.status2, none())
def test__shouldReturnNextApprovals(self):
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state3,
)
meta1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
)
meta2 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
next_approvals = workflow_object.model.river.my_field.next_approvals
assert_that(next_approvals, has_length(2))
assert_that(next_approvals, has_item(meta1.transition_approvals.first()))
assert_that(next_approvals, has_item(meta2.transition_approvals.first()))
def test_shouldCancelAllOtherStateTransition(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
state4 = StateObjectFactory(label="state4")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state4,
)
meta1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
meta2 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
meta3 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=state3)
assert_that(workflow_object.model.my_field, equal_to(state3))
assert_that(
meta2.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", APPROVED))
)
),
assert_that(
meta1.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", CANCELLED))
)
),
assert_that(
meta3.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", CANCELLED))
)
)
def test_shouldCancelAllOtherStateTransitionDescendants(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
state4 = StateObjectFactory(label="state4")
state5 = StateObjectFactory(label="state5")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state4,
)
transition_meta_4 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state4,
destination_state=state5,
)
meta1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
meta2 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
meta3 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0,
permissions=[authorized_permission]
)
meta4 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_4,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=state3)
assert_that(workflow_object.model.my_field, equal_to(state3))
assert_that(
meta2.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", APPROVED))
)
),
assert_that(
meta1.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", CANCELLED))
)
),
assert_that(
meta3.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", CANCELLED))
)
)
assert_that(
meta4.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", CANCELLED))
)
)
def test_shouldNotCancelDescendantsIfItIsPartOfPossibleFuture(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
first_state = StateObjectFactory(label="first")
diamond_left_state_1 = StateObjectFactory(label="diamond-left-1")
diamond_left_state_2 = StateObjectFactory(label="diamond-left-2")
diamond_right_state_1 = StateObjectFactory(label="diamond-right-1")
diamond_right_state_2 = StateObjectFactory(label="diamond-right-2")
diamond_join_state = StateObjectFactory(label="diamond-join")
final_state = StateObjectFactory(label="final")
workflow = WorkflowFactory(initial_state=first_state, content_type=self.content_type, field_name="my_field")
first_to_left_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=first_state,
destination_state=diamond_left_state_1,
)
first_to_right_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=first_state,
destination_state=diamond_right_state_1,
)
left_follow_up_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=diamond_left_state_1,
destination_state=diamond_left_state_2,
)
right_follow_up_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=diamond_right_state_1,
destination_state=diamond_right_state_2,
)
left_join_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=diamond_left_state_2,
destination_state=diamond_join_state
)
right_join_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=diamond_right_state_2,
destination_state=diamond_join_state
)
join_to_final_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=diamond_join_state,
destination_state=final_state
)
first_to_left = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=first_to_left_transition,
priority=0,
permissions=[authorized_permission]
)
first_to_right = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=first_to_right_transition,
priority=0,
permissions=[authorized_permission]
)
left_follow_up = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=left_follow_up_transition,
priority=0,
permissions=[authorized_permission]
)
right_follow_up = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=right_follow_up_transition,
priority=0,
permissions=[authorized_permission]
)
left_join = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=left_join_transition,
priority=0,
permissions=[authorized_permission]
)
right_join = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=right_join_transition,
priority=0,
permissions=[authorized_permission]
)
join_to_final = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=join_to_final_transition,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(first_state))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=diamond_left_state_1)
assert_that(workflow_object.model.my_field, equal_to(diamond_left_state_1))
assert_that(
first_to_left.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", APPROVED))
)
),
assert_that(
left_follow_up.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", PENDING))
)
)
assert_that(
left_join.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", PENDING))
)
)
assert_that(
first_to_right.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", CANCELLED))
)
),
assert_that(
right_follow_up.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", CANCELLED))
)
)
assert_that(
right_join.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", CANCELLED))
)
)
assert_that(
join_to_final.transition_approvals.all(),
all_of(
has_length(1),
has_item(has_property("status", PENDING))
)
)
def test_shouldAssessIterationsCorrectly(self):
authorized_permission1 = PermissionObjectFactory()
authorized_permission2 = PermissionObjectFactory()
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
meta1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission1]
)
meta2 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission1]
)
meta3 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=1,
permissions=[authorized_permission2]
)
workflow_object = BasicTestModelObjectFactory()
approvals = TransitionApproval.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(approvals, has_length(3))
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta1),
has_transition(state1, state2, iteration=0)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta2),
has_transition(state2, state3, iteration=1),
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta3),
has_transition(state2, state3, iteration=1),
)
)
)
def test_shouldAssessIterationsCorrectlyWhenCycled(self):
authorized_permission1 = PermissionObjectFactory()
authorized_permission2 = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission1, authorized_permission2])
cycle_state_1 = StateObjectFactory(label="cycle_state_1")
cycle_state_2 = StateObjectFactory(label="cycle_state_2")
cycle_state_3 = StateObjectFactory(label="cycle_state_3")
off_the_cycle_state = StateObjectFactory(label="off_the_cycle_state")
final_state = StateObjectFactory(label="final_state")
workflow = WorkflowFactory(initial_state=cycle_state_1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_1,
destination_state=cycle_state_2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_2,
destination_state=cycle_state_3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_3,
destination_state=cycle_state_1,
)
transition_meta_4 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_3,
destination_state=off_the_cycle_state,
)
transition_meta_5 = TransitionMetaFactory.create(
workflow=workflow,
source_state=off_the_cycle_state,
destination_state=final_state,
)
meta_1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission1]
)
meta_21 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission1]
)
meta_22 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=1,
permissions=[authorized_permission2]
)
meta_3 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0,
permissions=[authorized_permission1]
)
meta_4 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_4,
priority=0,
permissions=[authorized_permission1]
)
final_meta = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_5,
priority=0,
permissions=[authorized_permission1]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_2))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_2))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_3))
approvals = TransitionApproval.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(approvals, has_length(6))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=cycle_state_1)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
approvals = TransitionApproval.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(approvals, has_length(12))
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_1),
has_transition(cycle_state_1, cycle_state_2, iteration=0)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_21),
has_transition(cycle_state_2, cycle_state_3, iteration=1)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_22),
has_transition(cycle_state_2, cycle_state_3, iteration=1)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_3),
has_transition(cycle_state_3, cycle_state_1, iteration=2)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_4),
has_transition(cycle_state_3, off_the_cycle_state, iteration=2)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", final_meta),
has_transition(off_the_cycle_state, final_state, iteration=3)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_1),
has_transition(cycle_state_1, cycle_state_2, iteration=3)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_21),
has_transition(cycle_state_2, cycle_state_3, iteration=4)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_22),
has_transition(cycle_state_2, cycle_state_3, iteration=4)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_3),
has_transition(cycle_state_3, cycle_state_1, iteration=5)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", meta_4),
has_transition(cycle_state_3, off_the_cycle_state, iteration=5)
)
)
)
assert_that(
approvals, has_item(
all_of(
has_property("meta", final_meta),
has_transition(off_the_cycle_state, final_state, iteration=6)
)
)
)
def test_shouldJumpToASpecificState(self):
authorized_permission = PermissionObjectFactory()
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
transition_approval_meta_1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
transition_approval_meta_2 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
assert_that(
Transition.objects.filter(workflow_object=workflow_object.model),
has_items(
all_of(
has_property("status", PENDING),
has_property("meta", transition_meta_1),
),
all_of(
has_property("status", PENDING),
has_property("meta", transition_meta_2),
)
)
)
assert_that(
TransitionApproval.objects.filter(workflow_object=workflow_object.model),
has_items(
all_of(
has_property("status", PENDING),
has_property("meta", transition_approval_meta_1),
),
all_of(
has_property("status", PENDING),
has_property("meta", transition_approval_meta_2),
)
)
)
workflow_object.model.river.my_field.jump_to(state3)
assert_that(workflow_object.model.my_field, equal_to(state3))
assert_that(
Transition.objects.filter(workflow_object=workflow_object.model),
has_items(
all_of(
has_property("status", JUMPED),
has_property("meta", transition_meta_1),
),
all_of(
has_property("status", JUMPED),
has_property("meta", transition_meta_2),
)
)
)
assert_that(
TransitionApproval.objects.filter(workflow_object=workflow_object.model),
has_items(
all_of(
has_property("status", JUMPED),
has_property("meta", transition_approval_meta_1),
),
all_of(
has_property("status", JUMPED),
has_property("meta", transition_approval_meta_2),
)
)
)
def test_shouldNotJumpBackToAPreviousState(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=state2)
assert_that(
calling(workflow_object.model.river.my_field.jump_to).with_args(state1),
raises(RiverException, "This state is not available to be jumped in the future of this object")
)
def test_shouldJumpToASpecificStateWhenThereAreMultipleNextState(self):
authorized_permission = PermissionObjectFactory()
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
workflow = WorkflowFactory(initial_state=state1, content_type=self.content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state3,
)
transition_approval_meta_1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
transition_approval_meta_2 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(state1))
assert_that(
Transition.objects.filter(workflow_object=workflow_object.model),
has_items(
all_of(
has_property("status", PENDING),
has_property("meta", transition_meta_1),
),
all_of(
has_property("status", PENDING),
has_property("meta", transition_meta_2),
)
)
)
assert_that(
TransitionApproval.objects.filter(workflow_object=workflow_object.model),
has_items(
all_of(
has_property("status", PENDING),
has_property("meta", transition_approval_meta_1),
),
all_of(
has_property("status", PENDING),
has_property("meta", transition_approval_meta_2),
)
)
)
workflow_object.model.river.my_field.jump_to(state3)
assert_that(workflow_object.model.my_field, equal_to(state3))
assert_that(
Transition.objects.filter(workflow_object=workflow_object.model),
has_items(
all_of(
has_property("status", JUMPED),
has_property("meta", transition_meta_1),
),
all_of(
has_property("status", JUMPED),
has_property("meta", transition_meta_2),
)
)
)
assert_that(
TransitionApproval.objects.filter(workflow_object=workflow_object.model),
has_items(
all_of(
has_property("status", JUMPED),
has_property("meta", transition_approval_meta_1),
),
all_of(
has_property("status", JUMPED),
has_property("meta", transition_approval_meta_2),
)
)
)
def test_shouldNotCrashWhenAModelObjectWithStringPrimaryKeyIsApproved(self):
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
content_type = ContentType.objects.get_for_model(ModelWithStringPrimaryKey)
authorized_permission = PermissionObjectFactory(content_type=content_type)
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="status")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0,
permissions=[authorized_permission]
)
workflow_object = ModelWithStringPrimaryKey.objects.create()
assert_that(workflow_object.status, equal_to(state1))
workflow_object.river.status.approve(as_user=authorized_user)
assert_that(workflow_object.status, equal_to(state2))
<file_sep>import logging
import six
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from django.db.models import Q, Max
from django.db.transaction import atomic
from django.utils import timezone
from river.config import app_config
from river.models import TransitionApproval, PENDING, State, APPROVED, Workflow, CANCELLED, Transition, DONE, JUMPED
from river.signals import ApproveSignal, TransitionSignal, OnCompleteSignal
from river.utils.error_code import ErrorCode
from river.utils.exceptions import RiverException
LOGGER = logging.getLogger(__name__)
class InstanceWorkflowObject(object):
def __init__(self, workflow_object, field_name):
self.class_workflow = getattr(workflow_object.__class__.river, field_name)
self.workflow_object = workflow_object
self.content_type = app_config.CONTENT_TYPE_CLASS.objects.get_for_model(self.workflow_object)
self.field_name = field_name
self.workflow = Workflow.objects.filter(content_type=self.content_type, field_name=self.field_name).first()
self.initialized = False
@transaction.atomic
def initialize_approvals(self):
if not self.initialized:
if self.workflow and self.workflow.transition_approvals.filter(workflow_object=self.workflow_object).count() == 0:
transition_meta_list = self.workflow.transition_metas.filter(source_state=self.workflow.initial_state)
iteration = 0
processed_transitions = []
while transition_meta_list:
for transition_meta in transition_meta_list:
transition = Transition.objects.create(
workflow=self.workflow,
workflow_object=self.workflow_object,
source_state=transition_meta.source_state,
destination_state=transition_meta.destination_state,
meta=transition_meta,
iteration=iteration
)
for transition_approval_meta in transition_meta.transition_approval_meta.all():
transition_approval = TransitionApproval.objects.create(
workflow=self.workflow,
workflow_object=self.workflow_object,
transition=transition,
priority=transition_approval_meta.priority,
meta=transition_approval_meta
)
transition_approval.permissions.add(*transition_approval_meta.permissions.all())
transition_approval.groups.add(*transition_approval_meta.groups.all())
processed_transitions.append(transition_meta.pk)
transition_meta_list = self.workflow.transition_metas.filter(
source_state__in=transition_meta_list.values_list("destination_state", flat=True)
).exclude(pk__in=processed_transitions)
iteration += 1
self.initialized = True
LOGGER.debug("Transition approvals are initialized for the workflow object %s" % self.workflow_object)
@property
def on_initial_state(self):
return self.get_state() == self.class_workflow.initial_state
@property
def on_final_state(self):
return self.class_workflow.final_states.filter(pk=self.get_state().pk).count() > 0
@property
def next_approvals(self):
transitions = Transition.objects.filter(workflow=self.workflow, object_id=self.workflow_object.pk, source_state=self.get_state())
return TransitionApproval.objects.filter(transition__in=transitions)
@property
def recent_approval(self):
try:
return getattr(self.workflow_object, self.field_name + "_transition_approvals").filter(transaction_date__isnull=False).latest('transaction_date')
except TransitionApproval.DoesNotExist:
return None
@transaction.atomic
def jump_to(self, state):
def _transitions_before(iteration):
return Transition.objects.filter(workflow=self.workflow, workflow_object=self.workflow_object, iteration__lte=iteration)
try:
recent_iteration = self.recent_approval.transition.iteration if self.recent_approval else 0
jumped_transition = getattr(self.workflow_object, self.field_name + "_transitions").filter(
iteration__gte=recent_iteration, destination_state=state, status=PENDING
).earliest("iteration")
jumped_transitions = _transitions_before(jumped_transition.iteration).filter(status=PENDING)
for approval in TransitionApproval.objects.filter(pk__in=jumped_transitions.values_list("transition_approvals__pk", flat=True)):
approval.status = JUMPED
approval.save()
jumped_transitions.update(status=JUMPED)
self.set_state(state)
self.workflow_object.save()
except Transition.DoesNotExist:
raise RiverException(ErrorCode.STATE_IS_NOT_AVAILABLE_TO_BE_JUMPED, "This state is not available to be jumped in the future of this object")
def get_available_states(self, as_user=None):
all_destination_state_ids = self.get_available_approvals(as_user=as_user).values_list('transition__destination_state', flat=True)
return State.objects.filter(pk__in=all_destination_state_ids)
def get_available_approvals(self, as_user=None, destination_state=None):
qs = self.class_workflow.get_available_approvals(as_user, ).filter(object_id=self.workflow_object.pk)
if destination_state:
qs = qs.filter(transition__destination_state=destination_state)
return qs
@atomic
def approve(self, as_user, next_state=None):
available_approvals = self.get_available_approvals(as_user=as_user)
number_of_available_approvals = available_approvals.count()
if number_of_available_approvals == 0:
raise RiverException(ErrorCode.NO_AVAILABLE_NEXT_STATE_FOR_USER, "There is no available approval for the user.")
elif next_state:
available_approvals = available_approvals.filter(transition__destination_state=next_state)
if available_approvals.count() == 0:
available_states = self.get_available_states(as_user)
raise RiverException(ErrorCode.INVALID_NEXT_STATE_FOR_USER, "Invalid state is given(%s). Valid states is(are) %s" % (
next_state.__str__(), ','.join([ast.__str__() for ast in available_states])))
elif number_of_available_approvals > 1 and not next_state:
raise RiverException(ErrorCode.NEXT_STATE_IS_REQUIRED, "State must be given when there are multiple states for destination")
approval = available_approvals.first()
approval.status = APPROVED
approval.transactioner = as_user
approval.transaction_date = timezone.now()
approval.previous = self.recent_approval
approval.save()
if next_state:
self.cancel_impossible_future(approval)
has_transit = False
if approval.peers.filter(status=PENDING).count() == 0:
approval.transition.status = DONE
approval.transition.save()
previous_state = self.get_state()
self.set_state(approval.transition.destination_state)
has_transit = True
if self._check_if_it_cycled(approval.transition):
self._re_create_cycled_path(approval.transition)
LOGGER.debug("Workflow object %s is proceeded for next transition. Transition: %s -> %s" % (
self.workflow_object, previous_state, self.get_state()))
with self._approve_signal(approval), self._transition_signal(has_transit, approval), self._on_complete_signal():
self.workflow_object.save()
@atomic
def cancel_impossible_future(self, approved_approval):
transition = approved_approval.transition
qs = Q(
workflow=self.workflow,
object_id=self.workflow_object.pk,
iteration=transition.iteration,
source_state=transition.source_state,
) & ~Q(destination_state=transition.destination_state)
transitions = Transition.objects.filter(qs)
iteration = transition.iteration + 1
cancelled_transitions_qs = Q(pk=-1)
while transitions:
cancelled_transitions_qs = cancelled_transitions_qs | qs
qs = Q(
workflow=self.workflow,
object_id=self.workflow_object.pk,
iteration=iteration,
source_state__pk__in=transitions.values_list("destination_state__pk", flat=True)
)
transitions = Transition.objects.filter(qs)
iteration += 1
uncancelled_transitions_qs = Q(pk=-1)
qs = Q(
workflow=self.workflow,
object_id=self.workflow_object.pk,
iteration=transition.iteration,
source_state=transition.source_state,
destination_state=transition.destination_state
)
transitions = Transition.objects.filter(qs)
iteration = transition.iteration + 1
while transitions:
uncancelled_transitions_qs = uncancelled_transitions_qs | qs
qs = Q(
workflow=self.workflow,
object_id=self.workflow_object.pk,
iteration=iteration,
source_state__pk__in=transitions.values_list("destination_state__pk", flat=True),
status=PENDING
)
transitions = Transition.objects.filter(qs)
iteration += 1
actual_cancelled_transitions = Transition.objects.select_for_update(nowait=True).filter(cancelled_transitions_qs & ~uncancelled_transitions_qs)
for actual_cancelled_transition in actual_cancelled_transitions:
actual_cancelled_transition.status = CANCELLED
actual_cancelled_transition.save()
TransitionApproval.objects.filter(transition__in=actual_cancelled_transitions).update(status=CANCELLED)
def _approve_signal(self, approval):
return ApproveSignal(self.workflow_object, self.field_name, approval)
def _transition_signal(self, has_transit, approval):
return TransitionSignal(has_transit, self.workflow_object, self.field_name, approval)
def _on_complete_signal(self):
return OnCompleteSignal(self.workflow_object, self.field_name)
@property
def _content_type(self):
return ContentType.objects.get_for_model(self.workflow_object)
def _to_key(self, source_state):
return str(self.content_type.pk) + self.field_name + source_state.label
def _check_if_it_cycled(self, done_transition):
qs = Transition.objects.filter(
workflow_object=self.workflow_object,
workflow=self.class_workflow.workflow,
source_state=done_transition.destination_state
)
return qs.filter(status=DONE).count() > 0 and qs.filter(status=PENDING).count() == 0
def _get_transition_images(self, source_states):
meta_max_iteration = Transition.objects.filter(
workflow=self.workflow,
workflow_object=self.workflow_object,
source_state__pk__in=source_states,
).values_list("meta").annotate(max_iteration=Max("iteration"))
return Transition.objects.filter(
Q(workflow=self.workflow, object_id=self.workflow_object.pk) &
six.moves.reduce(lambda agg, q: q | agg, [Q(meta__id=meta_id, iteration=max_iteration) for meta_id, max_iteration in meta_max_iteration], Q(pk=-1))
)
def _re_create_cycled_path(self, done_transition):
old_transitions = self._get_transition_images([done_transition.destination_state.pk])
iteration = done_transition.iteration + 1
while old_transitions:
for old_transition in old_transitions:
cycled_transition = Transition.objects.create(
source_state=old_transition.source_state,
destination_state=old_transition.destination_state,
workflow=old_transition.workflow,
object_id=old_transition.workflow_object.pk,
content_type=old_transition.content_type,
status=PENDING,
iteration=iteration,
meta=old_transition.meta
)
for old_approval in old_transition.transition_approvals.all():
cycled_approval = TransitionApproval.objects.create(
transition=cycled_transition,
workflow=old_approval.workflow,
object_id=old_approval.workflow_object.pk,
content_type=old_approval.content_type,
priority=old_approval.priority,
status=PENDING,
meta=old_approval.meta
)
cycled_approval.permissions.set(old_approval.permissions.all())
cycled_approval.groups.set(old_approval.groups.all())
old_transitions = self._get_transition_images(old_transitions.values_list("destination_state__pk", flat=True)).exclude(
source_state=done_transition.destination_state)
iteration += 1
def get_state(self):
return getattr(self.workflow_object, self.field_name)
def set_state(self, state):
return setattr(self.workflow_object, self.field_name, state)
<file_sep>_author_ = 'ahmetdal'<file_sep>from django import forms
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType
from river.core.workflowregistry import workflow_registry
from river.models import Workflow
def get_workflow_choices():
class_by_id = lambda cid: workflow_registry.class_index[cid]
result = []
for class_id, field_names in workflow_registry.workflows.items():
cls = class_by_id(class_id)
content_type = ContentType.objects.get_for_model(cls)
for field_name in field_names:
result.append(("%s %s" % (content_type.pk, field_name), "%s.%s - %s" % (cls.__module__, cls.__name__, field_name)))
return result
class WorkflowForm(forms.ModelForm):
workflow = forms.ChoiceField(choices=[])
class Meta:
model = Workflow
fields = ('workflow', 'initial_state')
def __init__(self, *args, **kwargs):
instance = kwargs.get("instance", None)
self.declared_fields['workflow'].choices = get_workflow_choices()
if instance and instance.pk:
self.declared_fields['workflow'].initial = "%s %s" % (instance.content_type.pk, instance.field_name)
super(WorkflowForm, self).__init__(*args, **kwargs)
def clean_workflow(self):
if self.cleaned_data.get('workflow') == '' or ' ' not in self.cleaned_data.get('workflow'):
return None, None
else:
return self.cleaned_data.get('workflow').split(" ")
def save(self, *args, **kwargs):
content_type_pk, field_name = self.cleaned_data.get('workflow')
instance = super(WorkflowForm, self).save(commit=False)
instance.content_type = ContentType.objects.get(pk=content_type_pk)
instance.field_name = field_name
return super(WorkflowForm, self).save(*args, **kwargs)
# noinspection PyMethodMayBeStatic
class WorkflowAdmin(admin.ModelAdmin):
form = WorkflowForm
list_display = ('model_class', 'field_name', 'initial_state')
def model_class(self, obj):
cls = obj.content_type.model_class()
if cls:
return "%s.%s" % (cls.__module__, cls.__name__)
else:
return "Class not found in the workspace"
def field_name(self, obj): # pylint: disable=no-self-use
return obj.workflow.field_name
admin.site.register(Workflow, WorkflowAdmin)
<file_sep>.. _faq:
FAQ
===
What does "supporting on-the-fly changes" mean?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It means that the changes require neither a code change nor a deployment.
In other words it is called as ``Dynamic Workflow``.
What are the advantages of dynamic workflows?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ease of modifications on workflows. People most of the time lack of having
easily modifying workflow capability with their system. Especially when to often
workflow changes are needed. Adding up one more step, creating a callback function
right away and deleting them even for a specific workflow object when needed by
just modifying it in the Database is giving to much flexibility. It also doesn't
require any code knowledge to change a workflow as long as some user interfaces
are set up for those people.
What are the disadvantages of dynamic workflows?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Again, ease of modifications on workflows. Having too much freedom sometimes may
not be a good idea. Very critical workflows might need more attention and care
before they get modified. Even though having a workflow statically defined in the
code brings some bureaucracy, it might be good to have it to prevent accidental
modifications and to lessen human errors.
What are the differences between ``django-river`` and ``viewflow``?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are different kind of workflow libraries for ``django``. It can be
working either with dynamically defined workflows or with statically defined
workflows. ``django-river`` is one of those that works with dynamically defined
workflows (what we call that it supports on-the-fly changes) where as ``viewflow``
is one of those that works with statically defined workflows in the code.
What are the differences between ``django-river`` and ``django-fsm``?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are different kind of workflow libraries for ``django``. It can be
working either with dynamically defined workflows or with statically defined
workflows. ``django-river`` is one of those that works with dynamically defined
workflows (what we call that it supports on-the-fly changes) where as ``django-fsm``
is one of those that works with statically defined workflows in the code.
Can I have multiple initial states in a workflow?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
No. The way how ``django-river`` works is that, whenever one of your workflow
object is created, the state field of the workflow inside that object is set by
the initial field you specified. So it would be ambiguous to have more than one
initial state.
Can I have a workflow that circulates?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Yes. ``django-river`` allows that and as it circulates, ``django-river`` extends
the lifecycle of a particular workflow object with the circular part of it.
Is there a limit on how many states I can have in a workflow?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
No. You can have as many as you like.
Can I have an authorization rule consist of two user groups? (``Horizontal Authorization Rules``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Yes. It functions like an or operator. One authorization rule
is defined with multiple user groups or permissions and anyone
who is any of the groups or who has any of the permissions defined
in that authorization rule can see and approve that transition.
Can I have two authorization rules for one transition and have one of them wait the other? (``Vertical Authorization Rules``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Yes. ``django-river`` has some kind of a prioritization mechanism
between the authorization rules on the same transitions. One that is
with more priority will be able to be seen and approved before the one with
less priority on the same transitions. Let's say you have a workflow with a
transition which should be approved by a team leader before it bothers
the manager. That is so possible with ``django-river``.
Can I have two state fields in one ``Django`` model?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Yes. The qualifier of a workflow for ``django-river`` is the model class and field name.
You can have as many workflow as you like in a ``Django`` model.
Can I have two workflow in parallel?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Yes. The qualifier of a workflow for ``django-river`` is the model class and field name.
You can have as many workflow as you like in a ``Django`` model.
Can I have two workflow in different ``Django`` models?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Yes. The qualifier of a workflow for ``django-river`` is the model class and field name.
So it is possible to qualify yet another workflow with a different model class.
Does it support all the databases that are supported by ``Django``?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Theoretically yes but it is only tested with ``sqlite3`` and all ``PostgreSQL`` versions.
What happens to the existing workflow object if I add a new transition to the workflow?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simply nothing. Existing workflow objects are not affected by the changes
on the workflow (Except the hooks). The way how ``django-river`` works is
that, it creates an isolated lifecycle for an object when it is created
out of it's workflow specification once and remain the same forever. So it
lives in it's world. It is very hard to predict what is gonna happen to the
existing objects. It requires more manual interference of the workflow owners
something like a migration process. But for the time being, we rather don't
touch the existing workflow objects due to the changes on the workflow.
Can I add a new hook on-the-fly?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The answer has ben yes since ``django-river`` version ``3.0.0``.
Can I delete an existing hook on-the-fly?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The answer has ben yes since ``django-river`` version ``3.0.0``.
Can I modify a the source code of the function that is used in the hooks on-the-fly?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The answer has ben yes since ``django-river`` version ``3.0.0``. ``django-river`` also
comes with an input component on the admin page that supports basic code highlighting.
Is there any delay for functions updates?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is none. It is applied immediately.
Can I use ``django-river`` with ``sqlalchemy``?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The answer is no unless you can make ``Django`` work with ``sqlalchemy``.
``django-river`` uses ``Django``'s orm heavily. So it is probably not a
way to go.
What is the difference between ``Class API`` and ``Instance API``?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``django-river`` provides two kinds of API. One which is for the object and one
which is for the class of the object. The ``Class API`` is the API that you can access
via the class whereas the ``Instance API`` is the API that you can access via the instance
or in other words via the workflow object. The APIs on both sides differ from each other
So don't expect to have the same function on both sides.
.. code:: python
# Instance API
from models import Shipping
shipping_object = Shipping.objects.get(pk=1)
shipping_object.river.shipping_status.approve(as_user=someone)
.. code:: python
# Class API
from models import Shipping
Shipping.river.shipping_status.get_on_approval_objects(as_user=someone)
You can see all class api functions at `Class API`_
and all instance api functions at `Instance API`_.
What is the error ``'ClassWorkflowObject' object has no attribute 'approve'``?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``approve`` is a function of `Instance API`_ not a `Class API`_ one.
What is the error ``There is no available approval for the user.``?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It means the user that you are trying to approve with is not really authorized
to approve the next step of the transition. Catch the error and turn it to a
more user friendly error if you would like to warn your user about that.
.. _`Class API`: https://django-river.readthedocs.io/en/latest/api/class.html
.. _`Instance API`: https://django-river.readthedocs.io/en/latest/api/instance.html
<file_sep>from django.contrib import admin
from django.test import TestCase
from hamcrest import assert_that, is_not, has_item, instance_of
from river.admin import OnApprovedHookInline, OnTransitHookInline, OnCompleteHookInline, DefaultWorkflowModelAdmin
from river.models import Function
from river.tests.admin import BasicTestModelAdmin
from river.tests.models import BasicTestModel, BasicTestModelWithoutAdmin
class AppTest(TestCase):
def test__shouldInjectExistingAdminOfTheModelThatHasStateFieldInIt(self):
assert_that(admin.site._registry[BasicTestModel], instance_of(BasicTestModelAdmin))
assert_that(admin.site._registry[BasicTestModel].inlines, has_item(OnApprovedHookInline))
assert_that(admin.site._registry[BasicTestModel].inlines, has_item(OnTransitHookInline))
assert_that(admin.site._registry[BasicTestModel].inlines, has_item(OnCompleteHookInline))
def test__shouldInjectADefaultAdminWithTheHooks(self):
assert_that(admin.site._registry[BasicTestModelWithoutAdmin], instance_of(DefaultWorkflowModelAdmin))
assert_that(admin.site._registry[BasicTestModel].inlines, has_item(OnApprovedHookInline))
assert_that(admin.site._registry[BasicTestModel].inlines, has_item(OnTransitHookInline))
assert_that(admin.site._registry[BasicTestModel].inlines, has_item(OnCompleteHookInline))
def test__shouldNotInjectToAdminOfTheModelThatDoesNotHaveStateFieldInIt(self):
assert_that(admin.site._registry[Function].inlines, is_not(has_item(OnApprovedHookInline)))
assert_that(admin.site._registry[Function].inlines, is_not(has_item(OnTransitHookInline)))
assert_that(admin.site._registry[Function].inlines, is_not(has_item(OnCompleteHookInline)))
<file_sep>from uuid import uuid4
from django.test import TestCase
from river.models import Function, OnTransitHook, OnApprovedHook, OnCompleteHook
from river.models.hook import BEFORE, AFTER
callback_output = {
}
callback_method = """
from river.tests.hooking.base_hooking_test import callback_output
def handle(context):
print(context)
key = '%s'
callback_output[key] = callback_output.get(key,[]) + [context]
"""
class BaseHookingTest(TestCase):
def setUp(self):
self.identifier = str(uuid4())
self.callback_function = Function.objects.create(name=uuid4(), body=callback_method % self.identifier)
def get_output(self):
return callback_output.get(self.identifier, None)
def hook_pre_transition(self, workflow, transition_meta, workflow_object=None, transition=None):
OnTransitHook.objects.create(
workflow=workflow,
callback_function=self.callback_function,
transition_meta=transition_meta,
transition=transition,
hook_type=BEFORE,
workflow_object=workflow_object,
)
def hook_post_transition(self, workflow, transition_meta, workflow_object=None, transition=None):
OnTransitHook.objects.create(
workflow=workflow,
callback_function=self.callback_function,
transition_meta=transition_meta,
transition=transition,
hook_type=AFTER,
workflow_object=workflow_object,
)
def hook_pre_approve(self, workflow, transition_approval_meta, workflow_object=None, transition_approval=None):
OnApprovedHook.objects.create(
workflow=workflow,
callback_function=self.callback_function,
transition_approval_meta=transition_approval_meta,
hook_type=BEFORE,
workflow_object=workflow_object,
transition_approval=transition_approval
)
def hook_post_approve(self, workflow, transition_approval_meta, workflow_object=None, transition_approval=None):
OnApprovedHook.objects.create(
workflow=workflow,
callback_function=self.callback_function,
transition_approval_meta=transition_approval_meta,
hook_type=AFTER,
workflow_object=workflow_object,
transition_approval=transition_approval
)
def hook_pre_complete(self, workflow, workflow_object=None):
OnCompleteHook.objects.create(
workflow=workflow,
callback_function=self.callback_function,
hook_type=BEFORE,
workflow_object=workflow_object
)
def hook_post_complete(self, workflow, workflow_object=None):
OnCompleteHook.objects.create(
workflow=workflow,
callback_function=self.callback_function,
hook_type=AFTER,
workflow_object=workflow_object
)
<file_sep>from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from river.core.workflowregistry import workflow_registry
from river.models import OnApprovedHook, OnTransitHook, OnCompleteHook
class BaseHookInline(GenericTabularInline):
fields = ("callback_function", "hook_type")
class OnApprovedHookInline(BaseHookInline):
model = OnApprovedHook
def __init__(self, *args, **kwargs):
super(OnApprovedHookInline, self).__init__(*args, **kwargs)
self.fields += ("transition_approval_meta",)
class OnTransitHookInline(BaseHookInline):
model = OnTransitHook
def __init__(self, *args, **kwargs):
super(OnTransitHookInline, self).__init__(*args, **kwargs)
self.fields += ("transition_meta",)
class OnCompleteHookInline(BaseHookInline):
model = OnCompleteHook
class DefaultWorkflowModelAdmin(admin.ModelAdmin):
inlines = [
OnApprovedHookInline,
OnTransitHookInline,
OnCompleteHookInline
]
def __init__(self, *args, **kwargs):
super(DefaultWorkflowModelAdmin, self).__init__(*args, **kwargs)
self.readonly_fields += tuple(workflow_registry.get_class_fields(self.model))
class OnApprovedHookAdmin(admin.ModelAdmin):
list_display = ('workflow', 'callback_function', 'transition_approval_meta')
class OnTransitHookAdmin(admin.ModelAdmin):
list_display = ('workflow', 'callback_function', 'transition_meta')
class OnCompleteHookAdmin(admin.ModelAdmin):
list_display = ('workflow', 'callback_function')
admin.site.register(OnApprovedHook, OnApprovedHookAdmin)
admin.site.register(OnTransitHook, OnTransitHookAdmin)
admin.site.register(OnCompleteHook, OnCompleteHookAdmin)
<file_sep>.. _hooking_general_guide:
Hooking Guide
=============
.. toctree::
:maxdepth: 2
function
hooking
<file_sep>from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from hamcrest import assert_that, has_length, has_item, has_property, none
from river.models import TransitionApproval, APPROVED, PENDING
from river.models.factories import WorkflowFactory, StateObjectFactory, TransitionApprovalMetaFactory, TransitionMetaFactory
from river.tests.models import BasicTestModel
from river.tests.models.factories import BasicTestModelObjectFactory
# noinspection PyMethodMayBeStatic
class TransitionApprovalMetaModelTest(TestCase):
def test_shouldNotDeleteApprovedTransitionWhenDeleted(self):
content_type = ContentType.objects.get_for_model(BasicTestModel)
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
meta1 = TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta, priority=0)
BasicTestModelObjectFactory()
TransitionApproval.objects.filter(workflow=workflow).update(status=APPROVED)
approvals = TransitionApproval.objects.filter(workflow=workflow)
assert_that(approvals, has_length(1))
assert_that(approvals, has_item(has_property("meta", meta1)))
meta1.delete()
approvals = TransitionApproval.objects.filter(workflow=workflow)
assert_that(approvals, has_length(1))
assert_that(approvals, has_item(has_property("meta", none())))
def test_shouldNotDeletePendingTransitionWhenDeleted(self):
content_type = ContentType.objects.get_for_model(BasicTestModel)
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
meta1 = TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta, priority=0)
BasicTestModelObjectFactory()
TransitionApproval.objects.filter(workflow=workflow).update(status=PENDING)
assert_that(TransitionApproval.objects.filter(workflow=workflow), has_length(1))
meta1.delete()
assert_that(TransitionApproval.objects.filter(workflow=workflow), has_length(0))
<file_sep>from river.admin.function_admin import *
from river.admin.hook_admins import *
from river.admin.transitionapprovalmeta import *
from river.admin.transitionmeta import *
from river.admin.workflow import *
from river.models import State
admin.site.register(State)
<file_sep>from django.db import models
from django.db.models import CASCADE
from django.utils.translation import ugettext_lazy as _
from river.models import TransitionMeta, Transition
from river.models.hook import Hook
class OnTransitHook(Hook):
class Meta:
unique_together = [('callback_function', 'workflow', 'transition_meta', 'content_type', 'object_id', 'transition')]
transition_meta = models.ForeignKey(TransitionMeta, verbose_name=_("Transition Meta"), related_name='on_transit_hooks', on_delete=CASCADE)
transition = models.ForeignKey(Transition, verbose_name=_("Transition"), related_name='on_transit_hooks', null=True, blank=True, on_delete=CASCADE)
<file_sep>from django import forms
from django.contrib import admin
from river.models import TransitionMeta
class TransitionMetaForm(forms.ModelForm):
class Meta:
model = TransitionMeta
fields = ('workflow', 'source_state', 'destination_state')
class TransitionMetaAdmin(admin.ModelAdmin):
form = TransitionMetaForm
list_display = ('workflow', 'source_state', 'destination_state')
admin.site.register(TransitionMeta, TransitionMetaAdmin)
<file_sep>import os
import sys
from setuptools import setup, find_packages
readme_file = os.path.join(os.path.dirname(__file__), 'README.rst')
try:
long_description = open(readme_file).read()
except IOError as err:
sys.stderr.write("[ERROR] Cannot find file specified as "
"``long_description`` (%s)\n" % readme_file)
sys.exit(1)
setup(
name='django-river',
version='3.2.0',
author='<NAME>',
author_email='<EMAIL>',
packages=find_packages(),
url='https://github.com/javrasya/django-river.git',
description='Django Workflow Library',
long_description=long_description,
install_requires=[
"Django",
"django-mptt==0.9.1",
"django-cte==1.1.4",
"django-codemirror2==0.2"
],
include_package_data=True,
zip_safe=False,
license='BSD',
platforms=['any'],
)
<file_sep>from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from river.models.managers.rivermanager import RiverManager
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
class BaseModel(models.Model):
objects = RiverManager()
date_created = models.DateTimeField(_('Date Created'), null=True, blank=True, auto_now_add=True)
date_updated = models.DateTimeField(_('Date Updated'), null=True, blank=True, auto_now=True)
class Meta:
app_label = 'river'
abstract = True
def details(self):
return {'pk': self.pk}
<file_sep>import os
import sys
import django
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
USE_TZ = True
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'behave_django',
'codemirror2',
'river',
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
class DisableMigrations(object):
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
TESTING = any("py.test" in s for s in sys.argv) or 'test' in sys.argv
# TESTING = True
SITE_ID = 1
SECRET_KEY = '<KEY>'
ROOT_URLCONF = 'test_urls'
RIVER_INJECT_MODEL_ADMIN = True
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'default': {
'format': '(%(module)s) (%(name)s) (%(asctime)s) (%(levelname)s) %(message)s',
'datefmt': "%Y-%b-%d %H:%M:%S"
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'default',
}
},
'loggers': {
'river': {
'handlers': ['console'],
'level': 'DEBUG'
}
}
}
<file_sep>from django.contrib.contenttypes.models import ContentType
from hamcrest import equal_to, assert_that, has_entry, none, all_of, has_key, has_length, is_not
from river.models import TransitionApproval
from river.models.factories import PermissionObjectFactory, UserObjectFactory, StateObjectFactory, WorkflowFactory, TransitionApprovalMetaFactory, TransitionMetaFactory
from river.models.hook import AFTER
from river.tests.hooking.base_hooking_test import BaseHookingTest
from river.tests.models import BasicTestModel
from river.tests.models.factories import BasicTestModelObjectFactory
# noinspection DuplicatedCode
class TransitionHooking(BaseHookingTest):
def test_shouldInvokeCallbackThatIsRegisteredWithInstanceWhenTransitionHappens(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
content_type = ContentType.objects.get_for_model(BasicTestModel)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
self.hook_post_transition(workflow, transition_meta_2, workflow_object=workflow_object.model)
assert_that(self.get_output(), none())
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state2))
assert_that(self.get_output(), none())
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state3))
last_approval = TransitionApproval.objects.get(object_id=workflow_object.model.pk, transition__source_state=state2, transition__destination_state=state3)
output = self.get_output()
assert_that(output, has_length(1))
assert_that(output[0], has_key("hook"))
assert_that(output[0]["hook"], has_entry("type", "on-transit"))
assert_that(output[0]["hook"], has_entry("when", AFTER))
assert_that(output[0]["hook"], has_entry(
"payload",
all_of(
has_entry(equal_to("workflow_object"), equal_to(workflow_object.model)),
has_entry(equal_to("transition_approval"), equal_to(last_approval))
)
))
def test_shouldInvokeCallbackThatIsRegisteredWithoutInstanceWhenTransitionHappens(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
content_type = ContentType.objects.get_for_model(BasicTestModel)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
self.hook_post_transition(workflow, transition_meta_2)
assert_that(self.get_output(), none())
assert_that(workflow_object.model.my_field, equal_to(state1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state2))
assert_that(self.get_output(), none())
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(state3))
last_approval = TransitionApproval.objects.get(object_id=workflow_object.model.pk, transition__source_state=state2, transition__destination_state=state3)
output = self.get_output()
assert_that(output, has_length(1))
assert_that(output[0], has_key("hook"))
assert_that(output[0]["hook"], has_entry("type", "on-transit"))
assert_that(output[0]["hook"], has_entry("when", AFTER))
assert_that(output[0]["hook"], has_entry(
"payload",
all_of(
has_entry(equal_to("workflow_object"), equal_to(workflow_object.model)),
has_entry(equal_to("transition_approval"), equal_to(last_approval))
)
))
def test_shouldInvokeCallbackForTheOnlyGivenTransition(self):
authorized_permission = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission])
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
content_type = ContentType.objects.get_for_model(BasicTestModel)
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state3,
destination_state=state1,
)
meta1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission]
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0,
permissions=[authorized_permission]
)
workflow_object = BasicTestModelObjectFactory()
workflow_object.model.river.my_field.approve(as_user=authorized_user)
workflow_object.model.river.my_field.approve(as_user=authorized_user)
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(TransitionApproval.objects.filter(meta=meta1), has_length(2))
first_approval = TransitionApproval.objects.filter(meta=meta1, transition__iteration=0).first()
assert_that(first_approval, is_not(none()))
self.hook_pre_transition(workflow, transition_meta_1, transition=transition_meta_1.transitions.first())
output = self.get_output()
assert_that(output, none())
workflow_object.model.river.my_field.approve(as_user=authorized_user)
output = self.get_output()
assert_that(output, none())
<file_sep>class WorkflowRegistry(object):
def __init__(self):
self.workflows = {}
self.class_index = {}
def add(self, name, cls):
self.workflows[id(cls)] = self.workflows.get(id(cls), set())
self.workflows[id(cls)].add(name)
self.class_index[id(cls)] = cls
def get_class_fields(self, model):
return self.workflows[id(model)]
workflow_registry = WorkflowRegistry()
<file_sep>from django.contrib.contenttypes.models import ContentType
from django.db.models import ProtectedError
from django.test import TestCase
from hamcrest import assert_that, has_length, calling, raises
from river.models import TransitionApproval, APPROVED
from river.models.factories import WorkflowFactory, StateObjectFactory, TransitionApprovalMetaFactory, TransitionMetaFactory
from river.tests.models import BasicTestModel
from river.tests.models.factories import BasicTestModelObjectFactory
# noinspection PyMethodMayBeStatic,DuplicatedCode
class TransitionApprovalModelTest(TestCase):
def test_shouldNotAllowWorkflowToBeDeletedWhenThereIsATransitionApproval(self):
content_type = ContentType.objects.get_for_model(BasicTestModel)
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta, priority=0)
BasicTestModelObjectFactory()
TransitionApproval.objects.filter(workflow=workflow).update(status=APPROVED)
approvals = TransitionApproval.objects.filter(workflow=workflow)
assert_that(approvals, has_length(1))
assert_that(
calling(workflow.delete),
raises(ProtectedError, "Cannot delete some instances of model 'Workflow' because they are referenced through a protected foreign key")
)
def test_shouldNotAllowTheStateToBeDeletedWhenThereIsATransitionApprovalThatIsUsedAsSource(self):
content_type = ContentType.objects.get_for_model(BasicTestModel)
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta_1, priority=0)
TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta_2, priority=0)
BasicTestModelObjectFactory()
TransitionApproval.objects.filter(workflow=workflow).update(status=APPROVED)
approvals = TransitionApproval.objects.filter(workflow=workflow)
assert_that(approvals, has_length(2))
assert_that(
calling(state2.delete),
raises(ProtectedError, "Cannot delete some instances of model 'State' because they are referenced through a protected foreign key")
)
def test_shouldNotAllowTheStateToBeDeletedWhenThereIsATransitionApprovalThatIsUsedAsDestination(self):
content_type = ContentType.objects.get_for_model(BasicTestModel)
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta_1, priority=0)
TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta_2, priority=0)
BasicTestModelObjectFactory()
TransitionApproval.objects.filter(workflow=workflow).update(status=APPROVED)
approvals = TransitionApproval.objects.filter(workflow=workflow)
assert_that(approvals, has_length(2))
assert_that(
calling(state3.delete),
raises(ProtectedError, "Cannot delete some instances of model 'State' because they are referenced through a protected foreign key")
)
<file_sep>.. |Build Status| image:: https://travis-ci.org/javrasya/django-river.svg
:target: https://travis-ci.org/javrasya/django-river
.. |Coverage Status| image:: https://coveralls.io/repos/javrasya/django-river/badge.svg?branch=master&service=github
:target: https://coveralls.io/github/javrasya/django-river?branch=master
.. |Health Status| image:: https://landscape.io/github/javrasya/django-river/master/landscape.svg?style=flat
:target: https://landscape.io/github/javrasya/django-river/master
:alt: Code Health
.. |Documentation Status| image:: https://readthedocs.org/projects/django-river/badge/?version=latest
:target: https://readthedocs.org/projects/django-river/?badge=latest
.. |Quality Status| image:: https://api.codacy.com/project/badge/Grade/c3c73d157fe045e6b966d8d4416b6b17
:alt: Codacy Badge
:target: https://app.codacy.com/app/javrasya/django-river?utm_source=github.com&utm_medium=referral&utm_content=javrasya/django-river&utm_campaign=Badge_Grade_Dashboard
.. |Downloads| image:: https://img.shields.io/pypi/dm/django-river
:alt: PyPI - Downloads
.. |Discord| image:: https://img.shields.io/discord/651433240019599400
:target: https://discord.gg/DweUwZX
:alt: Discord
.. |Open Collective| image:: https://opencollective.com/django-river/all/badge.svg?label=financial+contributors
:alt: Financial Contributors
:target: #contributors
.. |Timeline| image:: https://cloud.githubusercontent.com/assets/1279644/9934893/921b543a-5d5c-11e5-9596-a5e067db79ed.png
.. |Logo| image:: docs/logo.svg
:width: 200
.. |Create Function Page| image:: docs/_static/create-function.png
Django River
============
|Logo|
|Build Status| |Coverage Status| |Documentation Status| |Quality Status| |Downloads| |Discord|
Contributors are welcome. Come and give a hand :-)
---------------------------------------------------
River is an open source workflow framework for ``Django`` which support on
the fly changes instead of hardcoding states, transitions and authorization rules.
The main goal of developing this framework is **to be able to edit any
workflow item on the fly.** This means that all the elements in a workflow like
states, transitions or authorizations rules are editable at any time so that no changes requires a re-deploying of your application anymore.
**Playground**: There is a fake jira example repository as a playground of django-river. https://github.com/javrasya/fakejira
Donations
---------
This is a fully open source project and it can be better with your donations.
If you are using ``django-river`` to create a commercial product,
please consider becoming our `sponsor`_ , `patron`_ or donate over `PayPal`_
.. _`patron`: https://www.patreon.com/javrasya
.. _`PayPal`: https://paypal.me/ceahmetdal
.. _`sponsor`: https://github.com/sponsors/javrasya
Documentation
-------------
Online documentation is available at http://django-river.rtfd.org/
Advance Admin
-------------
A very modern admin with some user friendly interfaces that is called `River Admin`_ has been published.
.. _`River Admin`: https://riveradminproject.com/
Requirements
------------
* Python (``2.7``, ``3.4``, ``3.5``, ``3.6``)
* Django (``1.11``, ``2.0``, ``2.1``, ``2.2``, ``3.0``)
* ``Django`` >= 2.0 is supported for ``Python`` >= 3.5
Supported (Tested) Databases:
-----------------------------
+------------+--------+---------+
| PostgreSQL | Tested | Support |
+------------+--------+---------+
| 9 | ✅ | ✅ |
+------------+--------+---------+
| 10 | ✅ | ✅ |
+------------+--------+---------+
| 11 | ✅ | ✅ |
+------------+--------+---------+
| 12 | ✅ | ✅ |
+------------+--------+---------+
+------------+--------+---------+
| MySQL | Tested | Support |
+------------+--------+---------+
| 5.6 | ✅ | ❌ |
+------------+--------+---------+
| 5.7 | ✅ | ❌ |
+------------+--------+---------+
| 8.0 | ✅ | ✅ |
+------------+--------+---------+
+------------+--------+---------+
| MSSQL | Tested | Support |
+------------+--------+---------+
| 19 | ✅ | ✅ |
+------------+--------+---------+
| 17 | ✅ | ✅ |
+------------+--------+---------+
Usage
-----
1. Install and enable it
.. code:: bash
pip install django-river
.. code:: python
INSTALLED_APPS=[
...
river
...
]
2. Create your first state machine in your model and migrate your db
.. code:: python
from django.db import models
from river.models.fields.state import StateField
class MyModel(models.Model):
my_state_field = StateField()
3. Create all your ``states`` on the admin page
4. Create a ``workflow`` with your model ( ``MyModel`` - ``my_state_field`` ) information on the admin page
5. Create your ``transition metadata`` within the workflow created earlier, source and destination states
6. Create your ``transition approval metadata`` within the workflow created earlier and authorization rules along with their priority on the admin page
7. Enjoy your ``django-river`` journey.
.. code-block:: python
my_model=MyModel.objects.get(....)
my_model.river.my_state_field.approve(as_user=transactioner_user)
my_model.river.my_state_field.approve(as_user=transactioner_user, next_state=State.objects.get(label='re-opened'))
# and much more. Check the documentation
.. note::
Whenever a model object is saved, it's state field will be initialized with the
state is given at step-4 above by ``django-river``.
Hooking Up With The Events
--------------------------
`django-river` provides you to have your custom code run on certain events. And since version v2.1.0 this has also been supported for on the fly changes. You can
create your functions and also the hooks to a certain events by just creating few database items. Let's see what event types that can be hooked a function to;
* An approval is approved
* A transition goes through
* The workflow is complete
For all these event types, you can create a hooking with a given function which is created separately and preliminary than the hookings for all the workflow objects you have
or you will possible have, or for a specific workflow object. You can also hook up before or after the events happen.
1. Create Function
^^^^^^^^^^^^^^^^^^
This will be the description of your functions. So you define them once and you can use them with multiple hooking up. Just go to ``/admin/river/function/`` admin page
and create your functions there. ``django-river`` function admin support python code highlights.
.. code:: python
INSTALLED_APPS=[
...
codemirror2
river
...
]
Here is an example function;
.. code:: python
from datetime import datetime
def handle(context):
print(datetime.now())
**Important:** **YOUR FUNCTION SHOULD BE NAMED AS** ``handle``. Otherwise ``django-river`` won't execute your function.
``django-river`` will pass a ``context`` down to your function in order for you to know why the function is triggered or for which object or so. And the ``context`` will look different for
different type of events. Please see detailed `context documentation`_ to know more on what you would get from context in your functions.
You can find an `advance function example`_ on the link.
|Create Function Page|
.. _`context documentation`: https://django-river.readthedocs.io/en/latest/hooking/function.html#context-parameter
.. _`advance function example`: https://django-river.readthedocs.io/en/latest/hooking/function.html#example-function
2. Hook It Up
^^^^^^^^^^^^^
The hookings in ``django-river`` can be created both specifically for a workflow object or for a whole workflow. ``django-river`` comes with some model objects and admin interfaces which you can use
to create the hooks.
* To create one for whole workflow regardless of what the workflow object is, go to
* ``/admin/river/onapprovedhook/`` to hook up to an approval
* ``/admin/river/ontransithook/`` to hook up to a transition
* ``/admin/river/oncompletehook/`` to hook up to the completion of the workflow
* To create one for a specific workflow object you should use the admin interface for the workflow object itself. One amazing feature of ``django-river`` is now that it creates a default admin interface with the hookings for your workflow model class. If you have already defined one, ``django-river`` enriches your already defined admin with the hooking section. It is default disabled. To enable it just define ``RIVER_INJECT_MODEL_ADMIN`` to be ``True`` in the ``settings.py``.
**Note:** They can programmatically be created as well since they are model objects. If it is needed to be at workflow level, just don't provide the workflow object column. If it is needed
to be for a specific workflow object then provide it.
Here are the list of hook models;
* OnApprovedHook
* OnTransitHook
* OnCompleteHook
Migrations
----------
2.X.X to 3.0.0
^^^^^^^^^^^^^^
``django-river`` v3.0.0 comes with quite number of migrations, but the good news is that even though those are hard to determine kind of migrations, it comes with the required migrations
out of the box. All you need to do is to run;
.. code:: bash
python manage.py migrate river
3.1.X to 3.2.X
^^^^^^^^^^^^^^
``django-river`` started to support **Microsoft SQL Server 17 and 19** after version 3.2.0 but the previous migrations didn't get along with it. We needed to reset all
the migrations to have fresh start. If you have already migrated to version `3.1.X` all you need to do is to pull your migrations back to the beginning.
.. code:: bash
python manage.py migrate --fake river zero
python manage.py migrate --fake river
FAQ
---
Have a look at `FAQ`_
.. _`FAQ`: https://django-river.readthedocs.io/en/latest/faq.html
Contributors
============
Code Contributors
------------------
This project exists thanks to all the people who contribute :rocket: :heart:
.. image:: https://opencollective.com/django-river/contributors.svg?width=890&button=false
:target: https://github.com/javrasya/django-river/graphs/contributors
Financial Contributors
----------------------
Become a financial contributor and help us sustain our community. Contribute_
Individuals
^^^^^^^^^^^
.. image:: https://opencollective.com/django-river/individuals.svg?width=890
:target: https://opencollective.com/django-river
Organizations
^^^^^^^^^^^^^
Support this project with your organization. Your logo will show up here with a link to your website. Contribute_
.. image:: https://opencollective.com/django-river/organization/0/avatar.svg
:target: https://opencollective.com/django-river/organization/0/website
.. _Contribute: https://opencollective.com/django-river
.. _license:
License
=======
This software is licensed under the `New BSD License`. See the ``LICENSE``
file in the top distribution directory for the full license text.
<file_sep>.. _api_guide:
API Guide
=========
.. toctree::
:maxdepth: 2
class
instance
<file_sep>from river.models.hook import Hook
class OnCompleteHook(Hook):
class Meta:
unique_together = [('callback_function', 'workflow', 'content_type', 'object_id')]
<file_sep>[tox]
envlist = {py27,py34}-{dj1.11}-{sqlite3},
{py35}-{dj1.11,dj2.0,dj2.1,dj2.2}-{sqlite3},
{py36}-{dj1.11,dj2.0,dj2.1,dj2.2,dj3.0}-{sqlite3},
{py36}-{dj2.2}-{postgresql9,postgresql10,postgresql11,postgresql12},
{py36}-{dj2.2}-{mysql8.0},
{py36}-{dj2.2}-{msqsql17,mssql19},
cov,
[testenv]
docker =
postgresql9: postgres:9-alpine
postgresql10: postgres:10-alpine
postgresql11: postgres:11-alpine
postgresql12: postgres:12-alpine
mysql8.0: mysql:8.0.18
mssql17: mcr.microsoft.com/mssql/server:2017-latest
mssql19: mcr.microsoft.com/mssql/server:2019-latest
dockerenv =
POSTGRES_USER=river
POSTGRES_PASSWORD=<PASSWORD>
POSTGRES_DB=river
MYSQL_ROOT_PASSWORD=river
MYSQL_USER=river
MYSQL_PASSWORD=<PASSWORD>
MYSQL_DATABASE=river
MSSQL_PID=Express
SA_PASSWORD=<PASSWORD>
ACCEPT_EULA=y
setenv =
sqlite3: DJANGO_SETTINGS_MODULE=settings.with_sqlite3
postgresql9,postgresql10,postgresql11,postgresql12: DJANGO_SETTINGS_MODULE=settings.with_postgresql
mysql8.0: DJANGO_SETTINGS_MODULE=settings.with_mysql
mssql17,mssql19: DJANGO_SETTINGS_MODULE=settings.with_mssql
deps =
pytest-django>3.1.2
pytest-cov
-rrequirements.txt
dj1.11: Django>=1.11,<1.12.0
dj2.0: Django>=2.0,<2.1.0
dj2.1: Django>=2.1,<2.2.0
dj2.2: Django>=2.2,<2.3.0
dj3.0: Django>=3.0,<3.1.0
postgresql9,postgresql10,postgresql11,postgresql12: psycopg2
mysql8.0: mysqlclient
mssql17,mssql19: django-mssql-backend
commands =
py.test --junitxml=../junit-{envname}.xml
python manage.py behave
[testenv:cov]
basepython = python3.6
deps =
pytest-django
pytest-cov
django>=2.2,<2.3.0
-rrequirements.txt
commands =
py.test --ds='settings.with_sqlite3' --cov ./ --cov-report term-missing
[docker:mysql:8.0.18]
healthcheck_cmd = 'mysqladmin ping --silent -u root --password=<PASSWORD>'
healthcheck_interval = 10
healthcheck_start_period = 5
healthcheck_retries = 30
healthcheck_timeout = 10
[docker:mcr.microsoft.com/mssql/server:2017-latest]
healthcheck_cmd = '/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P River@Credentials -Q "SELECT 1" || exit 1'
healthcheck_interval = 10
healthcheck_start_period = 10
healthcheck_retries = 10
healthcheck_timeout = 3
[docker:mcr.microsoft.com/mssql/server:2019-latest]
healthcheck_cmd = '/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P River@Credentials -Q "SELECT 1" || exit 1'
healthcheck_interval = 10
healthcheck_start_period = 10
healthcheck_retries = 10
healthcheck_timeout = 3<file_sep>.. _hooking_function_guide:
.. |Create Function Page| image:: /_static/create-function.png
Functions
=========
Functions are the description in ``Python`` of what you want to do on certain events happen. So you define them once and you can use them
with multiple hooking up. Just go to ``/admin/river/function/`` admin page and create your functions there.``django-river`` function admin support
python code highlighting as well if you enable the ``codemirror2`` app. Don't forget to collect statics for production deployments.
.. code:: python
INSTALLED_APPS=[
...
codemirror2
river
...
]
Here is an example function;
.. code:: python
from datetime import datetime
def handle(context):
print(datetime.now())
**Important:** **YOUR FUNCTION SHOULD BE NAMED AS** ``handle``. Otherwise ``django-river`` won't execute your function.
|Create Function Page|
Context Parameter
-----------------
``django-river`` will pass a ``context`` down to your function in order for you to know why the function is triggered or for which object or so. And the ``context``
will look different for different type of events. But it also has some common parts for all the events. Let's look at how it looks;
``context.hook ->>``
+---------------------+--------+--------------------+---------------------------------------------------------+
| Key | Type | Format | Description |
+=====================+========+====================+=========================================================+
| type | String | | * on-approved | | The event type that is hooked up. The payload will |
| | | | * on-transit | | likely differ according to this value |
| | | | * on-complete | |
+---------------------+--------+--------------------+---------------------------------------------------------+
| when | String | | * BEFORE | | Whether it is hooked right before the event happens |
| | | | * AFTER | | or right after |
+---------------------+--------+--------------------+---------------------------------------------------------+
| payload | dict | | | This is the context content that will differ for each |
| | | | | event type. The information that can be gotten from |
| | | | | payload is describe in the table below |
+---------------------+--------+--------------------+---------------------------------------------------------+
Context Payload
---------------
On-Approved Event Payload
^^^^^^^^^^^^^^^^^^^^^^^^^
+---------------------+------------------+---------------------------------------------------------+
| Key | Type | Description |
+=====================+==================+=========================================================+
| workflow | Workflow Model | The workflow that the transition currently happening |
+---------------------+------------------+---------------------------------------------------------+
| workflow_object | | Your Workflow | | The workflow object of the model that has the state |
| | | Object | | field in it |
+---------------------+------------------+---------------------------------------------------------+
| transition_approval | | Transition | | The approval object that is currently approved which |
| | | Approval | | contains the information of the transition(meta) as |
| | | | well as who approved it etc. |
+---------------------+------------------+---------------------------------------------------------+
On-Transit Event Payload
^^^^^^^^^^^^^^^^^^^^^^^^
+---------------------+------------------+---------------------------------------------------------+
| Key | Type | Description |
+=====================+==================+=========================================================+
| workflow | Workflow Model | The workflow that the transition currently happening |
+---------------------+------------------+---------------------------------------------------------+
| workflow_object | | Your Workflow | | The workflow object of the model that has the state |
| | | Object | | field in it |
+---------------------+------------------+---------------------------------------------------------+
| transition_approval | | Transition | | The last transition approval object which contains |
| | | Approval | | the information of the transition(meta) as well as |
| | | | who last approved it etc. |
+---------------------+------------------+---------------------------------------------------------+
On-Complete Event Payload
^^^^^^^^^^^^^^^^^^^^^^^^^
+---------------------+------------------+---------------------------------------------------------+
| Key | Type | Description |
+=====================+==================+=========================================================+
| workflow | Workflow Model | The workflow that the transition currently happening |
+---------------------+------------------+---------------------------------------------------------+
| workflow_object | | Your Workflow | | The workflow object of the model that has the state |
| | | Object | | field in it |
+---------------------+------------------+---------------------------------------------------------+
Example Function
^^^^^^^^^^^^^^^^
.. code:: python
from river.models.hook import BEFORE, AFTER
def _handle_my_transitions(hook):
workflow = hook['payload']['workflow']
workflow_object = hook['payload']['workflow_object']
source_state = hook['payload']['transition_approval'].meta.source_state
destination_state = hook['payload']['transition_approval'].meta.destination_state
last_approved_by = hook['payload']['transition_approval'].transactioner
if hook['when'] == BEFORE:
print('A transition from %s to %s will soon happen on the object with id:%s and field_name:%s!' % (source_state.label, destination_state.label, workflow_object.pk, workflow.field_name))
elif hook['when'] == AFTER:
print('A transition from %s to %s has just happened on the object with id:%s and field_name:%s!' % (source_state.label, destination_state.label, workflow_object.pk, workflow.field_name))
print('Who approved it lately is %s' % last_approved_by.username)
def _handle_my_approvals(hook):
workflow = hook['payload']['workflow']
workflow_object = hook['payload']['workflow_object']
approved_by = hook['payload']['transition_approval'].transactioner
if hook['when'] == BEFORE:
print('An approval will soon happen by %s on the object with id:%s and field_name:%s!' % ( approved_by.username, workflow_object.pk, workflow.field_name ))
elif hook['when'] == AFTER:
print('An approval has just happened by %s on the object with id:%s and field_name:%s!' % ( approved_by.username, workflow_object.pk, workflow.field_name ))
def _handle_completions(hook):
workflow = hook['payload']['workflow']
workflow_object = hook['payload']['workflow_object']
if hook['when'] == BEFORE:
print('The workflow will soon be complete for the object with id:%s and field_name:%s!' % ( workflow_object.pk, workflow.field_name ))
elif hook['when'] == AFTER:
print('The workflow has just been complete for the object with id:%s and field_name:%s!' % ( workflow_object.pk, workflow.field_name ))
def handle(context):
hook = context['hook']
if hook['type'] == 'on-transit':
_handle_my_transitions(hook)
elif hook['type'] == 'on-approved':
_handle_my_approvals(hook)
elif hook['type'] == 'on-complete':
_handle_completions(hook)
else:
print("Unknown event type %s" % hook['type'])
<file_sep>from codemirror2.widgets import CodeMirrorEditor
from django import forms
from django.contrib import admin
from river.models import Function
class FunctionForm(forms.ModelForm):
body = forms.CharField(widget=CodeMirrorEditor(options={'mode': 'python'}))
class Meta:
model = Function
fields = ('name', 'body',)
class FunctionAdmin(admin.ModelAdmin):
form = FunctionForm
list_display = ('name', 'function_version', 'date_created', 'date_updated')
readonly_fields = ('version', 'date_created', 'date_updated')
def function_version(self, obj): # pylint: disable=no-self-use
return "v%s" % obj.version
admin.site.register(Function, FunctionAdmin)
<file_sep>.. _instance_api_guide:
Instance API
============
This page will be covering the instance level API. It is all the function that you can access through your model object
like in the example below;
.. code-block:: python
my_model=MyModel.objects.get(....)
my_model.river.my_state_field.<function>(*args)
approve
-------
This is the function that helps you to approve next approval of the object easily. ``django-river`` will handle all
the availability and the authorization issues.
>>> my_model.river.my_state_field.approve(as_user=team_leader)
>>> my_model.river.my_state_field.approve(as_user=team_leader, next_state=State.objects.get(name='re_opened_state'))
+------------+-------+---------+------------+-------------+-----------------------------------------+
| | Type | Default | Optional | Format | Description |
+============+=======+=========+============+=============+=========================================+
| as_user | input | NaN | False | Django User | | A user to make the transaction. |
| | | | | | | ``django-river`` will check |
| | | | | | | if this user is authorized to |
| | | | | | | make next action by looking at |
| | | | | | | this user's permissions and |
| | | | | | | user groups. |
+------------+-------+---------+------------+-------------+-----------------------------------------+
| next_state | input | NaN | True/False | State | | This parameter is redundant |
| | | | | | | as long as there is only one |
| | | | | | | next state from the current |
| | | | | | | state. But if there is multiple |
| | | | | | | possible next state in place, |
| | | | | | | ``django-river`` is naturally |
| | | | | | | is unable know which one is |
| | | | | | | actually supposed to be picked. |
| | | | | | | If the given next state is not |
| | | | | | | a valid next state a `RiverException` |
| | | | | | | will be thrown. |
+------------+-------+---------+------------+-------------+-----------------------------------------+
get_available_approvals
-----------------------
This is the function that helps you to fetch all available approvals waiting for a specific user according to given source and
destination states. If the source state is not provided, ``django-river`` will pick the current objects source state.
>>> transition_approvals = my_model.river.my_state_field.get_available_approvals(as_user=manager)
>>> transition_approvals = my_model.river.my_state_field.get_available_approvals(as_user=manager, source_state=State.objects.get(name='in_progress'))
>>> transition_approvals = my_model.river.my_state_field.get_available_approvals(
as_user=manager,
source_state=State.objects.get(name='in_progress'),
destination_state=State.objects.get(name='resolved'),
)
+-------------------+--------+----------------+----------+--------------------------+------------------------------------------+
| | Type | Default | Optional | Format | Description |
+===================+========+================+==========+==========================+==========================================+
| as_user | input | NaN | False | Django User | | A user to find all the approvals |
| | | | | | | by user's permissions and groups |
+-------------------+--------+----------------+----------+--------------------------+------------------------------------------+
| source_state | input | | Current | True | State | | A base state to find all available |
| | | | Object's | | | | approvals comes after. Default is |
| | | | Source State | | | | current object's source state |
+-------------------+--------+----------------+----------+--------------------------+------------------------------------------+
| destination_state | input | NaN | True | State | | A specific destination state to |
| | | | | | | fetch all available state. If it |
| | | | | | | is not provided, the approvals |
| | | | | | | will be found for all available |
| | | | | | | destination states |
+-------------------+--------+----------------+----------+--------------------------+------------------------------------------+
| | Output | | | List<TransitionApproval> | | List of available transition approvals |
+-------------------+--------+----------------+----------+--------------------------+------------------------------------------+
recent_approval
-------------
This is a property that the transition approval which has recently been approved for the model object.
>>> transition_approval = my_model.river.my_state_field.last_approval
+--------+--------------------+-------------------------------------+
| Type | Format | Description |
+========+====================+=====================================+
| Output | TransitionApproval | | Last approved transition approval |
| | | | for the model object |
+--------+--------------------+-------------------------------------+
next_approvals
--------------
This is a property that the list of transition approvals as a next step.
>>> transition_approvals == my_model.river.my_state_field.next_approvals
True
+--------+--------------------------+--------------------------------------+
| Type | Format | Description |
+========+==========================+======================================+
| Output | List<TransitionApproval> | | List of transition approvals comes |
| | | | after last approved transition |
| | | | approval |
+--------+--------------------------+--------------------------------------+
on_initial_state
----------------
This is a property that indicates if object is on initial state.
>>> my_model.river.my_state_field.on_initial_state
True
+--------+---------+------------------------------------+
| Type | Format | Description |
+========+=========+====================================+
| Output | Boolean | True if object is on initial state |
+--------+---------+------------------------------------+
on_final_state
--------------
This is a property that indicates if object is on final state.
>>> my_model.river.my_state_field.on_final_state
True
+--------+---------+--------------------------------------+
| Type | Format | Description |
+========+=========+======================================+
| Output | Boolean | | True if object is on final state |
| | | | which also means that the workflow |
| | | | is complete |
+--------+---------+--------------------------------------+
jump_to
-------
This is the function that allows to jump to a specific future state
from the current state of the workflow object. It is good for testing
purposes.
>>> in_progress_state = State.object.get(label="In Progress")
>>> transition_approvals = my_model.river.my_state_field.jump_to(in_progress_state)
+-------------------+--------+--------------------------+------------------------------------------+
| | Type | Format | Description |
+===================+========+==========================+==========================================+
| target_state | input | State | | The target state that the workflow |
| | | | | object will jump to. It is supposed |
| | | | | to be a possible state in the future |
| | | | | of the workflow object |
+-------------------+--------+--------------------------+------------------------------------------+
.. toctree::
:maxdepth: 2
<file_sep>from django.contrib import admin
from django import forms
from river.models.transitionapprovalmeta import TransitionApprovalMeta
class TransitionApprovalMetaForm(forms.ModelForm):
class Meta:
model = TransitionApprovalMeta
fields = ('workflow', 'transition_meta', 'permissions', 'groups', 'priority')
class TransitionApprovalMetaAdmin(admin.ModelAdmin):
form = TransitionApprovalMetaForm
list_display = ('workflow', 'transition_meta', 'priority')
admin.site.register(TransitionApprovalMeta, TransitionApprovalMetaAdmin)
<file_sep>import os
import sys
from datetime import datetime, timedelta
from unittest import skipUnless, skip
from uuid import uuid4
import django
import six
from django.contrib.contenttypes.models import ContentType
from django.db import connection
from django.test.utils import override_settings
from hamcrest import assert_that, equal_to, has_length, has_item, is_not, less_than
from river.models import TransitionApproval, OnApprovedHook, Function, OnCompleteHook, OnTransitHook
from river.models.factories import StateObjectFactory, WorkflowFactory, TransitionApprovalMetaFactory, PermissionObjectFactory, UserObjectFactory, \
TransitionMetaFactory
from river.models.hook import BEFORE
from river.tests.models import BasicTestModel
from river.tests.models.factories import BasicTestModelObjectFactory
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
_author_ = 'ahmetdal'
MIGRATION_TEST_ENABLED = (
not django.VERSION[0] >= 2,
"Is not able to run with new version of django and sqlite3"
)
def clean_migrations():
for f in os.listdir("river/tests/volatile/river/"):
if f != "__init__.py" and f != "__pycache__":
os.remove(os.path.join("river/tests/volatile/river/", f))
for f in os.listdir("river/tests/volatile/river_tests/"):
if f != "__init__.py" and f != "__pycache__":
os.remove(os.path.join("river/tests/volatile/river_tests/", f))
class MigrationTests(TestCase):
"""
This is the case to detect missing migration issues like https://github.com/javrasya/django-river/issues/30
"""
migrations_before = []
migrations_after = []
def setUp(self):
"""
Remove migration file generated by test if there is any missing.
"""
clean_migrations()
def tearDown(self):
"""
Remove migration file generated by test if there is any missing.
"""
clean_migrations()
@override_settings(MIGRATION_MODULES={"river": "river.tests.volatile.river"})
def test_shouldCreateAllMigrations(self):
for f in os.listdir("river/migrations"):
if f != "__init__.py" and f != "__pycache__" and not f.endswith(".pyc"):
open(os.path.join("river/tests/volatile/river/", f), 'wb').write(open(os.path.join("river/migrations", f), 'rb').read())
self.migrations_before = list(filter(lambda f: f.endswith('.py') and f != '__init__.py', os.listdir('river/tests/volatile/river/')))
out = StringIO()
sys.stout = out
call_command('makemigrations', 'river', stdout=out)
self.migrations_after = list(filter(lambda f: f.endswith('.py') and f != '__init__.py', os.listdir('river/tests/volatile/river/')))
assert_that(out.getvalue(), equal_to("No changes detected in app 'river'\n"))
assert_that(self.migrations_after, has_length(len(self.migrations_before)))
@override_settings(MIGRATION_MODULES={"tests": "river.tests.volatile.river_tests"})
def test__shouldNotKeepRecreatingMigrationsWhenNoChange(self):
call_command('makemigrations', 'tests')
self.migrations_before = list(filter(lambda f: f.endswith('.py') and f != '__init__.py', os.listdir('river/tests/volatile/river_tests/')))
out = StringIO()
sys.stout = out
call_command('makemigrations', 'tests', stdout=out)
self.migrations_after = list(filter(lambda f: f.endswith('.py') and f != '__init__.py', os.listdir('river/tests/volatile/river_tests/')))
assert_that(out.getvalue(), equal_to("No changes detected in app 'tests'\n"))
assert_that(self.migrations_after, has_length(len(self.migrations_before)))
@skipUnless(*MIGRATION_TEST_ENABLED)
@skip("Migrations are reset")
def test__shouldMigrateTransitionApprovalStatusToStringInDB(self):
out = StringIO()
sys.stout = out
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=ContentType.objects.get_for_model(BasicTestModel), field_name="my_field")
transition_meta = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta,
priority=0
)
workflow_object = BasicTestModelObjectFactory()
with connection.cursor() as cur:
result = cur.execute("select status from river_transitionapproval where object_id=%s;" % workflow_object.model.pk).fetchall()
assert_that(result[0][0], equal_to("pending"))
call_command('migrate', 'river', '0004', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_transitionapproval');").fetchall()
status_col_type = list(filter(lambda column: column[1] == 'status', schema))[0][2]
assert_that(status_col_type, equal_to("integer"))
result = cur.execute("select status from river_transitionapproval where object_id=%s;" % workflow_object.model.pk).fetchall()
assert_that(result[0][0], equal_to(0))
call_command('migrate', 'river', '0005', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_transitionapproval');").fetchall()
status_col_type = list(filter(lambda column: column[1] == 'status', schema))[0][2]
assert_that(status_col_type, equal_to("varchar(100)"))
result = cur.execute("select status from river_transitionapproval where object_id=%s;" % workflow_object.model.pk).fetchall()
assert_that(result[0][0], equal_to("pending"))
@skipUnless(*MIGRATION_TEST_ENABLED)
@skip("Migrations are reset")
def test__shouldAssessIterationsForExistingApprovals(self):
out = StringIO()
sys.stout = out
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
state4 = StateObjectFactory(label="state4")
workflow = WorkflowFactory(initial_state=state1, content_type=ContentType.objects.get_for_model(BasicTestModel), field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state4,
)
meta_1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0
)
meta_2 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0
)
meta_3 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=1
)
meta_4 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0
)
workflow_object = BasicTestModelObjectFactory()
with connection.cursor() as cur:
result = cur.execute("""
select
river_transitionapproval.meta_id,
iteration
from river_transitionapproval
inner join river_transition rt on river_transitionapproval.transition_id = rt.id
where river_transitionapproval.object_id=%s;
""" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(4))
assert_that(result, has_item(equal_to((meta_1.pk, 0))))
assert_that(result, has_item(equal_to((meta_2.pk, 1))))
assert_that(result, has_item(equal_to((meta_3.pk, 1))))
assert_that(result, has_item(equal_to((meta_4.pk, 1))))
call_command('migrate', 'river', '0006', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_transitionapproval');").fetchall()
columns = six.moves.map(lambda column: column[1], schema)
assert_that(columns, is_not(has_item("iteration")))
call_command('migrate', 'river', '0007', stdout=out)
with connection.cursor() as cur:
result = cur.execute("select meta_id, iteration from river_transitionapproval where object_id=%s;" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(4))
assert_that(result, has_item(equal_to((meta_1.pk, 0))))
assert_that(result, has_item(equal_to((meta_2.pk, 1))))
assert_that(result, has_item(equal_to((meta_3.pk, 1))))
assert_that(result, has_item(equal_to((meta_4.pk, 1))))
@skipUnless(*MIGRATION_TEST_ENABLED)
@skip("Migrations are reset")
def test__shouldAssessIterationsForExistingApprovalsWhenThereIsCycle(self):
out = StringIO()
sys.stout = out
authorized_permission1 = PermissionObjectFactory()
authorized_permission2 = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission1, authorized_permission2])
cycle_state_1 = StateObjectFactory(label="cycle_state_1")
cycle_state_2 = StateObjectFactory(label="cycle_state_2")
cycle_state_3 = StateObjectFactory(label="cycle_state_3")
off_the_cycle_state = StateObjectFactory(label="off_the_cycle_state")
workflow = WorkflowFactory(initial_state=cycle_state_1, content_type=ContentType.objects.get_for_model(BasicTestModel), field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_1,
destination_state=cycle_state_2,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_2,
destination_state=cycle_state_3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_3,
destination_state=cycle_state_1,
)
transition_meta_4 = TransitionMetaFactory.create(
workflow=workflow,
source_state=cycle_state_3,
destination_state=off_the_cycle_state,
)
meta_1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0,
permissions=[authorized_permission1]
)
meta_21 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0,
permissions=[authorized_permission1]
)
meta_22 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=1,
permissions=[authorized_permission2]
)
meta_3 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0,
permissions=[authorized_permission1]
)
final_meta = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_4,
priority=0,
permissions=[authorized_permission1]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_2))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_2))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_3))
approvals = TransitionApproval.objects.filter(workflow=workflow, workflow_object=workflow_object.model)
assert_that(approvals, has_length(5))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=cycle_state_1)
assert_that(workflow_object.model.my_field, equal_to(cycle_state_1))
with connection.cursor() as cur:
result = cur.execute("""
select
river_transitionapproval.meta_id,
iteration
from river_transitionapproval
inner join river_transition rt on river_transitionapproval.transition_id = rt.id
where river_transitionapproval.object_id=%s;
""" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(10))
assert_that(result, has_item(equal_to((meta_1.pk, 0))))
assert_that(result, has_item(equal_to((meta_21.pk, 1))))
assert_that(result, has_item(equal_to((meta_22.pk, 1))))
assert_that(result, has_item(equal_to((meta_3.pk, 2))))
assert_that(result, has_item(equal_to((final_meta.pk, 2))))
assert_that(result, has_item(equal_to((meta_1.pk, 3))))
assert_that(result, has_item(equal_to((meta_21.pk, 4))))
assert_that(result, has_item(equal_to((meta_22.pk, 4))))
assert_that(result, has_item(equal_to((meta_3.pk, 5))))
assert_that(result, has_item(equal_to((final_meta.pk, 5))))
call_command('migrate', 'river', '0006', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_transitionapproval');").fetchall()
columns = six.moves.map(lambda column: column[1], schema)
assert_that(columns, is_not(has_item("iteration")))
call_command('migrate', 'river', '0007', stdout=out)
with connection.cursor() as cur:
result = cur.execute("select meta_id, iteration from river_transitionapproval where object_id=%s;" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(10))
assert_that(result, has_item(equal_to((meta_1.pk, 0))))
assert_that(result, has_item(equal_to((meta_21.pk, 1))))
assert_that(result, has_item(equal_to((meta_22.pk, 1))))
assert_that(result, has_item(equal_to((meta_3.pk, 2))))
assert_that(result, has_item(equal_to((final_meta.pk, 2))))
assert_that(result, has_item(equal_to((meta_1.pk, 3))))
assert_that(result, has_item(equal_to((meta_21.pk, 4))))
assert_that(result, has_item(equal_to((meta_22.pk, 4))))
assert_that(result, has_item(equal_to((meta_3.pk, 5))))
assert_that(result, has_item(equal_to((final_meta.pk, 5))))
@skipUnless(*MIGRATION_TEST_ENABLED)
@skip("Migrations are reset")
def test__shouldMigrationForIterationMustFinishInShortAmountOfTimeWithTooManyObject(self):
out = StringIO()
sys.stout = out
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
state4 = StateObjectFactory(label="state4")
workflow = WorkflowFactory(initial_state=state1, content_type=ContentType.objects.get_for_model(BasicTestModel), field_name="my_field")
transition_meta_1 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state1,
destination_state=state1,
)
transition_meta_2 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state3,
)
transition_meta_3 = TransitionMetaFactory.create(
workflow=workflow,
source_state=state2,
destination_state=state4,
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_1,
priority=0
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=0
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_2,
priority=1
)
TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_meta_3,
priority=0
)
BasicTestModelObjectFactory.create_batch(250)
call_command('migrate', 'river', '0006', stdout=out)
before = datetime.now()
call_command('migrate', 'river', '0007', stdout=out)
after = datetime.now()
assert_that(after - before, less_than(timedelta(minutes=5)))
@skipUnless(*MIGRATION_TEST_ENABLED)
@skip("Migrations are reset")
def test__shouldAssessIterationsForExistingApprovalsWhenThereIsMoreAdvanceCycle(self):
out = StringIO()
sys.stout = out
authorized_permission1 = PermissionObjectFactory()
authorized_permission2 = PermissionObjectFactory()
authorized_user = UserObjectFactory(user_permissions=[authorized_permission1, authorized_permission2])
opn = StateObjectFactory(label="open")
in_progress = StateObjectFactory(label="in_progress")
resolved = StateObjectFactory(label="resolved")
re_opened = StateObjectFactory(label="re_opened")
closed = StateObjectFactory(label="closed")
final = StateObjectFactory(label="final")
workflow = WorkflowFactory(initial_state=opn, content_type=ContentType.objects.get_for_model(BasicTestModel), field_name="my_field")
open_to_in_progress_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=opn,
destination_state=in_progress,
)
in_progress_to_resolved_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=in_progress,
destination_state=resolved
)
resolved_to_re_opened_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=resolved,
destination_state=re_opened
)
re_opened_to_in_progress_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=re_opened,
destination_state=in_progress
)
resolved_to_closed_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=resolved,
destination_state=closed
)
closed_to_final_transition = TransitionMetaFactory.create(
workflow=workflow,
source_state=closed,
destination_state=final
)
open_to_in_progress = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=open_to_in_progress_transition,
priority=0,
permissions=[authorized_permission1]
)
in_progress_to_resolved = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=in_progress_to_resolved_transition,
priority=0,
permissions=[authorized_permission1]
)
resolved_to_re_opened = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=resolved_to_re_opened_transition,
priority=0,
permissions=[authorized_permission2]
)
re_opened_to_in_progress = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=re_opened_to_in_progress_transition,
priority=0,
permissions=[authorized_permission1]
)
resolved_to_closed = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=resolved_to_closed_transition,
priority=0,
permissions=[authorized_permission1]
)
closed_to_final = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=closed_to_final_transition,
priority=0,
permissions=[authorized_permission1]
)
workflow_object = BasicTestModelObjectFactory()
assert_that(workflow_object.model.my_field, equal_to(opn))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(in_progress))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(resolved))
workflow_object.model.river.my_field.approve(as_user=authorized_user, next_state=re_opened)
assert_that(workflow_object.model.my_field, equal_to(re_opened))
workflow_object.model.river.my_field.approve(as_user=authorized_user)
assert_that(workflow_object.model.my_field, equal_to(in_progress))
with connection.cursor() as cur:
result = cur.execute("""
select
river_transitionapproval.meta_id,
iteration
from river_transitionapproval
inner join river_transition rt on river_transitionapproval.transition_id = rt.id
where river_transitionapproval.object_id=%s;
""" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(11))
assert_that(result, has_item(equal_to((open_to_in_progress.pk, 0))))
assert_that(result, has_item(equal_to((in_progress_to_resolved.pk, 1))))
assert_that(result, has_item(equal_to((resolved_to_closed.pk, 2))))
assert_that(result, has_item(equal_to((resolved_to_re_opened.pk, 2))))
assert_that(result, has_item(equal_to((re_opened_to_in_progress.pk, 3))))
assert_that(result, has_item(equal_to((closed_to_final.pk, 3))))
assert_that(result, has_item(equal_to((in_progress_to_resolved.pk, 4))))
assert_that(result, has_item(equal_to((resolved_to_closed.pk, 5))))
assert_that(result, has_item(equal_to((resolved_to_re_opened.pk, 5))))
assert_that(result, has_item(equal_to((re_opened_to_in_progress.pk, 6))))
assert_that(result, has_item(equal_to((closed_to_final.pk, 6))))
call_command('migrate', 'river', '0006', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_transitionapproval');").fetchall()
columns = six.moves.map(lambda column: column[1], schema)
assert_that(columns, is_not(has_item("iteration")))
call_command('migrate', 'river', '0007', stdout=out)
with connection.cursor() as cur:
result = cur.execute("select meta_id, iteration from river_transitionapproval where object_id=%s;" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(11))
assert_that(result, has_item(equal_to((open_to_in_progress.pk, 0))))
assert_that(result, has_item(equal_to((in_progress_to_resolved.pk, 1))))
assert_that(result, has_item(equal_to((resolved_to_closed.pk, 2))))
assert_that(result, has_item(equal_to((resolved_to_re_opened.pk, 2))))
assert_that(result, has_item(equal_to((re_opened_to_in_progress.pk, 3))))
assert_that(result, has_item(equal_to((closed_to_final.pk, 3))))
assert_that(result, has_item(equal_to((in_progress_to_resolved.pk, 4))))
assert_that(result, has_item(equal_to((resolved_to_closed.pk, 5))))
assert_that(result, has_item(equal_to((resolved_to_re_opened.pk, 5))))
assert_that(result, has_item(equal_to((re_opened_to_in_progress.pk, 6))))
assert_that(result, has_item(equal_to((closed_to_final.pk, 6))))
@skipUnless(*MIGRATION_TEST_ENABLED)
@skip("Migrations are reset")
def test__shouldCreateTransitionsAndTransitionMetasOutOfApprovalMetaAndApprovals(self):
out = StringIO()
sys.stout = out
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
state3 = StateObjectFactory(label="state3")
state4 = StateObjectFactory(label="state4")
workflow = WorkflowFactory(initial_state=state1, content_type=ContentType.objects.get_for_model(BasicTestModel), field_name="my_field")
transition_1 = TransitionMetaFactory.create(workflow=workflow, source_state=state1, destination_state=state2)
transition_2 = TransitionMetaFactory.create(workflow=workflow, source_state=state2, destination_state=state3)
transition_3 = TransitionMetaFactory.create(workflow=workflow, source_state=state2, destination_state=state4)
meta_1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_1,
priority=0
)
meta_2 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_2,
priority=0
)
meta_3 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_2,
priority=1
)
meta_4 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_3,
priority=0
)
workflow_object = BasicTestModelObjectFactory()
with connection.cursor() as cur:
result = cur.execute("select id, transition_meta_id from river_transitionapprovalmeta;").fetchall()
assert_that(result, has_length(4))
assert_that(result, has_item(equal_to((meta_1.pk, transition_1.pk))))
assert_that(result, has_item(equal_to((meta_2.pk, transition_2.pk))))
assert_that(result, has_item(equal_to((meta_3.pk, transition_2.pk))))
assert_that(result, has_item(equal_to((meta_4.pk, transition_3.pk))))
result = cur.execute("select id, transition_id from river_transitionapproval where object_id='%s';" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(4))
assert_that(result, has_item(equal_to((meta_1.transition_approvals.first().pk, transition_1.transitions.first().pk))))
assert_that(result, has_item(equal_to((meta_2.transition_approvals.first().pk, transition_2.transitions.first().pk))))
assert_that(result, has_item(equal_to((meta_3.transition_approvals.first().pk, transition_2.transitions.first().pk))))
assert_that(result, has_item(equal_to((meta_4.transition_approvals.first().pk, transition_3.transitions.first().pk))))
call_command('migrate', 'river', '0009', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_transitionapprovalmeta');").fetchall()
columns = [column[1] for column in schema]
assert_that(columns, is_not(has_item("transition_meta_id")))
assert_that(columns, has_item("source_state_id"))
assert_that(columns, has_item("destination_state_id"))
schema = cur.execute("PRAGMA table_info('river_transitionapproval');").fetchall()
columns = [column[1] for column in schema]
assert_that(columns, is_not(has_item("transition_id")))
assert_that(columns, has_item("source_state_id"))
assert_that(columns, has_item("destination_state_id"))
call_command('migrate', 'river', '0010', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_transitionapprovalmeta');").fetchall()
columns = six.moves.map(lambda column: column[1], schema)
assert_that(columns, has_item("transition_meta_id"))
assert_that(columns, is_not(has_item("source_state_id")))
assert_that(columns, is_not(has_item("destination_state_id")))
schema = cur.execute("PRAGMA table_info('river_transitionapproval');").fetchall()
columns = [column[1] for column in schema]
assert_that(columns, has_item("transition_id"))
assert_that(columns, is_not(has_item("source_state_id")))
assert_that(columns, is_not(has_item("destination_state_id")))
with connection.cursor() as cur:
result = cur.execute("select id, transition_meta_id from river_transitionapprovalmeta;").fetchall()
assert_that(result, has_length(4))
assert_that(result, has_item(equal_to((meta_1.pk, transition_1.pk))))
assert_that(result, has_item(equal_to((meta_2.pk, transition_2.pk))))
assert_that(result, has_item(equal_to((meta_3.pk, transition_2.pk))))
assert_that(result, has_item(equal_to((meta_4.pk, transition_3.pk))))
result = cur.execute("select id, transition_id from river_transitionapproval where object_id='%s';" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(4))
assert_that(result, has_item(equal_to((meta_1.transition_approvals.first().pk, transition_1.transitions.first().pk))))
assert_that(result, has_item(equal_to((meta_2.transition_approvals.first().pk, transition_2.transitions.first().pk))))
assert_that(result, has_item(equal_to((meta_3.transition_approvals.first().pk, transition_2.transitions.first().pk))))
assert_that(result, has_item(equal_to((meta_4.transition_approvals.first().pk, transition_3.transitions.first().pk))))
@skipUnless(*MIGRATION_TEST_ENABLED)
@skip("Migrations are reset")
def test__shouldMigrateObjectIdInHooksByCastingItToString(self):
out = StringIO()
sys.stout = out
state1 = StateObjectFactory(label="state1")
state2 = StateObjectFactory(label="state2")
workflow = WorkflowFactory(initial_state=state1, content_type=ContentType.objects.get_for_model(BasicTestModel), field_name="my_field")
transition_1 = TransitionMetaFactory.create(workflow=workflow, source_state=state1, destination_state=state2)
transition_approval_meta_1 = TransitionApprovalMetaFactory.create(
workflow=workflow,
transition_meta=transition_1,
priority=0
)
workflow_object = BasicTestModelObjectFactory()
callback_method = """
from river.tests.hooking.base_hooking_test import callback_output
def handle(context):
print(context)
key = '%s'
callback_output[key] = callback_output.get(key,[]) + [context]
"""
callback_function = Function.objects.create(name=uuid4(), body=callback_method % str(uuid4()))
OnApprovedHook.objects.create(
workflow=workflow,
callback_function=callback_function,
transition_approval_meta=transition_approval_meta_1,
hook_type=BEFORE,
workflow_object=workflow_object.model
)
OnCompleteHook.objects.create(
workflow=workflow,
callback_function=callback_function,
hook_type=BEFORE,
workflow_object=workflow_object.model
)
OnTransitHook.objects.create(
workflow=workflow,
callback_function=callback_function,
transition_meta=transition_1,
hook_type=BEFORE,
workflow_object=workflow_object.model
)
call_command('migrate', 'river', '0013', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_onapprovedhook');").fetchall()
column_type = next(iter([column[2] for column in schema if column[1] == 'object_id']), None)
assert_that(column_type, equal_to("integer unsigned"))
schema = cur.execute("PRAGMA table_info('river_ontransithook');").fetchall()
column_type = next(iter([column[2] for column in schema if column[1] == 'object_id']), None)
assert_that(column_type, equal_to("integer unsigned"))
schema = cur.execute("PRAGMA table_info('river_oncompletehook');").fetchall()
column_type = next(iter([column[2] for column in schema if column[1] == 'object_id']), None)
assert_that(column_type, equal_to("integer unsigned"))
result = cur.execute("select object_id from river_onapprovedhook where object_id='%s';" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(1))
assert_that(result[0][0], equal_to(workflow_object.model.pk))
result = cur.execute("select object_id from river_ontransithook where object_id='%s';" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(1))
assert_that(result[0][0], equal_to(workflow_object.model.pk))
result = cur.execute("select object_id from river_oncompletehook where object_id='%s';" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(1))
assert_that(result[0][0], equal_to(workflow_object.model.pk))
call_command('migrate', 'river', '0014', stdout=out)
with connection.cursor() as cur:
schema = cur.execute("PRAGMA table_info('river_onapprovedhook');").fetchall()
column_type = next(iter([column[2] for column in schema if column[1] == 'object_id']), None)
assert_that(column_type, equal_to("varchar(200)"))
schema = cur.execute("PRAGMA table_info('river_ontransithook');").fetchall()
column_type = next(iter([column[2] for column in schema if column[1] == 'object_id']), None)
assert_that(column_type, equal_to("varchar(200)"))
schema = cur.execute("PRAGMA table_info('river_oncompletehook');").fetchall()
column_type = next(iter([column[2] for column in schema if column[1] == 'object_id']), None)
assert_that(column_type, equal_to("varchar(200)"))
result = cur.execute("select object_id from river_onapprovedhook where object_id='%s';" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(1))
assert_that(result[0][0], equal_to(str(workflow_object.model.pk)))
result = cur.execute("select object_id from river_ontransithook where object_id='%s';" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(1))
assert_that(result[0][0], equal_to(str(workflow_object.model.pk)))
result = cur.execute("select object_id from river_oncompletehook where object_id='%s';" % workflow_object.model.pk).fetchall()
assert_that(result, has_length(1))
assert_that(result[0][0], equal_to(str(workflow_object.model.pk)))
<file_sep>#!/bin/bash
set -e
ENVIRONMENT=$1
if [ -z "$ENVIRONMENT" ]; then
ENVIRONMENT="test"
fi
if [ "$ENVIRONMENT" == "prod" ]; then
REPOSITORY=pypi
elif [ "$ENVIRONMENT" == "test" ]; then
REPOSITORY=testpypi
else
echo "First argument which is the environment has to be either 'prod' or 'test' not ${ENVIRONMENT}"
exit 1
fi
[ -e dist ] && rm -rf dist
[ -e build ] && rm -rf build
[ -e django_river.egg-info ] && rm -rf django_river.egg-info
python setup.py sdist bdist_wheel
twine check dist/*
echo "Publishing to ${REPOSITORY}"
twine upload --repository "$REPOSITORY" --config-file="${PWD}/.pypirc" dist/*
<file_sep>import logging
from django.contrib.contenttypes.models import ContentType
from django.db.models import CASCADE
from django.db.models.signals import post_save, post_delete
from river.core.riverobject import RiverObject
from river.core.workflowregistry import workflow_registry
from river.models import OnApprovedHook, OnTransitHook, OnCompleteHook
try:
from django.contrib.contenttypes.fields import GenericRelation
except ImportError:
from django.contrib.contenttypes.generic import GenericRelation
from river.models.state import State
from river.models.transitionapproval import TransitionApproval
from river.models.transition import Transition
from django.db import models
LOGGER = logging.getLogger(__name__)
class classproperty(object):
def __init__(self, getter):
self.getter = getter
def __get__(self, instance, owner):
return self.getter(instance) if instance else self.getter(owner)
class StateField(models.ForeignKey):
def __init__(self, *args, **kwargs):
self.field_name = None
kwargs['null'] = True
kwargs['blank'] = True
kwargs['to'] = '%s.%s' % (State._meta.app_label, State._meta.object_name)
kwargs['on_delete'] = kwargs.get('on_delete', CASCADE)
kwargs['related_name'] = "+"
super(StateField, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name, *args, **kwargs):
@classproperty
def river(_self):
return RiverObject(_self)
self.field_name = name
self._add_to_class(cls, self.field_name + "_transition_approvals",
GenericRelation('%s.%s' % (TransitionApproval._meta.app_label, TransitionApproval._meta.object_name)))
self._add_to_class(cls, self.field_name + "_transitions", GenericRelation('%s.%s' % (Transition._meta.app_label, Transition._meta.object_name)))
if id(cls) not in workflow_registry.workflows:
self._add_to_class(cls, "river", river)
super(StateField, self).contribute_to_class(cls, name, *args, **kwargs)
if id(cls) not in workflow_registry.workflows:
post_save.connect(_on_workflow_object_saved, self.model, False, dispatch_uid='%s_%s_riverstatefield_post' % (self.model, name))
post_delete.connect(_on_workflow_object_deleted, self.model, False, dispatch_uid='%s_%s_riverstatefield_post' % (self.model, name))
workflow_registry.add(self.field_name, cls)
@staticmethod
def _add_to_class(cls, key, value, ignore_exists=False):
if ignore_exists or not hasattr(cls, key):
cls.add_to_class(key, value)
def _on_workflow_object_saved(sender, instance, created, *args, **kwargs):
for instance_workflow in instance.river.all(instance.__class__):
if created:
instance_workflow.initialize_approvals()
if not instance_workflow.get_state():
init_state = getattr(instance.__class__.river, instance_workflow.field_name).initial_state
instance_workflow.set_state(init_state)
instance.save()
def _on_workflow_object_deleted(sender, instance, *args, **kwargs):
OnApprovedHook.objects.filter(object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance.__class__)).delete()
OnTransitHook.objects.filter(object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance.__class__)).delete()
OnCompleteHook.objects.filter(object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance.__class__)).delete()
<file_sep>import inspect
from river.core.classworkflowobject import ClassWorkflowObject
from river.core.instanceworkflowobject import InstanceWorkflowObject
from river.core.workflowregistry import workflow_registry
# noinspection PyMethodMayBeStatic
class RiverObject(object):
def __init__(self, owner):
self.owner = owner
self.is_class = inspect.isclass(owner)
def __getattr__(self, field_name):
cls = self.owner if self.is_class else self.owner.__class__
if field_name not in workflow_registry.workflows[id(cls)]:
raise Exception("Workflow with name:%s doesn't exist for class:%s" % (field_name, cls.__name__))
if self.is_class:
return ClassWorkflowObject(self.owner, field_name)
else:
return InstanceWorkflowObject(self.owner, field_name)
def all(self, cls):
return list([getattr(self, field_name) for field_name in workflow_registry.workflows[id(cls)]])
def all_field_names(self, cls): # pylint: disable=no-self-use
return [field_name for field_name in workflow_registry.workflows[id(cls)]]
<file_sep>from django.db import models
from django.db.models import CASCADE
from django.utils.translation import ugettext_lazy as _
from river.models import TransitionApprovalMeta, TransitionApproval
from river.models.hook import Hook
class OnApprovedHook(Hook):
class Meta:
unique_together = [('callback_function', 'workflow', 'transition_approval_meta', 'content_type', 'object_id', 'transition_approval')]
transition_approval_meta = models.ForeignKey(
TransitionApprovalMeta, verbose_name=_("Transition Approval Meta"), related_name='on_approved_hooks', on_delete=CASCADE)
transition_approval = models.ForeignKey(
TransitionApproval, verbose_name=_("Transition Approval"), related_name='on_approved_hooks', null=True, blank=True, on_delete=CASCADE)
<file_sep>default_app_config = 'river.apps.RiverApp'
<file_sep>import logging
import operator
from functools import reduce
from django.apps import AppConfig
from django.db.utils import OperationalError, ProgrammingError
LOGGER = logging.getLogger(__name__)
class RiverApp(AppConfig):
name = 'river'
label = 'river'
def ready(self):
for field_name in self._get_all_workflow_fields():
try:
workflows = self.get_model('Workflow').objects.filter(field_name=field_name)
if workflows.count() == 0:
LOGGER.warning("%s field doesn't seem have any workflow defined in database. You should create its workflow" % field_name)
except (OperationalError, ProgrammingError):
pass
from river.config import app_config
if app_config.INJECT_MODEL_ADMIN:
for model_class in self._get_all_workflow_classes():
self._register_hook_inlines(model_class)
LOGGER.debug('RiverApp is loaded.')
@classmethod
def _get_all_workflow_fields(cls):
from river.core.workflowregistry import workflow_registry
return reduce(operator.concat, map(list, workflow_registry.workflows.values()), [])
@classmethod
def _get_all_workflow_classes(cls):
from river.core.workflowregistry import workflow_registry
return list(workflow_registry.class_index.values())
@classmethod
def _get_workflow_class_fields(cls, model):
from river.core.workflowregistry import workflow_registry
return workflow_registry.workflows[id(model)]
def _register_hook_inlines(self, model): # pylint: disable=no-self-use
from django.contrib import admin
from river.core.workflowregistry import workflow_registry
from river.admin import OnApprovedHookInline, OnTransitHookInline, OnCompleteHookInline, DefaultWorkflowModelAdmin
registered_admin = admin.site._registry.get(model, None)
if registered_admin:
if OnApprovedHookInline not in registered_admin.inlines:
registered_admin.inlines = list(set(registered_admin.inlines + [OnApprovedHookInline, OnTransitHookInline, OnCompleteHookInline]))
registered_admin.readonly_fields = list(set(list(registered_admin.readonly_fields) + list(workflow_registry.get_class_fields(model))))
admin.site._registry[model] = registered_admin
else:
admin.site.register(model, DefaultWorkflowModelAdmin)
<file_sep>import logging
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.dispatch import Signal
from river.models import Workflow
from river.models.hook import BEFORE, AFTER
from river.models.on_approved_hook import OnApprovedHook
from river.models.on_complete_hook import OnCompleteHook
from river.models.on_transit_hook import OnTransitHook
pre_on_complete = Signal(providing_args=["workflow_object", "field_name", ])
post_on_complete = Signal(providing_args=["workflow_object", "field_name", ])
pre_transition = Signal(providing_args=["workflow_object", "field_name", "source_state", "destination_state"])
post_transition = Signal(providing_args=["workflow_object", "field_name", "source_state", "destination_state"])
pre_approve = Signal(providing_args=["workflow_object", "field_name", "transition_approval"])
post_approve = Signal(providing_args=["workflow_object", "field_name", "transition_approval", "transition_approval_meta"])
LOGGER = logging.getLogger(__name__)
class TransitionSignal(object):
def __init__(self, status, workflow_object, field_name, transition_approval):
self.status = status
self.workflow_object = workflow_object
self.field_name = field_name
self.transition_approval = transition_approval
self.content_type = ContentType.objects.get_for_model(self.workflow_object.__class__)
self.workflow = Workflow.objects.get(content_type=self.content_type, field_name=self.field_name)
def __enter__(self):
if self.status:
for hook in OnTransitHook.objects.filter(
(Q(object_id__isnull=True) | Q(object_id=self.workflow_object.pk, content_type=self.content_type)) &
(Q(transition__isnull=True) | Q(transition=self.transition_approval.transition)) &
Q(
workflow__field_name=self.field_name,
transition_meta=self.transition_approval.transition.meta,
hook_type=BEFORE
)
):
hook.execute(self._get_context(BEFORE))
LOGGER.debug("The signal that is fired right before the transition ( %s ) happened for %s"
% (self.transition_approval.transition, self.workflow_object))
def __exit__(self, type, value, traceback):
if self.status:
for hook in OnTransitHook.objects.filter(
(Q(object_id__isnull=True) | Q(object_id=self.workflow_object.pk, content_type=self.content_type)) &
(Q(transition__isnull=True) | Q(transition=self.transition_approval.transition)) &
Q(
workflow=self.workflow,
transition_meta=self.transition_approval.transition.meta,
hook_type=AFTER
)
):
hook.execute(self._get_context(AFTER))
LOGGER.debug("The signal that is fired right after the transition ( %s) happened for %s"
% (self.transition_approval.transition, self.workflow_object))
def _get_context(self, when):
return {
"hook": {
"type": "on-transit",
"when": when,
"payload": {
"workflow": self.workflow,
"workflow_object": self.workflow_object,
"transition_approval": self.transition_approval
}
},
}
class ApproveSignal(object):
def __init__(self, workflow_object, field_name, transition_approval):
self.workflow_object = workflow_object
self.field_name = field_name
self.transition_approval = transition_approval
self.content_type = ContentType.objects.get_for_model(self.workflow_object.__class__)
self.workflow = Workflow.objects.get(content_type=self.content_type, field_name=self.field_name)
def __enter__(self):
for hook in OnApprovedHook.objects.filter(
(Q(object_id__isnull=True) | Q(object_id=self.workflow_object.pk, content_type=self.content_type)) &
(Q(transition_approval__isnull=True) | Q(transition_approval=self.transition_approval)) &
Q(
workflow__field_name=self.field_name,
transition_approval_meta=self.transition_approval.meta,
hook_type=BEFORE
)
):
hook.execute(self._get_context(BEFORE))
LOGGER.debug("The signal that is fired right before a transition approval is approved for %s due to transition %s -> %s" % (
self.workflow_object, self.transition_approval.transition.source_state.label, self.transition_approval.transition.destination_state.label))
def __exit__(self, type, value, traceback):
for hook in OnApprovedHook.objects.filter(
(Q(object_id__isnull=True) | Q(object_id=self.workflow_object.pk, content_type=self.content_type)) &
(Q(transition_approval__isnull=True) | Q(transition_approval=self.transition_approval)) &
Q(
workflow__field_name=self.field_name,
transition_approval_meta=self.transition_approval.meta,
hook_type=AFTER
)
):
hook.execute(self._get_context(AFTER))
LOGGER.debug("The signal that is fired right after a transition approval is approved for %s due to transition %s -> %s" % (
self.workflow_object, self.transition_approval.transition.source_state.label, self.transition_approval.transition.destination_state.label))
def _get_context(self, when):
return {
"hook": {
"type": "on-approved",
"when": when,
"payload": {
"workflow": self.workflow,
"workflow_object": self.workflow_object,
"transition_approval": self.transition_approval
}
},
}
class OnCompleteSignal(object):
def __init__(self, workflow_object, field_name):
self.workflow_object = workflow_object
self.field_name = field_name
self.workflow = getattr(self.workflow_object.river, self.field_name)
self.status = self.workflow.on_final_state
self.content_type = ContentType.objects.get_for_model(self.workflow_object.__class__)
self.workflow = Workflow.objects.get(content_type=self.content_type, field_name=self.field_name)
def __enter__(self):
if self.status:
for hook in OnCompleteHook.objects.filter(
(Q(object_id__isnull=True) | Q(object_id=self.workflow_object.pk, content_type=self.content_type)) &
Q(
workflow__field_name=self.field_name,
hook_type=BEFORE
)
):
hook.execute(self._get_context(BEFORE))
LOGGER.debug("The signal that is fired right before the workflow of %s is complete" % self.workflow_object)
def __exit__(self, type, value, traceback):
if self.status:
for hook in OnCompleteHook.objects.filter(
(Q(object_id__isnull=True) | Q(object_id=self.workflow_object.pk, content_type=self.content_type)) &
Q(
workflow__field_name=self.field_name,
hook_type=AFTER
)
):
hook.execute(self._get_context(AFTER))
LOGGER.debug("The signal that is fired right after the workflow of %s is complete" % self.workflow_object)
def _get_context(self, when):
return {
"hook": {
"type": "on-complete",
"when": when,
"payload": {
"workflow": self.workflow,
"workflow_object": self.workflow_object,
}
},
}
| 42e47dcebbab278c0665c8b0d89953c19a98f562 | [
"SQL",
"reStructuredText",
"Markdown",
"INI",
"Python",
"Text",
"Shell"
] | 87 | Python | arjun2504/django-river | 8202905407e316aae5d95661376eed9b3fa85724 | 7326f5c24e136b171812d95388b37f65a7c4064b |
refs/heads/master | <file_sep>from InventoryAllocator import InventoryAllocator
import unittest
class Test(unittest.TestCase):
# case 1: one warehouse is enough
def test_case1(self):
orders1 = {'apple': 1, 'banana': 2}
w1 = [{'name': 'owd', 'inventory': {'apple': 1, 'banana': 2}}]
self.assertEqual([{'owd': {'apple': 1, 'banana': 2}}],InventoryAllocator.cheapestcost(orders1,w1))
# case 2: total stock is not enough for orders, then output empty
def test_case2(self):
orders2 = {'apple': 5, 'kiwi': 2}
w2 = [{'name': 'eve', 'inventory': {'kiwi': 1, 'banana': 2}}, {'name': 'ded', 'inventory': {'apple': 3}}]
self.assertEqual([], InventoryAllocator.cheapestcost(orders2, w2))
# case 3: some items in orders need to be seperated from different warehouses
def test_case3(self):
orders3 = {'apple': 5, 'banana': 2}
w3 = [{'name': 'owd', 'inventory': {'apple': 2, 'banana': 2}}, {'name': 'ded', 'inventory': {'apple': 3}}]
self.assertEqual([{'owd': {'apple': 2, 'banana': 2}}, {'ded': {'apple': 3}}], InventoryAllocator.cheapestcost(orders3, w3))
# case 4: we only take what we need in some warehouses not all of the stock in these warehouses
def test_case4(self):
orders4 = {'apple': 5, 'kiwi': 2, 'banana': 3}
w4 = [{'name': 'owd', 'inventory': {'apple': 2, 'banana': 2, 'prune': 2}},
{'name': 'eve', 'inventory': {'kiwi': 2, 'banana': 2}}, {'name': 'ded', 'inventory': {'apple': 3}}]
self.assertEqual([{'owd': {'apple': 2, 'banana': 2}}, {'eve': {'kiwi': 2, 'banana': 1}}, {'ded': {'apple': 3}}], InventoryAllocator.cheapestcost(orders4, w4))
# case 5:the warehouses which do not have what we want is useless
def test_case5(self):
orders5 = {'apple': 3, 'prune': 3}
w5 = [{'name': 'owd', 'inventory': {'apple': 2, 'banana': 2}},
{'name': 'ded', 'inventory': {'kiwi': 3, 'banana': 3}},
{'name': 'eve', 'inventory': {'prune': 3, 'apple': 2}}]
self.assertEqual([{'owd': {'apple': 2}}, {'eve': {'prune': 3, 'apple': 1}}], InventoryAllocator.cheapestcost(orders5, w5))
if __name__ == '__main__':
unittest.main(verbosity=1)<file_sep>
class InventoryAllocator(object):
@classmethod
def cheapestcost(self,orders, warehouses):
# get total numbers of items
total = sum(orders.values())
res = []
n = len(warehouses)
suc = False
for i in range(n):
#iterate each warehouse from cheapiest cost to highest cost
dic = {}
items = warehouses[i]['inventory']
for j in items:
#if we still need j item
if not items[j] or j not in orders or not orders[j]: continue
# we will add this warehouse to our solution
f = True
take = min(orders[j], items[j])
dic[j] = take
orders[j] -= take
total -= take
if len(dic) > 0:
w = {warehouses[i]['name']: dic}
res.append(w)
# once all items are satisfied, we will mark and break the loop
if not total:
break
return res if not total else []
if __name__ == '__main__':
#case 1: one warehouse is enough
orders1 = { 'apple':1 ,'banana':2}
w1 = [{'name': 'owd', 'inventory': {'apple': 1,'banana':2}}]
#case 2: total stock is not enough for orders, then output empty
orders2 = {'apple':5,'kiwi':2}
w2 = [{'name': 'eve', 'inventory': {'kiwi': 1,'banana':2}},{'name': 'ded', 'inventory': {'apple': 3}}]
#case 3: some items in orders need to be seperated from different warehouses
orders3 = {'apple':5,'banana':2}
w3 = [{'name': 'owd', 'inventory': {'apple': 2,'banana':2}},{'name': 'ded', 'inventory': {'apple': 3}}]
#case 4: we only take what we need in some warehouses not all of the stock in these warehouses
orders4 = {'apple':5,'kiwi':2,'banana':3}
w4 = [{'name': 'owd', 'inventory': {'apple': 2,'banana':2,'prune':2}},{'name': 'eve', 'inventory': {'kiwi': 2,'banana':2}},{'name': 'ded', 'inventory': {'apple': 3}}]
#case 5:the warehouses which do not have what we want is useless
orders5 = {'apple':3,'prune':3}
w5 = [{'name': 'owd', 'inventory': {'apple': 2,'banana':2}},{'name': 'ded', 'inventory': {'kiwi': 3,'banana':3}},{'name': 'eve', 'inventory': {'prune': 3,'apple':2}}]
print(InventoryAllocator.cheapestcost(orders3,w3))
| 33e523ef7fada640899d95b4c6f80b9f3e87147b | [
"Python"
] | 2 | Python | Chris-Yen68/recruiting-exercises | a1b6660829278ca6fa0c84efc48a780ea683e291 | 5a8892260e2b383219218c262688115996b3ae87 |
refs/heads/master | <repo_name>Mawa89/mon_agence_web<file_sep>/main.js
window.onscroll = () => {
const nav = document.querySelector("#navbar");
if (this.scrollY <= 10) nav.className = "";
else nav.className = "scroll";
};
$(document).ready(function() {
$(".js-scrollTo").on("click", function() {
// Au clic sur un élément
var page = $(this).attr("href"); // Page cible
var speed = 1500; // Durée de l'animation (en ms)
$("html, body").animate({ scrollTop: $(page).offset().top }, speed); // Go
return false;
});
});
function rouge_simple() {
document.getElementById("simple").style.backgroundColor = "red";
}
var i = 0;
var txt = "ui sommes nous?"; /* le text */
var speed = 100;
var presentation = document.getElementsByClassName("presentation");
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
typeWriter();
//toggle
// forEach method
window.console = window.console || function(t) {};
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {if (window.CP.shouldStopExecution(0)) break;
callback.call(scope, i, array[i]);
}window.CP.exitedLoop(0);
};
var spinner = document.querySelector("#spinner"),
angle = 0,
images = document.querySelectorAll("#spinner figure"),
numpics = images.length,
degInt = 360 / numpics,
start = 0,
current = 1;
forEach(images, function (index, value) {
images[index].style.webkitTransform = "rotateY(-" + start + "deg)";
images[index].style.transform = "rotateY(-" + start + "deg)";
});
images[index].addEventListener("click", function () {
if (this.classList.contains('current')) {
this.classList.toggle("focus");
}
start = start + degInt;
});
function setCurrent(current) {
document.querySelector('figure#spinner figure:nth-child(' + current + ')').classList.add('current');
}
function galleryspin(sign) {
forEach(images, function (index, value) {
images[index].classList.remove('current');
images[index].classList.remove('focus');
images[index].classList.remove('caption');
});
if (!sign) {angle = angle + degInt;
current = current + 1;
if (current > numpics) {current = 1;}
} else {
angle = angle - degInt;
current = current - 1;
if (current == 0) {current = numpics;}
}
spinner.setAttribute("style", "-webkit-transform: rotateY(" + angle + "deg); transform: rotateY(" + angle + "deg)");
setCurrent(current);
}
document.body.onkeydown = function (e) {
switch (e.which) {
case 37: // left cursor
galleryspin('-');
break;
case 39: // right cursor
galleryspin('');
break;
case 90: // Z - zoom image in forefront image
document.querySelector('figure#spinner figure.current').classList.toggle('focus');
break;
case 67: // C - show caption for forefront image
document.querySelector('figure#spinner figure.current').classList.toggle('caption');
break;
default:return; // exit this handler for other keys
}
e.preventDefault();
};
setCurrent(1);
//# sourceURL=pen.js
| 7b7d64902928503c1a0d290a38037e7c2711ea70 | [
"JavaScript"
] | 1 | JavaScript | Mawa89/mon_agence_web | 4bb8f73aac857d76005fe4239171c2d69683d434 | c9d2f7dd9f1d9c2d2527fddded1d8194f5ae0820 |
refs/heads/master | <repo_name>RajuRaghuwanshi/Tic-Tac-Toe-Game-in-C<file_sep>/TicTacToe.c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
char matrix[3][3];
int cordiX,cordiY;
void Draw_Rect();
void gotoxy(int x, int y);
void Draw_matrix();
void get_player();
void init_Matrix();
void get_computer();
char Check_win();
int main()
{
int i=0,check = 1;
SetConsoleTitle("Tic Tac Toe developed by Raghuwanshi !");
//Draw_Rect();
Draw_matrix();
init_Matrix();
while(check) {
get_player();
get_computer();
Draw_matrix();
if(Check_win()=='X'||Check_win()=='0')
{
printf(Check_win()=='X'?"\n\nCongratulations you have won !!":"\n\nSorry you have lose !!");
check = 0;
}
}
/* int i=0;
while(i++<=4) {
get_player();
get_computer();
// Draw_matrix();
}
/* int i=0,x,y;
while(i++<=10) {
printf("Enter x and Y : ");
scanf("%d %d",&x,&y);
printf("%d %d\n",Cordi_X(x),Cordi_Y(y));
}
*/
getch();
}
COORD coord = {0,0}; //set the cordinate 0,0{top most left}
void gotoxy(int x, int y)
{
coord.X = x,coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void init_Matrix()
{
auto int i,j;
for(i=0; i<3; i++)
for(j=0; j<3; j++)
matrix[i][j] = ' ';
}
void Draw_Rect()
{
auto int i;
gotoxy(0,0);
printf("%c",201);
for(i=1; i<120; i++)
{
gotoxy(i,0);
if(i==119)
printf("%c",187);
else
printf("%c",205);
}
for(i=1; i<45; i++)
{
gotoxy(0,i);
if(i==7)
printf("%c",204);
else
printf("%c",186);
}
gotoxy(0,45);
printf("%c",200);
for(i=1; i<45; i++)
{
gotoxy(119,i);
if(i==7)
printf("%c",185);
else
printf("%c",186);
}
for(i=1; i<119; i++)
{
gotoxy(i,7);
printf("%c",205);
}
gotoxy(119,45);
printf("%c",188);
for(i=1; i<119; i++)
{
gotoxy(i,45);
printf("%c",205);
}
}
void Draw_matrix()
{
auto int i;
for(i=0; i<3; i++)
{
printf("%c |%c |%c ",matrix[i][0],matrix[i][1],matrix[i][2]);
printf("\n | | ");
if(i!=2)
printf("\n===|===|===\n");
}
}
void get_player()
{
int X,Y;
printf("\nEnter x and y cordinate for your move :");
scanf("%d %d",&cordiX,&cordiY);
cordiX--;
cordiY--;
if((matrix[cordiX][cordiY] != ' ')||(Check_posi(cordiX,cordiY)==0)||cordiX>=3||cordiY>=3)
{
printf("\nInvalid move ! try again !");
get_player();
}
else {
matrix[cordiX][cordiY] = 'X';
}
}
int Check_posi(int x,int y)
{
if(matrix[x][y]!='X'&&matrix[x][y]!='0')
return 1;
else
return 0;
}
void get_computer() {
int temp1 = rand()%3;
int temp2 = rand()%3;
if((matrix[temp1][temp2] != ' ')||(Check_posi(temp1,temp2)==0))
{
get_computer();
}
else
matrix[temp1][temp2] = '0';
}
char Check_win() {
int i;
for(i=0; i<=2; i++) {
if((matrix[i][0]==matrix[i][1])&&(matrix[i][0]==matrix[i][2]))
return matrix[i][0];
}
for(i=0; i<=2; i++) {
if((matrix[0][i]==matrix[1][i])&&(matrix[0][i]==matrix[2][i]))
return matrix[0][i];
}
if(matrix[0][0]==matrix[1][1]&&matrix[0][0]==matrix[2][2])
return matrix[0][0];
if(matrix[0][2]==matrix[1][1]&&matrix[0][2]==matrix[2][0])
return matrix[0][2];
}
int Cordi_X() {
int temp;
srand ( time(NULL) );
temp = rand()%3;
return temp;
}
int Cordi_Y() {
int temp;
srand ( time(NULL) );
temp = rand()%3;
return temp;
}
| 43ff189a1d0f6de1565364eff8862727a48742b1 | [
"C"
] | 1 | C | RajuRaghuwanshi/Tic-Tac-Toe-Game-in-C | de786cf70292a3ae9dd29dac6a95e172c8447adc | 8333fd05ad8e1331aa08b1f447b10b52c10f8daa |
refs/heads/master | <file_sep># mstools [](https://travis-ci.org/szydell/mstools) [](https://coveralls.io/github/szydell/mstools?branch=master)
Tools I use in different GO projects.
..
<file_sep>package mstools
import (
"log"
"math"
"os"
"errors"
)
//Round
func Round(val float64, places int ) (float64) {
var round float64
pow := math.Pow(10, float64(places))
digit := pow * val
_, div := math.Modf(digit)
if div >= 0.5 {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
return round / pow
}
//ErrCheck log and die on error
func ErrCheck(e error) {
if e != nil {
log.Fatal(e)
}
}
//FExists does file exist?
func FExists(fName string) (exist bool , err error) {
exist = false
if _, err := os.Stat(fName); err == nil {
exist = true
}
return
}
//FileOrDir returns if it is a file (f), or dir (d) or 'u' and an error if does not exist
func FileOrDir(fName string) (fType byte, err error) {
fType = 'u'
fi, err := os.Stat(fName)
if err != nil {
return
}
switch mode := fi.Mode(); {
case mode.IsDir():
fType = 'd'
case mode.IsRegular():
fType = 'f'
default:
err = errors.New("unkown type")
}
return
}
<file_sep>//tests for mstools
package mstools
import "testing"
func TestRound(t *testing.T) {
rounded:= Round(1.230001121135135,2)
if rounded != 1.23 {
t.Errorf("Rounded value is wrong. Wanted: %f, got: %f.", 1.23, rounded)
}
}
| 71d03adb515112ab20fe2a7dc6908bcc0654509a | [
"Markdown",
"Go"
] | 3 | Markdown | szydell/mstools | 6dc592205339d8288416d88dd7f69a1bca27f086 | 39c9a8e0f5a92b23a081b57c2bc1ba6378588d88 |
refs/heads/master | <file_sep>angular.module('blockchainMonitorApp')
.directive('transactions', function(Blockchain) {
return {
restrict: 'E',
replace: true,
link: function(scope, element, attrs) {
scope.txList = [];
Blockchain.getTicker(function(data) {
if (data.op != 'utx')
return;
var total = 0;
for (var i=0; i<data.x.out.length; i++) {
total += data.x.out[i].value;
}
scope.txList.splice(0, 0, {
amt: parseFloat(total) / 100000000.0,
hash: data.x.hash
})
while (scope.txList.length > 50) {
scope.txList.pop();
}
})
},
template: '<div class="tx-wrapper"><div class="tx" ng-repeat="tx in txList"><strong>{{tx.amt}} BTC</strong> ({{ tx.hash.substring(0, 40) }}...)</div></div>'
}
})<file_sep># btc-viz
<file_sep>var gzippo = require('gzippo');
var express = require('express');
var morgan = require('morgan');
var http = require('http');
var app = express();
app.use(morgan('dev'));
app.use(gzippo.staticGzip("" + __dirname + "/dist"));
// app.use(gzippo.staticGzip("" + __dirname + "/app"));
app.listen(process.env.PORT || 5000);
app.get('/bitstamp', function(req, res){
var options = {
host: 'www.bitstamp.net',
path: '/api/order_book/'
};
var callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(str);
res.end();
});
}
http.request(options, callback).end();
});
app.get('/ticker', function(req, res){
var options = {
host: 'www.bitstamp.net',
path: '/api/ticker/'
};
var callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(str);
res.end();
});
}
http.request(options, callback).end();
});
console.log('\nReady!')<file_sep>angular.module('blockchainMonitorApp.services.bitstamp', [])
.factory('Bitstamp', function($pusher, $http, $resource) {
var client = new Pusher('de504dc5763aeef9ff52')
, pusher = $pusher(client)
, orderBookChannel = pusher.subscribe('diff_order_book')
, tickerChannel = pusher.subscribe('live_trades');
function getOrderBook(cb) {
$http.get('/bitstamp').success(cb);
}
function getRTOrderBookDiff(cb) {
orderBookChannel.bind('data', cb);
}
function getTicker(cb) {
tickerChannel.bind('trade', cb);
}
return {
getOrderBook: getOrderBook,
getRTOrderBookDiff: getRTOrderBookDiff,
getTicker: getTicker
};
});
<file_sep>angular.module('blockchainMonitorApp')
.directive('slidingGraph', function() {
return {
restrict: 'A',
scope: {
trackData: '='
},
link: function(scope, element, attrs) {
var min_y = 200
, max_y = 300;
var n = 100
// random = d3.random.normal(200),
, data = d3.range(n).map(function() {return 200.0;})
, avgdata = d3.range(n).map(function() {return 200.0;});
var x, y, line, avgline, svg, path, avgpath, newAvg;
var margin = {top: 20, right: 20, bottom: 20, left: 40},
width = 500 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
function redraw() {
x = d3.scale.linear()
.domain([1, n - 2])
.range([0, width]);
y = d3.scale.linear()
// .domain([min_y, max_y])
.domain([min_y - 20, max_y + 20])
.range([height, 0]);
line = d3.svg.line()
.interpolate("basis")
.x(function(d, i) { return x(i); })
.y(function(d, i) { return y(d); });
avgline = d3.svg.line()
.interpolate("basis")
.x(function(d, i) { return x(i); })
.y(function(d, i) { return y(d); });
if (svg)
svg.selectAll("*").remove();
svg = d3.select(element[0])
// console.log(d3.select(element))
// svg = d3.select(element[0])
// .remove()
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
// svg.append("g")
// .attr("class", "x axis")
// .attr("transform", "translate(0," + y(0) + ")")
// .call(d3.svg.axis().scale(x).orient("bottom"));
svg.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(y).orient("left"));
path = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
avgpath = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("path")
.datum(avgdata)
.attr("class", "avgline")
.attr("d", avgline);
}
redraw();
tick();
function tick() {
// push a new data point onto the back
// if (scope.trackData.buffer.length > 0) {
var newVal = parseFloat(scope.trackData.buffer.shift());
// , lastVal = scope.trackData.last20[scope.trackData.last.length - 1];
// console.log(newVal)
// if (scope.trackData.last === 0.0) {
// scope.trackData.last = newVal;
// } else if {
// if (newVal === 0 || (newVal/lastVal > 0.5 && newVal/lastVal < 1.5)) {
// scope.trackData.last = newVal;
// }
// }
// }
if (scope.trackData.last20.length > 0) {
var total = 0.0;
for (var i=0; i<scope.trackData.last20.length; i++) {
total += scope.trackData.last20[i];
}
// console.log('arr', scope.trackData.last20)
newAvg = total / parseFloat(scope.trackData.last20.length);
}
// console.log('newavg', newAvg)
var new_min_y = data[0]
, new_max_y = data[0];
for (var i=0; i<data.length; i++) {
if (data[i] < new_min_y) {
new_min_y = data[i];
} else if(data[i] > new_max_y) {
new_max_y = data[i];
}
}
if (new_min_y != min_y || new_max_y != max_y) {
max_y = new_max_y;
min_y = new_min_y;
// y = d3.scale.linear()
// .domain([min_y - 20, max_y + 20])
// .range([height, 0]);
redraw();
}
// console.log(scope.trackData.last)
if (newVal)
data.push(newVal);
else
data.push(data[data.length-1])
if (newAvg)
avgdata.push(newAvg)
else
avgdata.push(avgdata[avgdata.length-1])
// redraw the line, and slide it to the left
path
.attr("d", line)
.attr("transform", null)
.transition()
.duration(200)
.ease("linear")
.attr("transform", "translate(" + x(0) + ",0)")
// .each("end", tick);
// .each("end", tick);
// .each("end")
avgpath
.attr("d", avgline)
.attr("transform", null)
.transition()
.duration(200)
.ease("linear")
.attr("transform", "translate(" + x(0) + ",0)")
.each("end", tick);
// pop the old data point off the front
// if (newVal)
data.shift();
// if (newAvg)
avgdata.shift();
// console.log(data)
}
}
}
}) | f0e65d8ac827bc1a62e0efd2045d24a29b05dc68 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | msfrisbie/btc-viz | 6683a0bc7fc0c9f3adf2a6690b9b47344048f103 | 18e68aa0d8dba58db6ef24c96e033d879328895e |
refs/heads/master | <repo_name>moraisjessica/cosmeticos_bd<file_sep>/README.md
# cosmeticos_bd
repositório é uma pasta que contém uma pasta chamada .git que faz o gerenciamento dos arquivos.
- git init -> criar um repositorio
- git add -> adiciona um arquivo da pasta para o repositório
- git commit -> gera uma versão do repositório
- git config -> adiciona configurações
- user.email "<EMAIL>" -> configura o email
- user.name "seu nome" - > configura o nome
- git remote add <_nome do remoto_> <_url do remoto na nuvem_> -> configura para qual repositório da nuvem os arquivos vão ser enviados.
- git push <_nome do remoto_> <_branch_> -> envia os arquivos do repositório local para o repositório na nuvem
- git clone <_url do remoto_> -> baixa todo o repositório da nuvem para máquina local (geralmente, quando você ainda não tem o repositório)
- git pull <_nome do remoto_> <_branch_> -> Baixa só as alterações necessários para que o repositório local esteja igual ao repostório na nuvem (traz os novos commits/alteração em vez de trazer tudo)
<file_sep>/01_scripts/02_populacao.sql
/* Tabela de Cliente */
INSERT INTO Cliente (nome) VALUES
('Matheus'),
('Marcos');
SELECT * FROM Cliente;
-- Tabela de Revendedor
INSERT INTO Revendedor (nome) VALUES
('Paulo'),
('João');
SELECT * FROM Revendedor;
/*Tabela de Vendas */
INSERT INTO Venda (id_revendedor,id_cliente,produto,preco) VALUES
(1,1,'sabonete',1.00),
(1,1,'sabonete',1.00 ),
(1,1,'shampoo',7.00 ),
(1,1,'condicionador',8.00 ),
(1,1,'sabonete',1.10 ),
(1,1,'shampoo',7.30 ),
(1,1,'condicionador',8.50 ),
(2,1,'sabonete',1.50 ),
(2,1,'shampoo',7.60 ),
(2,1,'condicionador',9.00 ),
(1,2,'sabonete',1.50 ),
(1,2,'shampoo',7.60 ),
(1,2,'condicionador',9.00 );
SELECT * FROM Venda;
<file_sep>/01_scripts/04_relatorios_II.sql
-- 1. Qual a venda de maior valor: Max
select preco
FROM vw_relatorio
order by preco DESC
LIMIT 1;
select Max(preco) maior_valor_venda
from vw_relatorio;
-- 2. Qual a venda de menor valor: Min
select preco
FROM vw_relatorio
order by preco ASC
LIMIT 1;
select MIN(preco) menor_valor_venda
from vw_relatorio;
-- 3. Quantas vendas foram realizadas: Count
SELECT * FROM Venda;
SELECT * FROM vw_relatorio;
SELECT COUNT(*) contagem_vendas
FROM vw_relatorio;
-- 4. Quantos revendedores venderam produtos
SELECT COUNT(DISTINCT revendedor) contagem_revendedores
FROM vw_relatorio;
-- 5. Quantos clientes compraram produtos
SELECT COUNT(DISTINCT Cliente) contagem_clientes
FROM vw_relatorio;
-- 6. Quantos produtos distintos foram vendidos
SELECT COUNT(DISTINCT produto) contagem_produtos
FROM vw_relatorio;
-- 7. Quantos preços diferentes tem os produtos
SELECT COUNT(DISTINCT preco) contagem_clientes
FROM vw_relatorio;
-- 8. Quantos reais foram vendidos no total
SELECT SUM(preco) contagem_clientes
FROM vw_relatorio;
-- 9. Valor de Vendas por Vendedor
SELECT *
FROM vw_relatorio
Order by revendedor;
SELECT Sum(preco) vendas_joao
FROM vw_relatorio
where revendedor = 'João'
UNION
SELECT Sum(preco) vendas_paulo
FROM vw_relatorio
where revendedor = 'Paulo';
SELECT
revendedor,
SUM(preco) soma_vendas
from vw_relatorio
group by revendedor;
-- 10. Quantidade de Vendas por Vendedor
SELECT
revendedor,
COUNT(*) quantidade_vendas
from vw_relatorio
group by revendedor;
-- 11. Quantidade de clientes por vendedor
SELECT
revendedor,
COUNT(DISTINCT cliente) quantidade_clientes
from vw_relatorio
group by revendedor;
-- 12. Quanto cada produto vendeu (quantidade)
select * from Venda order by produto;
SELECT produto, count(produto)
FROM Venda
group by produto;
-- 13. Quanto cada produto vendeu (valor)
select * from Venda order by produto;
SELECT produto, SUM(preco), avg(preco), preco
FROM Venda
group by produto
order by SUM(preco) DESC;
-- 14. Produtos que venderam mais de 3 unidades
SELECT
produto,
count(produto),
CASE
WHEN count(produto) >= 3 THEN 'Vendeu mais que 3'
ELSE 'Vendeu menos que 3'
END
FROM Venda
group by produto
HAVING COUNT(produto) >= 3
ORDER BY COUNT(produto) DESC;
-- 15. Vendas do paulo por produto
SELECT produto, count(produto)
FROM vw_relatorio
where revendedor = 'Paulo'
group by produto
-- 15. Vendas do paulo por produto maior ou igual a 3
SELECT produto, count(produto)
FROM vw_relatorio
where revendedor = 'Paulo'
group by produto
HAVING count(produto) > 3;
/* Union */
SELECT produto, sum(preco)
FROM vw_relatorio
where revendedor = 'Paulo'
group by produto
UNION
SELECT 'Total', sum(preco)
FROM vw_relatorio
where revendedor = 'Paulo'
UNION ALL
SELECT 'shampoo', 21.9
/* Média */
SELECT avg(preco) from vw_relatorio;
SELECT
sum(preco) soma,
count(preco) quantidade,
sum(preco)/COUNT(preco) média,
avg(preco) media
FROM vw_relatorio;
/* Operações Matemáticas */
SELECT preco + 5
FROM vw_relatorio;
SELECT preco * 2
FROM vw_relatorio;
SELECT (preco * 2) * 0.50
FROM vw_relatorio;
SELECT (preco * 2)/2
FROM vw_relatorio;
SELECT preco/2
FROM vw_relatorio;
select 120/2 resultado, 121%2 resto
select 15978621585%100
/* Tratamento de Nulos */
CREATE VIEW vw_teste AS
select 1 id, null laboratorio, 'dorflex' remedio
UNION
select 2, 'labX', 'dorflex'
UNION
select 3, 'labY', 'dorflex'
UNION
select 4, null, null
UNION
select 5, 'labX', null
UNION
select 6, 'labY', null
;
select *
from vw_teste
select
id,
laboratorio,
remedio,
-- IFNULL(laboratorio, 0) laboratorio_trata_nulo,
-- IFNULL(laboratorio, 'desconhecido') laboratorio_trata_nulo,
IFNULL(laboratorio, remedio) laboratorio_trata_nulo,
COALESCE(laboratorio, remedio) laboratorio_trata_nulo
from vw_teste
select *
from (
select 1 id, null laboratorio, 'dorflex' remedio
UNION
select 2, 'labX', 'dorflex'
UNION
select 3, 'labY', 'dorflex'
UNION
select 4, null, null
UNION
select 5, 'labX', null
UNION
select 6, 'labY', null
) as teste
/* Sub-Select*/
select produto, preco
from vw_relatorio
where preco = (select max(preco) /*11*/ from vw_relatorio)<file_sep>/01_scripts/03_relatorios.sql
SELECT
r.nome revendedor,
c.nome cliente,
v.produto produto,
v.preco preco
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
;
-- 1. Quais são os produtos vendidos?
SELECT DISTINCT
v.produto produto
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
;
-- 2. Quais foram minhas últimas 3 vendas
SELECT
v.id_venda nu_pedido,
r.nome revendedor,
c.nome cliente,
v.produto produto,
v.preco preco
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
ORDER BY nu_pedido DESC
LIMIT 3
;
SELECT
v.id_venda nu_pedido,
r.nome revendedor,
c.nome cliente,
v.produto produto,
v.preco preco
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
WHERE v.id_venda > 10
ORDER BY nu_pedido DESC
;
-- 3. Quais são os produtos que começa com "s"
SELECT DISTINCT
v.produto produto
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
WHERE v.produto LIKE 's%'
;
-- 4. Todos os produto e seus preços em ordem decrescente
SELECT DISTINCT
v.produto produto,
v.preco preco
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
ORDER BY produto, preco DESC
;
-- 5. Todos os produto com preço entre 6 e 9 reais
SELECT DISTINCT
v.produto produto,
v.preco preco
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
WHERE v.preco BETWEEN 6 and 8.9
order BY v.preco DESC
;
-- 6. Quero minhas vendas de shampoo e condicionador
SELECT
r.nome revendedor,
c.nome cliente,
v.produto produto,
v.preco preco
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
where v.produto IN ('shampoo', 'condicionador')
;
-- 7. Quais produtos eu consigo comprar com 7 reais
SELECT DISTINCT
v.produto produto,
v.preco preco,
CASE
WHEN v.preco > 7 THEN 'Não'
-- WHEN v.preco <= 7 THEN 'Consigo comprar'
ELSE 'Sim'
END consigo_comprar
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
order by v.preco DESC
;
-- 8. Crie uma view que tenha o relatório de vendas
/* CTA */
CREATE Table tb_relatorio AS
SELECT
r.nome revendedor,
c.nome cliente,
v.produto produto,
v.preco preco
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
;
SELECT * FROM tb_relatorio;
/* View */
CREATE VIEW vw_relatorio AS
SELECT
r.nome revendedor,
c.nome cliente,
v.produto produto,
v.preco preco
FROM Cliente c
RIGHT JOIN Venda v
ON v.id_cliente = c.id_cliente
LEFT JOIN Revendedor r
on r.id_revendedor = v.id_revendedor
;
SELECT * FROM vw_relatorio;
INSERT INTO Venda (id_revendedor,id_cliente,produto,preco) VALUES
('2','2','desodorante','11.00');
SELECT * FROM Venda WHERE produto = 'desodorante';
SELECT * FROM vw_relatorio WHERE produto = 'desodorante';
SELECT * FROM tb_relatorio WHERE produto = 'desodorante';
SELECT * FROM tb_relatorio;
SELECT * FROM vw_relatorio;<file_sep>/01_scripts/01_criacao.sql
CREATE TABLE `Revendedor` (
`id_revendedor` INT NOT NULL UNIQUE AUTO_INCREMENT,
`nome` varchar(50) NOT NULL,
CONSTRAINT PK_Revendedor PRIMARY KEY (`id_revendedor`)
);
CREATE TABLE `Cliente` (
`id_cliente` INT NOT NULL UNIQUE AUTO_INCREMENT,
`nome` varchar(50) NOT NULL,
CONSTRAINT PK_Cliente PRIMARY KEY (`id_cliente`)
);
CREATE TABLE `Venda` (
`id_venda` INT NOT NULL UNIQUE AUTO_INCREMENT,
`id_revendedor` INT NOT NULL,
`id_cliente` INT NOT NULL,
`produto` varchar(50) NOT NULL,
`preco` DECIMAL(4,2) NOT NULL DEFAULT 0.00,
CONSTRAINT PK_Venda PRIMARY KEY (`id_venda`)
);
ALTER TABLE `Venda` ADD CONSTRAINT `FK_Revendedor` FOREIGN KEY (`id_revendedor`) REFERENCES `Revendedor`(`id_revendedor`);
ALTER TABLE `Venda` ADD CONSTRAINT `FK_Cliente` FOREIGN KEY (`id_cliente`) REFERENCES `Cliente`(`id_cliente`); | ce5e9d1811aa8c0fd38dc06b2ed2a1a1079a2704 | [
"Markdown",
"SQL"
] | 5 | Markdown | moraisjessica/cosmeticos_bd | edffb601c013f8fb00fae84b8429c1c21b6e90cf | 8f304d727e4875209eb0fae55caee5a196c70b29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.