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 | <file_sep>import React from 'react';
const MovieListEntry = (props) => (
<div>{props.movie.title}</div>
);
export {MovieListEntry};<file_sep>import _ from 'lodash';
import ReactDOM from 'react-dom';
import React from 'react';
import App from './components/App.js';
import {movieList} from '../data/exampleData';
ReactDOM.render(
<App movies={movieList} />,
document.getElementById('app')
);<file_sep>import React from 'react';
// Inputs should be controlled components https://reactjs.org/docs/forms.html
const Search = ({ handleMovieSearch }) => (
<div>
<label>
<input type='text'
onChange={(e) => handleMovieSearch(e.target.value)}
/>
</label>
{/* <button onClick={(e) => handleMovieSearch(e)}>Go</button> */}
</div>
);
export default Search;
| c7e9fc45c73dea7994e4a31510e483cd2d87c782 | [
"JavaScript"
] | 3 | JavaScript | Pfdiamond13/movies_list | 5551e32edd9c99cf084412b5001f3fc2d8b974d8 | 40f24700da590f58ad62ed5c8370034f5dd00603 |
refs/heads/master | <repo_name>murlinochka/ICT<file_sep>/15.py
foot = int(input("Input distance in feet: "))
inc = foot * 12
y = foot / 3.0
m = foot / 5280.0
print("The distance in inches is %i inches." % inc)
print("The distance in yards is %.2f yards." % y)
print("The distance in miles is %.2f miles." % m)<file_sep>/task 4/7.py
set_array = set()
string = input()
for i in string:
set_array.add(i)
print(len(set_array)) <file_sep>/task2/5.py
a1 = int(input("First column number: "))
b1 = int(input("First line number: "))
a2 = int(input("Second column number: "))
b2 = int(input("Second line number: "))
if((a1-a2==2) or (a1-a2==-2)) and ((b1-b2==1) or (b1-b2==-1)):
print("YES")
elif((b1-b2==2) or (b1-b2==-2)) and ((a1-a2==1) or (a1-a2==-1)):
print("YES")
else:
print ("NO")<file_sep>/26.py
import datetime
now = datetime.datetime.now()
# Printing value of now.
print ("Time now : ", now)
<file_sep>/5.py
a = int(input("Small containers: "))
b = int(input("Large containers: "))
c = (a * 0.10) + (b * 0.25)
print("Total", c)<file_sep>/task2/15.py
n = int(input())
count = 1
fib0 = 0
fib1 = 1
fibn = 1
while fibn<n:
fibn = fib0 + fib1
fib0 = fib1
fib1 = fibn
count = count+1
if fibn==n:
print(count)
else:
print(-1)<file_sep>/30.py
pa = float(input("Pressure in kPa: "))
psi = pa / 6.89475729
mm = pa * 760 / 101.325
atm = pa / 101.325
print("The pressure in pounds per square inch: %.2f psi" % (psi))
print("The pressure in millimeter of mercury: %.2f mm" % (mm))
print("Atmosphere pressure: %.2f atm." % (atm))<file_sep>/task2/19.py
n = int(input())
a = list(map(int, input().split()))
k = 0
a.sort()
for i in range(n):
if a[i-1]==a[i]:
k += 1
print(k)
<file_sep>/endterm/5.py
n = int(input())
ans = 1
for i in range(2, n):
if (n %i==0):
ans += 1
print (ans)
# Input
# The input consists of a single line containing a positive integer n — the number of employees in Fafa's company.
# Output
# Print a single integer representing the answer to the problem.
# Examples
# input
# 2
# output
# 1<file_sep>/2.py
a = str(input("what is your name? "))
print("Hello, ", a)<file_sep>/task2/20.py
a = list(map(int, input().split()))
n = a[0]
k = a[1]
while True:
b = input()
if b:
a.append(list(map(int, b)))
else:
break<file_sep>/23.py
from math import tan,pi
l = float(input("Length: "))
n = int(input("Number of sides: "))
area = (n * l ** 2)/(4 * tan(pi/n))
print("The area of Polygon ", area)<file_sep>/task 3/9.py
stringi = input()
a, d = 0, 0
for i in range(0, len(stringi)):
if stringi[i]== 'A':
a += 1
else:
d += 1
if a>d:
print("Anton")
elif d>a:
print("Danik")
else:
print("Friendship")
<file_sep>/29.py
t = int(input("Temperature in Celsius: "))
F = int(round((9 * t) / 5 + 32))
K = int(round((t + 273)))
print("Temperature in Fahrenheit is", F)
print("Temperature in Kelvin is", K)<file_sep>/task2/9.py
a1 = int(input())
b1 = int(input())
c1 = int(input())
a2 = int(input())
b2 = int(input())
c2 = int(input())
if((a1==a2) or(a1==b2) or (a1==c2)) and ((b1==a2) or(b1==b2) or (b1==c2)) and ((c1==a2) or(c1==b2) or (c1==c2)):
print("Boxes are equal")
elif(a1>a2) or(b1>b2) or (c1>c2):
print("The first box is larger than the second one")
else:
print("The first box is smaller than the second one")
<file_sep>/9.py
n = int(input("Amount of money: "))
x1 = n * 0.04
x2 = (n + x1) * 0.04
x3 = (n + x1 + x2) * 0.04
print(n+x1, round(n+x1+x2, 2) , round(n+x1+x2+x3, 2))<file_sep>/task 3/2.py
stringi = input()
listi = []
a = ""
for i in range(0, len(stringi)):
if stringi[i] != "+":
listi.append(stringi[i])
listi.sort()
for i in range(0, len(listi)-1):
a += (listi[i] + "+")
a += listi[len(listi)-1]
print(a)
<file_sep>/endterm/3.py
year = int(input())
n = 1
for i in range(0, 1000):
year += 1
tmp = year
a = tmp % 10
tmp //= 10
b = tmp % 10
tmp //= 10
c = tmp % 10
tmp //= 10
d = tmp % 10
if(a != b and a != c and a != d and b != c and b != d and c != d):
break
print(year)
# Input
# The single line contains integer y (1000 ≤ y ≤ 9000) — the year number.
# Output
# Print a single integer — the minimum year number that is strictly larger than y and all it's digits are distinct. It is guaranteed that the answer exists.
# Examples
# input
# 1987
# output
# 2013
# input
# 2013
# output
# 2014
<file_sep>/task2/18.py
n = int(input())
a = list(map(int, input().split()))
x = a[n-1]
for i in range(n-1,0,-1):
a[i] = a[i-1]
a[0] = x
print(' '.join(map(str, a)))<file_sep>/25.py
sec = float(input("Input seconds: "))
d = sec // (24 * 3600)
h = (sec % (24 * 3600)) // 3600
sec %= 3600
m = sec // 60
sec %= 60
seconds = sec
print("%d:%d:%d:%d" % (d, h, m, seconds))
<file_sep>/task2/10.py
import math
n = int(input())
a = [i**2 for i in range(1, int(math.sqrt(n))+1) if 1**2<n]
print(' '.join(map(str, a)))<file_sep>/32.py
a = int(input("Input first number: "))
b = int(input("Input second number: "))
c = int(input("Input third number: "))
x = min(a, b, c)
z = max(a, b, c)
y = (a + b + c) -x - z
print("Numbers in sorted order: ", x, y, z)<file_sep>/task2/7.py
n = int(input("N: "))
m = int(input("M: "))
x = int(input("X: "))
y = int(input("Y: "))
if (x>y):
print(y)
else:
print(x)<file_sep>/task 3/6.py
stringi = input()
upper = 0
lower = 0
for i in range(0, len(stringi)):
if stringi[i] >= 'a' and stringi[i] <= 'z':
lower += 1
if stringi[i] >= 'A' and stringi[i] <= 'Z':
upper += 1
if upper > lower:
print(stringi.upper())
else:
print(stringi.lower())<file_sep>/28.py
import math
v = float(input("Wind speed: "))
t = float(input("Air temperature: "))
w = 13.12 + 0.6215*t - 11.37*math.pow(v, 0.16) + 0.3965*t*math.pow(v, 0.16)
print("The wind chill index is ", int(round(w, 0)))
<file_sep>/8.py
n = int(input("Number of widgets: "))
m = int(input("Number of gizmos: "))
n = n * 75
m = m * 112
print(n+m)
<file_sep>/task 3/1.py
vowels = ['a', 'o', 'y', 'e', 'i', 'u']
stringi = input().lower()
k = ""
for i in range(0, len(stringi)):
if stringi[i] not in vowels:
k += "."
k += stringi[i]
print (k)
<file_sep>/task 3/7.py
import string
stringi = set(input().lower())
alphabet = set(string.ascii_lowercase)
if len(stringi) >= len(alphabet):
print("YES")
else:
print("NO")
<file_sep>/14.py
foot = int(input())
inc = int(input())
x = 5.4
y = 5.4
x = foot * 12 * 2.54
y = y * 2.54
print(y+x)
<file_sep>/18.py
HEAT_CAPACITY = 4.186
J_TO_KWH = 2.777e-7
v = float(input("Enter amount of water in milliliters: "))
t = float(input("Enter amount of temperature increase (degrees Celsius): "))
p = float(input("Enter electricity cost per unit: "))
energy = v * t * HEAT_CAPACITY
kwh = energy * J_TO_KWH
cost = kwh * p
print("Amount of energy needed ",round(energy,2),"Joules, which will cost", round(cost,2))<file_sep>/31.py
n = int(input("Number: "))
x = n //1000
x1 = (n - x*1000)//100
x2 = (n - x*1000 - x1*100)//10
x3 = n - x*1000 - x1*100 - x2*10
print("Suum: ", x+x1+x2+x3)<file_sep>/task2/12.py
n = int(input())
i = 0
a = []
while n>=2**i:
a.append(2**i)
i += 1
print(' '.join(map(str, a)))<file_sep>/3.py
a = int(input("Width: "))
b = int(input("Height: "))
print("Area: ", a*b)
<file_sep>/4.py
a = int(input("Width: "))
b = int(input("Height: "))
print("Area in acres: ", (a*b)/43560)
<file_sep>/20.py
p = int(input("Pressure : "))
v = int(input("Volume : "))
t = int(input("Temperature : "))
r = 8.314
n = ((p*v)/(r*t))
print("The number of moles %.2f mol." % n)
<file_sep>/12.py
from math import radians, cos, sin, asin, sqrt
print("Enter the latitude and longitude of two points on the Earth in degrees:")
lat1 = float(input(" Latitude 1: "))
lat2 = float(input(" Latitude 2: "))
lon1 = float(input(" Longitude 1: "))
lon2 = float(input(" Longitude 2: "))
lon1 = radians(lon1)
lon2 = radians(lon2)
lat1 = radians(lat1)
lat2 = radians(lat2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371
print("Distance is: ",c*r,"Kilometers")<file_sep>/17.py
m = int(input("Mass of water: "))
t = int(input("temperature change: "))
c= 4.186
q = c * m * t
print("Total amount of energy is %i J." % q)
<file_sep>/task2/3.py
a1 = int(input("First column number: "))
b1 = int(input("First line number: "))
a2 = int(input("Second column number: "))
b2 = int(input("Second line number: "))
if(a1-a2)==(b1-b2):
print("YES")
else:
print ("NO")<file_sep>/task2/4.py
a1 = int(input("First column number: "))
b1 = int(input("First line number: "))
a2 = int(input("Second column number: "))
b2 = int(input("Second line number: "))
if(a1==a2) and ((b1<b2) or (b1>b2)):
print("YES")
elif(b1==b2) and ((a1<a2) or (a1>a2)):
print("YES")
elif(a1-a2)==(b1-b2):
print("YES")
else:
print ("NO")<file_sep>/task 4/8.py
def check(s1, s2):
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
s1 ="evil"
s2 ="live"
check(s1, s2) <file_sep>/task 4/5.py
postalcode = {"A":"Newfoundland","B":"Nova Scotia","C":"Prince Edward Island",
"E":"New Brunswick","G":"Quebec","H":"Quebec","J":"Quebec",
"K":"Ontario","L":"Ontario","M":"Ontario","N":"Ontario","P":"Ontario",
"R":"Manitoba","S":"Saskatchewan","T":"Alberta","V":"British Columbia",
"X":"Nunavut,Northwest Territories","Y":"Yukon"}
code = input()
if code[0] not in postalcode:
print('Invalid postal code')
else:
province = postalcode[code[0]]
if code[1]==0:
address = "rural"
else:
address = "urban"
print('The postal code is for {:s} address in'.format(address),end=" ")
print(" or ".join(province.split(",")))<file_sep>/1.py
print("<NAME>")
print("<EMAIL>")
<file_sep>/task 4/1.py
def reverseLookup(dictionary, value):
finding_keys = []
for key, val in dictionary.items():
if val == value:
finding_keys.append(key)
return finding_keys
Lookup = { "Alina": 18, "Veronika": 20, "Zarina": 13, "Margo": 18}
print("Keys:" , reverseLookup(Lookup, 18))
<file_sep>/task 3/11.py
nn = int(input())
stringi = input()
stringi2 = ""
one = 0
zero = 0
for i in range(0, len(stringi)):
if stringi[i]=='n':
one += 1
elif stringi[i]=='z':
zero += 1
while(one):
stringi2 += "1 "
one -= 1
while(zero):
stringi2 += "0"
zero -= 1
print(stringi2)
<file_sep>/task 3/4.py
stringi = input()
cnt = 1
opasno = False
for i in range (0, len(stringi)):
if stringi[i] != stringi[len(stringi)-1]:
if stringi[i]== stringi[i+1]:
cnt +=1
if cnt >= 7:
opasno = True
break
else:
if cnt >=7:
opasno = True
break
cnt = 1
if opasno:
print("YES")
else:
print("NO")
<file_sep>/6.py
a = float(input("Cost of a meal: "))
nalog = 0.5
chaev = 0.18
b = (a*nalog) + (a*chaev) + a
print(b)
<file_sep>/task 3/3.py
stringi = input()
print(stringi.capitalize()) <file_sep>/19.py
from math import sqrt
g = 9.8
h = float(input("Height of dropping object : "))
v = sqrt(2 * g * h)
print("Object will hit the ground at %.2f m/s." % v)<file_sep>/24.py
d = int(input("Days: "))
h = int(input("Hours: "))
m = int(input("Minutes: "))
s = int(input("Seconds: "))
sec = (d*24*60*60 + h*60*60 + m*60 + s)
print("Seconds: ", sec)<file_sep>/task 4/2.py
import random
def roll():
return (random.randint(1,6)+random.randint(1,6))
def count(amount, ):
count_ = 0
for i in range(1, amount+1):
if roll() == 3:
count_ += 1
return count_
print(roll())<file_sep>/task2/8.py
a1 = int(input())
a2 = int(input())
a3 = int(input())
a = [a1, a2, a3]
a.sort()
for i in range(len(a)):
print(a[i], end = ' ') <file_sep>/task 3/10.py
stringi = input()
stringi2 = ""
norm = False
for i in range(1, len(stringi)):
if stringi[i] >= 'a' and stringi[i] <= 'z':
norm = True
break
if norm == False:
for i in range(0, len(stringi)):
if stringi[i] >= 'A' and stringi[i] <= 'Z':
stringi2 += chr(ord(stringi[i]) + 32)
else:
stringi2 += chr(ord(stringi[i]) - 32)
if norm:
print(stringi)
else:
print(stringi2)
<file_sep>/task2/16.py
i = int(input())
a = []
count = 0
while i!=0:
i = int(input())
a.append(i)
for i in range(len(a)):
if a[i]>a[i-1] and a[i]>a[i+1]:
count += 1
print(count)<file_sep>/7.py
n = int(input("Positive integer: "))
a = (n*(n+1))/2
print("Sum: ", int(a))<file_sep>/27.py
height = float(input("Height: "))
weight = float(input("Weight: "))
print("Your BMI: ", round(weight / (height * height), 2))
<file_sep>/endterm/2.py
n=int(input())
ans = 0
bns = 0
cns = 0
for i in range(n):
a,b,c=map(int,input().split())
ans += a
bns += b
cns += c
if(ans==0 and bns==0 and cns==0):
print("YES")
else:
print("NO")
# Input
# The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body.
# Output
# Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
# Examples
# input
# 3
# 4 1 7
# -2 4 -1
# 1 -5 -3
# output
# NO
# input
# 3
# 3 -1 7
# -5 2 -4
# 2 -1 -3
# output
# YES<file_sep>/11.py
n = float(input("Fuel: "))
print(n * 235.215)
<file_sep>/33.py
a=int(input("Number of loaves: "))
b=a*3.49
print("Regular Price: ",b)
print("Total Discount: ",b*.6)
print("Total Amount to be paid: ",b-(b*.6))<file_sep>/task 3/8.py
s=input()
t=input()
tt = str(s[::-1])
if tt==t:
print("YES")
else:
print ("NO")<file_sep>/task 3/12.py
n = int(input())
stringi = input()
cnt = 0
itog = 0
for i in range (0, len(stringi)):
if stringi[i] == 'x':
cnt += 1
if cnt >=3:
itog += 1
else:
cnt = 0
print(itog)<file_sep>/endterm/1.py
ans = 0
n, x = map(int, input().split())
for i in range(1, n + 1):
if (x % i == 0 and x / i <= n):
ans += 1
print(ans)
<file_sep>/task2/13.py
i = int(input())
sum = i
while(i!=0):
i = int(input())
sum += i
print(sum)<file_sep>/task2/14.py
i = int(input())
a = i
k = 0
while(i!=0):
i = int(input())
if a<i:
k = 1
a = i
elif a==i:
k += 1
print(k)<file_sep>/task 3/5.py
listii = set(input())
if len(listii) % 2 ==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")<file_sep>/endterm/4.py
users = list(set(input()))
if len(users) % 2 == 0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
# Input
# The first line contains a non-empty string, that contains only lowercase English letters — the user name. This string contains at most 100 letters.
# Output
# If it is a female by our hero's method, print "CHAT WITH HER!" (without the quotes), otherwise, print "IGNORE HIM!" (without the quotes).
# Examples
# input
# wjmzbmr
# output
# CHAT WITH HER!
# input
# xiaodao
# output
# IGNORE HIM!<file_sep>/task 4/9.py
def check(s1, s2):
if sorted(s1)== sorted(s1):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
s1 ="<NAME>"
s2 ="I am a weakish speller"
s11 = s1.replace(' ', '')
s22 = s2.replace(' ', '')
str1 = s11.upper()
str2 = s22.upper()
check(str1, str2) <file_sep>/task2/11.py
n = int(input())
k = 2
i = 3
if (n % 2 == 0):
k = 2
else:
while(i * i <= n):
if (n % i == 0):
k = i
i += 2
print(k)
# This code is contributed by mits | bfe8197448629be2654705a916743c5a4b9ff533 | [
"Python"
] | 67 | Python | murlinochka/ICT | 87cbeb82a70b3a5267f7d302fcf1a3fc9ed4dbcf | 6264aacdf7f1cfbc84ed95d5756fceb420a00134 |
refs/heads/main | <file_sep>package com.seecen.day01;
/**
* @program: javaOOP_Re
* @Author: <NAME>
* @Description:
* @create: 2020-11-23 16:01
*/
public class Cat {
//1.将属性私有化
//2.留出属性对外的访问接口
//3.在对应的方法里添加控制语句
private String name;
private String color;
private String species;
private int age;
public void catchMouse(){
System.out.println("猫抓老鼠!");
}
public void eat(){
System.out.println("猫吃小鱼干!");
}
public void sleep(int time){
System.out.println("小猫睡了"+time+"分钟!");
}
public void showAge(){
System.out.println("我是一只"+age+"月大的小猫!");
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public String getSpecies() {
return species;
}
public void setName(String name) {
this.name = name;
}
public void setColor(String color) {
this.color = color;
}
public void setSpecies(String species) {
this.species = species;
}
public void setAge(int age) {
if (age<=0){
this.age = 1;
System.err.println("您输入的年龄有误,已设置为默认年龄1岁!");
}else {
this.age = age;
}
}
public int getAge() {
return age;
}
}
<file_sep>package com.seecen.day01;
import java.util.Arrays;
/**
* @program: javaOOP_Re
* @Author: <NAME>
* @Description:
* @create: 2020-11-23 15:13
*/
public class ArrayPrintTest {
/*
* (1,2,3,4,5)
* 按格式打印出来
* [1,2,3,4,5]
*
* */
public static void main(String[] args) {
//定义数组
int[] arr = {1,2,3,4,5};
System.out.print("[");
/*System.out.print(arr[0]+",");
System.out.print(arr[1]+",");
System.out.print(arr[2]+",");
System.out.print(arr[3]+",");
System.out.print(arr[4]+"]");*/
for (int i = 0; i < arr.length; i++) {
if (i==arr.length-1){
System.out.print(arr[i]+"]");
}else {
System.out.print(arr[i]+",");
}
}
System.out.println(Arrays.toString(arr));
}
}
<file_sep>package com.seecen.day01;
/**
* @program: javaOOP_Re
* @Author: <NAME>
* @Description:
* @create: 2020-11-23 14:42
*/
public class HelloTest {
public static void main(String[] args) {
System.out.println("Hello,World!");
}
}
| 6fa2aac7ec8f0ca16fe0b0024f5981a0eaecf285 | [
"Java"
] | 3 | Java | LoveITTECHNOLOGY/javaweb-third | 87bf9918d5accc5d9351e2fbcf092494c5349061 | f30b4c15fe4118f8aa82c23df7f091f39be14b7a |
refs/heads/master | <repo_name>SoftmedTanzania/rucodia_backend<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call([
LevelsTableSeeder::class,
LocationsTableSeeder::class,
UsersTableSeeder::class,
UnitsTableSeeder::class,
CategoriesTableSeeder::class,
SubcategoriesTableSeeder::class,
CategorySubcategoryTableSeeder::class,
// ProductsTableSeeder::class,
RegionsTableSeeder::class,
DistrictsTableSeeder::class,
WardsTableSeeder::class,
UserWardTableSeeder::class,
LocationUserTableSeeder::class,
StatusesTableSeeder::class,
TransactiontypesTableSeeder::class,
]);
}
}
<file_sep>/database/seeds/LevelsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class LevelsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// First sample level
DB::table('levels')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Administrator',
'description' => 'Seeded system administrator level',
'buys_from' => '0, 0, 0, 0, 0',
'created_at' => date('Y-m-d H:i:s'),
]);
// Second sample level
DB::table('levels')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Manufacturer',
'description' => 'Producing company.',
'buys_from' => '0, 0, 0, 0, 0',
'created_at' => date('Y-m-d H:i:s'),
]);
// Third sample level
DB::table('levels')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Hub-Agrodealer',
'description' => 'An agrodealer with more than 10 agrodealer clients.',
'buys_from' => '0, 2, 3, 0, 0',
'created_at' => date('Y-m-d H:i:s'),
]);
// Fourth sample level
DB::table('levels')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Agrodealer',
'description' => 'An agrodealer who buys from hub-agrodealer and other agrodealers. Sells to resellers.',
'buys_from' => '0, 2, 3, 4, 0',
'created_at' => date('Y-m-d H:i:s'),
]);
// Fifth sample level
DB::table('levels')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Reseller',
'description' => 'A reseller buys from agrodealers in the hub and outta hub.',
'buys_from' => '0, 0, 3, 4, 5',
'created_at' => date('Y-m-d H:i:s'),
]);
}
}
<file_sep>/app/Http/Controllers/web/DashboardController.php
<?php
namespace App\Http\Controllers\web;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Transactions;
class DashboardController extends Controller
{
/**
* Total transactions made in the app.
*
* @return \Illuminate\Http\Response
*/
public function totalTransactions()
{
//
}
}
<file_sep>/app/District.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class District extends Model
{
/**
* Fields that can be mass assignable
*
* @return mixed
*/
protected $fillable = [
'uuid', 'name', 'deleted_by',
];
/**
* Get the wards for the district.
*/
public function wards()
{
return $this->hasMany('App\Ward');
}
/**
* Get the region that owns the district.
*/
public function region()
{
return $this->belongsTo('App\Region');
}
}
<file_sep>/database/factories/UserFactory.php
<?php
use Faker\Generator as Faker;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(App\User::class, function (Faker $faker) {
static $user, $status;
return [
'uuid' => $faker->uuid,
'firstname' => $faker->firstName,
'middlename' => $faker->firstNameMale,
'surname' => $faker->lastName,
'email' => $faker->email,
'username' => $faker->userName,
'password' => $<PASSWORD>,
'created_by' => $user ?: $user = 1,
'created_at' => $faker->dateTimeBetween($startDate = '-6 months', $endDate = 'now', $timezone = date_default_timezone_get())
];
});
<file_sep>/database/seeds/LocationsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class LocationsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// Seed using model factories
// $users = factory(App\Location::class, 30)->create();
// $this->command->info('Location table seeded!');
// First sample location
DB::table('locations')->insert([
'uuid' => (string) Str::uuid(),
'latitude' => -10.673565,
'longitude' => 35.659965,
'name' => 'Rucodia',
'created_at' => date('Y-m-d H:i:s'),
]);
// // Second sample location
// DB::table('locations')->insert([
// 'uuid' => (string) Str::uuid(),
// 'latitude' => -4.859547,
// 'longitude' => 29.625105,
// 'name' => '<NAME>',
// 'created_at' => date('Y-m-d H:i:s'),
// ]);
// // Third sample location
// DB::table('locations')->insert([
// 'uuid' => (string) Str::uuid(),
// 'latitude' => -4.592884,
// 'longitude' => 30.180055,
// 'name' => '<NAME>',
// 'created_at' => date('Y-m-d H:i:s'),
// ]);
// // Fourth sample location
// DB::table('locations')->insert([
// 'uuid' => (string) Str::uuid(),
// 'latitude' => -4.887088,
// 'longitude' => 29.620836,
// 'name' => '<NAME>',
// 'created_at' => date('Y-m-d H:i:s'),
// ]);
// // Fifth sample location
// DB::table('locations')->insert([
// 'uuid' => (string) Str::uuid(),
// 'latitude' => -4.858592,
// 'longitude' => 29.639505,
// 'name' => '<NAME>',
// 'created_at' => date('Y-m-d H:i:s'),
// ]);
// // Sixth sample location
// DB::table('locations')->insert([
// 'uuid' => (string) Str::uuid(),
// 'latitude' => -4.861908,
// 'longitude' => 29.646421,
// 'name' => '<NAME>',
// 'created_at' => date('Y-m-d H:i:s'),
// ]);
}
}
<file_sep>/database/seeds/RegionsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class RegionsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// Seed this table from an SQL file
DB::disableQueryLog();
$path = public_path('sql/regions.sql');
DB::unprepared(file_get_contents($path));
$this->command->info('Regions table seeded!');
}
}
<file_sep>/database/seeds/ProductsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use App\Product;
use App\Unit;
use App\Subcategory;
class ProductsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$kg_unit = Unit::where('name', 'Kg')->first();
$lt_unit = Unit::where('name', 'Lt')->first();
$can_unit = Unit::where('name', 'Can')->first();
$bag_unit = Unit::where('name', 'Bag')->first();
$ton_unit = Unit::where('name', 'Ton')->first();
$cutling_unit = Unit::where('name', 'Cutling')->first();
$piece_unit = Unit::where('name', 'Piece')->first();
$mahindi_subcategory = Subcategory::where('name', 'Mahindi')->first();
$maharage_subcategory = Subcategory::where('name', 'Maharage')->first();
$vifaa_subcategory = Subcategory::where('name', 'Pampu')->first();
$dawa_subcategory = Subcategory::where('name', 'Thiodan')->first();
$product = new Product();
$product->uuid = (string) Str::uuid();
$product->name = 'Katumani 2018H';
$product->price = 15000;
$product->description = 'Mahindi yanayokua kwa wiki 9.';
$product->created_by =0;
$product->created_at = date('Y-m-d H:i:s');
$product->save();
$product->units()->attach($kg_unit, array('uuid' => (string) Str::uuid()));
$product->subcategories()->attach($mahindi_subcategory, array('uuid' => (string) Str::uuid()));
$product = new Product();
$product->uuid = (string) Str::uuid();
$product->name = 'Mlingano 2018H';
$product->price = 13500;
$product->description = 'Mahindi yanayokua kwa wiki 7.';
$product->created_by =0;
$product->created_at = date('Y-m-d H:i:s');
$product->save();
$product->units()->attach($kg_unit, array('uuid' => (string) Str::uuid()));
$product->subcategories()->attach($mahindi_subcategory, array('uuid' => (string) Str::uuid()));
$product = new Product();
$product->uuid = (string) Str::uuid();
$product->name = 'Ilonga RH1';
$product->price = 25000;
$product->description = 'Maharage mekundu ya Mpwapwa yanastahmili ukame.';
$product->created_by =0;
$product->created_at = date('Y-m-d H:i:s');
$product->save();
$product->units()->attach($kg_unit, array('uuid' => (string) Str::uuid()));
$product->subcategories()->attach($maharage_subcategory, array('uuid' => (string) Str::uuid()));
$product = new Product();
$product->uuid = (string) Str::uuid();
$product->name = 'Solo Viper';
$product->price = 92000;
$product->description = 'Mashine ya kupulizia na kunyunyizia dawa shambani.';
$product->created_by =0;
$product->created_at = date('Y-m-d H:i:s');
$product->save();
$product->units()->attach($piece_unit, array('uuid' => (string) Str::uuid()));
$product->subcategories()->attach($vifaa_subcategory, array('uuid' => (string) Str::uuid()));
$product = new Product();
$product->uuid = (string) Str::uuid();
$product->name = 'Thiorolox';
$product->price = 7800;
$product->description = 'Sumu ya Thiodan ya AgroCull.';
$product->created_by =0;
$product->created_at = date('Y-m-d H:i:s');
$product->save();
$product->units()->attach($lt_unit, array('uuid' => (string) Str::uuid()));
$product->subcategories()->attach($dawa_subcategory, array('uuid' => (string) Str::uuid()));
}
}
<file_sep>/app/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* User Model
*
* @category API
* @package RUCODIA_API
* @author Kizito <<EMAIL>>
* @copyright 2018 - sOFTMED
* @license https://opensource.org/licenses/MIT MIT License
* @version Release: @0.1@
* @link http://softmed.co.tz/rucodia
*/
class User extends Authenticatable
{
use Notifiable;
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'uuid', 'firstname', 'middlename', 'surname', 'email', 'username', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the level where the user belongs.
*
* @return \Illuminate\Http\Response
*/
public function levels()
{
return $this
->belongsToMany('App\Level')
->withTimestamps()
->withPivot('uuid');
}
/**
* Get the loactions that owns the ward.
*
* @return \Illuminate\Http\Response
*/
public function locations()
{
return $this
->belongsToMany('App\Location')
->withTimestamps()
->withPivot('uuid');
}
/**
* Get the orders that this User owns
*
* @return \Illuminate\Http\Response
*/
public function orders()
{
return $this->hasMany('App\Order');
}
/**
* Get the ward for this user.
*/
public function wards()
{
return $this
->belongsToMany('App\Ward')
->withTimestamps()
->withPivot('uuid');
}
/**
* Get the orders that this User owns
*
* @return \Illuminate\Http\Response
*/
public function transactions()
{
return $this->hasMany('App\Transaction');
}
public function latest_transactions()
{
return $this->hasMany('App\Transaction')->latest();
}
public function subcategories()
{
return $this->hasMany('App\Subcategory');
}
}<file_sep>/app/Ward.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\District;
class Ward extends Model
{
/**
* Fields that can be mass assignable
*
* @return mixed
*/
protected $fillable = [
'uuid', 'name', 'deleted_by',
];
/**
* Get the users for the ward.
*/
public function users()
{
return $this->hasMany('App\User');
}
/**
* Get the district that owns the ward.
*/
public function district()
{
return $this->belongsTo('App\District');
}
}
<file_sep>/database/seeds/UnitsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class UnitsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('units')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Kg',
'description' => 'Kilograms',
// 'created_by' =>0
'created_at' => date('Y-m-d H:i:s'),
]);
DB::table('units')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Lt',
'description' => 'Litres',
// 'created_by' =>0
'created_at' => date('Y-m-d H:i:s'),
]);
DB::table('units')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Can',
'description' => 'Cans',
// 'created_by' =>0
'created_at' => date('Y-m-d H:i:s'),
]);
DB::table('units')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Bag',
'description' => 'Bags',
// 'created_by' =>0
'created_at' => date('Y-m-d H:i:s'),
]);
DB::table('units')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Ton',
'description' => 'Tons',
// 'created_by' =>0
'created_at' => date('Y-m-d H:i:s'),
]);
DB::table('units')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Cutling',
'description' => 'Cutlings',
// 'created_by' =>0
'created_at' => date('Y-m-d H:i:s'),
]);
DB::table('units')->insert([
'uuid' => (string) Str::uuid(),
'name' => 'Piece',
'description' => 'Pieces',
// 'created_by' =>0
'created_at' => date('Y-m-d H:i:s'),
]);
}
}
<file_sep>/app/Http/Controllers/web/CategoryController.php
<?php
namespace App\Http\Controllers\web;
use Response;
use App\Category;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use App\Http\Resources\Category as CategoryResource;
use Illuminate\Support\Facades\Auth;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//All categories from the database
$categories = Category::all();
$page = 'Category';
return view('categories/index')
->with('categories', $categories)
->with('page', $page);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
// Load the creation page
$page = 'Category';
return view('categories/create')
->with('page', $page);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new category from creation page
$category = new Category;
$category->uuid = (string) Str::uuid();
$category->name = $request['name'];
$category->description = $request['description'];
$category->created_by = Config::get('apiuser');
$category->save();
$categories = Category::all();
$page = 'Category';
return view('categories/index')
->with('categories', $categories)
->with('page', $page);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$category = Category::find($id);
// Check if category is not in the DB
if ($category === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'category',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific category
$category = Category::find($id);
$page = 'Category';
return view('categories/show')
->with('category', $category)
->with('page', $page);
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
// Get the details for a specific category
$page = 'Category';
$category = Category::find($id);
return view('categories/edit')
->with('category', $category)
->with('page', $page);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed ID
$category = Category::find($id);
$category->name = $request['name'];
$category->description = $request['description'];
$category->save();
$categories = Category::all();
$page = 'Category';
return view('categories/index')
->with('categories', $categories)
->with('page', $page);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific User by ID (Soft-Deletes)
$category = Category::find($id);
$category->update(['deleted_by' => Auth::user()->id]);
$category->delete();
$categories = Category::all();
$page = 'Category';
return view('categories/index')
->with('categories', $categories)
->with('page', $page);
}
}
<file_sep>/app/Http/Controllers/api/DistrictController.php
<?php
namespace App\Http\Controllers\api;
use App\District;
use Illuminate\Http\Request;
use Response;
use App\Http\Resources\District as DistrictResource;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;
class DistrictController extends Controller
{
/**
* List Districts
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the Districts in a collection
DistrictResource::WithoutWrapping();
return DistrictResource::collection(District::get());
}
/**
* Add District
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new district from the payload
$district = new District;
$district->uuid = (string) Str::uuid();
$district->name = $request['name'];
$district->region_id = $request['region_id'];
$district->created_by = Config::get('apiuser');
$district->save();
return response()->json([
'acton' => 'create',
'status' => 'OK',
'entity' => $district->uuid,
'type' => 'district',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show District
*
* Display the specified resource.
*
* @param \App\District $district
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$district = District::find($id);
// Check if district is not in the DB
if ($district === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'district',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific district
DistrictResource::WithoutWrapping();
return new DistrictResource(District::find($id));
}
}
/**
* Update District
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\District $district
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed district
$district = District::find($id)->first();
$district->name = $request['name'];
$district->region_id = $request['region_id'];
$district->updated_by = Config::get('apiuser');
$district->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $district->uuid,
'type' => 'district',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete District
*
* Remove the specified resource from storage.
*
* @param \App\District $district
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific district by regionID (Soft-Deletes)
$district = District::find($id)->first();
$district->update(['deleted_by' => Config::get('apiuser')]);
$district->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $district->uuid,
'type' => 'district',
'user' => Config::get('apiuser')
], 200);
}
public function districtWards($id)
{
$district = District::find($id);
// Check if district is not in the DB
if ($district === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'district',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific district
DistrictResource::WithoutWrapping();
return new DistrictResource(District::with('wards')->find($id));
}
}
}<file_sep>/app/Http/Controllers/web/UserController.php
<?php
namespace App\Http\Controllers\web;
use App\User;
use App\Region;
use App\District;
use App\Ward;
use App\Level;
use App\Location;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Validator;
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//All users from the database
$users = User::paginate(10);
$page = 'User';
return view('users/index')
->with('users', $users)
->with('page', $page);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
// Load the user creation page/form
$regions = Region::all();
$districts = District::all();
$wards = Ward::all();
$levels = Level::all();
$locations = Location::all();
$page = 'User';
return view('users/create')
->with('regions', $regions)
->with('districts', $districts)
->with('wards', $wards)
->with('levels', $levels)
->with('locations', $locations)
->with('page', $page);
}
/**
* A method to pull all districts for a given region
* @return [array] [districts]
*/
public function ajaxdistricts(Request $request, $id)
{
$districts = District::where('region_id', $id)->get();
return $districts;
}
/**
* A method to pull all wards for a given district
* @return [array] [wards]
*/
public function ajaxwards(Request $request, $id)
{
$wards = Ward::where('district_id', $id)->get();
return $wards;
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// The validation of the form
$this->validate($request, [
'number' => 'integer|nullable',
'firstname' => 'required|max:50',
'middlename' => 'required|max:50',
'surname' => 'required|max:50',
'phone' => 'required|unique:users|numeric|min:10',
'username' => 'required|unique:users|min:4',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
'region' => 'required',
'district' => 'required',
'ward' => 'required',
]);
$level = Level::where('id', $request->level)->first();
$ward = Ward::where('id', $request->ward)->first();
$location = Location::where('id', $request->location)->first();
$user = new User;
$user->uuid = (string) Str::uuid();
$user->firstname = $request->firstname;
$user->middlename = $request->middlename;
$user->surname = $request->surname;
$user->phone = $request->phone;
$user->username = $request->username;
$user->password = <PASSWORD>($request->password);
$user->created_by = Auth::id();
$user->save();
$location = new Location;
$location->uuid = (string) Str::uuid();
$location->name = $request->location;
$location->latitude = $request->latitude;
$location->longitude = $request->longitude;
$location->created_by = Auth::id();
$location->save();
$user->levels()->attach($level->id, array(
'level_id' => $level->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid(),
'created_by' => Auth::id()
));
$user->wards()->attach($ward->id, array(
'ward_id' => $ward->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid(),
'created_by' => Auth::id()
));
$user->locations()->attach($location->id, array(
'location_id' => $location->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid(),
'created_by' => Auth::id()
));
$users = User::paginate(10);
$page = 'User';
return view('users/index')
->with('users', $users)
->with('page', $page);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//Select a specific user and show details and form
$user = User::find($id);
$ward = User::find($id)->wards()->first();
$district = strtok($ward->district->name, " ");
$region = $ward->district->region->name;
$location = User::find($id)->locations()->first();
if (!empty($location->id)) {
$center = "center=".$ward->name.",".$district.",".$region.",TZ&";
$coordinates = (string) $location->latitude.",". (string) $location->longitude;
$label = substr($location->name, 0, 1);
$parameters = "zoom=12&size=400x160&maptype=roadmap&markers=color:red|label:".$label."|";
$key = "&key=".env("GOOGLE_API_KEY");
$map = "https://maps.googleapis.com/maps/api/staticmap?".$parameters.$coordinates.$key;
}
else {
$map = "assets/img/background/user_bg.jpg";
}
$page = "User";
$revenue = DB::table('transactions')
->selectRaw('SUM(price * amount) AS price')
->where('user_id', $id)
->where('transactiontype_id', 2)
->value('price');
return view('users/show')
->with('user', $user)
->with('revenue', $revenue)
->with('map', $map)
->with('page', $page);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$regions = Region::all();
$districts = District::all();
$wards = Ward::all();
$levels = Level::all();
$locations = Location::all();
$page = 'User';
// Get the details for a specific user
$user = User::find($id);
return view('users/edit')
->with('user', $user)
->with('regions', $regions)
->with('districts', $districts)
->with('wards', $wards)
->with('levels', $levels)
->with('locations', $locations)
->with('page', $page);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed ID
$level = Level::where('id', $request['level'])->first();
$level_uuid = DB::table('level_user')->where('user_id', $id)->value('uuid');
$level_id = DB::table('level_user')->where('user_id', $id)->value('id');
$location = Location::where('id', $request['location'])->first();
$location_uuid = DB::table('location_user')->where('user_id', $id)->value('uuid');
$location_id = DB::table('location_user')->where('user_id', $id)->value('id');
$ward = Ward::where('id', $request['ward'])->first();
$ward_uuid = DB::table('user_ward')->where('user_id', $id)->value('uuid');
$ward_id = DB::table('user_ward')->where('user_id', $id)->value('id');
$user = User::find($id);
$user->firstname = $request['firstname'];
$user->middlename = $request['middlename'];
$user->surname = $request['surname'];
$user->phone = $request['phone'];
$user->username = $request['username'];
$user->password = <PASSWORD>($request['password']);
$user->updated_by = Auth::id();
$user->levels()->sync($level->id);
$user->levels()->updateExistingPivot($level->id, array('uuid' => $level_uuid, 'id' => $level_id));
// $user->locations()->sync($location->id);
// $user->locations()->updateExistingPivot($location->id, array('uuid' => $location_uuid, 'id' => $location_id));
$user->wards()->sync($ward->id);
$user->wards()->updateExistingPivot($ward->id, array('uuid' => $ward_uuid, 'id' => $ward_id));
$user->save();
$users = User::paginate(10);
$page = 'User';
return view('users/index')
->with('users', $users)
->with('page', $page);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific User by ID (Soft-Deletes)
$user = User::find($id);
$user->update(['deleted_by' => Auth::id()]);
$user->delete();
$users = User::paginate(10);
$page = 'User';
return view('users/index')
->with('users', $users)
->with('page', $page);
}
/**
* Load file importation form for loading an excel sheet
*
* @return \Illuminate\Http\Response
*/
public function excelImportUsers()
{
$page = 'File Import';
return view('users/excel')
->with('page', $page);
}
/**
* Adding users amass using an excel file or csv
*
* @param file $spreadsheet
* @return \Illuminate\Http\Response
*/
public function massImportUsers(Request $request)
{
// Validate the xlsx file
$validator = Validator::make($request->all(), [
'spreadsheet' => 'required',
]);
// If the validation fails fall back to the previous page with errors flashed.
if ($validator->fails()) {
return redirect()->back()->withErrors($validator);
}
// For a valid file checkif it has payload then insert data to the DB
if($request->hasFile('spreadsheet')){
$path = $request->file('spreadsheet')->getRealPath();
$data = \Excel::load($path)->get();
// Loop through each entry in the excel file
if($data->count()){
foreach ($data as $key => $value) {
$level = Level::where('name', $value->level)->first();
$ward = Ward::where('name', $value->ward)->first();
$location = Location::where('name', $value->business_name)->first();
$user = new User;
$user->uuid =(string) Str::uuid();
$user->firstname = $value->firstname;
$user->middlename = $value->middlename;
$user->surname = $value->surname;
$user->phone = $value->phone;
$user->username = $value->username;
$user->password = <PASSWORD>::make($value->password);
$user->created_by = Auth::id();
$user->save();
$location = new Location;
$location->uuid = (string) Str::uuid();
$location->name = $value->business_name;
$location->latitude = $value->latitude;
$location->longitude = $value->longitude;
$location->created_by = Auth::id();
$location->save();
$user->levels()->attach($level->id, array(
'level_id' => $level->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid(),
'created_by' => Auth::id()
));
$user->wards()->attach($ward->id, array(
'ward_id' => $ward->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid(),
'created_by' => Auth::id()
));
$user->locations()->attach($location->id, array(
'location_id' => $location->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid(),
'created_by' => Auth::id()
));
}
$page = 'User';
$users = User::paginate(10);
return redirect()->route('users.index');
}
}
return redirect()->back()->withErrors($validator);
}
}
<file_sep>/app/Http/Controllers/web/SubcategoryController.php
<?php
namespace App\Http\Controllers\web;
use Response;
use App\Category;
use App\Subcategory;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use App\Http\Resources\Subcategory as SubcategoryResource;
class SubcategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//All categories from the database
$subcategories = Subcategory::with('categories')->get();
$page = 'Subcategory';
return view('subcategories/index')
->with('subcategories', $subcategories)
->with('page', $page);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
// Load the creation page
$page = 'Subcategory';
$categories = Category::get();
return view('subcategories/create')
->with('page', $page)
->with('categories', $categories);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new subcategory from creation page
$category = $request->category;
$category = Category::find($category);
$user = Auth::user();
$subcategory = new Subcategory;
$subcategory->uuid = (string) Str::uuid();
$subcategory->name = $request['name'];
$subcategory->description = $request['description'];
$subcategory->created_by = $user->id;
$subcategory->save();
$subcategory->categories()->attach($category->id, array('subcategory_id' => $subcategory->id, 'category_id' => $category->id, 'uuid' => (string) Str::uuid()));
$page = 'Subcategory';
$subcategories = Subcategory::get();
$categories = Category::get();
// return $subcategory->created_by;
return view('subcategories/index')
->with('page', $page)
->with('subcategories', $subcategories);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$subcategory = Subcategory::find($id);
// Check if subcategory is not in the DB
if ($subcategory === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'subcategory',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific subcategory
$subcategory = Subcategory::find($id);
$page = 'Subcategory';
return view('subcategories/show')
->with('subcategory', $subcategory)
->with('page', $page);
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
// Get the details for a specific category
$page = 'Subcategory';
$subcategory = Subcategory::find($id);
$categories = Category::all();
return view('subcategories/edit')
->with('page', $page)
->with('categories', $categories)
->with('subcategory', $subcategory);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed ID
$subcategory = Subcategory::find($id);
$subcategory->name = $request['name'];
$subcategory->description = $request['description'];
$subcategory->save();
$subcategories = Subcategory::all();
$page = 'Subcategory';
return view('subcategories/index')
->with('subcategories', $subcategories)
->with('page', $page);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific User by ID (Soft-Deletes)
$subcategory = Subcategory::find($id);
$subcategory->update(['deleted_by' => Auth::user()->id]);
$subcategory->categories()->detach();
$subcategory->delete();
$subcategories = Subcategory::all();
$page = 'Subcategory';
return view('subcategories/index')
->with('subcategories', $subcategories)
->with('page', $page);
}
}
<file_sep>/app/Http/Controllers/api/UnitController.php
<?php
namespace App\Http\Controllers\api;
use App\Unit;
use Illuminate\Http\Request;
use App\Http\Resources\Unit as UnitResource;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;
use Response;
class UnitController extends Controller
{
/**
* List Units
*
* Display a listing of all product units.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the Units in a collection
UnitResource::WithoutWrapping();
return UnitResource::collection(Unit::all());
}
/**
* Add Unit
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new unit from the payload
$unit = new Unit;
$unit->uuid = (string) Str::uuid();
$unit->name = $request['name'];
$unit->description = $request['description'];
$unit->created_by = Config::get('apiuser');
$unit->save();
return response()->json([
'acton' => 'create',
'status' => 'OK',
'entity' => $unit->uuid,
'type' => 'unit',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Unit
*
* Display the specified resource.
*
* @param \App\Unit $unit
* @return \Illuminate\Http\Response
*/
public function show(Unit $unit)
{
$unit = Unit::find($unit);
// Check if unit is not in the DB
if ($unit === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'unit',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific unit
UnitResource::WithoutWrapping();
return new UnitResource(Unit::find($unit));
}
}
/**
* Update Unit
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Unit $unit
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Unit $unit)
{
// Update the resource with the addressed unit
$unit = Unit::find($unit)->first();
$unit->name = $request['name'];
$unit->description = $request['description'];
$unit->updated_by = Config::get('apiuser');
$unit->updated_at = date('Y-m-d H:i:s');
$unit->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $unit->uuid,
'type' => 'unit',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Unit
*
* Remove the specified resource from storage.
*
* @param \App\Unit $unit
* @return \Illuminate\Http\Response
*/
public function destroy(Unit $unit)
{
// Delete a specific unit by unitID (Soft-Deletes)
$unit = Unit::find($unit)->first();
$unit->update(['deleted_by' => Config::get('apiuser')]);
$unit->delete();
// Fire the JSON response
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $unit->uuid,
'type' => 'unit',
'user' => Config::get('apiuser')
], 200);
}
}
<file_sep>/app/Http/Controllers/api/TransactiontypeController.php
<?php
namespace App\Http\Controllers\api;
use App\Transactiontype;
use Illuminate\Http\Request;
use App\Http\Resources\Transactiontype as TransactiontypeResource;
class TransactiontypeController extends Controller
{
/**
* Show Transaction Types
*
* Display a listing of the types of transactions.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the users in a collection
TransactiontypeResource::WithoutWrapping();
return TransactiontypeResource::collection(Transactiontype::get());
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Transaction;
use App\Product;
use App\User;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the user home.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function dashboard()
{
$totalTransactions = Transaction::count('id');
$totalSales = Transaction::where('transactiontype_id', 2)->sum('price');
$totalProducts = Product::count('id');
$totalUsers = User::count('id');
return view('dashboard')
->with('totalSales', $totalSales)
->with('totalProducts', $totalProducts)
->with('totalUsers', $totalUsers)
->with('totalTransactions', $totalTransactions);
}
/**
* Show API Documentation page application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function apidocs()
{
return view('apidocs');
}
}
<file_sep>/app/Status.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Status extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'uuid', 'name',
];
/**
* Get the order where the status belongs.
*
* @return \Illuminate\Http\Response
*/
public function statuses()
{
return $this
->hasMany('App\Order');
}
/**
* Get the transaction where the status belongs.
*
* @return \Illuminate\Http\Response
*/
public function transactions()
{
return $this
->hasMany('App\Transaction');
}
}
<file_sep>/public/sql/regions.sql
INSERT INTO regions (id, uuid, name, created_at) VALUES(1, UUID(), 'Kagera', NOW());
INSERT INTO regions (id, uuid, name, created_at) VALUES(2, UUID(), 'Kigoma', NOW());
INSERT INTO regions (id, uuid, name, created_at) VALUES(3, UUID(), 'Arusha', NOW());
INSERT INTO regions (id, uuid, name, created_at) VALUES(4, UUID(), 'Ruvuma', NOW());<file_sep>/database/seeds/UsersTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use App\User;
use App\Level;
use App\Location;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$administrator_level = Level::where('name', 'administrator')->first();
// $manufacturer_level = Level::where('name', 'manufacturer')->first();
// $hubagrodealer_level = Level::where('name', 'hub-agrodealer')->first();
// $agrodealer_level = Level::where('name', 'agrodealer')->first();
// $reseller_level = Level::where('name', 'reseller')->first();
$administrator_location = Location::where('id', 1)->first();
// $manufacturer_location = Location::where('id', 2)->first();
// $hubagrodealer_location = Location::where('id', 3)->first();
// $agrodealer_location = Location::where('id', 4)->first();
// $reseller_location = Location::where('id', 5)->first();
// $reseller2_location = Location::where('id', 6)->first();
// Create the first sample user named admin
$user = new User();
$user->uuid = (string) Str::uuid();
$user->firstname = 'Craysonde';
$user->middlename = 'Nyilongo';
$user->surname = 'Ngelangela';
$user->phone = '0753983337';
$user->username = 'administrator';
$user->password = bcrypt('<PASSWORD>.');
$user->created_by = 0;
$user->created_at = date('Y-m-d H:i:s');
$user->save();
$user->levels()->attach($administrator_level, array('uuid' => (string) Str::uuid()));
$user->locations()->attach($administrator_location, array('uuid' => (string) Str::uuid()));
// // Create the second sample user named admin
// $user = new User();
// $user->uuid = (string) Str::uuid();
// $user->firstname = 'Original';
// $user->middlename = 'Input';
// $user->surname = 'Manufacturer';
// $user->phone = '0755'.mt_rand(100000, 999999);
// $user->username = 'manufacturer';
// $user->password = bcrypt('<PASSWORD>');
// $user->created_by = 0;
// $user->created_at = date('Y-m-d H:i:s');
// $user->save();
// $user->levels()->attach($manufacturer_level, array('uuid' => (string) Str::uuid()));
// $user->locations()->attach($manufacturer_location, array('uuid' => (string) Str::uuid()));
// // Create the third sample user named kizito
// $user = new User();
// $user->uuid = (string) Str::uuid();
// $user->firstname = 'Sebastian';
// $user->middlename = 'Petro';
// $user->surname = 'Hamba';
// $user->phone = '0754123456';
// $user->username = 'hubagrodealer';
// $user->password = bcrypt('<PASSWORD>');
// $user->created_by = 0;
// $user->created_at = date('Y-m-d H:i:s');
// $user->save();
// $user->levels()->attach($hubagrodealer_level, array('uuid' => (string) Str::uuid()));
// $user->locations()->attach($hubagrodealer_location, array('uuid' => (string) Str::uuid()));
// // Create the fourth sample user named supplier
// $user = new User();
// $user->uuid = (string) Str::uuid();
// $user->firstname = 'Ali';
// $user->middlename = 'Agrodealer';
// $user->surname = 'Zungu';
// $user->phone = '0755'.mt_rand(100000, 999999);
// $user->username = 'agrodealer';
// $user->password = bcrypt('<PASSWORD>');
// $user->created_by = 0;
// $user->created_at = date('Y-m-d H:i:s');
// $user->save();
// $user->levels()->attach($agrodealer_level, array('uuid' => (string) Str::uuid()));
// $user->locations()->attach($agrodealer_location, array('uuid' => (string) Str::uuid()));
// // Create the fifth sample user named agrodealer
// $user = new User();
// $user->uuid = (string) Str::uuid();
// $user->firstname = 'Christine';
// $user->middlename = 'Reseller';
// $user->surname = 'Gamba';
// $user->phone = '0755'.mt_rand(100000, 999999);
// $user->username = 'reseller';
// $user->password = <PASSWORD>('<PASSWORD>');
// $user->created_by = 0;
// $user->created_at = date('Y-m-d H:i:s');
// $user->save();
// $user->levels()->attach($reseller_level, array('uuid' => (string) Str::uuid()));
// $user->locations()->attach($reseller_location, array('uuid' => (string) Str::uuid()));
// // Create the sixth sample user named farmer
// $user = new User();
// $user->uuid = (string) Str::uuid();
// $user->firstname = 'Dauda';
// $user->middlename = 'Namamba';
// $user->surname = 'Waziri';
// $user->phone = '0755'.mt_rand(100000, 999999);
// $user->username = 'reseller2';
// $user->password = bcrypt('<PASSWORD>');
// $user->created_by = 0;
// $user->created_at = date('Y-m-d H:i:s');
// $user->save();
// $user->levels()->attach($reseller_level, array('uuid' => (string) Str::uuid()));
// $user->locations()->attach($reseller2_location, array('uuid' => (string) Str::uuid()));
// $users = factory(App\User::class, 30)->create();
// $this->command->info('User table seeded!');
}
}
<file_sep>/app/Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
/**
* Get the dealer for specific order.
*/
public function dealer()
{
return $this->belongsTo('App\User', 'dealer_id', 'id');
}
/**
* Get the supplier for specific order.
*/
public function supplier()
{
return $this->belongsTo('App\User', 'supplier_id', 'id');
}
/**
* Get the product for specific order.
*/
public function product()
{
return $this->belongsTo('App\Product', 'product_id', 'id');
}
}
<file_sep>/app/Http/Controllers/api/LevelController.php
<?php
namespace App\Http\Controllers\api;
use App\Level;
use Illuminate\Http\Request;
use App\Http\Resources\Level as LevelResource;
use Illuminate\Support\Str;
use Response;
use Illuminate\Support\Facades\Config;
class LevelController extends Controller
{
/**
* List Levels
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the Levels in a collection
LevelResource::WithoutWrapping();
return LevelResource::collection(Level::all());
}
/**
* Add Level
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new level from the payload
$level = new Level;
$level->uuid = (string) Str::uuid();
$level->name = $request['name'];
$level->description = $request['description'];
$level->created_by = Config::get('apiuser');
$level->save();
return response()->json([
'acton' => 'create',
'status' => 'OK',
'entity' => $level->uuid,
'type' => 'level',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Level
*
* Display the specified resource.
*
* @param \App\Level $level
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$level = Level::find($id);
// Check if level is not in the DB
if ($level === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'level',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific level
LevelResource::WithoutWrapping();
return new LevelResource(Level::find($id));
}
}
/**
* Update Level
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Level $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed level
$level = Level::find($id)->first();
$level->name = $request['name'];
$level->description = $request['description'];
$level->updated_by = Config::get('apiuser');
$level->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $level->uuid,
'type' => 'level',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Level
*
* Remove the specified resource from storage.
*
* @param \App\Level $level
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific level by levelID (Soft-Deletes)
$level = Level::find($id);
$level->update(['deleted_by' => Config::get('apiuser')]);
$level->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $level->uuid,
'type' => 'level',
'user' => Config::get('apiuser')
], 200);
}
}
<file_sep>/public/sql/wards.sql
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bisibo", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kabindi", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kalenge", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kaniha", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Lusahunga", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nemba", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyabusozi", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakahura", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyamahanga", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyamigogo", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyantakara", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyarubungo", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Runazi", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ruziba", 1, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buhendangabo", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bujugo", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Butelankuzi", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Butulage", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ibwera", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Izimbya", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kaagya", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kaibanja", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kanyangereko", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Karabagaine", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kasharu", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Katerero", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Katoma", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Katoro", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kemondo", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibilizi", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kikomero", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kishanje", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kishogo", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kyamulaile", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Maruku", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mikoni", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mugajwale", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakato", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakibimbili", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rubafu", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rubale", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ruhunga", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rukoma", 2, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bakoba", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bilele", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buhemba", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Hamugembe", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ijuganyondo", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kagondo", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kahororo", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kashai", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibeta", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kitendaguro", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Miembeni", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nshambya", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyanga", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rwamishenye", 3, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bugene", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bugomora", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bweranyange", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Igurwa", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ihanda", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ihembe", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Isingiro", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kaisho", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kamuli", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kanoni", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kayanga", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibingo", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibondo", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kihanga", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kimuli", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kiruruma", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kituntu", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kyerwa", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mabira", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Murongo", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ndama", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nkwenda", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyabiyonza", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyaishozi", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakahanga", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakakika", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakabanga", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Achapa", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Chabuhora", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakasimbi", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rugu", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rwabwere", 4, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bugomora", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Businde", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Isingiro", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kaisho", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kamuli", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibale", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibingo", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kikukuru", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kimuli", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kyerwa", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mabira", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Murongo", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nkwenda", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakatuntu", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rukuraijo", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rutunguru", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rwabwere", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Songambele", 5, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bugandika", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bugorora", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buyango", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bwanjai", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Gera", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ishozi", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ishunju", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kakunyu", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kanyigo", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kashenye", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kassambya", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kilimilil", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kitobo", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kyaka", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mabale", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Minziro", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mushasha", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mutukula", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nsunga", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ruzinga", 6, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bisheke", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Biirabo", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buganguzi", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bulyakashaju", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bumbile", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Burungura", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Goziba", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ibuga", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ijumbi", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ikondo", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Izigo", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kabirizi", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kagoma", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kamachumu", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Karambi", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kasharunga", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kashasha", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibanga", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kimwani", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kishanda", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kyebitembe", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mazinga", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mubunda", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muhutwe", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muleba", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muyondwe", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ngenge", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nshamba", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ruhanga", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rushwa", 7, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bukiriro", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bugarama", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kabanga", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kanazi", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibimba", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kirushya", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Keza", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mabawe", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mbuba", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muganza", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mugoma", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Murusagamba", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ntobeye", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakisasa", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyamiyaga", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rulenge", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rusumo", 8, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Biharu", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buhigwe(Buhigwe DC)", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Janda(Buhigwe DC)", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kajana(Buhigwe DC)", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibande", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kilelema", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mugera", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muhinda", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Munanila", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Munyegera", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Munzeze", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muyama", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mwayaya", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyamugali", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rusaba", 9, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Gwarama", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Gwanumpu", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kakonko", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kasanda", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kasuga", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Katanga", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kiziguzigu", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mugunzu", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muhange", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kanyonza", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyabibuye", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyamtukuza", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rugenge", 10, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "KasuluMjini", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kigondo", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Msambara", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muganza", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muhunga", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Murufiti", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyansha", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyumbigwa", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ruhita", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bugaga", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buhoro", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Herushingo", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kagerankanda", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kigembe", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kitagata", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kitanga", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kurugongo", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kwaga", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Muzye", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyachenda", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyakitonto", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyamidaho", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyamnyusi", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rusesa", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Shunguliba", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Titye", 12, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bunyambo", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Busagara", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Itaba", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kitahana", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kagezi", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Busunzu", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kizazi", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kumsenga", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mabamba", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kumwambu", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Misezero", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bukabuye", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Murungu", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyaruyoba", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "rusohoko", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Turana ward", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rugongwe", 13, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bangwe", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buhanda", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Businde", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buzebazeba", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Gungu", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kagera", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kasimbu", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kasingirima", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Katubuka", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kibirizi", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kigoma", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kipampa", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kitongoji", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Machinjoni", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Majengo", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rubuga", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Rusimbi", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Bitale", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kagongo", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kagunga", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kalinzi", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mahembe", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Matendo", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mkigo", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mkongoro", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mngonya", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mwamgongo", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mwandiga", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Buhingu", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Igalula", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Ilagala", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Itebula", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kalya", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kandaga", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kazuramimba", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Mganza", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nguruka", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Sigunga", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Simbo", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Sunuka", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Uvinza", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Kaloleni", 17, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Unga Limited", 17, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "<NAME>", 18, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Unknown", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Airport", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyarubanda", 15, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Herembe", 16, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Murubona", 11, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Nyarubanda", 14, NOW());
INSERT INTO wards (uuid, wards.name, district_id, created_at) VALUES(UUID(), "Murubona", 11, NOW());<file_sep>/database/factories/UserWardFactory.php
<?php
use Faker\Generator as Faker;
use App\User;
use App\Level;
use App\Location;
use App\Ward;
use App\Transaction;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(App\User_Ward::class, function (Faker $faker) {
static $user;
return [
'uuid' => $faker->uuid,
'ward_id' => App\Ward::all()->random()->id,
'user_id' => App\User::all()->unique()->random()->id,
'created_by' => $user ?: $user = 1,
'created_at' => $faker->dateTimeBetween($startDate = '-6 months', $endDate = 'now', $timezone = date_default_timezone_get()),
];
});<file_sep>/app/Http/Controllers/api/TransactionController.php
<?php
namespace App\Http\Controllers\api;
use App\Transaction;
use App\Product;
use App\Balance;
use Illuminate\Http\Request;
use App\Http\Resources\Transaction as TransactionResource;
use Illuminate\Support\Str;
use Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use App\User;
class TransactionController extends Controller
{
/**
* List Transactions
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the users in a collection
TransactionResource::WithoutWrapping();
return TransactionResource::collection(Transaction::with('transactiontype')
->with('user')
->with('product')
->with('status')
->get());
}
/**
* Add Transaction
*
* Store a newly created resource in transaction storage.
* Update the count of the specific product for a specific user in Balances
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$balance = Balance::where('user_id', $request['user_id'])->where('product_id', $request['product_id'])->first();
if ($request['transactiontype_id'] == 1) {
$transaction = new Transaction;
$transaction->uuid = (string) Str::uuid();
$transaction->amount = $request['amount'];
$transaction->price = $request['price'];
$transaction->transactiontype_id = $request['transactiontype_id'];
$transaction->user_id = $request['user_id'];
$transaction->product_id = $request['product_id'];
$transaction->status_id = 1;
$transaction->created_by = Config::get('apiuser');
$transaction->save();
if(empty($balance)){
$balance = new Balance;
$balance->uuid = (string) Str::uuid();
$balance->count = $request['amount'];
$balance->user_id = $request['user_id'];
$balance->product_id = $request['product_id'];
$balance->buying_price = $request['price'];
$balance->selling_price = $request['price'];
$balance->created_by = Config::get('apiuser');
$balance->save();
}
else{
$balance->count = $balance->count + $request['amount'];
$balance->buying_price = $request['price'];
$balance->save();
}
}
elseif ($request['transactiontype_id'] == 2) {
if(empty($balance)){
return response()->json(['error' => 'This user does not have this product'], 400);
}
elseif ($request['amount'] > $balance->count) {
return response()->json(['error' => 'This user has has less than the requested amount.', 'balance' => $balance->count], 400);
}
else{
$transaction = new Transaction;
$transaction->uuid = (string) Str::uuid();
$transaction->amount = $request['amount'];
$transaction->price = $request['price'];
$transaction->transactiontype_id = $request['transactiontype_id'];
$transaction->user_id = $request['user_id'];
$transaction->product_id = $request['product_id'];
$transaction->status_id = 1;
$transaction->created_by = Config::get('apiuser');
$transaction->save();
$balance->count = $balance->count - $request['amount'];
$balance->selling_price = $request['price'];
$balance->save();
}
}
else{
return response()->json(['error' => 'Unknown transaction type'], 404);
}
return response()->json([
'action' => 'create',
'status' => 'OK',
'entity' => $transaction->uuid,
'type' => 'transaction',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show a single Transaction by using its ID
*
* Display the specified resource.
*
* @param \App\Transaction $transaction
* @return \Illuminate\Http\Response
*/
public function show(Transaction $transaction)
{
// List all the users in a collection
TransactionResource::WithoutWrapping();
// return new UserResource(User::with('levels')->with('locations')->with('wards')->find($id));
return new TransactionResource(Transaction::with('transactiontype')->with('user')->with('product')->with('status')->find($transaction));
}
/**
* Update Transaction
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Transaction $transaction
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$transaction = Transaction::find($id);
$transaction->status_id = 1;
$transaction->updated_by = Config::get('apiuser');
$transaction->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $transaction->uuid,
'type' => 'transaction',
'user' => Config::get('apiuser')
], 201);
}
/**
* Delete Transaction
*
* Remove the specified resource from storage.
*
* @param \App\Transaction $transaction
* @return \Illuminate\Http\Response
*/
public function destroy(Transaction $id)
{
// Delete a specific Transaction by ID (Soft-Deletes)
$transaction = Transaction::find($id);
$transaction->update(['deleted_by' => Config::get('apiuser')]);
$transaction->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $transaction->uuid,
'type' => 'transaction',
'user' => Config::get('apiuser')
], 200);
}
/**
* User's Transactions
*
* JSON List of specific user's transactions.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function userTransactions($user)
{
// List all the transactions for a user
TransactionResource::WithoutWrapping();
return new TransactionResource(Transaction::where('user_id', $user)->with('transactiontype')->with('user')->with('product')->with('status')->get());
}
}
<file_sep>/app/Sms.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Sms extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'sms';
/**
* Fields that can be mass assignable
*
* @return mixed
*/
protected $fillable = [
'uuid', 'urn', 'text',
];
}
<file_sep>/public/docs/source/index.md
---
title: API Reference
language_tabs:
- bash
- javascript
includes:
search: true
toc_footers:
- <a href='http://github.com/mpociot/documentarian'>Documentation Powered by Documentarian</a>
---
<!-- START_INFO -->
# Info
Welcome to the generated API reference.
[Get Postman Collection](http://localhost/rucodia/docs/collection.json)
<!-- END_INFO -->
#general
<!-- START_080f3ecebb7bcc2f93284b8f5ae1ac3b -->
## List Users
JSON List of all users.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/users" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/users",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
[
{
"id": 1,
"uuid": "27b5b8aa-4f13-4310-8d84-fe33476777dd",
"firstname": "Default",
"middlename": "System",
"surname": "Administrator",
"phone": "0755556100",
"username": "administrator",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:46",
"updated_at": "2018-09-24 13:15:46",
"deleted_at": null,
"levels": [
{
"id": 1,
"uuid": "03b8424f-2c8b-49b9-b94b-afefea58c24a",
"name": "Administrator",
"description": "Seeded system administrator level",
"buys_from": "0, 0, 0, 0, 0",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:45",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 1,
"level_id": 1,
"created_at": "2018-09-24 13:15:46",
"updated_at": "2018-09-24 13:15:46",
"uuid": "16c39ee9-2564-4ca2-b59d-637f212fde6f"
}
}
],
"locations": [
{
"id": 1,
"uuid": "4c26e7fd-2689-4446-9cd4-cbe4cea0368c",
"name": "<NAME>",
"latitude": "-4.859657",
"longitude": "29.625055",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:45",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 1,
"location_id": 1,
"created_at": "2018-09-24 13:15:46",
"updated_at": "2018-09-24 13:15:46",
"uuid": "a1e8dc36-bbef-4942-9f67-6a6da4c7bc6a"
}
}
],
"wards": [
{
"id": 262,
"uuid": "ee0d6453-bfe2-11e8-8e80-d4258bf8ac27",
"name": "Kibirizi",
"district_id": 14,
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:16:03",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 1,
"ward_id": 262,
"created_at": "2018-09-24 13:16:04",
"updated_at": null,
"uuid": "eee6bd0b-bfe2-11e8-8e80-d4258bf8ac27"
}
}
]
},
{
"id": 2,
"uuid": "ec791ca3-7a56-4c38-bbff-77cb076946c5",
"firstname": "Original",
"middlename": "Input",
"surname": "Manufacturer",
"phone": "0755893982",
"username": "manufacturer",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:46",
"updated_at": "2018-09-24 13:15:46",
"deleted_at": null,
"levels": [
{
"id": 2,
"uuid": "514cbf50-7edb-4c9c-80e6-936348838784",
"name": "Manufacturer",
"description": "Producing company.",
"buys_from": "0, 0, 0, 0, 0",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:45",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 2,
"level_id": 2,
"created_at": "2018-09-24 13:15:46",
"updated_at": "2018-09-24 13:15:46",
"uuid": "12363e5c-7421-42fa-b9aa-a38fded8933c"
}
}
],
"locations": [
{
"id": 2,
"uuid": "3825d9ae-2315-4a33-986d-f5a5fe0e6a0c",
"name": "<NAME>",
"latitude": "-4.859547",
"longitude": "29.625105",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:46",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 2,
"location_id": 2,
"created_at": "2018-09-24 13:15:46",
"updated_at": "2018-09-24 13:15:46",
"uuid": "a590071a-7a2f-4951-91a5-6ac9baed7d29"
}
}
],
"wards": [
{
"id": 262,
"uuid": "ee0d6453-bfe2-11e8-8e80-d4258bf8ac27",
"name": "Kibirizi",
"district_id": 14,
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:16:03",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 2,
"ward_id": 262,
"created_at": "2018-09-24 13:16:04",
"updated_at": null,
"uuid": "eef0a72f-bfe2-11e8-8e80-d4258bf8ac27"
}
}
]
},
{
"id": 3,
"uuid": "ca993ea0-cc22-4ae3-aa40-e6b470bd067b",
"firstname": "Sebastian",
"middlename": "Petro",
"surname": "Hamba",
"phone": "0754123456",
"username": "hubagrodealer",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"deleted_at": null,
"levels": [
{
"id": 3,
"uuid": "bc011590-87bf-4d9f-ac05-2cef6de29f42",
"name": "Hub-Agrodealer",
"description": "An agrodealer with more than 10 agrodealer clients.",
"buys_from": "0, 2, 3, 0, 0",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:45",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 3,
"level_id": 3,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"uuid": "668aecfc-8a0d-4bf1-9894-8a3a6a50e624"
}
}
],
"locations": [
{
"id": 3,
"uuid": "b8c93a2b-c2cd-41be-a6cc-3482fb38e7f4",
"name": "<NAME>",
"latitude": "-4.592884",
"longitude": "30.180055",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:46",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 3,
"location_id": 3,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"uuid": "8fac59c4-1e53-466c-8138-917054891c06"
}
}
],
"wards": [
{
"id": 207,
"uuid": "ecb201bf-bfe2-11e8-8e80-d4258bf8ac27",
"name": "Kigondo",
"district_id": 11,
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:16:00",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 3,
"ward_id": 207,
"created_at": "2018-09-24 13:16:04",
"updated_at": null,
"uuid": "eef78ed1-bfe2-11e8-8e80-d4258bf8ac27"
}
}
]
},
{
"id": 4,
"uuid": "a96586e7-4d18-4e15-b492-ebc5d034226b",
"firstname": "Ali",
"middlename": "Agrodealer",
"surname": "Zungu",
"phone": "0755836195",
"username": "agrodealer",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"deleted_at": null,
"levels": [
{
"id": 4,
"uuid": "b5a0e910-218d-41fe-b05f-38d5341573fa",
"name": "Agrodealer",
"description": "An agrodealer who buys from hub-agrodealer and other agrodealers. Sells to resellers.",
"buys_from": "0, 2, 3, 4, 0",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:45",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 4,
"level_id": 4,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"uuid": "05f11bc7-f3f0-4710-a154-b8e67950da51"
}
}
],
"locations": [
{
"id": 4,
"uuid": "4b0aa415-115f-4452-a019-ce3a81e66a57",
"name": "<NAME>",
"latitude": "-4.887088",
"longitude": "29.620836",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:46",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 4,
"location_id": 4,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"uuid": "7900727a-960f-4481-9fdf-052ada5699ee"
}
}
],
"wards": [
{
"id": 253,
"uuid": "edd3c165-bfe2-11e8-8e80-d4258bf8ac27",
"name": "Bangwe",
"district_id": 14,
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:16:02",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 4,
"ward_id": 253,
"created_at": "2018-09-24 13:16:04",
"updated_at": null,
"uuid": "ef0860af-bfe2-11e8-8e80-d4258bf8ac27"
}
}
]
},
{
"id": 5,
"uuid": "309358bc-681f-4f06-82ad-5efba6877ddb",
"firstname": "Christine",
"middlename": "Reseller",
"surname": "Gamba",
"phone": "0755768808",
"username": "reseller",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"deleted_at": null,
"levels": [
{
"id": 5,
"uuid": "58e6f11b-f847-4c9a-b96d-d95b2c3d7f53",
"name": "Reseller",
"description": "A reseller buys from agrodealers in the hub and outta hub.",
"buys_from": "0, 0, 3, 4, 5",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:45",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 5,
"level_id": 5,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"uuid": "ae30d327-6a51-4bb3-808d-0418d511e63d"
}
}
],
"locations": [
{
"id": 5,
"uuid": "729ec9f5-e58f-4ca2-891e-97d97d13d515",
"name": "<NAME>",
"latitude": "-4.858592",
"longitude": "29.639505",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:46",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 5,
"location_id": 5,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"uuid": "91d18a9d-7bcd-413b-9f88-38f2fa456fdb"
}
}
],
"wards": [
{
"id": 257,
"uuid": "edf2717c-bfe2-11e8-8e80-d4258bf8ac27",
"name": "Gungu",
"district_id": 14,
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:16:03",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 5,
"ward_id": 257,
"created_at": "2018-09-24 13:16:04",
"updated_at": null,
"uuid": "ef1127b5-bfe2-11e8-8e80-d4258bf8ac27"
}
}
]
},
{
"id": 6,
"uuid": "29b5d14c-344a-4fcc-8484-d286eda7df39",
"firstname": "Dauda",
"middlename": "Namamba",
"surname": "Waziri",
"phone": "0755278326",
"username": "reseller2",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"deleted_at": null,
"levels": [
{
"id": 5,
"uuid": "58e6f11b-f847-4c9a-b96d-d95b2c3d7f53",
"name": "Reseller",
"description": "A reseller buys from agrodealers in the hub and outta hub.",
"buys_from": "0, 0, 3, 4, 5",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:45",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 6,
"level_id": 5,
"created_at": "2018-09-24 13:15:47",
"updated_at": "2018-09-24 13:15:47",
"uuid": "896aaad0-dcac-437a-a843-ffa43c00a43b"
}
}
],
"locations": [
{
"id": 6,
"uuid": "cce25aed-6388-407b-972e-96281bfeab0e",
"name": "<NAME>",
"latitude": "-4.861908",
"longitude": "29.646421",
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:15:46",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 6,
"location_id": 6,
"created_at": "2018-09-24 13:15:48",
"updated_at": "2018-09-24 13:15:48",
"uuid": "61cc8627-02f9-4c44-9630-1a2f192be916"
}
}
],
"wards": [
{
"id": 257,
"uuid": "edf2717c-bfe2-11e8-8e80-d4258bf8ac27",
"name": "Gungu",
"district_id": 14,
"created_by": 0,
"updated_by": null,
"deleted_by": null,
"created_at": "2018-09-24 13:16:03",
"updated_at": null,
"deleted_at": null,
"pivot": {
"user_id": 6,
"ward_id": 257,
"created_at": "2018-09-24 13:16:04",
"updated_at": null,
"uuid": "ef1d818a-bfe2-11e8-8e80-d4258bf8ac27"
}
}
]
}
]
```
### HTTP Request
`GET api/v1/users`
`HEAD api/v1/users`
<!-- END_080f3ecebb7bcc2f93284b8f5ae1ac3b -->
<!-- START_4194ceb9a20b7f80b61d14d44df366b4 -->
## Add User
Store a newly created user resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/users" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/users",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/users`
<!-- END_4194ceb9a20b7f80b61d14d44df366b4 -->
<!-- START_b4ea58dd963da91362c51d4088d0d4f4 -->
## Update User
Edit an existing User details.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/users/{user}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/users/{user}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/users/{user}`
`HEAD api/v1/users/{user}`
<!-- END_b4ea58dd963da91362c51d4088d0d4f4 -->
<!-- START_296fac4bf818c99f6dd42a4a0eb56b58 -->
## Update User
Update the specified user resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/users/{user}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/users/{user}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/users/{user}`
`PATCH api/v1/users/{user}`
<!-- END_296fac4bf818c99f6dd42a4a0eb56b58 -->
<!-- START_22354fc95c42d81a744eece68f5b9b9a -->
## Delete User
Remove the specified user resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/users/{user}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/users/{user}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/users/{user}`
<!-- END_22354fc95c42d81a744eece68f5b9b9a -->
<!-- START_6fe9ddd4051fe5f4d6a44edbc5aa49d0 -->
## List Levels
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/levels" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/levels",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/levels`
`HEAD api/v1/levels`
<!-- END_6fe9ddd4051fe5f4d6a44edbc5aa49d0 -->
<!-- START_2a76a4d56ad2e36725f2c974d65ff78b -->
## Add Level
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/levels" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/levels",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/levels`
<!-- END_2a76a4d56ad2e36725f2c974d65ff78b -->
<!-- START_441b77ed9396faeddb36e9447ac83ea7 -->
## Show Level
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/levels/{level}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/levels/{level}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/levels/{level}`
`HEAD api/v1/levels/{level}`
<!-- END_441b77ed9396faeddb36e9447ac83ea7 -->
<!-- START_0ebe8b3e3da9c405ebd17fb04df92766 -->
## Update Level
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/levels/{level}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/levels/{level}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/levels/{level}`
`PATCH api/v1/levels/{level}`
<!-- END_0ebe8b3e3da9c405ebd17fb04df92766 -->
<!-- START_779bf44d67c05fb52722bedfbd346f60 -->
## Delete Level
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/levels/{level}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/levels/{level}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/levels/{level}`
<!-- END_779bf44d67c05fb52722bedfbd346f60 -->
<!-- START_f1724111ed2d4fef6facdc245c1628a6 -->
## List Locations
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/locations" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/locations",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/locations`
`HEAD api/v1/locations`
<!-- END_f1724111ed2d4fef6facdc245c1628a6 -->
<!-- START_2a7b18b14a7304f286af447a290241db -->
## Add Location
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/locations" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/locations",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/locations`
<!-- END_2a7b18b14a7304f286af447a290241db -->
<!-- START_9b7cd26cae477c96a0a5b3980b8f9e7e -->
## Show Location
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/locations/{location}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/locations/{location}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/locations/{location}`
`HEAD api/v1/locations/{location}`
<!-- END_9b7cd26cae477c96a0a5b3980b8f9e7e -->
<!-- START_b4f8b0edd6aa6eedab3bfc9510a4ed5d -->
## Update Location
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/locations/{location}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/locations/{location}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/locations/{location}`
`PATCH api/v1/locations/{location}`
<!-- END_b4f8b0edd6aa6eedab3bfc9510a4ed5d -->
<!-- START_d74b55bb0676b4b842b6afeddb3f626f -->
## Delete Location
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/locations/{location}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/locations/{location}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/locations/{location}`
<!-- END_d74b55bb0676b4b842b6afeddb3f626f -->
<!-- START_82952855fc557e95349a5414e2473bd3 -->
## List Units
Display a listing of all product units.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/units" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/units",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/units`
`HEAD api/v1/units`
<!-- END_82952855fc557e95349a5414e2473bd3 -->
<!-- START_f2d1b34b2207e414c3225c8ad0b241df -->
## Add Unit
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/units" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/units",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/units`
<!-- END_f2d1b34b2207e414c3225c8ad0b241df -->
<!-- START_2aa6f72e42d9643aae971e0a2226d752 -->
## Show Unit
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/units/{unit}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/units/{unit}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/units/{unit}`
`HEAD api/v1/units/{unit}`
<!-- END_2aa6f72e42d9643aae971e0a2226d752 -->
<!-- START_e7070c9fef003c03b460ea4f58916be0 -->
## Update Unit
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/units/{unit}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/units/{unit}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/units/{unit}`
`PATCH api/v1/units/{unit}`
<!-- END_e7070c9fef003c03b460ea4f58916be0 -->
<!-- START_0f2a8b1271170295a5eb880cfbc1a49a -->
## Delete Unit
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/units/{unit}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/units/{unit}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/units/{unit}`
<!-- END_0f2a8b1271170295a5eb880cfbc1a49a -->
<!-- START_bdd3ccf7db9f96843f0bb3617eac0164 -->
## List Categories
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/categories" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/categories",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/categories`
`HEAD api/v1/categories`
<!-- END_bdd3ccf7db9f96843f0bb3617eac0164 -->
<!-- START_51652a01dd7666395568dd6ba9d67d58 -->
## Add Category
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/categories" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/categories",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/categories`
<!-- END_51652a01dd7666395568dd6ba9d67d58 -->
<!-- START_2bd3e8cdd1330aa83f81993ffdd2dac8 -->
## Show Category
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/categories/{category}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/categories/{category}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/categories/{category}`
`HEAD api/v1/categories/{category}`
<!-- END_2bd3e8cdd1330aa83f81993ffdd2dac8 -->
<!-- START_58b09cda1a6b4241d0b8f55289d7bd09 -->
## Update Category
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/categories/{category}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/categories/{category}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/categories/{category}`
`PATCH api/v1/categories/{category}`
<!-- END_58b09cda1a6b4241d0b8f55289d7bd09 -->
<!-- START_75b173cefee1332cf71f9d29370afde7 -->
## Delete Category
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/categories/{category}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/categories/{category}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/categories/{category}`
<!-- END_75b173cefee1332cf71f9d29370afde7 -->
<!-- START_a001499785a9a8800113bd09d1787d43 -->
## List Subcategories
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/subcategories" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/subcategories",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/subcategories`
`HEAD api/v1/subcategories`
<!-- END_a001499785a9a8800113bd09d1787d43 -->
<!-- START_070bab7822f73e995ab10d10ccd84cb7 -->
## Add Subcategory
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/subcategories" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/subcategories",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/subcategories`
<!-- END_070bab7822f73e995ab10d10ccd84cb7 -->
<!-- START_19635e4fc08bae6ae5341b2caa9e71f0 -->
## Show Subcategory
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/subcategories/{subcategory}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/subcategories/{subcategory}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/subcategories/{subcategory}`
`HEAD api/v1/subcategories/{subcategory}`
<!-- END_19635e4fc08bae6ae5341b2caa9e71f0 -->
<!-- START_dd871538b0001d4d8457f325a58bd654 -->
## Update Subcategory
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/subcategories/{subcategory}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/subcategories/{subcategory}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/subcategories/{subcategory}`
`PATCH api/v1/subcategories/{subcategory}`
<!-- END_dd871538b0001d4d8457f325a58bd654 -->
<!-- START_b63327a46ae40e4996b96293131a9cbf -->
## Delete Subcategory
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/subcategories/{subcategory}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/subcategories/{subcategory}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/subcategories/{subcategory}`
<!-- END_b63327a46ae40e4996b96293131a9cbf -->
<!-- START_675d57da5d2df3ad3cf2459c3020ccf6 -->
## List Products
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/products" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/products",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/products`
`HEAD api/v1/products`
<!-- END_675d57da5d2df3ad3cf2459c3020ccf6 -->
<!-- START_c5a77561baaaf96156fa4f456281b25f -->
## Add Product
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/products" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/products",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/products`
<!-- END_c5a77561baaaf96156fa4f456281b25f -->
<!-- START_7616ac68c37e261ec5619a6d82ca8774 -->
## Show Product
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/products/{product}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/products/{product}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/products/{product}`
`HEAD api/v1/products/{product}`
<!-- END_7616ac68c37e261ec5619a6d82ca8774 -->
<!-- START_c7a6a2912490841bc7c990bdba4945c7 -->
## Update Product
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/products/{product}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/products/{product}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/products/{product}`
`PATCH api/v1/products/{product}`
<!-- END_c7a6a2912490841bc7c990bdba4945c7 -->
<!-- START_8170e43979dbc7d681c58185ab9efbac -->
## Delete Product
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/products/{product}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/products/{product}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/products/{product}`
<!-- END_8170e43979dbc7d681c58185ab9efbac -->
<!-- START_985d87fa04a157f2d8b59ef306bf6f06 -->
## List Orders
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/orders" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/orders",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/orders`
`HEAD api/v1/orders`
<!-- END_985d87fa04a157f2d8b59ef306bf6f06 -->
<!-- START_c79cb2035f69ac8078c2cec9fc2fab4a -->
## Add Order
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/orders" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/orders",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/orders`
<!-- END_c79cb2035f69ac8078c2cec9fc2fab4a -->
<!-- START_13f4a2ba5be2993e266a0acf8d3bd280 -->
## Show Order
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/orders/{order}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/orders/{order}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/orders/{order}`
`HEAD api/v1/orders/{order}`
<!-- END_13f4a2ba5be2993e266a0acf8d3bd280 -->
<!-- START_2e6d997181b1c50b2b94eaa14b66f016 -->
## Update Order
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/orders/{order}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/orders/{order}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/orders/{order}`
`PATCH api/v1/orders/{order}`
<!-- END_2e6d997181b1c50b2b94eaa14b66f016 -->
<!-- START_f34ad9d71f18dd67576cc6db60268192 -->
## Delete Order
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/orders/{order}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/orders/{order}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/orders/{order}`
<!-- END_f34ad9d71f18dd67576cc6db60268192 -->
<!-- START_e5ef8da0d48d4872662c23e9b43e7aba -->
## List Regions
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/regions" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/regions",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/regions`
`HEAD api/v1/regions`
<!-- END_e5ef8da0d48d4872662c23e9b43e7aba -->
<!-- START_10956e91c550ae38a3b36236189ae732 -->
## Add Region
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/regions" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/regions",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/regions`
<!-- END_10956e91c550ae38a3b36236189ae732 -->
<!-- START_0d1310d91f2d3c8a47eab5b9569e9c5b -->
## Show Region
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/regions/{region}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/regions/{region}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/regions/{region}`
`HEAD api/v1/regions/{region}`
<!-- END_0d1310d91f2d3c8a47eab5b9569e9c5b -->
<!-- START_7e62eaeff1cb28ae02ea2ea677fcf22d -->
## Update Region
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/regions/{region}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/regions/{region}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/regions/{region}`
`PATCH api/v1/regions/{region}`
<!-- END_7e62eaeff1cb28ae02ea2ea677fcf22d -->
<!-- START_9e180f04734ea75c4e06c99b1d45e7c2 -->
## Delete Region
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/regions/{region}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/regions/{region}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/regions/{region}`
<!-- END_9e180f04734ea75c4e06c99b1d45e7c2 -->
<!-- START_58eb952624df98b6309ba359fec5f5ad -->
## List Districts
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/districts" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/districts",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/districts`
`HEAD api/v1/districts`
<!-- END_58eb952624df98b6309ba359fec5f5ad -->
<!-- START_0612b0c5f0d5889ac2ff240090fb66c1 -->
## Add District
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/districts" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/districts",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/districts`
<!-- END_0612b0c5f0d5889ac2ff240090fb66c1 -->
<!-- START_86971e5cbf1e9f32abff59c127cf8b90 -->
## Show District
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/districts/{district}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/districts/{district}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/districts/{district}`
`HEAD api/v1/districts/{district}`
<!-- END_86971e5cbf1e9f32abff59c127cf8b90 -->
<!-- START_cadca96e711703132002f3a9c13eaa41 -->
## Update District
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/districts/{district}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/districts/{district}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/districts/{district}`
`PATCH api/v1/districts/{district}`
<!-- END_cadca96e711703132002f3a9c13eaa41 -->
<!-- START_f37afad9b460dca296e689e0f380ed3a -->
## Delete District
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/districts/{district}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/districts/{district}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/districts/{district}`
<!-- END_f37afad9b460dca296e689e0f380ed3a -->
<!-- START_f61651addfd42540ecf94b8922a72119 -->
## List Wards
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/wards" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/wards",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/wards`
`HEAD api/v1/wards`
<!-- END_f61651addfd42540ecf94b8922a72119 -->
<!-- START_57a5a263721108e8e9c4de9e8144a8b2 -->
## Add Ward
Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/wards" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/wards",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/wards`
<!-- END_57a5a263721108e8e9c4de9e8144a8b2 -->
<!-- START_acc16fc50d93d497efb12161702d6b15 -->
## Show Ward
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/wards/{ward}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/wards/{ward}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/wards/{ward}`
`HEAD api/v1/wards/{ward}`
<!-- END_acc16fc50d93d497efb12161702d6b15 -->
<!-- START_c638c1bfb87e6fc1e802c36fd3204b20 -->
## Update Ward
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/wards/{ward}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/wards/{ward}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/wards/{ward}`
`PATCH api/v1/wards/{ward}`
<!-- END_c638c1bfb87e6fc1e802c36fd3204b20 -->
<!-- START_6766e626edee236553ea0666b1138cdd -->
## Delete Ward
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/wards/{ward}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/wards/{ward}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/wards/{ward}`
<!-- END_6766e626edee236553ea0666b1138cdd -->
<!-- START_1c7836fdf6c4ef12e0079294f2a37b97 -->
## List Transactions
Display a listing of the resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/transactions" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactions",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/transactions`
`HEAD api/v1/transactions`
<!-- END_1c7836fdf6c4ef12e0079294f2a37b97 -->
<!-- START_739dd7a62441def2c98078f39bb39e8f -->
## Add Transaction
Store a newly created resource in transaction storage.
Update the count of the specific product for a specific user in Balances
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/transactions" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactions",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/transactions`
<!-- END_739dd7a62441def2c98078f39bb39e8f -->
<!-- START_4e255dfcafd0bfd8378692fb241663d4 -->
## Show a single Transaction by using its ID
Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/transactions/{transaction}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactions/{transaction}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/transactions/{transaction}`
`HEAD api/v1/transactions/{transaction}`
<!-- END_4e255dfcafd0bfd8378692fb241663d4 -->
<!-- START_37f2399c6d5a4924b49e1f325b010fb6 -->
## Update Transaction
Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/transactions/{transaction}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactions/{transaction}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/transactions/{transaction}`
`PATCH api/v1/transactions/{transaction}`
<!-- END_37f2399c6d5a4924b49e1f325b010fb6 -->
<!-- START_e6979628fb538071fb057b854b0f926e -->
## Delete Transaction
Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/transactions/{transaction}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactions/{transaction}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/transactions/{transaction}`
<!-- END_e6979628fb538071fb057b854b0f926e -->
<!-- START_6b9b019695554bf9dcf732fb4768a86b -->
## Show Transaction Types
Display a listing of the types of transactions.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/transactiontypes" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactiontypes",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Invalid credentials.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 338,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php",
"line": 295,
"function": "failedBasicResponse",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php",
"line": 292,
"function": "onceBasic",
"class": "Illuminate\\Auth\\SessionGuard",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Facades\\Facade.php",
"line": 221,
"function": "__call",
"class": "Illuminate\\Auth\\AuthManager",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\app\\Http\\Middleware\\AuthenticateOnceWithBasicAuth.php",
"line": 19,
"function": "__callStatic",
"class": "Illuminate\\Support\\Facades\\Facade",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "App\\Http\\Middleware\\AuthenticateOnceWithBasicAuth",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\SubstituteBindings.php",
"line": 41,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/transactiontypes`
`HEAD api/v1/transactiontypes`
<!-- END_6b9b019695554bf9dcf732fb4768a86b -->
<!-- START_2f8cda166a6cb23ba3665097c4560690 -->
## Store a newly created resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/transactiontypes" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactiontypes",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/transactiontypes`
<!-- END_2f8cda166a6cb23ba3665097c4560690 -->
<!-- START_3e7f38ffd7826b7c4f70e9318b859715 -->
## Display the specified resource.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/transactiontypes/{transactiontype}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactiontypes/{transactiontype}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Too Many Attempts.",
"exception": "Illuminate\\Http\\Exceptions\\ThrottleRequestsException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 122,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 52,
"function": "buildException",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/transactiontypes/{transactiontype}`
`HEAD api/v1/transactiontypes/{transactiontype}`
<!-- END_3e7f38ffd7826b7c4f70e9318b859715 -->
<!-- START_86e48bdb19dfd3bd810a3afe23d0565f -->
## Update the specified resource in storage.
> Example request:
```bash
curl -X PUT "http://localhost/rucodia/api/v1/transactiontypes/{transactiontype}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactiontypes/{transactiontype}",
"method": "PUT",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`PUT api/v1/transactiontypes/{transactiontype}`
`PATCH api/v1/transactiontypes/{transactiontype}`
<!-- END_86e48bdb19dfd3bd810a3afe23d0565f -->
<!-- START_377450b1e69703699ad1f9f619591803 -->
## Remove the specified resource from storage.
> Example request:
```bash
curl -X DELETE "http://localhost/rucodia/api/v1/transactiontypes/{transactiontype}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/transactiontypes/{transactiontype}",
"method": "DELETE",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`DELETE api/v1/transactiontypes/{transactiontype}`
<!-- END_377450b1e69703699ad1f9f619591803 -->
<!-- START_2844064d57cef80772662abf1c7f58fb -->
## api/v1/auth
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/auth" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/auth",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Too Many Attempts.",
"exception": "Illuminate\\Http\\Exceptions\\ThrottleRequestsException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 122,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 52,
"function": "buildException",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/auth`
`HEAD api/v1/auth`
<!-- END_2844064d57cef80772662abf1c7f58fb -->
<!-- START_a6aa6fe45441a99dfef5d475379786a9 -->
## Show Region Districts
Display the districts of the region.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/regions/{region}/districts" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/regions/{region}/districts",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Too Many Attempts.",
"exception": "Illuminate\\Http\\Exceptions\\ThrottleRequestsException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 122,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 52,
"function": "buildException",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/regions/{region}/districts`
`HEAD api/v1/regions/{region}/districts`
<!-- END_a6aa6fe45441a99dfef5d475379786a9 -->
<!-- START_9324bb496d5d57b343ef97983e8eb1b6 -->
## Show Region Wards
Display wards of a region listed by districts.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/regions/{region}/districts/wards" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/regions/{region}/districts/wards",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Too Many Attempts.",
"exception": "Illuminate\\Http\\Exceptions\\ThrottleRequestsException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 122,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 52,
"function": "buildException",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/regions/{region}/districts/wards`
`HEAD api/v1/regions/{region}/districts/wards`
<!-- END_9324bb496d5d57b343ef97983e8eb1b6 -->
<!-- START_38b7404318c446437d94c72ef822a56e -->
## api/v1/districts/{district}/wards
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/districts/{district}/wards" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/districts/{district}/wards",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Too Many Attempts.",
"exception": "Illuminate\\Http\\Exceptions\\ThrottleRequestsException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 122,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 52,
"function": "buildException",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/districts/{district}/wards`
`HEAD api/v1/districts/{district}/wards`
<!-- END_38b7404318c446437d94c72ef822a56e -->
<!-- START_fdb4907a6da218135e82b394a7b30abf -->
## Show Product Balances
Specific user product details such as Totals, Cash, Balances and Profit.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/user/{user_id}/product/{product_id}/balance" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/user/{user_id}/product/{product_id}/balance",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\RouteCollection.php",
"line": 179,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 613,
"function": "match",
"class": "Illuminate\\Routing\\RouteCollection",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "findRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/user/{user_id}/product/{product_id}/balance`
`HEAD api/v1/user/{user_id}/product/{product_id}/balance`
<!-- END_fdb4907a6da218135e82b394a7b30abf -->
<!-- START_b36a309b74110fa2ebbfa9adb1849869 -->
## Show Product Balances
Specific user product details such as Totals, Cash, Balances and Profit.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/users/{user}/products" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/users/{user}/products",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Too Many Attempts.",
"exception": "Illuminate\\Http\\Exceptions\\ThrottleRequestsException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 122,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 52,
"function": "buildException",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/users/{user}/products`
`HEAD api/v1/users/{user}/products`
<!-- END_b36a309b74110fa2ebbfa9adb1849869 -->
<!-- START_fb8abf664186616849f74ef8bccb8865 -->
## User's Transactions
JSON List of specific user's transactions.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/users/{user}/transactions" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/users/{user}/transactions",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Too Many Attempts.",
"exception": "Illuminate\\Http\\Exceptions\\ThrottleRequestsException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 122,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 52,
"function": "buildException",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/users/{user}/transactions`
`HEAD api/v1/users/{user}/transactions`
<!-- END_fb8abf664186616849f74ef8bccb8865 -->
<!-- START_f521d9b27f52ddaf7b824da0fe75b1bc -->
## Receive SMS
Store a newly created user resource in storage.
> Example request:
```bash
curl -X POST "http://localhost/rucodia/api/v1/sms" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/sms",
"method": "POST",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
### HTTP Request
`POST api/v1/sms`
<!-- END_f521d9b27f52ddaf7b824da0fe75b1bc -->
<!-- START_c0d5f2593ca9c245cece59e3c4d2b239 -->
## Show balances of a specific product that each user holds
The balances only show the users that the logged in user can buy from.
Specific product balance details for each user.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/products/{product}/users" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/products/{product}/users",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Too Many Attempts.",
"exception": "Illuminate\\Http\\Exceptions\\ThrottleRequestsException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 122,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Middleware\\ThrottleRequests.php",
"line": 52,
"function": "buildException",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 661,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 636,
"function": "runRouteWithinStack",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "runRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/products/{product}/users`
`HEAD api/v1/products/{product}/users`
<!-- END_c0d5f2593ca9c245cece59e3c4d2b239 -->
<!-- START_a528b97fb431de1e035d8245ee44521b -->
## Get SMS from a user
Respond to a user with relevant SMS content.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/receive&sender={sender}&message={message}" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/receive&sender={sender}&message={message}",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\RouteCollection.php",
"line": 179,
"trace": [
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 613,
"function": "match",
"class": "Illuminate\\Routing\\RouteCollection",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 602,
"function": "findRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
"line": 591,
"function": "dispatchToRoute",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 176,
"function": "dispatch",
"class": "Illuminate\\Routing\\Router",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 30,
"function": "Illuminate\\Foundation\\Http\\{closure}",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\fideloper\\proxy\\src\\TrustProxies.php",
"line": 57,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Fideloper\\Proxy\\TrustProxies",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest.php",
"line": 31,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize.php",
"line": 27,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode.php",
"line": 51,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 151,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Pipeline.php",
"line": 53,
"function": "Illuminate\\Pipeline\\{closure}",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Pipeline\\Pipeline.php",
"line": 104,
"function": "Illuminate\\Routing\\{closure}",
"class": "Illuminate\\Routing\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 151,
"function": "then",
"class": "Illuminate\\Pipeline\\Pipeline",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php",
"line": 116,
"function": "sendRequestThroughRouter",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 116,
"function": "handle",
"class": "Illuminate\\Foundation\\Http\\Kernel",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\AbstractGenerator.php",
"line": 98,
"function": "callRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Generators\\LaravelGenerator.php",
"line": 58,
"function": "getRouteResponse",
"class": "Mpociot\\ApiDoc\\Generators\\AbstractGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 261,
"function": "processRoute",
"class": "Mpociot\\ApiDoc\\Generators\\LaravelGenerator",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\mpociot\\laravel-apidoc-generator\\src\\Mpociot\\ApiDoc\\Commands\\GenerateDocumentation.php",
"line": 83,
"function": "processLaravelRoutes",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"function": "handle",
"class": "Mpociot\\ApiDoc\\Commands\\GenerateDocumentation",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 29,
"function": "call_user_func_array"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 87,
"function": "Illuminate\\Container\\{closure}",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\BoundMethod.php",
"line": 31,
"function": "callBoundMethod",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php",
"line": 564,
"function": "call",
"class": "Illuminate\\Container\\BoundMethod",
"type": "::"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 183,
"function": "call",
"class": "Illuminate\\Container\\Container",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Command\\Command.php",
"line": 251,
"function": "execute",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Command.php",
"line": 170,
"function": "run",
"class": "Symfony\\Component\\Console\\Command\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 865,
"function": "run",
"class": "Illuminate\\Console\\Command",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 241,
"function": "doRunCommand",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\symfony\\console\\Application.php",
"line": 143,
"function": "doRun",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Console\\Application.php",
"line": 89,
"function": "run",
"class": "Symfony\\Component\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php",
"line": 122,
"function": "run",
"class": "Illuminate\\Console\\Application",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\rucodia\\artisan",
"line": 37,
"function": "handle",
"class": "Illuminate\\Foundation\\Console\\Kernel",
"type": "->"
}
]
}
```
### HTTP Request
`GET api/v1/receive&sender={sender}&message={message}`
`HEAD api/v1/receive&sender={sender}&message={message}`
<!-- END_a528b97fb431de1e035d8245ee44521b -->
<!-- START_af71f3ac56b72b8bff80f06a0accec74 -->
## Show API Documentation page application dashboard.
> Example request:
```bash
curl -X GET "http://localhost/rucodia/api/v1/docs" \
-H "Accept: application/json"
```
```javascript
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/rucodia/api/v1/docs",
"method": "GET",
"headers": {
"accept": "application/json"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
```
> Example response:
```json
{
"message": "Unauthenticated."
}
```
### HTTP Request
`GET api/v1/docs`
`HEAD api/v1/docs`
<!-- END_af71f3ac56b72b8bff80f06a0accec74 -->
<file_sep>/app/Subcategory.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subcategory extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'uuid',
'name',
'description',
];
/**
* Get the products for specific subcategory.
*/
public function products()
{
return $this
->belongsToMany('App\Product')
->withTimestamps()
->withPivot('uuid');
}
public function categories()
{
return $this
->belongsToMany('App\Category')
->withTimestamps()
->withPivot('uuid');
}
/*
* Get the user that owns this category
*/
public function user()
{
return $this
->belongsTo('App\User', 'id', 'created_by');
}
}
<file_sep>/app/Region.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Region extends Model
{
/**
* Fields that can be mass assignable
*
* @return mixed
*/
protected $fillable = [
'uuid', 'name', 'deleted_by',
];
/**
* Get the districts for the region.
*/
public function districts()
{
return $this->hasMany('App\District');
}
/**
* Get all of the wards for the region.
*/
public function wards()
{
return $this->hasManyThrough('App\Ward', 'App\District');
}
}
<file_sep>/public/sql/user_ward.sql
INSERT INTO user_ward (uuid, user_id, ward_id, created_at) VALUES(UUID(), 1, 299, NOW());
-- INSERT INTO user_ward (uuid, user_id, ward_id, created_at) VALUES(UUID(), 2, 262, NOW());
-- INSERT INTO user_ward (uuid, user_id, ward_id, created_at) VALUES(UUID(), 3, 207, NOW());
-- INSERT INTO user_ward (uuid, user_id, ward_id, created_at) VALUES(UUID(), 4, 253, NOW());
-- INSERT INTO user_ward (uuid, user_id, ward_id, created_at) VALUES(UUID(), 5, 257, NOW());
-- INSERT INTO user_ward (uuid, user_id, ward_id, created_at) VALUES(UUID(), 6, 257, NOW());<file_sep>/database/factories/LocationFactory.php
<?php
use Faker\Generator as Faker;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(App\Location::class, function (Faker $faker) {
static $user;
return [
'uuid' => $faker->uuid,
'name' => $faker->streetName,
'latitude' => $faker->latitude($min = -5, $max = -1),
'longitude' => $faker->longitude($min = -27, $max = 31),
'created_by' => $user ?: $user = 1,
'created_at' => $faker->dateTimeBetween($startDate = '-6 months', $endDate = 'now', $timezone = date_default_timezone_get()),
];
});<file_sep>/app/Balance.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Balance extends Model
{
/**
* Fields that can be mass assignable
*
* @return mixed
*/
protected $fillable = [
'uuid', 'count', 'user_id', 'product_id', 'buying_price', 'selling_price',
];
}
<file_sep>/app/Http/Controllers/api/ProductController.php
<?php
namespace App\Http\Controllers\api;
use App\Product;
use App\Subcategory;
use App\Unit;
use Illuminate\Http\Request;
use App\Http\Resources\Product as ProductResource;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;
class ProductController extends Controller
{
/**
* List Products
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the Products in a collection
ProductResource::WithoutWrapping();
return ProductResource::collection(Product::with('units')->with('subcategories')->get());
}
/**
* Add Product
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Get all the details for Product creation
$subcategory = Subcategory::where('id', $request['subcategory_id'])->first();
$unit = Unit::where('id', $request['unit_id'])->first();
$product = new Product;
$product->uuid = (string) Str::uuid();
$product->name = $request['name'];
$product->price = $request['price'];
$product->description = $request['description'];
$product->created_by = Config::get('apiuser');
$product->save();
$product->subcategories()->attach($subcategory->id, array('subcategory_id' => $subcategory->id, 'product_id' => $product->id, 'uuid' => (string) Str::uuid()));
$product->units()->attach($unit->id, array('unit_id' => $unit->id, 'product_id' => $product->id, 'uuid' => (string) Str::uuid()));
return response()->json([
'action' => 'create',
'status' => 'OK',
'entity' => $product->uuid,
'id' => $product->id,
'type' => 'product',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Product
*
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$product = Product::find($id);
// Check if product is not in the DB
if ($product === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'product',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific product
ProductResource::WithoutWrapping();
return new ProductResource(Product::with('units')->with('subcategories')->find($id));
}
}
/**
* Update Product
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed ID
$subcategory = Subcategory::where('id', $request['subcategory_id'])->first();
$subcategory_uuid = DB::table('product_subcategory')->where('product_id', $id)->value('uuid');
$subcategory_id = DB::table('product_subcategory')->where('product_id', $id)->value('id');
$unit = Unit::where('id', $request['unit_id'])->first();
$unit_uuid = DB::table('product_unit')->where('product_id', $id)->value('uuid');
$unit_id = DB::table('product_unit')->where('product_id', $id)->value('id');
$product = Product::find($id);
$product->name = $request['name'];
$product->price = $request['price'];
$product->description = $request['description'];
$product->updated_by = Config::get('apiuser');
$product->subcategories()->sync($subcategory->id);
$product->subcategories()->updateExistingPivot($subcategory->id, array('uuid' => $subcategory_uuid, 'id' => $subcategory_id));
$product->units()->sync($unit->id);
$product->units()->updateExistingPivot($unit->id, array('uuid' => $unit_uuid, 'id' => $unit_id));
$product->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $product->uuid,
'type' => 'product',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Product
*
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
// Delete a specific Product by ID (Soft-Deletes)
$product = Product::find($product);
$product->update(['deleted_by' => Config::get('apiuser')]);
$product->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $product->uuid,
'type' => 'product',
'user' => Config::get('apiuser')
], 200);
}
}
<file_sep>/app/User_Ward.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User_Ward extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user_ward';
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('/logout', function () {
return Auth::logout();
// return 'success';
});
Route::group(
array(
'namespace' => 'api',
'prefix' => 'v1',
'middleware' => ['auth.basic.once']),
function () {
Route::apiResource('users', 'UserController');
Route::apiResource('levels', 'LevelController');
Route::apiResource('locations', 'LocationController');
Route::apiResource('units', 'UnitController');
Route::apiResource('categories', 'CategoryController');
Route::apiResource('subcategories', 'SubcategoryController');
Route::apiResource('products', 'ProductController');
Route::apiResource('orders', 'OrderController');
Route::apiResource('regions', 'RegionController');
Route::apiResource('districts', 'DistrictController');
Route::apiResource('wards', 'WardController');
Route::apiResource('transactions', 'TransactionController');
Route::apiResource('transactiontypes', 'TransactiontypeController');
Route::get('auth', 'UserController@auth');
// Geographical divisions
Route::get('regions/{region}/districts', 'RegionController@regionDistricts');
Route::get('regions/{region}/districts/wards', 'RegionController@regionDistrictsWards');
Route::get('districts/{district}/wards', 'DistrictController@districtWards');
Route::get('user/{user_id}/product/{product_id}/balance', 'UserController@userBalance');
Route::get('users/{user}/products', 'UserController@userBalances');
Route::get('users/{user}/transactions', 'TransactionController@userTransactions');
Route::get('products/{product}/users', 'UserController@productUsers')->name('product.users');
// Sms receiving from SMSsync and Transmission via RapidPro
Route::post('sms', 'UserController@sms')->name('sms.store');
Route::get('receive&sender={sender}&message={message}', 'UserController@receive');
// Orders and their control
Route::get('ordersreceived', 'OrderController@receivedOrders');
Route::get('ordersplaced', 'OrderController@placedOrders');
});
Route::group(
array(
'namespace' => 'api',
'prefix' => 'v2'),
function () {
Route::post('sms', 'UserController@sms')->name('sms.store');
Route::post('receive', 'UserController@receive')->name('sms.receive');
});<file_sep>/app/Http/Controllers/api/LocationController.php
<?php
namespace App\Http\Controllers\api;
use App\Location;
use App\User;
use Illuminate\Http\Request;
use App\Http\Resources\Location as LocationResource;
use Illuminate\Support\Str;
use Response;
use Illuminate\Support\Facades\Config;
class LocationController extends Controller
{
/**
* List Locations
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//List locations
LocationResource::WithoutWrapping();
return LocationResource::collection(Location::all());
}
/**
* Add Location
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new location from the payload
$location = new Location;
$location->uuid = (string) Str::uuid();
$location->latitude = $request['latitude'];
$location->longitude = $request['longitude'];
$location->name = $request['name'];
$location->created_by = Config::get('apiuser')->id();
$location->save();
return response()->json([
'acton' => 'create',
'status' => 'OK',
'entity' => $location->uuid,
'type' => 'location',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Location
* Display the specified resource.
*
* @param \App\Location $location
* @return \Illuminate\Http\Response
*/
public function show(Location $id)
{
// Individual location details
$location = Location::find($id);
// Check if location is not in the DB
if ($location === NULL) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'location',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific location
LocationResource::WithoutWrapping();
return new LocationResource(Location::find($id));
}
}
/**
* Update Location
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Location $location
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $location)
{
// Update the resource with the addressed location
$location = Location::find($location);
$location->latitude = $request['latitude'];
$location->longitude = $request['longitude'];
$location->name = $request['name'];
$location->update(['updated_by' => Config::get('apiuser')]);
$location->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $location->uuid,
'type' => 'location',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Location
*
* Remove the specified resource from storage.
*
* @param \App\Location $location
* @return \Illuminate\Http\Response
*/
public function destroy(Location $d)
{
// Delete a specific location by locationID (Soft-Deletes)
$location = Location::findOrFail($d);
$location->update(['deleted_by' => Config::get('apiuser')]);
$location->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $location->uuid,
'type' => 'location',
'user' => Config::get('apiuser')
], 200);
// return $location;
}
}
<file_sep>/app/Http/Controllers/api/OrderController.php
<?php
namespace App\Http\Controllers\api;
use App\Order;
use App\Subcategory;
use App\Unit;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;
use App\Http\Resources\Order as OrderResource;
class OrderController extends Controller
{
/**
* List Orders
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the Orders in a collection
OrderResource::WithoutWrapping();
return OrderResource::collection(Order::with('dealer')->with('supplier')->with('product')->get());
}
/**
* Add Order
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Get all the details for Order creation
$order = new Order;
$order->uuid = (string) Str::uuid();
$order->ordered = $request['ordered'];
$order->batch = $request['batch'];
$order->status_id = 1;
$order->product_id = $request['product_id'];
$order->dealer_id = $request['dealer_id'];
$order->supplier_id = $request['supplier_id'];
$order->created_by = Config::get('apiuser');
$order->save();
return response()->json([
'action' => 'create',
'status' => 'OK',
'entity' => $order->uuid,
'type' => 'order',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Order
*
* Display the specified resource.
*
* @param \App\Order $order
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$order = Order::find($id);
// Check if order is not in the DB
if ($order === NULL) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'order',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific order
OrderResource::WithoutWrapping();
return new OrderResource(Order::with('dealer')->with('supplier')->with('product')->find($id));
}
}
/**
* Update Order
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Order $order
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed ID
$order = Order::find($id);
$order->ordered = $request['ordered'];
$order->delivered = $request['delivered'];
$order->status = $request['status'];
$order->updated_by = Config::get('apiuser');
$order->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $order->uuid,
'type' => 'order',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Order
*
* Remove the specified resource from storage.
*
* @param \App\Order $order
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific Order by ID (Soft-Deletes)
$order = Order::find($id);
$order->update(['deleted_by' => Config::get('apiuser')]);
$order->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $order->uuid,
'type' => 'order',
'user' => Config::get('apiuser')
], 200);
}
/**
* List Single User's Received Orders
*
* Display a listing of received resource for a secific user.
*
* @return \Illuminate\Http\Response
*/
public function receivedOrders()
{
// List all the received Orders for a specific user
OrderResource::WithoutWrapping();
return OrderResource::collection(Order::where('supplier_id', Config::get('apiuser'))->where('status_id', 1)
->with('dealer.locations:locations.name')
->get(['id', 'uuid', 'ordered', 'delivered', 'batch', 'status_id', 'product_id', 'dealer_id', ]));
}
/**
* List Single User's placed Orders
*
* Display a listing of placed resource for a secific user.
*
* @return \Illuminate\Http\Response
*/
public function placedOrders()
{
// List all the placed Orders for a specific user
OrderResource::WithoutWrapping();
return OrderResource::collection(Order::where('dealer_id', Config::get('apiuser'))->where('status_id', 1)
->with('supplier.locations:locations.name')
->get(['id', 'uuid', 'ordered', 'delivered', 'batch', 'status_id', 'product_id', 'supplier_id']));
}
}<file_sep>/app/Http/Controllers/api/UserController.php
<?php
namespace App\Http\Controllers\api;
use Illuminate\Http\Request;
use App\User;
use App\Level;
use App\Location;
use App\Ward;
use App\Transaction;
use App\Sms;
use App\District;
use App\Product;
use App\Subcategory;
use App\Balance;
use App\Http\Resources\User as UserResource;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
class UserController extends Controller
{
// /**
// * A Construct setting up User and Response
// *
// * @return NULL
// */
public function __construct(Request $request, User $user) {
$this->request = $request;
$this->user = $user;
}
/**
* List Users
*
* JSON List of all users.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the users in a collection
UserResource::WithoutWrapping();
return UserResource::collection(User::with('levels')->with('locations')->with('wards')->get());
}
/**
* Add User
*
* Store a newly created user resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Get all the details for User creation
$level = Level::where('name', $request['level'])->first();
$location = Location::where('name', $request['location'])->first();
$location = Ward::where('name', $request['ward'])->first();
$user = new User;
$user->uuid = (string) Str::uuid();
$user->firstname = $request['firstname'];
$user->middlename = $request['middlename'];
$user->surname = $request['surname'];
$user->phone = $request['phone'];
$user->username = $request['username'];
$user->password = <PASSWORD>($request['password']);
$user->created_by = Config::get('apiuser');
$user->save();
$user->levels()
->attach($level->id, array(
'level_id' => $level->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid()
));
$user->locations()
->attach($location->id, array(
'location_id' => $location->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid()
));
$user->wards()
->attach($ward->id, array(
'ward_id' => $ward->id,
'user_id' => $user->id,
'uuid' => (string) Str::uuid()
));
return response()->json([
'action' => 'create',
'status' => 'OK',
'entity' => $user->uuid,
'type' => 'user',
'user' => Config::get('apiuser')
], 201);
}
/**
* Update User
*
* Edit an existing User details.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
// Check if user is not in the DB
if ($user === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'user',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific user
UserResource::WithoutWrapping();
return new UserResource(User::with('levels')->with('locations')->with('wards')->find($id));
}
}
/**
* Update User
*
* Update the specified user resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed ID
$level = Level::where('name', $request['level'])->first();
$level_uuid = DB::table('level_user')->where('user_id', $id)->value('uuid');
$level_id = DB::table('level_user')->where('user_id', $id)->value('id');
$location = Location::where('name', $request['location'])->first();
$location_uuid = DB::table('location_user')->where('user_id', $id)->value('uuid');
$location_id = DB::table('location_user')->where('user_id', $id)->value('id');
$ward = Ward::where('name', $request['ward'])->first();
$ward_uuid = DB::table('user_ward')->where('user_id', $id)->value('uuid');
$ward_id = DB::table('user_ward')->where('user_id', $id)->value('id');
$user = User::find($id);
$user->firstname = $request['firstname'];
$user->middlename = $request['middlename'];
$user->surname = $request['surname'];
$user->phone = $request['phone'];
$user->username = $request['username'];
$user->password = <PASSWORD>($request['<PASSWORD>']);
$user->updated_by = Config::get('apiuser');
$user->levels()->sync($level->id);
$user->levels()->updateExistingPivot($level->id, array('uuid' => $level_uuid, 'id' => $level_id));
$user->locations()->sync($location->id);
$user->locations()->updateExistingPivot($location->id, array('uuid' => $location_uuid, 'id' => $location_id));
$user->wards()->sync($ward->id);
$user->wards()->updateExistingPivot($ward->id, array('uuid' => $ward_uuid, 'id' => $ward_id));
$user->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $user->uuid,
'type' => 'user',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete User
*
* Remove the specified user resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific User by ID (Soft-Deletes)
$user = User::find($id);
$user->update(['deleted_by' => Config::get('apiuser')]);
$user->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $user->uuid,
'type' => 'user',
'user' => Config::get('apiuser')
], 200);
}
/**Show Auth Details
*
* Get the auth page then send back user details
*
* @return \Ilumminate\Http\Response
*/
public function auth()
{
$user = User::where('id', Config::get('apiuser'))->with('levels')->with('locations')->with('wards')->get();
return response()->json($user);
}
/**
* Show Product Balances
*
* Specific user product details such as Totals, Cash, Balances and Profit.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function userBalance($user_id, $product_id)
{
$user = User::find($user_id);
$totalBought = Transaction::where('user_id', $user_id)
->where('product_id', $product_id)
->where('transactiontype_id', 1)
->sum('amount');
$totalSold = Transaction::where('user_id', $user_id)
->where('product_id', $product_id)
->where('transactiontype_id', 2)
->sum('amount');
$expenditure = DB::table('transactions')
->selectRaw('SUM(price * amount) AS price')
->where('user_id', $user_id)
->where('product_id', $product_id)
->where('transactiontype_id', 1)
->value('price');
$revenues = DB::table('transactions')
->selectRaw('SUM(price * amount) AS price')
->where('user_id', $user_id)
->where('product_id', $product_id)
->where('transactiontype_id', 2)
->value('price');
$profit = $revenues - $expenditure;
$balance = $totalBought - $totalSold;
return response()->json([
'action' => 'balance',
'status' => 'OK',
'entity' => $user->uuid,
'type' => 'user',
'product' => (int)$product_id,
'bought' => (int)$totalBought,
'sold' => (int)$totalSold,
'balance' => $balance,
'expenditure' => (int)$expenditure,
'revenues' => (int)$revenues,
'profit' => $profit,
'user' => Config::get('apiuser')
], 200);
}
/**
* Show Product Balances
*
* Specific user product details such as Totals, Cash, Balances and Profit.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function userBalances($user)
{
$user = User::find($user);
$products = Transaction::where('user_id', $user->id)
->addSelect(
DB::raw('
product_id,
CAST(SUM(CASE transactiontype_id WHEN 1 THEN amount ELSE 0 END) as signed) AS product_bought,
CAST(SUM(CASE transactiontype_id WHEN 2 THEN amount ELSE 0 END) as signed) AS product_sold,
CAST(SUM(CASE transactiontype_id WHEN 1 THEN amount WHEN 2 THEN -amount ELSE 0 END) AS SIGNED) AS product_balance,
COUNT(CASE transactiontype_id WHEN 1 THEN id END) AS product_purchases,
COUNT(CASE transactiontype_id WHEN 2 THEN id END) AS product_sales,
CAST(SUM(CASE transactiontype_id WHEN 1 THEN amount * price ELSE 0 END) as signed) AS product_expenditure,
CAST(SUM(CASE transactiontype_id WHEN 2 THEN amount * price ELSE 0 END) as signed) AS product_revenue,
CAST(SUM(CASE transactiontype_id WHEN 1 THEN amount * -price WHEN 2 THEN amount * price ELSE 0 END) as signed) AS product_profit
'))
->orderBy('created_at', 'DESC')
->groupBy('product_id')
->get();
$prices = Transaction::where('user_id', $user->id)
->addSelect(DB::raw('
product_id, MAX(id) AS id,
CASE transactiontype_id WHEN 1 THEN price ELSE 0 END AS buying_price,
CASE transactiontype_id WHEN 2 THEN price ELSE 0 END AS selling_price
'))
->orderBy('id', 'DESC')
->groupBy('transactiontype_id', 'product_id')
->get();
return response()->json([
'action' => 'user_products',
'status' => 'OK',
'entity' => $user->uuid,
'type' => 'user',
'products' => $products,
'prices' => $prices,
'user' => Config::get('apiuser')
], 200);
}
/**
* Receive SMS
*
* Store a newly created user resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function sms(Request $request)
{
$data = $request->input('input.urn');
$sms = new Sms;
$sms->uuid = (string) Str::uuid();
$sms->urn = $request->input('input.urn');
$sms->text = strtolower($request->input('input.text'));
$sms->save();
$text_array = explode(' ', $sms->text);
if (str_word_count($sms->text) == 3) {
$district = $text_array[2];
$district = District::where('name', $district)->first();
$product = $text_array[1];
$product = Subcategory::where('name', $product)->first();
$agrodealers = DB::select(DB::raw ("
select distinct users.firstname as name, MAX(transactions.price) as price from transactions
inner join users on users.id = transactions.user_id
inner join products on products.id = transactions.product_id
inner join transactiontypes on transactiontypes.id = 1
inner join product_subcategory on product_subcategory.product_id = products.id
inner join subcategories on product_subcategory.subcategory_id = subcategories.id
inner join user_ward on user_ward.user_id = users.id
inner join wards on wards.id = user_ward.ward_id
inner join districts on wards.district_id = districts.id
where districts.id = ".$district->id."
AND subcategories.id = ".$product->id."
group by users.firstname;
"));
$agrodealers = json_decode(json_encode($agrodealers), true);
$result = array();
foreach($agrodealers as $key=> $val)
{
$result[] = $val['name'].':'.$val['price'];
}
$uri = "https://api.textit.in/api/v2/broadcasts.json";
$urn = $sms->urn;
$text = $product->name." > ". implode(', ', $result);
$client = new Client();
$response = $client->request(
'POST',
'https://api.textit.in/api/v2/broadcasts.json',
[
'headers' => [
'Authorization' => 'Token '.env("TEXTIN_TOKEN"),
'Accept' => 'application/json',
],
'json' => [
'urns' => [$urn],
'text' => $text
]
]);
return response()->json([
'agrodealers' => $agrodealers,
'district' => $district,
'product' => $product,
'sender' => $urn,
'text' => $text,
'user' => Config::get('apiuser')
], 200);
}
else {
return response()->json([
'error' => 'kuna error mahali'
], 500);
}
}
/**
* Show balances of a specific product that each user holds
* The balances only show the users that the logged in user can buy from.
*
* Specific product balance details for each user.
*
* @param int $product
* @return \Illuminate\Http\Response
*/
public function productUsers($product)
{
$product = Product::find($product);
$user = User::where('id', Config::get('apiuser'))->first();
$buys_from = $user->levels[0]->buys_from;
if (empty(!$product)) {
$balances = DB::select(DB::raw("
SELECT locations.name, balances.user_id, balances.count, balances.buying_price, balances.selling_price
FROM balances
INNER JOIN level_user ON balances.user_id = level_user.user_id
INNER JOIN levels ON level_user.level_id = levels.id
INNER JOIN products ON balances.product_id = products.id
INNER JOIN location_user ON balances.user_id = location_user.user_id
INNER JOIN locations ON location_user.location_id = locations.id
WHERE products.id = $product->id
AND levels.id IN ($buys_from)
"));
return response()->json([
'action' => 'product_users',
'status' => 'OK',
'entity' => $product->uuid,
'type' => 'product',
'balances' => $balances,
'user' => Config::get('apiuser')
], 200);
}
else {
return response()->json([
'action' => 'product_users',
'status' => 'EMPTY',
'entity' => $product,
'type' => 'product',
'error' => 'The product is has not been bought by anyone yet!',
'user' => Config::get('apiuser')
], 500);
}
}
/**
* Get SMS from a user
*
* Respond to a user with relevant SMS content.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function receive(Request $request)
{
$from = $request->from;
$message = str_replace('+', ' ', $request->message);
$secret = $request->secret;
if ($secret == '<KEY>') {
if (empty(!$from)) {
if(empty(!$message)){
$sms = new Sms;
$sms->uuid = (string) Str::uuid();
$sms->urn = $from;
$sms->text = strtolower($message);
$sms->save();
Storage::append('sms.txt', date('Y-m-d H:i:s').' From: '.$from.' '.'Message: '.str_replace('+', ' ', $message));
$text_array = explode(' ', $sms->text);
if (str_word_count($sms->text) == 2) {
$ward = $text_array[1];
$ward = Ward::where('name', $ward)->first();
$subcategory = $text_array[0];
$subcategory = Subcategory::where('name', $subcategory)->first();
}
else {
return response()->json([
'error' => 'Meseji ina makosa, meseji inatakiwa kuwa na maneno mawili tu, BIDHAA na KATA. Kwa mfano: <NAME>'
], 500);
}
$sellers = DB::select(DB::raw("
SELECT
users.id AS User,
locations.name AS Location,
wards.name AS Ward,
products.name AS Product,
balances.selling_price AS Selling_price,
users.phone AS Phone
FROM balances
INNER JOIN location_user ON balances.user_id=location_user.user_id
INNER JOIN locations ON location_user.location_id=locations.id
INNER JOIN products ON balances.product_id=products.id
INNER JOIN product_subcategory ON products.id=product_subcategory.product_id
INNER JOIN subcategories ON product_subcategory.subcategory_id=subcategories.id
INNER JOIN user_ward ON user_ward.user_id=balances.user_id
INNER JOIN wards ON user_ward.ward_id=wards.id
INNER JOIN districts on wards.district_id=districts.id
INNER JOIN users ON balances.user_id = users.id
WHERE districts.id=".$ward->district['id']."
-- WHERE wards.id=".$ward->id."
AND subcategories.id=". $subcategory->id
));
$sellers = json_decode(json_encode($sellers), true);
$result = array();
foreach($sellers as $key=> $val)
{
$result[] = $val['Location'].'('.$val['Ward'].'): '.$val['Selling_price'];
}
$client = new Client(); //GuzzleHttp\Client
$user = env("SMS_USER");
$key = env("SMS_KEY");
$message = $subcategory->name."- ". implode(', ', $result);
$response = $client->request(
'GET', 'https://api.africastalking.com/restless/send?username='.$user.'&Apikey='.$key.'&to='.$from.'&message='.$message
);
return response()->json([
'from' => $from,
'entity' => 'SMS',
'message' => $message,
'ward' => $ward->id,
'district' => $ward->district['name'],
'subcategory' => $subcategory->name,
'sellers' => $sellers,
'saved' => TRUE
], 200);
}
else {
return response()->json([
'error' => 'EMPTY sms received',
'entity' => 'SMS',
'saved' => FALSE
], 500);
}
}
else {
return response()->json([
'error' => 'EMPTY from field',
'entity' => 'SMS',
'saved' => FALSE
], 500);
}
}
else {
return response()->json([
'error' => 'You are not authorized from sending messages to this server',
'entity' => 'SMS',
'saved' => FALSE
], 500);
}
}
}
<file_sep>/app/Level.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\User;
class Level extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'uuid', 'name', 'description',
];
/**
* Get the users for the level.
*/
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps()->withPivot('uuid');
}
}
<file_sep>/app/Transaction.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Transaction extends Model
{
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'uuid', 'price', 'amount', 'user_id', 'transactiontype_id', 'product_id', 'status_id',
];
/**
* The storage format of the model's date columns.
*
* @var string
*/
// protected $dateFormat = 'U';
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'created_at' => ('timestamp'),
'updated_at' => ('timestamp'),
];
/**
* Get the type to which the transaction belongs.
*
* @return \Illuminate\Http\Response
*/
public function transactiontype()
{
return $this
->belongsTo('App\Transactiontype');
}
/**
* Get the user where the transaction belongs.
*
* @return \Illuminate\Http\Response
*/
public function user()
{
return $this
->belongsTo('App\User');
}
/**
* Get the product where the transaction belongs.
*
* @return \Illuminate\Http\Response
*/
public function product()
{
return $this
->belongsTo('App\Product');
}
/**
* Get the status where the transaction belongs.
*
* @return \Illuminate\Http\Response
*/
public function status()
{
return $this
->belongsTo('App\Status');
}
}
<file_sep>/app/Transactiontype.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Transactiontype extends Model
{
/**
* Get the type to which the transaction belongs.
*
* @return \Illuminate\Http\Response
*/
public function transactions()
{
return $this
->hasMany('App\Transactions');
}
}
<file_sep>/app/Http/Controllers/api/CategoryController.php
<?php
namespace App\Http\Controllers\api;
use App\Category;
use Illuminate\Http\Request;
use App\Http\Resources\Category as CategoryResource;
use Illuminate\Support\Str;
use Response;
use Illuminate\Support\Facades\Config;
class CategoryController extends Controller
{
/**
* List Categories
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the Categorys in a collection
CategoryResource::WithoutWrapping();
return CategoryResource::collection(Category::with('subcategories')->get());
}
/**
* Add Category
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new category from the payload
$category = new Category;
$category->uuid = (string) Str::uuid();
$category->name = $request['name'];
$category->description = $request['description'];
$category->created_by = Config::get('apiuser');
$category->save();
return response()->json([
'acton' => 'create',
'status' => 'OK',
'entity' => $category->uuid,
'type' => 'category',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Category
*
* Display the specified resource.
*
* @param \App\Category $category
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$category = Category::find($id);
// Check if category is not in the DB
if ($category === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'category',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific category
CategoryResource::WithoutWrapping();
return new CategoryResource(Category::with('subcategories')->find($id));
}
}
/**
* Update Category
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Category $category
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed category
$category = Category::find($id)->first();
$category->name = $request['name'];
$category->description = $request['description'];
$category->updated_by = Config::get('apiuser');
$category->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $category->uuid,
'type' => 'category',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Category
*
* Remove the specified resource from storage.
*
* @param \App\Category $category
* @return \Illuminate\Http\Response
*/
public function destroy(Category $category)
{
// Delete a specific category by categoryID (Soft-Deletes)
$category = Category::find($category)->first();
$category->update(['deleted_by' => Config::get('apiuser')]);
$category->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $category->uuid,
'type' => 'category',
'user' => Config::get('apiuser')
], 200);
}
}
<file_sep>/app/Http/Controllers/api/WardController.php
<?php
namespace App\Http\Controllers\api;
use App\Ward;
use Illuminate\Http\Request;
use Response;
use App\Http\Resources\Ward as WardResource;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;
class WardController extends Controller
{
/**
* List Wards
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the Wards in a collection
WardResource::WithoutWrapping();
return WardResource::collection(Ward::get());
}
/**
* Add Ward
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new ward from the payload
$ward = new Ward;
$ward->uuid = (string) Str::uuid();
$ward->name = $request['name'];
$ward->district_id = $request['district_id'];
$ward->created_by = Config::get('apiuser');
$ward->save();
return response()->json([
'acton' => 'create',
'status' => 'OK',
'entity' => $ward->uuid,
'type' => 'ward',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Ward
*
* Display the specified resource.
*
* @param \App\Ward $ward
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$ward = Ward::find($id);
// Check if ward is not in the DB
if ($ward === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'ward',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific ward
WardResource::WithoutWrapping();
return new WardResource(Ward::find($id));
}
}
/**
* Update Ward
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Ward $ward
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed ward
$ward = Ward::find($id)->first();
$ward->name = $request['name'];
$ward->district_id = $request['district_id'];
$ward->updated_by = Config::get('apiuser');
$ward->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $ward->uuid,
'type' => 'ward',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Ward
*
* Remove the specified resource from storage.
*
* @param \App\Ward $ward
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific ward by wardID (Soft-Deletes)
$ward = Ward::find($id)->first();
$ward->update(['deleted_by' => Config::get('apiuser')]);
$ward->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $ward->uuid,
'type' => 'ward',
'user' => Config::get('apiuser')
], 200);
}
}<file_sep>/app/Http/Controllers/api/RegionController.php
<?php
namespace App\Http\Controllers\api;
use App\Region;
use Illuminate\Http\Request;
use Response;
use App\Http\Resources\Region as RegionResource;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;
class RegionController extends Controller
{
/**
* List Regions
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the Regions in a collection
RegionResource::WithoutWrapping();
return RegionResource::collection(Region::get());
}
/**
* Add Region
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Insert a new region from the payload
$region = new Region;
$region->uuid = (string) Str::uuid();
$region->name = $request['name'];
$region->created_by = Config::get('apiuser');
$region->save();
return response()->json([
'acton' => 'create',
'status' => 'OK',
'entity' => $region->uuid,
'type' => 'region',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Region
*
* Display the specified resource.
*
* @param \App\Region $region
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$region = Region::find($id);
// Check if region is not in the DB
if ($region === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'region',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific region
RegionResource::WithoutWrapping();
return new RegionResource(Region::find($id));
}
}
/**
* Update Region
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Region $region
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed region
$region = Region::find($id)->first();
$region->name = $request['name'];
$region->updated_by = Config::get('apiuser');
$region->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $region->uuid,
'type' => 'region',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Region
*
* Remove the specified resource from storage.
*
* @param \App\Region $region
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific region by regionID (Soft-Deletes)
$region = Region::find($id)->first();
$region->update(['deleted_by' => Config::get('apiuser')]);
$region->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $region->uuid,
'type' => 'region',
'user' => Config::get('apiuser')
], 200);
}
/**
* Show Region Districts
*
* Display the districts of the region.
*
* @return \Illuminate\Http\Response
*/
public function regionDistricts($id)
{
$region = Region::find($id);
// Check if region is not in the DB
if ($region === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'region',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific region
RegionResource::WithoutWrapping();
return new RegionResource(Region::with('districts')->find($id));
}
}
/**
* Show Region Wards
* Display wards of a region listed by districts.
*
* @return \Illuminate\Http\Response
*/
public function regionDistrictsWards($id)
{
$region = Region::find($id);
// Check if region is not in the DB
if ($region === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'region',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific region
RegionResource::WithoutWrapping();
return new RegionResource(Region::with('districts.wards')->find($id));
}
}
}
<file_sep>/app/Http/Controllers/api/SubcategoryController.php
<?php
namespace App\Http\Controllers\api;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use App\Category;
use App\Subcategory;
use App\Http\Resources\Subcategory as SubcategoryResource;
class SubcategoryController extends Controller
{
/**
* List Subcategories
*
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// List all the subcategories in a collection
SubcategoryResource::WithoutWrapping();
return SubcategoryResource::collection(Subcategory::with('category')->get());
}
/**
* Add Subcategory
*
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Get all the details for Subcategory creation
$subcategory = new Subcategory;
$subcategory->uuid = (string) Str::uuid();
$subcategory->name = $request['name'];
$subcategory->description = $request['description'];
$subcategory->created_by = Config::get('apiuser');
$subcategory->save();
$subcategory->category()
->attach
($request['category_id'], array(
'category_id' => $request['category_id'],
'subcategory_id' => $subcategory->id,
'uuid' => (string) Str::uuid()
)
);
return response()->json([
'action' => 'create',
'status' => 'OK',
'entity' => $subcategory->uuid,
'type' => 'subcategory',
'user' => Config::get('apiuser')
], 201);
}
/**
* Show Subcategory
*
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$subcategory = Subcategory::find($id);
// Check if user is not in the DB
if ($subcategory === null) {
return response()->json([
'action' => 'show',
'status' => 'FAIL',
'entity' => NULL,
'type' => 'user',
'user' => Config::get('apiuser')
], 404);
}
else {
// List the details of a specific user
SubcategoryResource::WithoutWrapping();
return new SubcategoryResource(Subcategory::with('category')->find($id));
}
}
/**
* Update Subcategory
*
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Update the resource with the addressed ID
$category = Category::where('id', $request['category_id'])->first();
$category_uuid = DB::table('category_subcategory')->where('subcategory_id', $id)->value('uuid');
$category_id = DB::table('category_subcategory')->where('subcategory_id', $id)->value('id');
$subcategory = Subcategory::find($id);
$subcategory->name = $request['name'];
$subcategory->description = $request['description'];
$subcategory->updated_by = Config::get('apiuser');
$subcategory->category()->sync($category->id);
$subcategory->category()->updateExistingPivot($category->id, array('uuid' => $category_uuid, 'id' => $category_id));
$subcategory->save();
return response()->json([
'action' => 'update',
'status' => 'OK',
'entity' => $subcategory->uuid,
'type' => 'subcategory',
'user' => Config::get('apiuser')
], 200);
}
/**
* Delete Subcategory
*
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// Delete a specific Subcategory by ID (Soft-Deletes)
$subcategory = Subcategory::find($id);
$subcategory->update(['deleted_by' => Config::get('apiuser')]);
$subcategory->delete();
return response()->json([
'action' => 'delete',
'status' => 'OK',
'entity' => $subcategory->uuid,
'type' => 'subcategory',
'user' => Config::get('apiuser')
], 200);
}
}
<file_sep>/app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use App\User;
use Illuminate\Support\Facades\Config;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Modification for Mysql specified key is too long error
Schema::defaultStringLength(191);
if (isset($_SERVER['PHP_AUTH_USER'])) {
Config::set('apiuser', User::where('username', $_SERVER['PHP_AUTH_USER'])->first()->id);
}
$this->app->register(\Mpociot\ApiDoc\ApiDocGeneratorServiceProvider::class);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/dashboard', 'HomeController@dashboard')->name('dashboard');
Route::get('/api/v1/docs', 'HomeController@apidocs')->name('apidocs');
Route::group(
array(
'namespace' => 'web',
'middleware' => 'auth'),
function () {
Route::Resource('users', 'UserController');
Route::Resource('categories', 'CategoryController');
Route::Resource('subcategories', 'SubcategoryController');
Route::get('/users/districts/{id}', 'UserController@ajaxdistricts');
Route::get('/users/wards/{id}', 'UserController@ajaxwards');
Route::get('/excel/import/users', 'UserController@excelImportUsers')->name('excelImportUsers');
Route::post('excel/import/mass', 'UserController@massImportUsers')->name('massImportUsers');
});<file_sep>/public/sql/statuses.sql
INSERT INTO statuses (id, uuid, name, created_at) VALUES(1, UUID(), 'Ordered', NOW());
INSERT INTO statuses (id, uuid, name, created_at) VALUES(2, UUID(), 'Received', NOW());
INSERT INTO statuses (id, uuid, name, created_at) VALUES(3, UUID(), 'Sent', NOW());
INSERT INTO statuses (id, uuid, name, created_at) VALUES(4, UUID(), 'Delivered', NOW());
INSERT INTO statuses (id, uuid, name, created_at) VALUES(5, UUID(), 'Cancelled', NOW());<file_sep>/database/factories/LocationUserFactory.php
<?php
use Faker\Generator as Faker;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(App\Location_User::class, function (Faker $faker) {
static $user;
return [
'uuid' => $faker->uuid,
'location_id' => App\Location::all()->random()->id,
'user_id' => App\User::all()->unique()->random()->id,
'created_by' => $user ?: $user = 1,
'created_at' => $faker->dateTimeBetween($startDate = '-6 months', $endDate = 'now', $timezone = date_default_timezone_get()),
];
});<file_sep>/database/seeds/LocationUserTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class LocationUserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// Seed using model factories
// $users = factory(App\Location_User::class, 30)->create();
// $this->command->info('Location user table seeded!');
}
}
| 302b7571ca4d932a4beff11f25ecfa117dacc2d5 | [
"Markdown",
"SQL",
"PHP"
] | 51 | PHP | SoftmedTanzania/rucodia_backend | 011e9bb03e4f5cf5e091a240845d669c6ac5919d | 239bd2adc5ad949f252c920eee809aa785ee9c5c |
refs/heads/master | <repo_name>Milliss/algorithms<file_sep>/GAMEobject/starcount.cs
using UnityEngine;
using System.Collections;
public class RangeCount : MonoBehaviour {
private int startValue = 0;
private int endValue = 0;
private int nowValue = 0;
public RangeCount(){
}
public RangeCount(int startValue, int endValue){
SetRange (startValue, endValue);
}
public void SetRange (int startValue, int endValue) {
this.startValue = startValue;
this.endValue = endValue;
this.nowValue = startValue;
}
public void SetNowValue(int nowValue){
this.nowValue = nowValue;
}
public int GetNowValue(){
return nowValue;
}
public int GetNowShiftValue(int shiftValue){
int v = nowValue;
if (shiftValue < 0) {
while(shiftValue++ < 0){
if (v - 1 < startValue) {
v = endValue;
}else{
v--;
}
}
} else if (shiftValue > 0) {
while(shiftValue-- > 0){
if (v > endValue - 1) {
v = startValue;
}else{
v++;
}
}
}
return v;
}
public int Previous () {
if (--nowValue < startValue) {
nowValue = endValue;
}
return nowValue;
}
public int Next () {
if (++nowValue > endValue) {
nowValue = startValue;
}
return nowValue;
}
}<file_sep>/hw1_algorithm.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//步驟1:讀取整串
//步驟2:判斷->1.設max讀取當前最大情況 2.若相加<0,斷。
int main()
{
int input, input_num; //input1=有幾個
cin >> input;
while (input != EOF)//到讀完為止
{
vector<int>input_array;
while(input--)
{
cin >> input_num;
input_array.push_back(input_num);
}
int count = 0;
int start = 0;
int max = 0;
int sum = 0;
int end;
for(;;)
{
sum = sum + input_array[count];
count++;
if (sum > max)
{
max = sum;
end = count - 1;
}
else if (sum < 0)
{
sum = 0;
start = count;
}
if (count == input_array.size())
break;
}
cout << start << ' ' << end << ' ' << max << endl;
cin >> input;
}
return 0;
} <file_sep>/GAMEobject/character.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Char : MonoBehaviour {
// public score_test;
// Use this for initialization
public Text Text2;
public float score;
void Start () {
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "coin")
{
Destroy(collision.gameObject);
score += 100;
Text2.text = score.ToString();
}
if (collision.gameObject.name == "Portal1")
{
gameObject.transform.localPosition = new Vector3(498.7438F, 0.09998041F, 498.4573F); //起點
}
// Destroy(collision.gameObject);
}
// Update is called once per frame
void Update () {
}
}<file_sep>/hw1_algorithm_recur_new.cpp
#include <iostream> //
#include <string>
#include <vector>
using namespace std;
//步驟1:讀取整串
//步驟2:判斷->1.設max讀取當前最大情況 2.若相加<0,斷。
void recurr(vector<int>input_arr, int countt)
{
int count = 0;
int start = 0;
int max = 0;
int sum = 0;
int end;
if (countt == 0)
{
for (;;)
{
sum = sum + input_arr[count];
count++;
if (sum > max)
{
max = sum;
end = count - 1;
}
else if (sum < 0)
{
sum = 0;
start = count;
}
if (count == input_arr.size())
break;
}
cout << start << ' ' << end << ' ' << max << endl;
}
else
{
countt--;
recurr(input_arr, countt);
}
}
int main()
{
int input, input_num; //input1=有幾個
int counting = 87;
cin >> input;
while (input != EOF)//到讀完為止
{
vector<int>input_array;
while (input--)
{
cin >> input_num;
input_array.push_back(input_num);
}
recurr(input_array, counting);
cin >> input;
}
return 0;
}<file_sep>/GF_HW.c
#include "stdio.h"
void main()
{
int input,inputx,inputy,inputlist;//input為值 inputx,y為x,y軸
int arr[10][10];
int delinputx,delinputy;//刪除的那個點的x,y軸
printf("插入功能請按1,刪除功能請按2\n");
scanf("%d",&inputlist);
if(inputlist=='1')//插入功能
{
printf("請輸入三個數字...\n");
int count=0;//計數
for(int i=0;i<11;i++)//先把每個格子初始設成0~99
{
for(int j=0;j<11;j++)
{
arr[i][j]=count;
count++;
}
}
for(int i=0;i<11;i++)//把初始格子print出來 就是0~99
{
for(int j=0;j<11;j++)
{
printf("%d ",&arr);
}
printf("\n");
}
scanf("%d %d %d",&input,&inputx,&inputy);//讀取數字 依序是 數值,x軸,y軸
arr[inputx][inputy]=input;//把輸入的值丟去那個格子
for(int i=0;i<11;i++)//把全部print出來一次
{
for(int j=0;j<11;j++)
{
printf("%d ",&arr);
}
printf("\n");
}
}
if(inputlist=='2')//刪除功能
{
printf("請輸入二個數字...\n");
scanf("%d %d",&delinputx,&delinputy);//讀取要刪除的位置
arr[delinputx][delinputy]=0;//刪除位置變成0
for(int i=delinputx;i<11;i++)//把後面的全部往前移動一格
{
for(int j=delinputy;j<11;j++)
{
arr[delinputx][delinputy]=arr[delinputx+1][delinputy];
}
}
arr[10][10]=0;//最後一格設成0
for(int i=0;i<11;i++)//print出來
{
for(int j=0;j<11;j++)
{
printf("%d ",&arr);
}
printf("\n");
}
}
system"pause";//暫停動作
return 0;
}<file_sep>/GAMEobject/texture.cs
using UnityEngine;
using System.Collections;
public class Guitexturesize : MonoBehaviour {
public Vector2 oriScale = new Vector2(1440.0f, 900.0f);
void Start () {
GUITexture[] guis = FindObjectsOfType(typeof(GUITexture)) as GUITexture[];
Vector2 size = new Vector2();
size.x = Screen.width / oriScale.x;
size.y = Screen.height / oriScale.y;
foreach(GUITexture gui in guis)
{
gui.pixelInset = new Rect(gui.pixelInset.x * size.x, gui.pixelInset.y * size.y, gui.pixelInset.width * size.x, gui.pixelInset.height * size.y);
}
}
}
<file_sep>/hw1_algorithm_recur.cpp
#include<iostream>
#include<string>
#include<vector>
using namespace std;
/*16
-13 -3 -25 20 -3 -16 -23 18 20 -1 12 -5 -22 15 -4 7
8
1 2 3 4 5 6 7 -7
7 10 49↵
0 6 28↵*/
void find_max_subarray(vector<int>input_array,int x){
int head,tail,max_head,max_tail,sum,max;
if(x==0){
head = 0;
tail = 0;
sum= 0;
max_head = 0;
max_tail = 0;
max = 0;
for(;;){
sum+=input_array[tail++];
if(sum > max){
max = sum ;
max_tail = tail - 1;
max_head=head;
}else if(sum<0){
sum=0;
head = tail;
}
if( tail == input_array.size()){
break;
}
}
cout << max_head << ' ' << max_tail << ' ' << max << endl;
}else {
x--;
find_max_subarray(input_array,x);
}
}
int main(){
int input,input_number,x=100;
//int a[]={-13,-3,-25,20 ,-3,-16,-23,18,20,-1 ,12, -5, -22, 15, -4, 7};
cin >> input;
while(input != EOF){
vector<int>input_array;
while(input--){
cin >> input_number;
input_array.push_back(input_number);
}
//cout<< input_array.size();
//find_crossing_subarray(input_array,low,mid,high,max_left,max_right,sum);
//max_subarray(input_array,input_array.size());
find_max_subarray(input_array,x);
cin >> input;
}
return 0;
} | 8bfca68bb448315cb8540640371a63a92a71b6e6 | [
"C#",
"C",
"C++"
] | 7 | C# | Milliss/algorithms | 597f578f1178d44ed48ae6ea3e434dd58ce006b3 | c3fab57c572881cfef7b7299e9c7fe586f47fa7e |
refs/heads/main | <repo_name>Tlacaelel97/Diabetes_prediction<file_sep>/utils.py
import pandas as pd
import joblib
from sklearn.model_selection import train_test_split
class Utils:
def load_from_csv(self,path):
return pd.read_csv(path)
def load_from_mysql(self):
pass
def show_info(self,data):
print(data.head())
#number of rows and columns
print("="*70)
print("Number of rows and columns: ",data.shape)
#statistical measures
def stat_measures(self,data):
print("="*70)
print(data.describe())
#output values
def out_measures(self,data):
print("="*70)
print("Number of output values, where 0 = non-diabetic and 1 = diabetic")
print(data['Outcome'].value_counts())
print("="*70)
print(data.groupby('Outcome').mean())
def features_target(self,dataset,drop_cols, y):
X=dataset.drop(drop_cols, axis=1)
y = dataset[y]
return X,y
def features_extract(self,X,y):
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2, stratify=y, random_state=42)
print(X.shape, X_train.shape, X_test.shape)
return X_train, X_test, y_train, y_test
def model_export(self, clf):
joblib.dump(clf, './models/diabetes_model.plk')<file_sep>/main.py
from numpy.lib import npyio
from utils import Utils
from models import Models
import numpy as np
from sklearn.preprocessing import StandardScaler
if __name__ == "__main__":
utils = Utils()
models=Models()
#loading dataset
diabetes_ds = utils.load_from_csv('./in/diabetes.csv')
#Show data
utils.show_info(diabetes_ds)
#getting the statistical measures
utils.stat_measures(diabetes_ds)
#getting output measures
utils.out_measures(diabetes_ds)
#separating the data and labels
X,y = utils.features_target(diabetes_ds,['Outcome'],['Outcome'])
#DAta standarization--the range are diferent
scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)
print("="*70)
#features stract
X_train, X_test, y_train, y_test = utils.features_extract(X,y.values.ravel())
#training the suppoort vector machinme Classifier
models.model_training(X_train,y_train)
#Model ecaluation
#Accuracy score
#accuracy score on the trainin data
X_train_prediction = models.model_prediction(X_train)
training_data_accuracy = models.model_evaluation(X_train_prediction,y_train)
print('Accuracy score of the training data: ', training_data_accuracy)
#accuracy score on the test data
X_test_prediction = models.model_prediction(X_test)
test_data_accuracy = models.model_evaluation(X_test_prediction,y_test)
print('Accuracy score of the test data: ', test_data_accuracy)
#Making a predictive system
input_data = (0,137,40,35,168,43.1,2.288,33)
#changingn the input data to numpy array
input_data_as_numpy_array = np.asarray(input_data)
#reshape the array as we are predicting for one instance
input_data_reshaped= input_data_as_numpy_array.reshape(1,-1)
# standarize input data
std_data = scaler.transform(input_data_reshaped)
print(std_data)
prediction = models.model_prediction(std_data)
print(prediction)
if prediction[0] == 0:
print('The person is not diabetic')
else:
print('The person is diabetic')
<file_sep>/README.md
# Diabetes prediction
Model that helps to predict if a pacient has or not diabetes
The model use a dataset from pacients that includes Pregnancies, Glucose, Blood Pressure, Skin Thickness,
Insulin, BMI, Diabetes Pedigree Function, Age, Outcome, where Outcome represents if the pacient is diabetic (1)
or non-diabetic (0).
# Models
The [models.py](models.py) includes the following classes:
• [__init__](__init__) - Define the machine learning model.
• model_training - Train the model and export in a pickle archive
• model_prediction - prediction
• model_evaluation - Evaluate the accuracy of the model
# Utils
The [utils.py](utils.py) includes the following classes:
load_from_csv(self,path):
return pd.read_csv(path)
def load_from_mysql(self):
pass
def show_info(self,data):
print(data.head())
#number of rows and columns
print("="*70)
print("Number of rows and columns: ",data.shape)
#statistical measures
def stat_measures(self,data):
print("="*70)
print(data.describe())
#output values
def out_measures(self,data):
print("="*70)
print("Number of output values, where 0 = non-diabetic and 1 = diabetic")
print(data['Outcome'].value_counts())
print("="*70)
print(data.groupby('Outcome').mean())
def features_target(self,dataset,drop_cols, y):
X=dataset.drop(drop_cols, axis=1)
y = dataset[y]
return X,y
def features_extract(self,X,y):
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2, stratify=y, random_state=42)
print(X.shape, X_train.shape, X_test.shape)
return X_train, X_test, y_train, y_test
def model_export
run the [main.py](main.py) to train the model and test with one data
<file_sep>/models.py
import pandas as pd
import numpy as np
from sklearn import svm
from sklearn.ensemble import GradientBoostingRegressor
#from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
from utils import Utils
class Models:
def __init__(self):
self.classifier = svm.SVC(kernel='linear')
def model_training(self,X,y):
self.classifier.fit(X, y)
utils = Utils()
utils.model_export(self.classifier)
def model_prediction(self,X):
X_prediction = self.classifier.predict(X)
return X_prediction
def model_evaluation(self,prediction,y):
data_accuracy = accuracy_score(prediction,y)
print("="*70)
return data_accuracy | 266e3eaffe44a5722fe0f85c6e28a15f707627f2 | [
"Markdown",
"Python"
] | 4 | Python | Tlacaelel97/Diabetes_prediction | 7034b0e84264ee0a07ff66a1d45d74e1f21d5811 | 571d120b4ba1575689897617fe63f2b91cd5fadc |
refs/heads/master | <file_sep>(function(){
var app = angular.module('bookApp', ['firebase'])
}())<file_sep>(function(){
angular.module('bookApp')
.component('booksComponent', {
templateUrl: 'app/components/books.html',
controller: BooksController
})
function BooksController($firebaseArray) {
var bc = this;
var booksRefs = new Firebase('https://favs15.firebaseio.com/books')
bc.list = $firebaseArray(booksRefs)
bc.addBook = function (book) {
if(book.$id){
bc.list.$save(book)
}else{
bc.list.$add(book)
}
bc.newBook = null
}
bc.removeBook = function (book){
bc.list.$remove(book)
}
bc.editBook = function(book){
bc.newBook = book;
}
}
}()) | 42f4d9038f003cd3410fb7a39484bad1b951a55b | [
"JavaScript"
] | 2 | JavaScript | JECII/book-app | 4770143d4b8ba2a39c4e396588a1129fc360260d | 0d453d9a2e0c99f2aba6f462dfdf1b1fdbd4f8da |
refs/heads/master | <repo_name>k-chen8888/AstralProjector<file_sep>/Assets/Scripts/DeathPause.cs
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class DeathPause : MonoBehaviour
{
public static DeathPause S;
/* A GUI Death Message */
private Canvas self;
public Text countdown;
public float respawnTimer = 1.0f;
// Happens before the thing starts up
void Awake()
{
S = this;
}
// Use this for initialization
void Start()
{
self = GameObject.FindGameObjectWithTag("DeathDisplay").GetComponent<Canvas>();
self.enabled = false;
}
// Update is called once per frame
void Update()
{
}
/* Co-Routines */
// This co-routine pauses the game, restarting the level after 3 seconds or when the player hits the spacebar
IEnumerator PauseWhenDead()
{
// Pause the game and display a message
Time.timeScale = 0;
self.enabled = true;
float endPause = Time.realtimeSinceStartup + respawnTimer;
// After 3 seconds or if the user presses [SPACEBAR], reload the level
while (Time.realtimeSinceStartup < endPause && !Input.GetKeyDown("space"))
{
countdown.text = "" + (Mathf.Floor(endPause - Time.realtimeSinceStartup) + 1);
yield return null;
}
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Time.timeScale = 1;
}
// Runs the coroutine
public void PauseDead()
{
StartCoroutine(PauseWhenDead());
}
}<file_sep>/Assets/Scripts/GoalController.cs
using UnityEngine;
using System.Collections;
public class GoalController : MonoBehaviour
{
/* Spinning Goals */
public float spinSpeed = 10.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
Quaternion q = Quaternion.AngleAxis(Time.deltaTime * 10f, Vector3.up);
transform.rotation = q * transform.rotation;
}
}<file_sep>/Assets/Scripts/CameraController.cs
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour
{
// A reference to this object so that other scripts can access its public methods
public static CameraController Static;
// The currently active camera
private Camera active;
// Information about the GameObject being tracked
public GameObject trace = null;
private GameObject newTrace = null;
// Initial positions
private Vector3 offset = Vector3.zero;
// Camera movement
public float moveSpeed = 0.5f;
public float flySpeed = 500.0f;
[Range(0, 2 * Mathf.PI)]
public float yawSpeed = Mathf.PI / 4.0f;
// Default location
enum CameraMode { FirstPerson, ThirdPerson, God };
public Vector3[] views = new Vector3[3];
public Vector3[] orientations = new Vector3[3];
private int moveToMode = -1;
private int isMode = (int)CameraMode.FirstPerson; // Game starts in first person
private float percentTravelled = 1.0f;
private bool doneRotating = true;
// 3 cameras that the script can switch between to change views
public Camera[] cameras = new Camera[3];
/* Variables for Utilities */
// Easing function
[Range(0, 2)]
public float easeFactor = 1;
// Use this for initialization
void Start()
{
// Expose CameraController to other scripts
Static = this;
// Get the currently active camera
if (cameras[isMode] != null)
{
active = cameras[isMode];
if (cameras[(int)CameraMode.ThirdPerson] != null)
{
cameras[(int)CameraMode.ThirdPerson].enabled = false;
}
if (cameras[(int)CameraMode.God] != null)
{
cameras[(int)CameraMode.God].enabled = false;
}
}
else
{
active = this.GetComponent<Camera>();
}
// Get an offset from a tracked object
offset = transform.position - (trace == null ? Vector3.zero : trace.transform.position);
// Assume the camera starts out in first person
if (views[0] == Vector3.zero)
{
views[0] = transform.position;
}
// Move the camera with arrow keys, or vertically with keybindings
StartCoroutine(MoveCamera());
// Rotate the camera with the mouse
StartCoroutine(RotateCamera());
// Smooth camera movement between pre-defined waypoints
StartCoroutine(ModeChange());
StartCoroutine(MoveToWaypoint());
// Switch camera view between designated cameras
StartCoroutine(SwitchCamera());
}
// Update is called once every frame
void Update()
{
}
// LateUpdate is called after everything else updates
void LateUpdate()
{
// If the camera is tracking a player or an object, follow that object using the offset
if (trace != null)
{
active.transform.position = trace.transform.position + offset;
}
}
/* Co-Routines */
// Defines the camera controls (keyboard, moves camera)
private IEnumerator MoveCamera()
{
while (true)
{
if (percentTravelled >= 1.0)
{
float moveHorizontal = Input.GetAxis("CameraHorizontal");
float moveVertical = Input.GetAxis("CameraVertical");
float moveHeight = Input.GetAxis("CameraHeight"); // Set this in the InputManager
if (trace != null) offset += new Vector3(moveHorizontal, moveHeight, moveVertical) * moveSpeed;
else active.transform.position += new Vector3(moveHorizontal, moveHeight, moveVertical) * moveSpeed;
}
yield return null;
}
}
// Defines the camera controls (mouse movement left and right, rotates camera on the y axis ONLY)
private IEnumerator RotateCamera()
{
while (true)
{
if (percentTravelled >= 1.0 && doneRotating)
{
Vector3 rotation = new Vector3(0.0f, yawSpeed * Input.GetAxis("CameraPanLeftRight"), 0.0f);
active.transform.Rotate(rotation, Space.Self);
}
yield return null;
}
}
// Switch camera modes between "First Person," "Third Person," and "God"
private IEnumerator ModeChange()
{
while (true)
{
// Move to X Mode if not moving between modes and not currently in X mode
if (percentTravelled >= 1.0f)
{
if (Input.GetAxis("FirstPersonView") > 0) // Set this in the InputManager
{
moveToMode = (int)CameraMode.FirstPerson;
}
else if (Input.GetAxis("ThirdPersonView") > 0) // Set this in the InputManager
{
moveToMode = (int)CameraMode.ThirdPerson;
}
else if (Input.GetAxis("GodView") > 0) // Set this in the InputManager
{
moveToMode = (int)CameraMode.God;
}
else { }
}
yield return null;
}
}
// Move between waypoints (First person, Third person, and God)
private IEnumerator MoveToWaypoint()
{
float moveDistance = 0.0f;
Vector3 startLocation = Vector3.zero,
targetLocation = Vector3.zero;
Quaternion targetRotation = Quaternion.Euler(Vector3.zero);
while (true)
{
// Perform movement
if (percentTravelled < 1.0f || !doneRotating)
{
if (percentTravelled < 1.0f)
{
// Calculate easing between current and target locations
percentTravelled += (Time.deltaTime * flySpeed) / moveDistance;
percentTravelled = Mathf.Clamp01(percentTravelled);
float easedPercent = Ease(percentTravelled);
// Calculate new position based on easing
Vector3 newPos = Vector3.Lerp(startLocation, targetLocation, easedPercent);
// Move to the new position and immediately go to the next iteration
if (trace != null) offset = newPos - trace.transform.position;
else active.transform.position = newPos;
}
if (!doneRotating)
{
// Start rotating towards the new angle without overshooting
active.transform.rotation = Quaternion.RotateTowards(active.transform.rotation, targetRotation, Time.time * yawSpeed);
doneRotating = active.transform.rotation == targetRotation;
}
// Reset variables when done moving and rotating
if (percentTravelled >= 1 && doneRotating)
{
isMode = moveToMode;
moveToMode = -1;
moveDistance = 0.0f;
if (newTrace != null)
{
trace = newTrace;
newTrace = null;
}
}
yield return null;
}
else
{
startLocation = active.transform.position;
// Change the camera mode by moving if (1) there is an intent to move, and (2) there is no camera for the current mode OR there is no camera for the desired mode
// Allow recentering on the current view by moving if the user moves the camera away from the starting point of the view (with an error of .5f) and presses the button for the current view
if (moveToMode > -1 && Vector3.Distance(active.transform.position, views[moveToMode]) > 0.5f && (cameras[isMode] != null || cameras[moveToMode] == null))
{
// Calculate distance to new location
targetLocation = (trace == null ? views[moveToMode] : trace.transform.position + views[moveToMode]);
targetRotation = Quaternion.Euler(orientations[moveToMode]);
moveDistance = Vector3.Distance(active.transform.position, targetLocation);
// Set things in motion
percentTravelled = 0.0f;
doneRotating = false;
}
else
{
// Can't move to a place you're already at
moveToMode = -1;
}
yield return null;
}
}
}
// Changes the camera to the one that represents the desired view (First person, Third person, and God)
private IEnumerator SwitchCamera()
{
while (true)
{
// Check if the switch should happen
if (moveToMode != isMode && moveToMode > -1 && cameras[moveToMode] != null)
{
// Change camera view
cameras[moveToMode].enabled = true;
cameras[isMode].enabled = false;
// Set active camera and its index
active = cameras[moveToMode];
isMode = moveToMode;
}
yield return null;
}
}
/* Utilities */
// Movement Easing equation: y = x^a / (x^a + (1-x)^a)
//
// Takes x values between 0 and 1 and maps them to y values also between 0 and 1
// a = 1 -> straight line
// This is a logistic function; as a increases, y increases faster for values of x near .5 and slower for values of x near 0 or 1
//
// For animation, 1 < a < 3 is pretty good
private float Ease(float x)
{
float a = easeFactor + 1.0f;
return Mathf.Pow(x, a) / (Mathf.Pow(x, a) + Mathf.Pow(1 - x, a));
}
/* Module static methods
*
* Use these to allow other scripts to interact with this module
* They can be accessed using CameraController.Static.<MethodName>
*/
// Allow the user to change the locations of each of the views
// Optionally, move to that view
public void SetFirstPersonView(Vector3 newFirstPerson, bool move = false)
{
views[(int)CameraMode.FirstPerson] = newFirstPerson;
if (move) moveToMode = (int)CameraMode.FirstPerson;
}
public void SetThirdPersonView(Vector3 newThirdPerson, bool move = false)
{
views[(int)CameraMode.ThirdPerson] = newThirdPerson;
if (move) moveToMode = (int)CameraMode.ThirdPerson;
}
public void SetGodView(Vector3 newGod, bool move = false)
{
views[(int)CameraMode.God] = newGod;
if (move) moveToMode = (int)CameraMode.God;
}
// Allow the user to change the orientations of each of the views
// Optionally, move to that view
public void SetFirstPersonOrientation(Vector3 newFirstPersonOrientation, bool move = false)
{
orientations[(int)CameraMode.FirstPerson] = newFirstPersonOrientation;
if (move) moveToMode = (int)CameraMode.FirstPerson;
}
public void SetThirdPersonOrientation(Vector3 newThirdPersonOrientation, bool move = false)
{
orientations[(int)CameraMode.ThirdPerson] = newThirdPersonOrientation;
if (move) moveToMode = (int)CameraMode.ThirdPerson;
}
public void SetGodOrientation(Vector3 newGodOrientation, bool move = false)
{
orientations[(int)CameraMode.God] = newGodOrientation;
if (move) moveToMode = (int)CameraMode.God;
}
// Allow the user to define new cameras to use for each of the views
// ALWAYS moves to that view
public void SetFirstPersonCamera(Camera newFirstPersonCamera)
{
cameras[(int)CameraMode.FirstPerson] = newFirstPersonCamera;
moveToMode = (int)CameraMode.FirstPerson;
}
public void SetThirdPersonCamera(Camera newThirdPersonCamera)
{
cameras[(int)CameraMode.ThirdPerson] = newThirdPersonCamera;
moveToMode = (int)CameraMode.ThirdPerson;
}
public void SetGodCamera(Camera newGodCamera)
{
cameras[(int)CameraMode.God] = newGodCamera;
moveToMode = (int)CameraMode.God;
}
// Allow the user to programatically go to a target mode
public void GoToFirstPerson()
{
moveToMode = (int)CameraMode.FirstPerson;
}
public void GoToThirdPerson()
{
moveToMode = (int)CameraMode.ThirdPerson;
}
public void GoToGod()
{
moveToMode = (int)CameraMode.God;
}
// Start tracking target object in a particular view
// Can specify a new view configuration or use a keyword
public void TrackObject(GameObject target, string viewMode = "First Person")
{
// Get ready to change the trace
trace = null;
newTrace = target;
offset = Vector3.zero;
// Based on the desired view, move the camera to a new position
switch (viewMode)
{
case "First Person":
moveToMode = (int)CameraMode.FirstPerson;
break;
case "Third Person":
moveToMode = (int)CameraMode.ThirdPerson;
break;
case "God":
moveToMode = (int)CameraMode.God;
break;
default:
break;
}
}
// An overload of TrackObject() that allows the caller to specify a new camera location, orientation, and camera
public void TrackObject(GameObject target, Vector3 viewLocation, Vector3 orientation, Camera newCamera = null, string viewMode = "First Person")
{
// Get ready to change the trace
trace = null;
newTrace = target;
offset = Vector3.zero;
// Based on the desired view and settings, change the parameters and move the camera to a new position
switch (viewMode)
{
case "First Person":
views[(int)CameraMode.FirstPerson] = viewLocation;
orientations[(int)CameraMode.FirstPerson] = orientation;
if (newCamera != null) cameras[(int)CameraMode.FirstPerson] = newCamera;
moveToMode = (int)CameraMode.FirstPerson;
break;
case "Third Person":
views[(int)CameraMode.ThirdPerson] = viewLocation;
orientations[(int)CameraMode.ThirdPerson] = orientation;
if (newCamera != null) cameras[(int)CameraMode.ThirdPerson] = newCamera;
moveToMode = (int)CameraMode.ThirdPerson;
break;
case "God":
views[(int)CameraMode.God] = viewLocation;
orientations[(int)CameraMode.God] = orientation;
if (newCamera != null) cameras[(int)CameraMode.God] = newCamera;
moveToMode = (int)CameraMode.God;
break;
default:
break;
}
}
}<file_sep>/Assets/Scripts/WinPause.cs
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class WinPause : MonoBehaviour
{
public static WinPause S;
/* A GUI Victory Message */
private Canvas self;
public Text countdown;
public float playAgainTimer = 3.0f;
// Happens before the thing starts up
void Awake()
{
S = this;
}
// Use this for initialization
void Start()
{
self = GameObject.FindGameObjectWithTag("WinDisplay").GetComponent<Canvas>();
self.enabled = false;
}
// Update is called once per frame
void Update()
{
}
/* Co-Routines */
// This co-routine pauses the game, going to the next level after 3 seconds or when the player hits the spacebar
IEnumerator PauseWhenWin(string level)
{
// Pause the game and display a message
Time.timeScale = 0;
self.enabled = true;
float endPause = Time.realtimeSinceStartup + playAgainTimer;
// After 3 seconds or if the user presses [SPACEBAR], reload the level
while (Time.realtimeSinceStartup < endPause && !Input.GetKeyDown("space"))
{
countdown.text = "" + (Mathf.Floor(endPause - Time.realtimeSinceStartup) + 1);
yield return null;
}
SceneManager.LoadScene(level);
Time.timeScale = 1;
}
// Runs the coroutine
public void PauseWin(string level)
{
StartCoroutine(PauseWhenWin(level));
}
}<file_sep>/Assets/Scripts/PlayerController.cs
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour {
// Describes how possessed objects work
private static GameObject possessedObject;
private Rigidbody rb;
public float possessDistance = 20.0f;
public bool possessCooldown = false; // Whether or not you can possess something at the moment
public float activateTimer = 3.0f; // After a certain amount of time, the possessed object exhibits physics properties
// The camera that represents the spoopy ghost
public Camera playerCamera;
// Objects in range
private RaycastHit[] inRange;
// Layer to check for collisions
public int possessLayer = 9;
// Perspectives to use when this object gets possessed
public Vector3[] firstPerson = new Vector3[2] { Vector3.zero, Vector3.zero };
public Vector3[] thirdPerson = new Vector3[2] { Vector3.zero, Vector3.zero };
// Initial conditions
public float resetTimer = 2.0f; // Resets after 2 seconds of not being possessed
private Vector3 initialPosition;
private Vector3 initialOrientation;
public float initialForceMagnitude = 10.0f; // Magnitude of the initial force
// Out of bounds death condition
public float floor = -2.0f,
forwardWall = 500.0f,
backwardWall = -500.0f,
leftWall = -500.0f,
rightWall = 500.0f;
// Use this for initialization
void Start () {
// Before the object is possessed, it doesn't use gravity
rb = this.GetComponent<Rigidbody>();
rb.useGravity = false;
// Save initial conditions
initialPosition = transform.position;
initialOrientation = transform.eulerAngles;
// The object that shares a location with the camera when the game starts is the possessed object
if (playerCamera.transform.position == transform.position)
{
possessedObject = transform.gameObject;
}
// Object resetter
StartCoroutine(ResetObject());
}
// Update is called once per frame
void Update () {
// Detect clicks and see if the object can be possessed
if (Input.GetMouseButtonDown(0))
{
Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, maxDistance: Mathf.Infinity, layerMask: 1 << possessLayer))
{
// Check if on cooldown
if (possessCooldown == false)
{
// Attempt to possess the object that was hit if it's not already possessed
if (possessedObject != hit.transform.gameObject)
{
Possess(hit.transform.gameObject);
}
}
else
{
print("On cooldown");
}
}
else
{
print("Nothing");
}
}
// Check if the possessed object is still in play
if (possessedObject.transform.position.y < floor ||
possessedObject.transform.position.x > rightWall || possessedObject.transform.position.x < leftWall ||
possessedObject.transform.position.z > forwardWall || possessedObject.transform.position.z < backwardWall
)
{
DeathPause.S.PauseDead();
}
}
/* Gameplay helper methods */
// Possess target object
void Possess(GameObject target)
{
RaycastHit hit;
PlayerController targetController = target.GetComponent<PlayerController>();
// Attempt to raycast from the currently possessed object to the target
if (Physics.Raycast(possessedObject.transform.position, (target.transform.position - possessedObject.transform.position), out hit, possessDistance))
{
if (hit.transform.gameObject == target)
{
// Reset view
CameraController.Static.GoToFirstPerson();
// A new object has been possessed
possessedObject = target;
// Adjust the camera so that its first- and third-person perspectives are relative to the new possessed object
CameraController.Static.SetThirdPersonView(targetController.thirdPerson[0]);
CameraController.Static.SetThirdPersonOrientation(targetController.thirdPerson[1]);
CameraController.Static.TrackObject(target, targetController.firstPerson[0], targetController.firstPerson[1]); // Track the new object
// Now on cooldown...
targetController.possessCooldown = true;
}
else
{
// Notification: Something's in the way
print("Something's in the way...");
}
}
else
{
// Notification: Too far
print("Too far...");
}
}
/* Co-Routines */
// Reset an object to its initial state if it hasn't been possessed in a while
IEnumerator ResetObject()
{
while (true)
{
// Check if the object is not in its proper configuration AND it is not currently being possessed
if (possessedObject != this && transform.position != initialPosition && transform.eulerAngles != initialOrientation)
{
yield return new WaitForSeconds(resetTimer);
// If it's still not possessed at this time, reset
if (possessedObject != this.transform.gameObject)
{
// Reset physics
rb.useGravity = false;
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
// Reset position and orientation
transform.position = initialPosition;
transform.eulerAngles = initialOrientation;
}
}
// Check if on cooldown; if so, then get ready to activate physics
if (possessCooldown == true)
{
// Wait for the player to get their bearings
yield return new WaitForSeconds(resetTimer);
// On reaching the goal, display a victory screen and ask to restart the game
if (transform.gameObject.tag == "Goal")
{
WinPause.S.PauseWin("Level0");
}
else
{
// Otherwise, turn on gravity and apply any forces
rb.useGravity = true;
rb.AddForce(transform.rotation * Vector3.forward * initialForceMagnitude);
}
// No longer on cooldown
possessCooldown = false;
}
yield return null;
}
}
}
<file_sep>/README.md
# AstralProjector
Jumping between objects has never been so dangerous
| 739a108e91af63275c350f7ea639b513edc58177 | [
"Markdown",
"C#"
] | 6 | C# | k-chen8888/AstralProjector | 40f2209b203c320dd3738cf4a6b628cc9b8f4b2c | 0e04510f0940b97e7042ac8435b0294126ed57a7 |
refs/heads/master | <file_sep>/**
* Creates the gcloud SDK release URL for the specified arguments, verifying
* its existence.
*
* @param os The OS of the requested release.
* @param arch The system architecture of the requested release.
* @param version The version of the requested release.
* @returns The verified gcloud SDK release URL.
*/
export declare function getReleaseURL(
os: string,
arch: string,
version: string,
): Promise<string>;
<file_sep><!--
Copyright 2019 Google LLC
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
https://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.
-->
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unresolved]
### Security
### Added
### Changed
### Removed
### Fixed
### [0.2.1](https://www.github.com/google-github-actions/setup-gcloud/compare/v0.2.0...v0.2.1) (2021-02-12)
### Bug Fixes
* Update action names ([#250](https://www.github.com/google-github-actions/setup-gcloud/issues/250)) ([#251](https://www.github.com/google-github-actions/setup-gcloud/issues/251)) ([95e2d15](https://www.github.com/google-github-actions/setup-gcloud/commit/95e2d15420adee2aa7d97b08aff5d50feacb17b0))
## [0.2.0](https://www.github.com/google-github-actions/setup-gcloud/compare/0.1.3...v0.2.0) (2020-11-16)
### Features
* add build and release ([#190](https://www.github.com/google-github-actions/setup-gcloud/issues/190)) ([11f1439](https://www.github.com/google-github-actions/setup-gcloud/commit/11f14399789c7ee67a0dab93e55aa61db68c1a0d))
* Add optional credentials_file_path input for setup-gcloud ([#153](https://www.github.com/google-github-actions/setup-gcloud/issues/153)) ([#213](https://www.github.com/google-github-actions/setup-gcloud/issues/213)) ([a4a3ab7](https://www.github.com/google-github-actions/setup-gcloud/commit/a4a3ab71b6a161eda3d0ba771380e9eb13bf83c7))
* clean up user agent ([#231](https://www.github.com/google-github-actions/setup-gcloud/issues/231)) ([478a42b](https://www.github.com/google-github-actions/setup-gcloud/commit/478a42baee02e58b183e8e82ba1800f5080bfa0a))
### Bug Fixes
* add @actions/exec library ([db3c7d6](https://www.github.com/google-github-actions/setup-gcloud/commit/db3c7d6e8477b8cdf9324c00d1d2c78de60fac7e))
* add GITHUB_PATH to unit test process stub ([#236](https://www.github.com/google-github-actions/setup-gcloud/issues/236)) ([6feeef5](https://www.github.com/google-github-actions/setup-gcloud/commit/6feeef597ba1bbc682d13ec32e53a4c223f3064e))
* bump @actions/tool-cache to 1.6.1 ([#232](https://www.github.com/google-github-actions/setup-gcloud/issues/232)) ([862c53e](https://www.github.com/google-github-actions/setup-gcloud/commit/862c53e843a9a04a006533f9340110845d292982))
* import * as exec ([2c0de75](https://www.github.com/google-github-actions/setup-gcloud/commit/2c0de755dfc78d287881043c1c7e0e4aa676460d))
* reference compiled dist/index.js in action.yml ([ccab249](https://www.github.com/google-github-actions/setup-gcloud/commit/ccab24911266f9267e21b7b3234613244bab3eeb))
### Reverts
* Revert "Use RUNNER_TEMP to export credentials" (#149) ([0926395](https://www.github.com/google-github-actions/setup-gcloud/commit/0926395459ca75ce323bcc26564f2843cd48ed98)), closes [#149](https://www.github.com/google-github-actions/setup-gcloud/issues/149) [#148](https://www.github.com/google-github-actions/setup-gcloud/issues/148)
## [0.1.3] - 2020-07-30
### Security
### Added
- [deploy-cloudrun](https://github.com/GoogleCloudPlatform/github-actions/pull/117): Added action for deploying to Google Cloud Run
- [appengine-deploy](https://github.com/GoogleCloudPlatform/github-actions/pull/91): Added action for deploying to Google App Engine
- [upload-cloud-storage](https://github.com/GoogleCloudPlatform/github-actions/pull/121): Added action for uploading an artifact to GCS
- [get-secretmanager-secrets](https://github.com/GoogleCloudPlatform/github-actions/pull/53): Fetch secrets from Secret Manager
### Changed
- [setup-gcloud]: Allow setting of project Id
### Removed
### Fixed
- cached gcloud path
- missing credential input field in action.yml
- allow GAE tests to run in parallel
## [0.1.2] - 2020-02-28
### Security
### Added
- Added support for setting up GOOGLE APPLICATION CREDENTIALS
- Can specify creds as b64 or plain json
### Changed
- Changed testing framework for mocha
- Updated linter config
### Removed
### Fixed
## [0.1.1] - 2020-01-30
### Security
### Added
- [setup-gcloud]: Added support for specifying 'latest' SDK version
- [setup-gcloud]: Made authentication optional
- [setup-gcloud]: Added metrics tracking label
- [setup-gcloud]: Added CloudRun example workflow
- [setup-gcloud]: Added integration tests
### Changed
### Removed
### Fixed
## [0.1.0] - 2019-11-08
### Security
### Added
- Initial release of setup-gcloud action.
- Provides support for configuring Google Cloud SDK within the GitHub Actions v2 environment.
### Changed
### Removed
### Fixed
<file_sep>/**
* Installs the gcloud SDK into the actions environment.
*
* @param version The version being installed.
* @param gcloudExtPath The extraction path for the gcloud SDK.
* @returns The path of the installed tool.
*/
export declare function installGcloudSDK(
version: string,
gcloudExtPath: string,
): Promise<string>;
| 5bd2ed70011d66d893cd97b1470911e8cd2d3e95 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | hasimyerlikaya/setup-gcloud | e647fdc963db695d93c2ec13e65fd4acc2471ec3 | 547f3376609bb9b3cd0a8783f49783c4fcd8c157 |
refs/heads/master | <repo_name>azat385/rClock<file_sep>/getMC.py
# -*- coding: utf-8 -*-
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
data = ["CO2", "T", "ts"]
value = mc.get_multi(data)
for k,v in value.iteritems():
print "{} = {}".format(k,v)<file_sep>/mbClient.py
# -*- coding: utf-8 -*-
"""The most basic chat protocol possible.
sudo kill -TERM $(sudo cat mbClient.pid)
sudo twistd --python=mbClient.py --pidfile=mbClient.pid --logfile=logs/mbClient.log
"""
port = 14230
delayBeforeDropConnection = 180
getPowerCRC = "\x10\x03\x01\x00\x00\x02\xC6\xB6"
#from twisted.protocols import basic
from twisted.internet import protocol, reactor, error
from twisted.application import service, internet
from twisted.python import log
from struct import pack, unpack
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
def get_data_from_mc():
str2return = pack(">BBBHHBB", 16, 3, 4 , mc.get("CO2"), mc.get("T"), 255, 255)
return str2return
class MyChat(protocol.Protocol):
def connectionMade(self):
log.msg( "Got new client: {}".format(self.transport.getPeer()) )
self.factory.clients.append(self)
self.timeout = reactor.callLater(delayBeforeDropConnection, self.dropConnection)
def connectionLost(self, reason):
log.msg( "Lost a client! reason: {}".format(reason) )
self.factory.clients.remove(self)
def dataReceived(self, line):
log.msg( "received {}".format( repr(line) ) )
self.timeout.reset(delayBeforeDropConnection)
if line==getPowerCRC:
self.message(get_data_from_mc())
else:
log.msg( "Drop connection from server due to unknown client{}".format(self.transport.getPeer()) )
self.dropConnection()
# for c in self.factory.clients:
# if c != self:
# c.message(line)
def message(self, message):
self.transport.write(message)
def dropConnection(self):
#self.myError.UserError(string='drop connection from server due to silence')
log.msg( "Drop connection from server due to silence{}".format(self.transport.getPeer()) )
self.transport.loseConnection()
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(port, factory).setServiceParent(application)<file_sep>/analog.py
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color, Line
from kivy.uix.floatlayout import FloatLayout
from math import cos, sin, pi
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
import datetime
import socket
import time
from struct import unpack
hexString = lambda byteString : " ".join(x.encode('hex') for x in byteString)
# TCP_IP = '192.168.155.11'
# TCP_PORT = 4001
TCP_IP = '192.168.3.11'
TCP_PORT = 14230
BUFFER_SIZE = 1024
getPowerCRC = "\x10\x03\x01\x00\x00\x02\xC6\xB6"
def getMB():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5.0)
s.connect((TCP_IP, TCP_PORT))
s.settimeout(5.0)
s.send(getPowerCRC)
data = s.recv(BUFFER_SIZE)
s.close()
# print "write: {}\nread: {}".format(hexString(getPowerCRC), hexString(data))
data = unpack(">BBBHHBB", data)
# print data[3:5]
CO2, T = data[3]/10, data[4]/10.0
except:
CO2, T = "Nan", "Nan"
return "CO2: {}ppm T: {}°C".format(CO2, T)
class DataLabel(Label):
def update(self, *args):
self.text = getMB()
self.font_size = 75
kv = '''
#:import math math
[ClockNumber@Label]:
text: str(ctx.i)
pos_hint: {"center_x": 0.5+0.42*math.sin(math.pi/6*(ctx.i-12)), "center_y": 0.5+0.42*math.cos(math.pi/6*(ctx.i-12))}
font_size: self.height/8
<MyClockWidget>:
face: face
ticks: ticks
FloatLayout:
id: face
size_hint: None, None
pos_hint: {"center_x":0.5, "center_y":0.5}
size: 0.9*min(root.size), 0.9*min(root.size)
canvas:
Color:
rgb: 0.1, 0.1, 0.1
Ellipse:
size: self.size
pos: self.pos
ClockNumber:
i: 1
ClockNumber:
i: 2
ClockNumber:
i: 3
ClockNumber:
i: 4
ClockNumber:
i: 5
ClockNumber:
i: 6
ClockNumber:
i: 7
ClockNumber:
i: 8
ClockNumber:
i: 9
ClockNumber:
i: 10
ClockNumber:
i: 11
ClockNumber:
i: 12
Ticks:
id: ticks
r: min(root.size)*0.9/2
'''
Builder.load_string(kv)
class MyClockWidget(FloatLayout):
pass
k=1.15
class Ticks(Widget):
def __init__(self, **kwargs):
super(Ticks, self).__init__(**kwargs)
self.bind(pos=self.update_clock)
self.bind(size=self.update_clock)
def update_clock(self, *args):
self.canvas.clear()
with self.canvas:
time = datetime.datetime.now()
Color(0.2, 0.5, 0.2)
Line(points=[self.center_x, self.center_y*k, self.center_x+0.8*self.r*sin(pi/30*time.second), self.center_y*k+0.8*self.r*cos(pi/30*time.second)], width=3, cap="round")
Color(0.3, 0.6, 0.3)
Line(points=[self.center_x, self.center_y*k, self.center_x+0.7*self.r*sin(pi/30*time.minute), self.center_y*k+0.7*self.r*cos(pi/30*time.minute)], width=4, cap="round")
Color(0.4, 0.7, 0.4)
th = time.hour*60 + time.minute
Line(points=[self.center_x, self.center_y*k, self.center_x+0.5*self.r*sin(pi/360*th), self.center_y*k+0.5*self.r*cos(pi/360*th)], width=5, cap="round")
class MyClockApp(App):
def build(self):
d = DataLabel()
Clock.schedule_interval(d.update, 5)
clock = MyClockWidget()
Clock.schedule_interval(clock.ticks.update_clock, 1)
root = BoxLayout(orientation='vertical')
root.add_widget(clock)
layout = BoxLayout(size_hint=(1, None), height=70)
layout.add_widget(d)
root.add_widget(layout)
return root
if __name__ == '__main__':
MyClockApp().run()
<file_sep>/mb.py
# -*- coding: utf-8 -*-
from serial import Serial
from struct import pack, unpack
from time import sleep
from datetime import datetime
from sql_create_table import Data, session, check_if_data_table_exists
hexString = lambda byteString : " ".join(x.encode('hex') for x in byteString)
# ser = Serial(
# port='COM1',
# baudrate=9600,
# bytesize=8,
# parity='N',
# stopbits=1,
# timeout=0.5,
# xonxoff=0,
# rtscts=0
# )
# sample rq&rs
getPowerCRC = "\x10\x03\x01\x00\x00\x02\xC6\xB6"
# ser.write(getPowerCRC)
# response = ser.read(size=100)
# print "write: {}\nread: {}".format(hexString(getPowerCRC),hexString(response))
import socket
# TCP_IP = '192.168.155.11'
# TCP_PORT = 4001
# TCP_IP = '172.16.17.32'
TCP_IP = '127.0.0.1'
TCP_PORT = 14220
BUFFER_SIZE = 1024
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
check_if_data_table_exists()
for _ in range(8):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5.0)
s.connect((TCP_IP, TCP_PORT))
s.send(getPowerCRC)
data = s.recv(BUFFER_SIZE)
s.close()
ts = datetime.now()
print "write: {}\nread: {}".format(hexString(getPowerCRC),hexString(data))
data = unpack(">BBBHHBB", data)
print "{}ppm {}°C".format(data[3]/10, data[4]/10)
mc.set("CO2", data[3])
mc.set("T", data[4])
mc.set("ts", ts)
session.add(Data(tag_id=1, value=data[3] / 10, stime=ts))
session.add(Data(tag_id=2, value=data[4] / 10.0, stime=ts))
session.commit()
sleep(5)
<file_sep>/rClockBot.py
# -*- coding: utf-8 -*-
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
import humanize
from datetime import datetime, timedelta
from plotly.offline import plot
from plotly.graph_objs import Bar, Scatter
def get_data_from_mc():
data = ["CO2", "T", "ts"]
value = mc.get_multi(data)
_t = humanize.i18n.activate('ru_RU')
return "{}({})\nCO2: {}ppm\nT: {}°C".format(humanize.naturaltime(datetime.now() - value['ts']),
value['ts'],
value['CO2']/10,
value['T']/10.0,
)
from telegram.ext import Updater, CommandHandler
def figure(bot, update):
update.message.reply_text('Hello World!')
def start(bot, update):
update.message.reply_text('Hello World!')
def hello(bot, update):
update.message.reply_text(
'Hello {}'.format(update.message.from_user.first_name))
def data(bot, update):
update.message.reply_text(get_data_from_mc())
updater = Updater('394896923:AAFHq9Y3efI_kO44cVNeuRAwBtJTpplBLKs')
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('hello', hello))
updater.dispatcher.add_handler(CommandHandler('data', data))
updater.dispatcher.add_handler(CommandHandler('pic', figure))
updater.start_polling()
updater.idle()<file_sep>/run_py.sh
#!/bin/bash
FILEPY=$1
cd /home/ruvds/rClock/
python $FILEPY
<file_sep>/sql_create_table.py
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, ForeignKey, REAL, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
db_name = "common.db"
Base = declarative_base()
class Device(Base):
__tablename__ = 'device'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False, unique=True)
desc_short = Column(String(50))
desc_long = Column(String(250))
def __repr__(self):
return "<Device(id='{}', name='{}')>".format(self.id, self.name)
class Tag(Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False, unique=True)
desc = Column(String(500))
def __repr__(self):
return "<Tag(id='{}', name='{}')>".format(self.id, self.name)
class Data(Base):
__tablename__ = 'data'
id = Column(Integer, primary_key=True)
device_id = Column(Integer, ForeignKey('device.id'), default=1)
device = relationship(Device)
tag_id = Column(Integer, ForeignKey('tag.id'), default=1)
tag = relationship(Tag)
value = Column(REAL)
stime = Column(DateTime, default=datetime.now())
def __repr__(self):
return "<Data(id='{}', device='{}' tag='{}' )>".format(
self.id, self.device_id, self.tag_id, )
engine = create_engine('sqlite:///{}'.format(db_name), echo=False)
DBSession = sessionmaker()
# DBSession.bind = engine
session = DBSession(bind=engine)
def create_tables():
Base.metadata.create_all(engine)
def add_init_data():
new_device = Device(name="XKinstr")
session.add(new_device)
for tag_name in ["CO2", "T"]:
new_tag = Tag(name=tag_name)
session.add(new_tag)
session.commit()
def check_if_data_table_exists():
if not engine.dialect.has_table(engine, 'data'):
create_tables()
print "create tables"
add_init_data()
print "fill init data"
else:
print "table already exists"
if __name__ == '__main__':
# create_tables()
# add_init_data()
check_if_data_table_exists()
# print session.query(Data).order_by(Data.id.desc()).first()
# print session.query(Data).order_by(Data.id.desc()).all()[:2]<file_sep>/rPhotoBot.py
# -*- coding: utf-8 -*-
import picamera
camera = picamera.PiCamera()
camera.vflip = True
import humanize
from datetime import datetime, timedelta
from telegram.ext import Updater, CommandHandler
def figure(bot, update):
photo_name = 'pics/{}.jpg'.format(datetime.now().isoformat())
camera.capture(photo_name)
# bot.send_photo(chat_id=update.message.chat_id, photo=open(photo_name, 'rb'))
update.message.reply_photo(photo=open(photo_name, 'rb'))
def start(bot, update):
update.message.reply_text('Hello World!')
def hello(bot, update):
update.message.reply_text(
'Hello {}'.format(update.message.from_user.first_name))
updater = Updater('389009198:AAGA_q_KOxAKa38nNHiuixDPR1f44baxqwM')
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('hello', hello))
updater.dispatcher.add_handler(CommandHandler('pic', figure))
updater.start_polling()
updater.idle()<file_sep>/main2.py
# -*- coding: utf-8 -*-
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock
import socket
import time
from struct import unpack
hexString = lambda byteString : " ".join(x.encode('hex') for x in byteString)
TCP_IP = '192.168.155.11'
TCP_PORT = 4001
BUFFER_SIZE = 1024
getPowerCRC = "\x10\x03\x01\x00\x00\x02\xC6\xB6"
def getMB():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(getPowerCRC)
data = s.recv(BUFFER_SIZE)
s.close()
# print "write: {}\nread: {}".format(hexString(getPowerCRC), hexString(data))
data = unpack(">BBBHHBB", data)
# print data[3:5]
return "{}ppm {}°C".format(data[3]/10.0, data[4]/10.0)
class DataLabel(Label):
def update(self, *args):
self.text = getMB()
class IncrediblyCrudeClock(Label):
def update(self, *args):
self.text = time.asctime()
class TimeApp(App):
def build(self):
crudeclock = IncrediblyCrudeClock()
d = DataLabel()
Clock.schedule_interval(d.update, 5)
Clock.schedule_interval(crudeclock.update, 1)
# root = GridLayout(cols=2, padding=50, spacing=50)
root = BoxLayout(orientation='vertical')
root.add_widget(crudeclock)
layout = BoxLayout(size_hint=(1, None), height=50)
layout.add_widget(d)
root.add_widget(layout)
return root
if __name__ == "__main__":
TimeApp().run() | 23c5e1406fa234cd0e83db57389da8626c5d3283 | [
"Python",
"Shell"
] | 9 | Python | azat385/rClock | d0cdb3fe9054b3272dbdeebd1b42f7b7cfb9e840 | 3311517ceb6e8c46a6561b61bf240d17d119dabf |
refs/heads/master | <repo_name>MarkRobles/M0502<file_sep>/M0502/Controllers/ProductController.cs
using M0502.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace M0502.Controllers
{
public class ProductController : Controller
{
// GET: Product
public ActionResult Index()
{
return View();
}
public ActionResult Display(int id)
{
var Context = new Models.NORTHWNDEntities();
Product Producto = Context.Products.FirstOrDefault(p => p.ProductID == id);
return View(Producto);
}
}
}<file_sep>/M0502/Controllers/CategoryController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace M0502.Controllers
{
public class CategoryController : Controller
{
// GET: Category
public ActionResult Index()
{
return View();
}
public FileStreamResult GetImage(int id) {
var Context = new Models.NORTHWNDEntities();
int OffSet = 78;
var bytes = Context.Categories.Where(c=> c.CategoryID == id).Select(c=>c.Picture).FirstOrDefault();
return File(
new MemoryStream(
bytes,OffSet,bytes.Length-OffSet)
,"image/jpeg");
}
}
}
<file_sep>/M0502/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace M0502.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return Content("(c) TI Capacitacion 2014");
}
}
} | d8689f066daf4c435d8af3983e5a528ad33b0fc3 | [
"C#"
] | 3 | C# | MarkRobles/M0502 | 178b71cb593abbfc950306c47f5061e87ccacdb1 | ec52e04aa99364f04c412071b4bfee7dc0d698ee |
refs/heads/master | <file_sep>
#include <iostream>
int main()
{
int N;
std::cin >> N;
for (int i = 0; i < N; ++i)
{
if (i % 2 == 0) //Проверка на четность
{
std::cout << i << " ";
}
else
std::cout << i << " ";
}
}
| 782f4cea21c48aa13054153893a01cf7a1e720e1 | [
"C++"
] | 1 | C++ | stupidmotherfuckingfucker/Lesson-15 | 74e7354e549e9ed2c43d875a9294207cdcd1dae7 | 09c97aa950e42660ecb7e089021325caa54345cc |
refs/heads/master | <file_sep>
// AnniversaryDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "Anniversary.h"
#include "AnniversaryDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAnniversaryDlg 对话框
CAnniversaryDlg::CAnniversaryDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CAnniversaryDlg::IDD, pParent)
, m_timeStart(2015, 4, 20, 8, 57, 4)
, m_timeGirlFriend(2015, 5, 17 ,0 , 0, 0)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CAnniversaryDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAnniversaryDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDCANCEL, &CAnniversaryDlg::OnBnClickedCancel)
ON_BN_CLICKED(IDOK, &CAnniversaryDlg::OnBnClickedOk)
ON_WM_TIMER()
END_MESSAGE_MAP()
// CAnniversaryDlg 消息处理程序
BOOL CAnniversaryDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
RefreshTime();
SetTimer(1, 500, NULL);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CAnniversaryDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CAnniversaryDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CAnniversaryDlg::OnBnClickedCancel()
{
// TODO: Add your control notification handler code here
CDialogEx::OnCancel();
}
void CAnniversaryDlg::OnBnClickedOk()
{
// TODO: Add your control notification handler code here
CDialogEx::OnOK();
}
void CAnniversaryDlg::RefreshTime()
{
CString strTime;
CString strTimeGirlFriend;
CTime timeNow = CTime::GetCurrentTime();
CTimeSpan timeSpan = timeNow - m_timeStart;
int nDays = timeSpan.GetDays();
int nHours = timeSpan.GetHours();
int nMins = timeSpan.GetMinutes();
int nSecs = timeSpan.GetSeconds();
strTime.Format(_T("%d天%02d小时%02d分%02d秒"), nDays, nHours, nMins, nSecs);
CTimeSpan timeSpanGirlFriend= timeNow - m_timeGirlFriend;
int nDays2 = timeSpanGirlFriend.GetDays();
int nHours2 = timeSpanGirlFriend.GetHours();
int nMins2 = timeSpanGirlFriend.GetMinutes();
int nSecs2 = timeSpanGirlFriend.GetSeconds();
strTimeGirlFriend.Format(_T("%d天%02d小时%02d分%02d秒"),
nDays2, nHours2, nMins2, nSecs2);
GetDlgItem(IDC_TIME_RESULT)->SetWindowText(strTime);
GetDlgItem(IDC_TIME_RESULT_GIRL_FRIEND)->SetWindowText(strTimeGirlFriend);
}
void CAnniversaryDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: Add your message handler code here and/or call default
RefreshTime();
CDialogEx::OnTimer(nIDEvent);
}
| baa04d19c3309006bb5882298a7809aaaf9ddf39 | [
"C++"
] | 1 | C++ | zdwzkl/Anniversary | 74a8d99d66027c114ba4e0176d3f1c52b8dfd61f | 8c8067ea5e02bb4b3df797b6da4a4988071d8832 |
refs/heads/master | <file_sep>fetch("//api.github.com/users/VictorWinberg").then(async (res) => {
if (!res.ok) return;
const json = await res.json();
const head = document.head || document.getElementsByTagName("head")[0];
const div = document.getElementById("github");
const wrapper = document.createElement("div");
const style = document.createElement("style");
style.type = "text/css";
head.appendChild(style);
div.appendChild(wrapper);
wrapper.setAttribute("class", "github");
const repos = document.createElement("a");
const gists = document.createElement("a");
wrapper.appendChild(repos);
wrapper.appendChild(gists);
repos.appendChild(document.createTextNode(json.public_repos + " Repos"));
gists.appendChild(document.createTextNode(json.public_gists + " Gists"));
repos.setAttribute("href", "//github.com/VictorWinberg?tab=repositories");
gists.setAttribute("href", "//gist.github.com/VictorWinberg");
const css = `
#github {
position: relative;
}
.github {
position: absolute;
z-index: 1;
top: 0;
left: 0;
right: 0;
margin: 1em;
animation: fade .5s ease-in-out;
}
.github a {
margin: 0.5em;
padding: 0.75em;
text-decoration: none;
color: rgba(0,0,0,0.87);
border: 1px solid;
background: white;
}
.github a:hover {
background: khaki;
}
@keyframes fade {
from { opacity: 0; }
to { opacity: 1; }
}
`;
style.appendChild(document.createTextNode(css));
});
<file_sep>window.onload = function () {
var year = document.getElementById("year");
if (year) {
year.innerHTML = new Date().getFullYear();
}
}<file_sep># My Portfolio Website
Website at https://victorwinberg.github.io, built from scratch without any frameworks or bootstrap.
| 1ed0408359632c4ed71b796ca425fa8cf474098a | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | VictorWinberg/VictorWinberg.github.io | 7b3228a77f5702673e14c716f5bb7cbea9f9012f | 02bb07c30c0f6360a165557e43927bfd3420a1df |
refs/heads/master | <file_sep># pdftoimageusingpython
Simple pdf to image coverter tool created by <a href="https://www.facebook.com/vijaysahuofficialpage"><NAME></a>
Required Package:
pdf2image
Installation
sudo pip3 install pdf2image
<file_sep>#created by <NAME>
#facebook.com/vijaysahuofficialpage
import os
from pdf2image import convert_from_path
folder_path = input("enter folder path >>> ")
file_name = input("Enter file name with extension >>> ")
final_folder_path = os.path.abspath(folder_path)
final = os.path.join(final_folder_path, file_name)
file_exists = os.path.exists(final)
if file_exists == False:
print("File Not Found")
else:
print("File detected")
pages = convert_from_path(final, output_folder=final_folder_path, fmt="JPEG", dpi=200)
print("File successfully converted")
| 5b866bde4fcbdf0c127e4cb156aa68aa604800a3 | [
"Markdown",
"Python"
] | 2 | Markdown | vijaysahuofficial/pdftoimageusingpython | 37a2f6feeb2516912df382a725d0cdb56b64fc88 | 6aca326374d52febbe8a7afea1fdd9544c6cfe78 |
refs/heads/master | <file_sep>
package net.exiva.fido;
import danger.app.*;
import java.util.Random;
import danger.ui.*;
import danger.util.DEBUG;
import java.io.File;
import danger.storage.*;
import danger.util.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import danger.net.*;
import java.net.URLEncoder;
public class QueViewer extends ScreenWindow implements Resources, Commands {
private static ActiveListView listView;
public QueViewer() {
buildMenu();
}
public static QueViewer makeNew() {
QueViewer t = (QueViewer)Application.getCurrentApp().getResources().getScreen(ID_FEEDSCREEN);
return t;
}
public void loadFile(String filepath)
{
}
public void onDecoded() {
listView = (ActiveListView) this.getDescendantWithID(ID_ACTIVE_VIEW);
}
public final void buildMenu() {
}
public static void updateView() {
StdActiveList templist = new StdActiveList();
for(int i=0;i<Fido.fileque.size();i++)
{
FileInfo tempinfo = (FileInfo)Fido.fileque.get(i);
templist.addItem(tempinfo.getURL());
}
listView.setList(templist);
templist = null;
}
public boolean receiveEvent(Event e) {
switch (e.type) {
}
return super.receiveEvent(e);
}
public boolean eventWidgetUp(int inWidget, Event e) {
switch (inWidget) {
case Event.DEVICE_BUTTON_CANCEL:
Application.getCurrentApp().returnToLauncher();
return true;
case Event.DEVICE_BUTTON_BACK:
Application.getCurrentApp().returnToLauncher();
return true;
}
return super.eventWidgetUp(inWidget, e);
}
}
<file_sep><?xml version="1.0"?>
<project name="fido" default="run">
<property environment="env"/>
<property name="DANGER_HOME" value="${env.DANGER_HOME}"/>
<property name="APP_CLASS_NAME" value="fido"/>
<property name="APP_PACKAGE_NAME" value="net.exiva.fido"/>
<property name="VERSION" value="3.3"/>
<property name="APP_VERSION_MAJOR" value="3"/>
<property name="APP_VERSION_MINOR" value="1"/>
<property name="APP_VERSION_BUILD" value="0"/>
<property name="BUILD" value="149695" />
<import file="${DANGER_HOME}/tools/build_common.xml"/>
</project>
<file_sep>// Copyright 2001-2005, Danger, Inc. All Rights Reserved.
// This file is subject to the Danger, Inc. Sample Code License,
// which is provided in the file SAMPLE_CODE_LICENSE.
// Copies are also available from http://developer.danger.com/
/*
Todo: Rename the package for your application.
This package name should be replaced with your compa
ny domain
(ie. com.danger for applications Danger writes).
To do this you need to:
1. Move all the java source files from com/example to the new path.
2. Change the package declaration in all the java source files.
3. Change the package declaration in all the .rsrc files.
3. Change the path in the interface and events declarations in all the .rsrc files.
*/
package net.exiva.fido;
import danger.app.Application;
import danger.app.IPCIncoming;
import danger.app.IPCMessage;
import danger.util.DEBUG;
import danger.parsing.*;
import danger.net.*;
import danger.util.*;
import java.io.StringReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import danger.storage.*;
import java.util.Vector;
import danger.system.Hardware;
import danger.ui.MarqueeAlert;
import danger.ui.NotificationManager;
import danger.app.IPCMessage;
import danger.app.Registrar;
import danger.app.Event;
/**
* Implements the main application class.
*/
public class Fido
extends Application
implements Resources, Commands {
static private QueViewer mQue;
private static FileOutputStream outstream;
private static String fetchfilepath;
static public Vector fileque = new Vector();
//* -------------------- Fido
/**
* Creates the main application class.
*/
public Fido() {
// register as a link provider so our app shows up on wheel holding
Registrar.registerProvider("send-via",this,6969,getResources().getBitmap(ID_FETCH_ICON),"Fido");
}
//* -------------------- launch
/**
* Handles the launch event. Called once whenever the application is
* launched.
*/
public void launch() {
fetchfilepath = new String();
// listprovider();
DEBUG.p("Fido: launch");
try
{
fetchfilepath = new String(((String[])StorageManager.getRemovablePaths())[0]);
}
catch (Exception e2)
{
DEBUG.p("Failed to mount path");
fetchfilepath = null;
}
if(fetchfilepath != null)
{
DEBUG.p("Mount Not Null Mount is: "+fetchfilepath);
File basedirs = new File(fetchfilepath+"/DCIM/12seconds/");
try
{
if(!basedirs.exists())
basedirs.mkdir();
DEBUG.p("fetch: mkdir");
}
catch (Exception e2)
{
DEBUG.p("Shit, wtf happened?");
}
}
mQue = QueViewer.makeNew();
mQue.show();
StorageManager.registerStorageDeviceListener(this);
}
//* -------------------- resume
/**
* Handles the resume event. Called automatically whenever the
* application is resumed.
*/
public void resume() {
DEBUG.p("Fido: resume");
}
//* -------------------- Suspend
/**
* Handles the Suspend event. Called automatically whenever the
* application is suspended.
*/
public void suspend() {
DEBUG.p("Fido: suspend");
}
public boolean
receiveEvent(Event e)
{
switch (e.type)
{
case Event.EVENT_STORAGE_DEVICE_STATE_CHANGED :
updateMountPath();
break;
case Event.EVENT_MESSAGE:
if (e.what == 6969)
{
return handleIPCMessage((IPCIncoming)e.argument);
}
break;
default:
break;
}
return (super.receiveEvent(e));
}
public void updateMountPath()
{
DEBUG.p("Fido Updating Mount Path");
try
{
fetchfilepath = new String(((String[])StorageManager.getRemovablePaths())[0]);
}
catch (Exception e2)
{
DEBUG.p("Failed To Mount Path");
fetchfilepath = null;
}
if(fetchfilepath != null)
{
DEBUG.p("Mount Not Null Mount is: "+fetchfilepath);
File basedirs = new File(fetchfilepath+"/Fetched/");
try
{
if(!basedirs.exists())
basedirs.mkdir();
}
catch (Exception e2)
{
}
}
}
private final boolean handleIPCMessage(IPCIncoming incoming)
{
IPCMessage message = incoming.getMessage();
String command = message.findString("action");
if(command.equals("send"))
{
DEBUG.p("Command: "+command);
//String body = message.findString("body");
//String to = message.findString("to");
String body = message.findString("body");
URL tempurl = new URL(body);
//DEBUG.p("file: "+tempurl.getFile());
FileInfo tempinfo = new FileInfo(Hardware.getSystemTime(), body, fetchfilepath+"/Fetched/"+tempurl.getFile());
fileque.add(tempinfo);
DEBUG.p("Fileque is now: "+fileque.size());
HTTPConnection.get(tempinfo.getURL(),"",(short)0,tempinfo.getID());
DEBUG.p("URL: "+message.findString("body"));
tempinfo = null;
QueViewer.updateView();
}
return true;
}
// public static String listprovider() {
// DEBUG.p("Providers: "+Registrar.listAllProviders());
// }
public void networkEvent(Object object)
{
if (object instanceof HTTPTransaction)
{
HTTPTransaction t = (HTTPTransaction) object;
System.err.println("Got network event: " + t);
//System.err.println("Class version: " + t.getClassVersion());
//System.err.println("App class name: " + t.getAppClassName());
//System.err.println("Command: " + t.getCommand());
//System.err.println("Sequence ID: " + t.getSequenceID());
//System.err.println("Bytes: " + t.getBytes());
//System.err.println("String: " + t.getString());
//DEBUG.p("Headers: "+t.getHTTPHeaders());
//System.err.println("Time: " + System.currentTimeMillis());
//DEBUG.p("RESPONSECODE: "+t.getResponse());
//DEBUG.p("String: "+t.getString());
if(t.getSequenceID() == 1)
{
if(t.getResponse() == 200)
{
}
else
{
DEBUG.p("Response "+t.getResponse()+" not 200");
}
}
else
{
if(fetchfilepath != null)
{
FileInfo tempfileinfo;
for(int i=0;i<fileque.size();i++)
{
tempfileinfo = (FileInfo)fileque.get(i);
if(tempfileinfo.getID() == t.getSequenceID())
{
//DEBUG.p("Received file for queued feed: "+tempfileinfo.getID());
fileque.removeElementAt(i);
//DEBUG.p("Vector Size is Now: "+fileque.size());
if(!tempfileinfo.getFile().exists())
{
//DEBUG.p("URL :"+t.getURL());
//String[] p = StorageManager.getRemovablePaths();
File curfile = tempfileinfo.getFile();
try {
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
/////////////////////// must use a \\ instead of / on indexOf if using on sdk
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
File dirs = new File(curfile.getPath().substring(0,curfile.getPath().lastIndexOf("/")));
DEBUG.p("Making dirs: "+dirs.getPath());
dirs.mkdirs();
dirs = null;
//DEBUG.p("Made Directories");
}
catch (Exception e2)
{
DEBUG.p("Directory Creation Failed");
}
try {
curfile.createNewFile();
}
catch (Exception e2)
{
//DEBUG.p("Failed To Make File: "+e2.toString());
}
DEBUG.p("File is: "+curfile.getName());
DEBUG.p("Path: "+curfile.getPath());
//curfile.delete();
//curfile.createNewFile();
//DEBUG.p("Write Length Is: "+ThisText.getText().getBytes().length);
try {
outstream = new FileOutputStream(curfile, false);
//DEBUG.p("FileOutputStream Created");
}
catch (Exception e2) {
DEBUG.p("Failed to create FileOutputStream on file "+e2.toString());
}
try {
outstream.write(t.getBytes());
//DEBUG.p("Stream Written");
}
catch (Exception e2) {
DEBUG.p("Failed to Write to Stream");
}
try {
outstream.close();
IPCMessage ipc = new IPCMessage();
ipc.addItem("action", "rebuild-index");
Registrar.sendMessage("music-player", ipc, null);
// NotificationManager.marqueeAlertNotify(new MarqueeAlert("Fetched: "+tempfileinfo.getURL(),1));
// NotificationManager.marqueeAlertNotify(new MarqueeAlert("Successfully Fetched: "+tempfileinfo.getFile(),Application.getCurrentApp().getResources().getBitmap(ID_SMALL_ICON),1));
NotificationManager.marqueeAlertNotify(new MarqueeAlert("Successfully Fetched: "+curfile.getName(),getResources().getBitmap(ID_MAR_ICON),1));
//DEBUG.p("FILE CLOSED");
}
catch (Exception e2)
{
DEBUG.p("Error closing file: "+e2.toString());
}
}
QueViewer.updateView();
}
}
tempfileinfo = null;
}
else
{
NotificationManager.marqueeAlertNotify(new MarqueeAlert("Fetch Failed: No Mount Point Detected",getResources().getBitmap(ID_MAR_ICON),1));
}
} //end of else
t = null;
} //end of if object HTTPTransaction
//network event ends below
}
}
<file_sep>Fido - Hiptop File Downloader
======
Fido is a file downloader for the Danger Hiptop device.
Usage
-----
Hold down the trackball on a file link you want to download, or use the send to menu.
Misc
-----
Fido is provided in source form only. I will not provide any bundles. I will not update it. If you want to update it, or add features, or bug fixes... please email me so I can have you either send me a patch, or push a patch to the git repository. Thanks.
| 62219b3acae84c23a9dc1f272b3c72f4b2fe18f7 | [
"Markdown",
"Java",
"Ant Build System"
] | 4 | Java | exiva/Fido | 9dbd9b8e4d642547fa758e9b84e617c9d3bf6776 | 5bfbd468d043e460b3cb3506954d88e3d4c29e4f |
refs/heads/master | <file_sep>$(function(){
$('.video__blok-video img.play').hover(function(){
$(this).attr('src','img/playHover.png');
}, function(){
$(this).attr('src','img/play.png');
}
);
$('.video__blok-video img.play').click(function(){
$('.video-popup').fadeIn(800).css('display','flex');
});
$('.video-popup span').click(function(){
$('.video-popup').fadeOut(1000);
});
$('.callWindow').click(function(){
$('.joinIn').fadeIn(800);
});
$('.joinIn span').click(function(){
$('.joinIn').fadeOut(1000);
});
$('.mask').mask("+38(999) 999-99-99");
function valid(form){
$(form).validate({
rules: {
// simple rule, converted to {required:true}
name: "required",
phone: "required",
// compound rule
email: {
required: true,
email: true
}
},
messages: {
name: "Пожалуйста, укажите ваше имя",
phone: "По телефону мы сможем связаться с вами быстрей",
email: {
required: "Нам нужен ваш адрес электронной почты, чтобы связаться с вами",
email: "Ваш адрес электронной почты должен быть в формате <EMAIL>"
}
}
});
}
valid("#Touch-form");
valid("#joinIn");
$(document).scroll(function(){
if($(document).scrollTop() > 300){
$('.ScrollTop').addClass('ScrollTop__activ');
} else {
$('.ScrollTop').removeClass('ScrollTop__activ');
}
});
$(function(){
$("a[href^='#']").click(function(){
var _href = $(this).attr("href");
$("html, body").animate({scrollTop: $(_href).offset().top+"px"});
return false;
});
});
$('.header .fa-bars').click(function(){
$('.header__nav').addClass('header__nav-activ');
});
$('.header__nav .fa-times-circle').click(function(){
$('.header__nav').toggleClass('header__nav-activ');
});
}); | 5d3a8114ba2be28adeaf5f9d4dc726ae7f4f4be9 | [
"JavaScript"
] | 1 | JavaScript | valekutce/yogalandingPage | 50d46018a360318fdef5832936d9a1fa0392b07d | f5a7c4aa58a6743de02eef6d4175a14f40e65144 |
refs/heads/master | <repo_name>NailKhalimov/book-engine-canvas-animation<file_sep>/trash/testingOldCode.js
function getLeftTopCornerPoints(startPoint_x, startPoint_y, endPoint_x, endPoint_y, pageWidth, pageHeight) {
var offsetPagingVector_x = endPoint_x
var offsetPagingVector_y = endPoint_y
var offsetPagingVector_length = Math.sqrt(offsetPagingVector_x * offsetPagingVector_x + offsetPagingVector_y * offsetPagingVector_y)
var A_a = offsetPagingVector_y
var A_b = offsetPagingVector_length
var A_beta = Math.acos(A_a / A_b)
var B_a = startPoint_y
var B_beta = A_beta
var B_b = Math.cos(B_beta) * B_a
var C_a = B_b
var C_beta = Math.PI * 0.5 - B_beta
var C_b = C_a * Math.cos(C_beta)
var D_b = B_b
var D_beta = B_beta
var D_a = D_b * Math.cos(D_beta)
var B_x = C_b
var B_y = D_a
var pagingVector_x = 2 * B_x + offsetPagingVector_x // rename
var pagingVector_y = 2 * B_y + offsetPagingVector_y //rename
var pagingVector_length = offsetPagingVector_length + 2 * B_b
var boundingVector_x = pagingVector_x - pageWidth
var boundingVector_y = pagingVector_y
var
boundingVector_length = Math.sqrt(boundingVector_x * boundingVector_x + boundingVector_y * boundingVector_y)
pagingVector_beta = Math.acos(pagingVector_y / pagingVector_length)
if (boundingVector_length > pageWidth) {
var ratio = (pageWidth / boundingVector_length)
boundingVector_x = boundingVector_x * ratio
boundingVector_y = boundingVector_y * ratio
pagingVector_x = boundingVector_x + pageWidth
pagingVector_y = boundingVector_y
pagingVector_beta = Math.acos(pagingVector_y / pagingVector_length)
pagingVector_length = Math.sqrt(pagingVector_x * pagingVector_x + pagingVector_y * pagingVector_y)
}
var E_a = pagingVector_y
var E_b = pagingVector_length
var E_c = pagingVector_x
var E_beta = Math.acos(E_a / E_b)
var G_b = 0.5 * pagingVector_length
var G_beta = E_beta
var G_a = G_b / Math.cos(G_beta)
var F_a = 0.5 * pagingVector_length
var F_beta = Math.PI * 0.5 - G_beta
var F_b = F_a / Math.cos(F_beta)
var bottomBandPoint_x = 0
var bottomBandPoint_y = G_a
var topBandPoint_x = F_b
var topBandPoint_y = 0
if (bottomBandPoint_y > pageHeight) {
var H_a = bottomBandPoint_y - pageHeight,
var H_alpha = Math.PI * 0.5 - pagingVector_beta
var H_b = H_a * Math.tan(H_alpha)
bottomBandPoint_x = H_b
bottomBandPoint_y = pageHeight
}
return {
topBandPoint_x,
topBandPoint_y,
bottomBandPoint_x,
bottomBandPoint_y,
pagingVector_x,
pagingVector_y
}
}
<file_sep>/js/drawPaging.js
const COUNT = 1000
const COEFFS = []
for (var i = 1; i <= COUNT; i += 1) {
COEFFS[i - 1] = Math.pow(i / COUNT, 1)
}
function drawPaging(ctx, secondContext, x, y, startPoint_x, startPoint_y, endPoint_x, endPoint_y, A, B, C, D, pageWidth, pageHeight) {
startPoint_x -= x
startPoint_y -= y
endPoint_x -= x
endPoint_y -= y
if (startPoint_x < pageWidth) {
startPoint_x = 0
} else {
startPoint_x = pageWidth << 1
}
if (startPoint_y < 0) {
startPoint_y = 0
} else if (startPoint_y > pageHeight) {
startPoint_y = pageHeight
}
if (endPoint_x + x < x) {
var path = new Path2D()
ctx.save()
path.moveTo(0, 0)
path.lineTo(x, 0)
path.lineTo(x, ctx.canvas.height)
path.lineTo(0, ctx.canvas.height)
path.closePath()
ctx.clip(path)
ctx.restore()
endPoint_x = 0
}
if (endPoint_x > pageWidth << 1) {
var path = new Path2D()
ctx.save()
path.moveTo(ctx.canvas.width, 0)
path.lineTo(ctx.canvas.width - y, 0)
path.lineTo(ctx.canvas.width - y, ctx.canvas.height)
path.lineTo(ctx.canvas.width, ctx.canvas.height)
path.closePath()
ctx.clip(path)
ctx.restore()
endPoint_x = pageWidth + pageWidth
}
var {topBandPoint_x, topBandPoint_y, bottomBandPoint_x, bottomBandPoint_y, pagingVector_x, pagingVector_y, effectTopPoint_x, effectTopPoint_y, effectBottomPoint_x, effectBottomPoint_y, effectPoint_x, effectPoint_y, corner, angle, effectAngle, pagingVector_length, effectPoint_length, J_h, ratio, bottomPoint_x, bottomPoint_y} = getAnyCornerPoints(startPoint_x, startPoint_y, endPoint_x, endPoint_y, pageWidth, pageHeight)
ctx.save()
var path = new Path2D()
secondContext.clearRect(0, 0, secondContext.canvas.width, secondContext.canvas.height)
secondContext.save()
switch (corner) {
case LT:
secondContext.translate(0, secondContext.canvas.width)
secondContext.rotate(-effectAngle)
secondContext.translate(-bottomBandPoint_x, -bottomBandPoint_y)
break
case LB:
secondContext.translate(0, secondContext.canvas.height - secondContext.canvas.width)
secondContext.rotate(effectAngle)
secondContext.translate(-topBandPoint_x, -topBandPoint_y)
break
case RT:
secondContext.translate(secondContext.canvas.width, secondContext.canvas.width)
secondContext.rotate(effectAngle)
secondContext.translate(-bottomBandPoint_x, -bottomBandPoint_y)
break
case RB:
secondContext.translate(secondContext.canvas.width, secondContext.canvas.height - secondContext.canvas.width)
secondContext.rotate(-effectAngle)
secondContext.translate(-topBandPoint_x, -topBandPoint_y)
break
}
drawRawPaging(secondContext, corner, A, B, C, D, bookWidth, bookHeight, pagingVector_x, pagingVector_y, angle, effectPoint_x, effectPoint_y, pagingVector_length, topBandPoint_x, topBandPoint_y, bottomBandPoint_x, bottomBandPoint_y, effectTopPoint_x, effectTopPoint_y, effectBottomPoint_x, effectBottomPoint_y, effectPoint_length, ratio, bottomPoint_x, bottomPoint_y)
effectBottomPoint_x += x
effectBottomPoint_y += y
effectTopPoint_x += x
effectTopPoint_y += y
topBandPoint_x += x
topBandPoint_y += y
bottomBandPoint_x += x
bottomBandPoint_y += y
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.save()
var effectPath = new Path2D()
ctx.save()
var shadowClip = new Path2D()
ctx.translate(x, y)
switch (corner) {
case LT:
case LB:
ctx.drawImage(C, 0, 0)
shadowClip.moveTo(topBandPoint_x - x, topBandPoint_y - y)
shadowClip.lineTo(pageWidth, 0)
shadowClip.lineTo(pageWidth, pageHeight)
shadowClip.lineTo(0, pageHeight)
shadowClip.lineTo(bottomBandPoint_x - x, bottomBandPoint_y - y)
break
case RT:
case RB:
ctx.drawImage(B, pageWidth, 0)
break
}
shadowClip.closePath()
ctx.clip(shadowClip)
var gradient = secondContext.createLinearGradient(pageWidth, 0, 0, pageHeight)
gradient.addColorStop(0, 'rgba(0, 0, 0, 0.1)')
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)')
secondContext.globalCompositeOperation = 'source-atop'
ctx.fillStyle = gradient
ctx.fillRect(0, 0, 1000, 1000)
secondContext.globalCompositeOperation = 'source-over'
ctx.globalAlpha = 1
ctx.restore()
switch (corner) {
case LT:
effectPath.moveTo(effectTopPoint_x, effectTopPoint_y)
effectPath.lineTo(effectTopPoint_x + (effectTopPoint_x - effectBottomPoint_x), effectTopPoint_y - (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(ctx.canvas.width, 0)
effectPath.lineTo(ctx.canvas.width, ctx.canvas.height)
effectPath.lineTo(0, ctx.canvas.height)
effectPath.lineTo(effectBottomPoint_x - (effectTopPoint_x - effectBottomPoint_x), effectBottomPoint_y + (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(effectBottomPoint_x, effectBottomPoint_y)
effectPath.closePath()
ctx.clip(effectPath)
ctx.translate(bottomBandPoint_x, bottomBandPoint_y)
ctx.rotate(effectAngle)
ctx.drawImage(canvasRendering, 0, -(secondContext.canvas.width))
break
case LB:
effectPath.moveTo(effectTopPoint_x, effectTopPoint_y)
effectPath.lineTo(effectTopPoint_x + (effectTopPoint_x - effectBottomPoint_x), effectTopPoint_y - (effectBottomPoint_y - effectTopPoint_y))
if (effectTopPoint_x == x) {
effectPath.lineTo(0, 0)
}
effectPath.lineTo(ctx.canvas.width, 0)
effectPath.lineTo(ctx.canvas.width, ctx.canvas.height)
effectPath.lineTo(0, ctx.canvas.height)
effectPath.lineTo(effectBottomPoint_x - (effectTopPoint_x - effectBottomPoint_x), effectBottomPoint_y + (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(effectBottomPoint_x, effectBottomPoint_y)
effectPath.closePath()
ctx.clip(effectPath)
ctx.translate(topBandPoint_x, topBandPoint_y)
ctx.rotate(-effectAngle)
ctx.drawImage(canvasRendering, 0, -secondContext.canvas.height + secondContext.canvas.width)
break
case RT:
effectPath.moveTo(effectTopPoint_x, effectTopPoint_y)
effectPath.lineTo(effectTopPoint_x + (effectTopPoint_x - effectBottomPoint_x), effectTopPoint_y - (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(0, 0)
effectPath.lineTo(0, ctx.canvas.height)
effectPath.lineTo(ctx.canvas.width, ctx.canvas.height)
effectPath.lineTo(effectBottomPoint_x - (effectTopPoint_x - effectBottomPoint_x), effectBottomPoint_y + (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(effectBottomPoint_x, effectBottomPoint_y)
effectPath.closePath()
ctx.clip(effectPath)
ctx.translate(bottomBandPoint_x, bottomBandPoint_y)
ctx.rotate(-effectAngle)
ctx.drawImage(canvasRendering, -secondContext.canvas.width, -secondContext.canvas.width)
break
case RB:
effectPath.moveTo(effectTopPoint_x, effectTopPoint_y)
effectPath.lineTo(effectTopPoint_x + (effectTopPoint_x - effectBottomPoint_x), effectTopPoint_y - (effectBottomPoint_y - effectTopPoint_y))
if (effectTopPoint_x - x == bookWidth) {
effectPath.lineTo(ctx.canvas.width, 0)
}
effectPath.lineTo(0, 0)
effectPath.lineTo(0, ctx.canvas.height)
effectPath.lineTo(ctx.canvas.width, ctx.canvas.height)
effectPath.lineTo(effectBottomPoint_x - (effectTopPoint_x - effectBottomPoint_x), effectBottomPoint_y + (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(effectBottomPoint_x, effectBottomPoint_y)
effectPath.closePath()
ctx.clip(effectPath)
ctx.translate(topBandPoint_x, topBandPoint_y)
ctx.rotate(effectAngle)
ctx.drawImage(canvasRendering, -secondContext.canvas.width, -secondContext.canvas.height + secondContext.canvas.width)
break
}
ctx.restore()
ctx.save()
var effectOffset = 0
const vectorPeace = J_h / COUNT
switch (corner) {
case LT:
ctx.translate(bottomBandPoint_x, bottomBandPoint_y)
ctx.rotate(effectAngle)
ctx.translate(0, -secondContext.canvas.width)
for (var i = 0; i < COUNT; i += 1) {
effectOffset += vectorPeace * COEFFS[COUNT - i - 1]
ctx.drawImage(
canvasRendering,
J_h - vectorPeace * (i + 1),
0,
vectorPeace,
secondContext.canvas.height,
J_h - effectOffset,
0,
vectorPeace * COEFFS[COUNT - i - 1],
secondContext.canvas.height
)
}
break
case LB:
ctx.translate(topBandPoint_x, topBandPoint_y)
ctx.rotate(-effectAngle)
ctx.translate(0, -canvasRendering.height + secondContext.canvas.width)
for (var i = 0; i < COUNT; i += 1) {
effectOffset += vectorPeace * COEFFS[COUNT - i - 1]
ctx.drawImage(
canvasRendering,
J_h - vectorPeace * (i + 1),
0,
vectorPeace,
secondContext.canvas.height,
J_h - effectOffset,
0,
vectorPeace * COEFFS[COUNT - i - 1],
secondContext.canvas.height
)
}
break
case RT:
ctx.translate(bottomBandPoint_x, bottomBandPoint_y)
ctx.rotate(-effectAngle)
ctx.translate(-secondContext.canvas.width, -secondContext.canvas.width)
for (var i = 0; i < COUNT; i += 1) {
effectOffset += vectorPeace * COEFFS[COUNT - i - 1]
if (i == 0) {
ctx.drawImage(
canvasRendering,
(secondContext.canvas.width - J_h),
0,
vectorPeace,
secondContext.canvas.height,
(secondContext.canvas.width - J_h),
0,
vectorPeace * COEFFS[COUNT - i - 1],
secondContext.canvas.height
)
}
ctx.drawImage(
canvasRendering,
(secondContext.canvas.width - J_h) + vectorPeace * (i + 1),
0,
vectorPeace,
secondContext.canvas.height,
(secondContext.canvas.width - J_h) + effectOffset,
0,
vectorPeace * COEFFS[COUNT - i - 1],
secondContext.canvas.height
)
}
break
case RB:
ctx.translate(topBandPoint_x, topBandPoint_y)
ctx.rotate(effectAngle)
ctx.translate(-secondContext.canvas.width, -canvasRendering.height + secondContext.canvas.width)
for (var i = 0; i < COUNT; i += 1) {
effectOffset += vectorPeace * COEFFS[COUNT - i - 1]
if (i == 0) {
ctx.drawImage(
canvasRendering,
(secondContext.canvas.width - J_h),
0,
vectorPeace,
secondContext.canvas.height,
(secondContext.canvas.width - J_h),
0,
vectorPeace * COEFFS[COUNT - i - 1],
secondContext.canvas.height
)
}
ctx.drawImage(
canvasRendering,
(secondContext.canvas.width - J_h) + vectorPeace * (i + 1),
0,
vectorPeace,
secondContext.canvas.height,
(secondContext.canvas.width - J_h) + effectOffset,
0,
vectorPeace * COEFFS[COUNT - i - 1],
secondContext.canvas.height
)
}
break
}
ctx.restore()
// ctx.save()
// ctx.translate(x, y)
// ctx.beginPath()
// ctx.arc(bottomPoint_x, bottomPoint_y, 4, 0, 2 * Math.PI, false)
// ctx.setLineDash([3, 3])
// ctx.strokeStyle = '#333'
// ctx.stroke()
// ctx.closePath()
// ctx.restore()
//
// secondContext.save()
// secondContext.beginPath()
// secondContext.moveTo(secondContext.canvas.width - J_h, 0)
// secondContext.lineTo(secondContext.canvas.width - J_h, secondContext.canvas.height)
// secondContext.strokeStyle = '#333'
// secondContext.stroke()
// secondContext.closePath()
// secondContext.restore()
// //
// ctx.save()
// ctx.translate(x, y)
// ctx.beginPath()
// ctx.font = '10px Georgia'
// //ctx.fillText('angle: ' + effectAngle, effectTopPoint_x - x, effectTopPoint_y - y - 30)
// ctx.arc(effectTopPoint_x - x, effectTopPoint_y - y, 4, 0, 2 * Math.PI, false)
// ctx.strokeStyle = '#ff0000'
// ctx.stroke()
// ctx.closePath()
// ctx.restore()
//
// ctx.save()
// ctx.translate(x, y)
// ctx.beginPath()
// ctx.font = '10px Georgia'
// //ctx.fillText('angle: ' + effectAngle, effectTopPoint_x - x, effectTopPoint_y - y - 30)
// ctx.arc(0, NoName_y, 4, 0, 2 * Math.PI, false)
// ctx.strokeStyle = '#ff0000'
// ctx.stroke()
// ctx.closePath()
// ctx.restore()
//
// ctx.save()
// ctx.translate(x, y)
// ctx.beginPath()
// ctx.font = '10px Georgia'
// //ctx.fillText('angle: ' + effectAngle, effectTopPoint_x - x, effectTopPoint_y - y - 30)
// ctx.arc(topBandPoint_x - x, topBandPoint_y - y, 4, 0, 2 * Math.PI, false)
// ctx.strokeStyle = '#ff0000'
// ctx.stroke()
// ctx.closePath()
// ctx.restore()
//
// var newTriangle_b_or_y = triangleOfEdgeBottomPoint_c * Math.sin(Math.PI * 0.5 - angle)
// var newTriangle_a_or_x = Math.sqrt((triangleOfEdgeBottomPoint_c * triangleOfEdgeBottomPoint_c) - (newTriangle_b_or_y * newTriangle_b_or_y)) + bottomBandPoint_x
// newTriangle_b_or_y += pageHeight
// console.log(newTriangle_b_or_y)
// console.log(newTriangle_a_or_x)
// ctx.save()
// ctx.translate(x, y)
// ctx.beginPath()
// ctx.arc(newTriangle_a_or_x, newTriangle_b_or_y, 4, 0, 2 * Math.PI, false)
// ctx.strokeStyle = '#ff0000'
// ctx.stroke()
// ctx.closePath()
// ctx.restore()
//
// ctx.save()
// ctx.translate(x, y)
// ctx.beginPath()
// ctx.arc(effectBottomPoint_x - x, effectBottomPoint_y - y, 4, 0, 2 * Math.PI, false)
// ctx.strokeStyle = '#ff0001'
// ctx.stroke()
// ctx.closePath()
// ctx.restore()
// //
// ctx.save()
// ctx.translate(x, y)
// ctx.beginPath()
// ctx.arc(effectPoint_x, effectPoint_y, 4, 0, 2 * Math.PI, false)
// ctx.strokeStyle = '#ff0001'
// ctx.stroke()
// ctx.closePath()
// ctx.restore()
//
// var secondCanvas = document.getElementById('secondCanvas')
// var secCtx = secondCanvas.getContext('2d')
//
// secCtx.save()
// secCtx.translate(x, y)
// secCtx.clearRect(0, 0, secCtx.canvas.width, secCtx.canvas.height)
// secCtx.drawImage(D, 0, 0)
// secCtx.drawImage(A, pageWidth, 0)
// secCtx.restore()
}
// console.log(ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height))
// ctx.drawImage(trim(ctx), 0, 0)
function trim(c) {
var ctx = c,
copy = document.createElement('canvas').getContext('2d'),
pixels = ctx.getImageData(0, 0, c.canvas.width, c.canvas.height),
l = pixels.data.length,
i,
bound = {
top: null,
left: null,
right: null,
bottom: null
},
x, y;
for (i = 0; i < l; i += 4) {
if (pixels.data[i+3] !== 0) {
x = (i / 4) % c.canvas.width;
y = ~~((i / 4) / c.canvas.width);
if (bound.top === null) {
bound.top = y;
}
if (bound.left === null) {
bound.left = x;
} else if (x < bound.left) {
bound.left = x;
}
if (bound.right === null) {
bound.right = x;
} else if (bound.right < x) {
bound.right = x;
}
if (bound.bottom === null) {
bound.bottom = y;
} else if (bound.bottom < y) {
bound.bottom = y;
}
}
}
var trimHeight = bound.bottom - bound.top
var trimWidth = bound.right - bound.left
var trimmed = c.getImageData(bound.left, bound.top, trimWidth, trimHeight);
copy.canvas.width = trimWidth;
copy.canvas.height = trimHeight;
copy.putImageData(trimmed, 0, 0);
// open new window with trimmed image:
return copy.canvas;
}
<file_sep>/trash/AnyCorner.js
function getAnyCornerPoints(startPoint, endPoint, pageWidth, pageHeight) {
var data
if (startPoint.x > pageWidth) {
if (endPoint.y > startPoint.y) {
/* Перевод с правой на левую сторону страницы */
startPoint.x = 960
startPoint.y = startPoint.y
endPoint.x = pageWidth * 2 - endPoint.x
endPoint.y = endPoint.y
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = pageWidth * 2 - data.topBandPoint.x
data.topBandPoint.y = data.topBandPoint.y
data.bottomBandPoint.x = pageWidth * 2 - data.bottomBandPoint.x
data.bottomBandPoint.y = data.bottomBandPoint.y
data.pagingVector.x = pageWidth * 2 - data.pagingVector.x
data.pagingVector.y = data.pagingVector.y
startPoint.x = 960
startPoint.y = startPoint.y
endPoint.x = pageWidth * 2 - endPoint.x
endPoint.y = endPoint.y
} else {
/* Перевод с правой на левую сторону страницы */
// startPoint.x = 0
startPoint.y = startPoint.y
endPoint.x = pageWidth * 2 - endPoint.x
endPoint.y = endPoint.y
/* Зеркальная интерпретация вектора для низа */
// startPoint.x = 0
startPoint.y = pageHeight - startPoint.y
endPoint.x = endPoint.x
endPoint.y = pageHeight - endPoint.y
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = pageWidth * 2 - data.topBandPoint.x
data.topBandPoint.y = pageHeight
data.bottomBandPoint.x = pageWidth * 2 - data.bottomBandPoint.x
data.bottomBandPoint.y = pageHeight - data.bottomBandPoint.y
data.pagingVector.x = pageWidth * 2 - data.pagingVector.x
data.pagingVector.y = pageHeight - data.pagingVector.y
// startPoint.x = 0
startPoint.y = pageHeight - startPoint.y
endPoint.x = endPoint.x
endPoint.y = pageHeight - endPoint.y
}
if (startPoint.y == endPoint.y) {
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = (pageWidth * 2 - endPoint.x) + endPoint.x * 0.5
data.topBandPoint.y = 0
data.bottomBandPoint.x = (pageWidth * 2 - endPoint.x) + endPoint.x * 0.5
data.bottomBandPoint.y = pageHeight
data.pagingVector.x = pageWidth * 2 - endPoint.x
data.pagingVector.y = 0
}
} else {
if (endPoint.y > startPoint.y) {
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
} else {
startPoint.x = 0
startPoint.y = pageHeight - startPoint.y
endPoint.x = endPoint.x
endPoint.y = pageHeight - endPoint.y
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = data.topBandPoint.x
data.topBandPoint.y = pageHeight
data.bottomBandPoint.x = data.bottomBandPoint.x
data.bottomBandPoint.y = pageHeight - data.bottomBandPoint.y
data.pagingVector.x = data.pagingVector.x
data.pagingVector.y = pageHeight - data.pagingVector.y
startPoint.x = 0
startPoint.y = pageHeight - startPoint.y
endPoint.x = endPoint.x
endPoint.y = pageHeight - endPoint.y
}
if (startPoint.y == endPoint.y) {
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = endPoint.x * 0.5
data.topBandPoint.y = 0
data.bottomBandPoint.x = endPoint.x * 0.5
data.bottomBandPoint.y = pageHeight
data.pagingVector.x = endPoint.x
data.pagingVector.y = 0
}
}
return data
}
<file_sep>/trash/save.js
function getCornerData(startPoint, endPoint, pageWidth) {
var offsetPagingVector = {
x: endPoint.x,
y: endPoint.y - startPoint.y
}
offsetPagingVector.length = calcVectorLength(offsetPagingVector)
var A = {
a: offsetPagingVector.y,
b: offsetPagingVector.length
}
A.beta = Math.acos(A.a / A.b)
var B = {
a: startPoint.y,
beta: A.beta
}
B.b = Math.cos(B.beta) * B.a
var C = {
a: B.b,
beta: Math.PI * 0.5 - B.beta
}
C.b = C.a * Math.cos(C.beta)
var D = {
b: B.b,
beta: B.beta
}
D.a = D.b * Math.cos(D.beta)
/* Найдем координаты части вектора pagingVector */
B.x = C.b
B.y = D.a
/* ---- */
var pagingVector = {
x: 2 * B.x + offsetPagingVector.x,
y: 2 * B.y + offsetPagingVector.y,
length: offsetPagingVector.length + 2 * B.b
}
var boundedVector = {
x: pagingVector.x - pageWidth,
y: pagingVector.y
}
boundedVector.length = calcVectorLength(boundedVector)
if (boundedVector.length > pageWidth) {
var ratio = (pageWidth / boundedVector.length)
boundedVector.x = boundedVector.x * ratio
boundedVector.y = boundedVector.y * ratio
pagingVector.x = boundedVector.x + pageWidth
pagingVector.y = boundedVector.y
}
console.log('paging:')
console.log(pagingVector)
console.log('boudnded:')
console.log(boundedVector)
var bottomBandPoint = {
x: 0,
y: startPoint.y + ((0.5 * offsetPagingVector.length) / Math.cos(A.beta))
}
var ratio = (offsetPagingVector.length + B.b) / Math.cos(Math.PI * 0.5 - A.beta)
var topBandPoint = {
x: (0.5 * offsetPagingVector.length + B.b) / Math.cos(Math.PI * 0.5 - A.beta),
y: 0
}
return {
topBandPoint,
bottomBandPoint,
pagingVector,
boundedVector,
A,
B,
C,
D
}
}
function calcVectorLength(vector) {
return Math.sqrt(vector.x * vector.x + vector.y * vector.y)
}
<file_sep>/trash/saveScripts.js
function getAnyCornerPoints(startPoint, endPoint, pageWidth, pageHeight) {
var data
var bookWidth = bookWidth
if (startPoint.x > pageWidth) {
if (endPoint.y > startPoint.y) {
/* Перевод с правой на левую сторону страницы */
startPoint.x = 960
startPoint.y = startPoint.y
endPoint.x = bookWidth - endPoint.x
endPoint.y = endPoint.y
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = bookWidth - data.topBandPoint.x
data.topBandPoint.y = data.topBandPoint.y
data.bottomBandPoint.x = bookWidth - data.bottomBandPoint.x
data.bottomBandPoint.y = data.bottomBandPoint.y
data.pagingVector.x = bookWidth - data.pagingVector.x
data.pagingVector.y = data.pagingVector.y
startPoint.x = 960
startPoint.y = startPoint.y
endPoint.x = bookWidth - endPoint.x
endPoint.y = endPoint.y
} else {
/* Перевод с правой на левую сторону страницы */
// startPoint.x = 0
startPoint.y = startPoint.y
endPoint.x = bookWidth - endPoint.x
endPoint.y = endPoint.y
/* Зеркальная интерпретация вектора для низа */
// startPoint.x = 0
startPoint.y = pageHeight - startPoint.y
endPoint.x = endPoint.x
endPoint.y = pageHeight - endPoint.y
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = bookWidth - data.topBandPoint.x
data.topBandPoint.y = pageHeight
data.bottomBandPoint.x = bookWidth - data.bottomBandPoint.x
data.bottomBandPoint.y = pageHeight - data.bottomBandPoint.y
data.pagingVector.x = bookWidth - data.pagingVector.x
data.pagingVector.y = pageHeight - data.pagingVector.y
// startPoint.x = 0
startPoint.y = pageHeight - startPoint.y
endPoint.x = endPoint.x
endPoint.y = pageHeight - endPoint.y
}
if (startPoint.y == endPoint.y) {
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = (bookWidth - endPoint.x) + endPoint.x * 0.5
data.topBandPoint.y = 0
data.bottomBandPoint.x = (bookWidth - endPoint.x) + endPoint.x * 0.5
data.bottomBandPoint.y = pageHeight
data.pagingVector.x = bookWidth - endPoint.x
data.pagingVector.y = 0
}
} else {
if (endPoint.y > startPoint.y) {
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
} else {
startPoint.x = 0
startPoint.y = pageHeight - startPoint.y
endPoint.x = endPoint.x
endPoint.y = pageHeight - endPoint.y
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = data.topBandPoint.x
data.topBandPoint.y = pageHeight
data.bottomBandPoint.x = data.bottomBandPoint.x
data.bottomBandPoint.y = pageHeight - data.bottomBandPoint.y
data.pagingVector.x = data.pagingVector.x
data.pagingVector.y = pageHeight - data.pagingVector.y
startPoint.x = 0
startPoint.y = pageHeight - startPoint.y
endPoint.x = endPoint.x
endPoint.y = pageHeight - endPoint.y
}
if (startPoint.y == endPoint.y) {
data = getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight)
data.topBandPoint.x = endPoint.x * 0.5
data.topBandPoint.y = 0
data.bottomBandPoint.x = endPoint.x * 0.5
data.bottomBandPoint.y = pageHeight
data.pagingVector.x = endPoint.x
data.pagingVector.y = 0
}
}
return data
}
function getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight) {
var offsetPagingVector = {
x: endPoint.x,
y: endPoint.y - startPoint.y
}
offsetPagingVector.length = calcVectorLength(offsetPagingVector)
var A = {
a: offsetPagingVector.y,
b: offsetPagingVector.length
}
A.beta = Math.acos(A.a / A.b)
var B = {
a: startPoint.y,
beta: A.beta
}
B.b = Math.cos(B.beta) * B.a
var C = {
a: B.b,
beta: Math.PI * 0.5 - B.beta
}
C.b = C.a * Math.cos(C.beta)
var D = {
b: B.b,
beta: B.beta
}
D.a = D.b * Math.cos(D.beta)
/* Найдем координаты части вектора pagingVector */
B.x = C.b //rename
B.y = D.a //
/* ---- */
var pagingVector = {
x: 2 * B.x + offsetPagingVector.x, // rename
y: 2 * B.y + offsetPagingVector.y, //rename
length: offsetPagingVector.length + 2 * B.b
}
var boundingVector = {
x: pagingVector.x - pageWidth,
y: pagingVector.y
}
boundingVector.length = calcVectorLength(boundingVector)
pagingVector.beta = Math.acos(pagingVector.y / pagingVector.length)
if (boundingVector.length > pageWidth) {
var ratio = (pageWidth / boundingVector.length)
boundingVector.x = boundingVector.x * ratio
boundingVector.y = boundingVector.y * ratio
pagingVector.x = boundingVector.x + pageWidth
pagingVector.y = boundingVector.y
pagingVector.beta = Math.acos(pagingVector.y / pagingVector.length)
pagingVector.length = calcVectorLength(pagingVector)
}
var E = {
a: pagingVector.y,
b: pagingVector.length,
c: pagingVector.x
}
E.beta = Math.acos(E.a / E.b)
var G = {
b: 0.5 * pagingVector.length,
beta: E.beta
}
G.a = G.b / Math.cos(G.beta)
var F = {
a: 0.5 * pagingVector.length,
beta: Math.PI * 0.5 - G.beta
}
F.b = F.a / Math.cos(F.beta)
var bottomBandPoint = {
x: 0,
y: G.a
}
var topBandPoint = {
x: F.b,
y: 0
}
if (bottomBandPoint.y > pageHeight) {
var H = {
a: bottomBandPoint.y - pageHeight,
alpha: Math.PI * 0.5 - pagingVector.beta
}
H.b = H.a * Math.tan(H.alpha)
bottomBandPoint.x = H.b
bottomBandPoint.y = pageHeight
}
return {
topBandPoint,
bottomBandPoint,
pagingVector
}
}
function calcVectorLength(vector) {
return Math.sqrt(vector.x * vector.x + vector.y * vector.y)
}
/* upd 22.01*/
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
var fingerOffset = {x: 0, y: 100}
// const A = new Image(480, 720)
// img.src = './src/img.jpg'
//
// const B = new Image(480, 720)
// img.src = './src/img.jpg'
//
// const C = new Image(480, 720)
// img.src = './src/img.jpg'
//
// const D = new Image(480, 720)
// img.src = './src/img.jpg'
//drawPaging(ctx, x, y, fingerOffset.x, fingerOffset.y, event.clientX, event.clientY, A, B, C, D, 480, 720)
canvas.addEventListener('mousemove', function(event) {
var data = getAnyCornerPoints(fingerOffset.x, fingerOffset.y, event.clientX, event.clientY, 320, 480)
paint(fingerOffset, {x: event.clientX, y: event.clientY}, data)
})
canvas.addEventListener('click', function(event) {
fingerOffset = {x: 0, y: event.clientY}
if (event.clientX > 320) {
fingerOffset = {x: 640, y: event.clientY}
}
var data = getAnyCornerPoints(fingerOffset.x, fingerOffset.y, event.clientX, event.clientY, 320, 480)
paint(fingerOffset, {x: event.clientX, y: event.clientY}, data)
})
function paint(startPoint, endPoint, {topBandPoint_x, topBandPoint_y, bottomBandPoint_x, bottomBandPoint_y, pagingVector_x, pagingVector_y, corner, angle}) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.save()
//ctx.drawImage(img, pagingVector_x, pagingVector_y)
var path = new Path2D()
switch (corner) {
case LT:
path.moveTo(topBandPoint_x, topBandPoint_y)
path.lineTo(canvas.width, 0)
path.lineTo(canvas.width, canvas.height)
if (bottomBandPoint_y < canvas.height) {
path.lineTo(0, canvas.height)
}
path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
path.closePath()
break
case LB:
path.moveTo(topBandPoint_x, topBandPoint_y)
if (topBandPoint_y > 0) {
path.lineTo(0, 0)
}
path.lineTo(canvas.width, 0)
path.lineTo(canvas.width, canvas.height)
path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
path.closePath()
break
case RT:
path.moveTo(0, 0)
path.lineTo(topBandPoint_x, topBandPoint_y)
path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
if (bottomBandPoint_x === canvas.width) {
path.lineTo(canvas.width, canvas.height)
}
path.lineTo(0, canvas.height)
path.closePath()
break
case RB:
path.moveTo(0, 0)
if (topBandPoint_x === canvas.width) {
path.lineTo(canvas.width, 0)
}
path.lineTo(topBandPoint_x, topBandPoint_y)
path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
path.lineTo(0, canvas.height)
path.closePath()
break
}
ctx.clip(path)
ctx.translate(pagingVector_x, pagingVector_y)
ctx.rotate(angle)
switch (corner) {
case LT:
ctx.drawImage(img, -canvas.width * 0.5, 0)
break
case LB:
ctx.drawImage(img, -canvas.width * 0.5, -canvas.height)
break
case RT:
ctx.drawImage(img, 0, 0)
break
case RB:
ctx.drawImage(img, 0, -canvas.height)
break
}
//ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.restore()
ctx.beginPath()
ctx.moveTo(startPoint.x, startPoint.y)
ctx.lineTo(endPoint.x, endPoint.y)
ctx.strokeStyle = '#ff0000';
ctx.setLineDash([0, 0])
ctx.stroke()
ctx.closePath()
//
// ctx.beginPath()
// ctx.moveTo(0, 0)
// ctx.lineTo(pagingVector.x, pagingVector.y)
// ctx.strokeStyle = '#1E90FF';
// ctx.setLineDash([0, 0])
// ctx.stroke()
// ctx.closePath()
// ctx.beginPath()
// ctx.moveTo(canvas.width, 0)
// ctx.lineTo(boundingVector.x + 480, boundingVector.y)
// ctx.strokeStyle = '#008000';
// ctx.setLineDash([0, 0])
// ctx.stroke()
// ctx.closePath()
ctx.beginPath()
ctx.moveTo(bottomBandPoint_x, bottomBandPoint_y)
//ctx.lineTo(pagingVector.x, pagingVector.y)//Линия от нижней точки до центральной
//ctx.lineTo(topBandPoint_x, topBandPoint.y)//Линия от центральной точки до верхней
//ctx.lineTo(bottomBandPoint.x, bottomBandPoint.y)//Линия от верхней точки до нижней
ctx.arc(pagingVector_x, pagingVector_y, 4, 0, 2 * Math.PI, false)
ctx.arc(topBandPoint_x, topBandPoint_y, 4, 0, 2 * Math.PI, false)
ctx.arc(bottomBandPoint_x, bottomBandPoint_y, 4, 0, 2 * Math.PI, false)
ctx.setLineDash([3, 3])
ctx.strokeStyle = '#333'
ctx.stroke()
ctx.closePath()
// console.log('bottom:')
// console.log(bottomBandPoint_x, bottomBandPoint_y)
// console.log('top')
// console.log(topBandPoint_x, topBandPoint_y)
//
// function drawT(T, color, x, y) {
// ctx.beginPath()
// ctx.strokeStyle = color
// ctx.translate(x, y)
// ctx.moveTo(0, 0)
// ctx.lineTo(0, -T.a)
// ctx.translate(0, -T.a)
// ctx.rotate(Math.PI - T.beta)
// ctx.lineTo(0, -T.b)
// ctx.translate(0, -T.b)
// ctx.rotate(Math.PI - T.gamma)
// ctx.lineTo(0, -T.c)
// ctx.stroke()
// ctx.setTransform(1, 0, 0, 1, 0, 0)
// ctx.closePath()
// }
//drawT(A, '#00FF00', startPoint_x, endPoint.y)
//drawT(B, '#00BFE0', bottomBandPoint.x, bottomBandPoint.y)
//drawT(C, '#4510A0', bottomBandPoint.x, bottomBandPoint.y)
}
/*OPTIMAZE CODE*/
// endPoint_y = endPoint_y - startPoint_y
// var offsetPagingVector_length_or_G_cosBeta = Math.sqrt(endPoint_x * endPoint_x + endPoint_y * endPoint_y)
//
// var boundingVector_x_or_B_cosBeta_or_G_minusBeta = endPoint_y / offsetPagingVector_length_or_G_cosBeta
// var bottomBandPoint_x_or_B_b_x2 = boundingVector_x_or_B_cosBeta_or_G_minusBeta * startPoint_y * 2
//
// /* Координаты части вектора pagingVector */
//
// var pagingVector_x = bottomBandPoint_x_or_B_b_x2 * Math.cos(Math.PI * 0.5 - Math.acos(boundingVector_x_or_B_cosBeta_or_G_minusBeta)) + endPoint_x
// var pagingVector_y = bottomBandPoint_x_or_B_b_x2 * boundingVector_x_or_B_cosBeta_or_G_minusBeta + endPoint_y
//
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = pagingVector_x - pageWidth
// startPoint_y = Math.sqrt(boundingVector_x_or_B_cosBeta_or_G_minusBeta * boundingVector_x_or_B_cosBeta_or_G_minusBeta + pagingVector_y * pagingVector_y)
//
// if (startPoint_y > pageWidth) {
//
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = boundingVector_x_or_B_cosBeta_or_G_minusBeta * (pageWidth / startPoint_y)
//
// pagingVector_x = boundingVector_x_or_B_cosBeta_or_G_minusBeta + pageWidth
// pagingVector_y = pagingVector_y * (pageWidth / startPoint_y)
//
// endPoint_y = Math.sqrt(pagingVector_x * pagingVector_x + pagingVector_y * pagingVector_y)
// } else {
// endPoint_y = offsetPagingVector_length_or_G_cosBeta + bottomBandPoint_x_or_B_b_x2
// }
//
// offsetPagingVector_length_or_G_cosBeta = pagingVector_y / endPoint_y
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = Math.PI * 0.5 - Math.acos(offsetPagingVector_length_or_G_cosBeta)
//
// bottomBandPoint_x_or_B_b_x2 = 0
// startPoint_y = 0.5 * endPoint_y / offsetPagingVector_length_or_G_cosBeta
//
// if (startPoint_y > pageHeight) {
// bottomBandPoint_x_or_B_b_x2 = (startPoint_y - pageHeight) * Math.tan(boundingVector_x_or_B_cosBeta_or_G_minusBeta)
// startPoint_y = pageHeight
// }
//
// topBandPoint_x = 0.5 * endPoint_y / Math.cos(boundingVector_x_or_B_cosBeta_or_G_minusBeta)
// topBandPoint_y = 0
// bottomBandPoint_x = bottomBandPoint_x_or_B_b_x2
// bottomBandPoint_y = startPoint_y
/* -upd 27.01- */
// function paint(startPoint, endPoint, {topBandPoint_x, topBandPoint_y, bottomBandPoint_x, bottomBandPoint_y, pagingVector_x, pagingVector_y, corner, angle}) {
//
// ctx.clearRect(0, 0, canvas.width, canvas.height)
// ctx.save()
// ctx.translate(pageTranslateX, pageTranslateY)
// //ctx.drawImage(img, pagingVector_x, pagingVector_y)
// var path = new Path2D()
// switch (corner) {
// case LT:
// path.moveTo(topBandPoint_x, topBandPoint_y)
//
// path.lineTo(canvas.width, 0)
// path.lineTo(canvas.width, canvas.height)
// if (bottomBandPoint_y < canvas.height) {
// path.lineTo(0, canvas.height)
// }
// path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
// path.closePath()
// break
// case LB:
// path.moveTo(topBandPoint_x, topBandPoint_y)
// if (topBandPoint_y > 0) {
// path.lineTo(0, 0)
// }
// path.lineTo(canvas.width, 0)
// path.lineTo(canvas.width, canvas.height)
// path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
// path.closePath()
// break
// case RT:
// path.moveTo(0, 0)
// path.lineTo(topBandPoint_x, topBandPoint_y)
// path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
// if (bottomBandPoint_x === bookWidth) {
// path.lineTo(bookWidth, bookHeight)
// }
// path.lineTo(0, bookHeight)
// path.closePath()
// break
// case RB:
// path.moveTo(0, 0)
// if (topBandPoint_x === bookWidth) {
// path.lineTo(bookWidth, 0)
// }
// path.lineTo(topBandPoint_x, topBandPoint_y)
// path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
// path.lineTo(0, bookHeight)
// path.closePath()
// break
// }
//
// ctx.clip(path)
//
// ctx.translate(pagingVector_x, pagingVector_y)
//
// ctx.rotate(angle)
// switch (corner) {
// case LT:
// ctx.drawImage(img, -bookWidth * 0.5, 0)
// break
// case LB:
// ctx.drawImage(img, -bookWidth * 0.5, -bookHeight)
// break
// case RT:
// ctx.drawImage(img, 0, 0)
// break
// case RB:
// ctx.drawImage(img, 0, -bookHeight)
// break
// }
// //ctx.setTransform(1, 0, 0, 1, 0, 0)
// ctx.restore()
//
// ctx.save()
// ctx.translate(pageTranslateX, pageTranslateY)
// ctx.beginPath()
// ctx.moveTo(startPoint.x, startPoint.y)
// ctx.lineTo(endPoint.x, endPoint.y)
// ctx.strokeStyle = '#ff0000';
// ctx.setLineDash([0, 0])
// ctx.stroke()
// ctx.closePath()
//
// ctx.beginPath()
// ctx.moveTo(0, 0)
// ctx.lineTo(pagingVector.x, pagingVector.y)
// ctx.strokeStyle = '#1E90FF';
// ctx.setLineDash([0, 0])
// ctx.stroke()
// ctx.closePath()
//
// ctx.beginPath()
// ctx.moveTo(bookWidth, 0)
// ctx.lineTo(boundingVector.x + 480, boundingVector.y)
// ctx.strokeStyle = '#008000';
// ctx.setLineDash([0, 0])
// ctx.stroke()
// ctx.closePath()
//
// ctx.beginPath()
// ctx.moveTo(bottomBandPoint_x, bottomBandPoint_y)
// ctx.lineTo(pagingVector.x, pagingVector.y)//Линия от нижней точки до центральной
// ctx.lineTo(topBandPoint_x, topBandPoint.y)//Линия от центральной точки до верхней
// ctx.lineTo(bottomBandPoint.x, bottomBandPoint.y)//Линия от верхней точки до нижней
// ctx.arc(pagingVector_x, pagingVector_y, 4, 0, 2 * Math.PI, false)
// ctx.arc(topBandPoint_x, topBandPoint_y, 4, 0, 2 * Math.PI, false)
// ctx.arc(bottomBandPoint_x, bottomBandPoint_y, 4, 0, 2 * Math.PI, false)
// ctx.setLineDash([3, 3])
// ctx.strokeStyle = '#333'
// ctx.stroke()
// ctx.closePath()
// ctx.restore()
//
// console.log('bottom:')
// console.log(bottomBandPoint_x, bottomBandPoint_y)
// console.log('top')
// console.log(topBandPoint_x, topBandPoint_y)
//
// function drawT(T, color, x, y) {
// ctx.beginPath()
// ctx.strokeStyle = color
// ctx.translate(x, y)
// ctx.moveTo(0, 0)
// ctx.lineTo(0, -T.a)
// ctx.translate(0, -T.a)
// ctx.rotate(Math.PI - T.beta)
// ctx.lineTo(0, -T.b)
// ctx.translate(0, -T.b)
// ctx.rotate(Math.PI - T.gamma)
// ctx.lineTo(0, -T.c)
// ctx.stroke()
// ctx.setTransform(1, 0, 0, 1, 0, 0)
// ctx.closePath()
// }
// drawT(A, '#00FF00', startPoint_x, endPoint.y)
// drawT(B, '#00BFE0', bottomBandPoint.x, bottomBandPoint.y)
// drawT(C, '#4510A0', bottomBandPoint.x, bottomBandPoint.y)
//}
/*28.01.2017 11:22*/
/*
const COUNT = 1000
const COEFFS = []
for (var i = 1; i <= COUNT; i += 1) {
COEFFS[i - 1] = Math.pow(i / COUNT, 1)
}
function drawPaging(ctx, x, y, startPoint_x, startPoint_y, endPoint_x, endPoint_y, A, B, C, D, pageWidth, pageHeight) {
startPoint_x -= x
startPoint_y -= y
endPoint_x -= x
endPoint_y -= y
if (startPoint_x < pageWidth) {
startPoint_x = 0
} else {
startPoint_x = pageWidth << 1
}
if (startPoint_y < 0) {
startPoint_y = 0
} else if (startPoint_y > pageHeight) {
startPoint_y = pageHeight
}
if (endPoint_x + x < x) {
var path = new Path2D()
ctx.save()
path.moveTo(0, 0)
path.lineTo(x, 0)
path.lineTo(x, ctx.canvas.height)
path.lineTo(0, ctx.canvas.height)
path.closePath()
ctx.clip(path)
ctx.restore()
endPoint_x = 0
}
if (endPoint_x > pageWidth << 1) {
var path = new Path2D()
ctx.save()
path.moveTo(ctx.canvas.width, 0)
path.lineTo(ctx.canvas.width - y, 0)
path.lineTo(ctx.canvas.width - y, ctx.canvas.height)
path.lineTo(ctx.canvas.width, ctx.canvas.height)
path.closePath()
ctx.clip(path)
ctx.restore()
endPoint_x = pageWidth + pageWidth
}
var {topBandPoint_x, topBandPoint_y, bottomBandPoint_x, bottomBandPoint_y, pagingVector_x, pagingVector_y, effectTopPoint_x, effectTopPoint_y, effectBottomPoint_x, effectBottomPoint_y, effectPoint_x, effectPoint_y, corner, angle, effectAngle, pagingVector_length} = getAnyCornerPoints(startPoint_x, startPoint_y, endPoint_x, endPoint_y, pageWidth, pageHeight)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.save()
var path = new Path2D()
topBandPoint_x += x
topBandPoint_y += y
bottomBandPoint_x += x
bottomBandPoint_y += y
switch (corner) {
case LT:
path.moveTo(topBandPoint_x, topBandPoint_y)
path.lineTo(ctx.canvas.width, y)
path.lineTo(ctx.canvas.width, ctx.canvas.height)
path.lineTo(bottomBandPoint_x, ctx.canvas.height)
path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
path.closePath()
break
case LB:
path.moveTo(bottomBandPoint_x, bottomBandPoint_y)
path.lineTo(ctx.canvas.width, pageHeight + y)
path.lineTo(ctx.canvas.width, 0)
path.lineTo(topBandPoint_x, 0)
path.lineTo(topBandPoint_x, topBandPoint_y)
path.closePath()
break
case RT:
path.moveTo(topBandPoint_x, topBandPoint_y)
path.lineTo(0, y)
path.lineTo(0, ctx.canvas.height)
path.lineTo(bottomBandPoint_x, ctx.canvas.height)
path.lineTo(bottomBandPoint_x, bottomBandPoint_y)
path.closePath()
break
case RB:
path.moveTo(bottomBandPoint_x, bottomBandPoint_y)
path.lineTo(0, pageHeight + y)
path.lineTo(0, 0)
path.lineTo(topBandPoint_x, 0)
path.lineTo(topBandPoint_x, topBandPoint_y)
path.closePath()
}
ctx.clip(path)
ctx.translate(x, y)
ctx.drawImage(B, 0, 0)
ctx.drawImage(C, pageWidth, 0)
ctx.translate(pagingVector_x, pagingVector_y)
ctx.rotate(angle)
switch (corner) {
case LT:
ctx.drawImage(A, -pageWidth, 0)
break
case LB:
ctx.drawImage(A, -pageWidth, -pageHeight)
break
case RT:
ctx.drawImage(D, 0, 0)
break
case RB:
ctx.drawImage(D, 0, -pageHeight)
break
}
ctx.restore()
var canvasRendering = paint(ctx.canvas, x, y, pageWidth, pageHeight, effectPoint_x, effectPoint_y, effectAngle, corner, pagingVector_length, A, B, C, D )
effectBottomPoint_x += x
effectBottomPoint_y += y
effectTopPoint_x += x
effectTopPoint_y += y
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.save()
var effectPath = new Path2D()
switch (corner) {
case LT:
effectPath.moveTo(effectTopPoint_x, effectTopPoint_y)
effectPath.lineTo(effectTopPoint_x + (effectTopPoint_x - effectBottomPoint_x), effectTopPoint_y - (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(ctx.canvas.width, 0)
effectPath.lineTo(ctx.canvas.width, ctx.canvas.height)
effectPath.lineTo(0, ctx.canvas.height)
effectPath.lineTo(effectBottomPoint_x - (effectTopPoint_x - effectBottomPoint_x), effectBottomPoint_y + (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(effectBottomPoint_x, effectBottomPoint_y)
effectPath.closePath()
ctx.clip(effectPath)
ctx.translate(effectPoint_x + x, effectPoint_y + y)
ctx.rotate(effectAngle)
ctx.drawImage(canvasRendering, -pageWidth, -pageHeight * 1.5)
break
case LB:
effectPath.moveTo(effectTopPoint_x, effectTopPoint_y)
effectPath.lineTo(effectTopPoint_x + (effectTopPoint_x - effectBottomPoint_x), effectTopPoint_y - (effectBottomPoint_y - effectTopPoint_y))
if (effectTopPoint_x - x == 0) {
effectPath.lineTo(0, 0)
}
effectPath.lineTo(ctx.canvas.width, 0)
effectPath.lineTo(ctx.canvas.width, ctx.canvas.height)
effectPath.lineTo(0, ctx.canvas.height)
effectPath.lineTo(effectBottomPoint_x - (effectTopPoint_x - effectBottomPoint_x), effectBottomPoint_y + (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(effectBottomPoint_x, effectBottomPoint_y)
effectPath.closePath()
ctx.clip(effectPath)
ctx.translate(effectPoint_x + x, effectPoint_y + y)
ctx.rotate(-effectAngle)
ctx.drawImage(canvasRendering, -pageWidth, -pageHeight * 1.5)
break
case RT:
effectPath.moveTo(effectTopPoint_x, effectTopPoint_y)
effectPath.lineTo(effectTopPoint_x + (effectTopPoint_x - effectBottomPoint_x), effectTopPoint_y - (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(0, 0)
effectPath.lineTo(0, ctx.canvas.height)
effectPath.lineTo(ctx.canvas.width, ctx.canvas.height)
effectPath.lineTo(effectBottomPoint_x - (effectTopPoint_x - effectBottomPoint_x), effectBottomPoint_x + (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(effectBottomPoint_x, effectBottomPoint_y)
effectPath.closePath()
ctx.clip(effectPath)
ctx.translate(effectPoint_x + x, effectPoint_y + y)
ctx.rotate(-effectAngle)
ctx.drawImage(canvasRendering, -pageWidth * 2.5, -pageHeight * 1.5)
break
case RB:
effectPath.moveTo(effectTopPoint_x, effectTopPoint_y)
effectPath.lineTo(effectTopPoint_x + (effectTopPoint_x - effectBottomPoint_x), effectTopPoint_y - (effectBottomPoint_y - effectTopPoint_y))
if (effectTopPoint_x - x == bookWidth) {
effectPath.lineTo(ctx.canvas.width, 0)
}
effectPath.lineTo(0, 0)
effectPath.lineTo(0, ctx.canvas.height)
effectPath.lineTo(ctx.canvas.width, ctx.canvas.height)
effectPath.lineTo(effectBottomPoint_x - (effectTopPoint_x - effectBottomPoint_x), effectBottomPoint_y + (effectBottomPoint_y - effectTopPoint_y))
effectPath.lineTo(effectBottomPoint_x, effectBottomPoint_y)
effectPath.closePath()
ctx.clip(effectPath)
ctx.translate(effectPoint_x + x, effectPoint_y + y)
ctx.rotate(effectAngle)
ctx.drawImage(canvasRendering, -pageWidth * 2.5, -pageHeight * 1.5)
break
}
ctx.restore()
ctx.save()
ctx.translate(x + effectPoint_x, y + effectPoint_y)
const vectorPeace = (pagingVector_length * 0.5) / COUNT
var effectOffset = 0
switch (corner) {
case LT:
ctx.rotate(effectAngle)
ctx.translate(0, -pageHeight * 1.5)
for (var i = 0; i < COUNT; i+=1) {
effectOffset += vectorPeace * COEFFS[COUNT - i - 1]
ctx.drawImage(
canvasRendering,
pageWidth - vectorPeace * (i + 1),
0,
vectorPeace,
pageHeight * 3,
-effectOffset,
0,
vectorPeace * COEFFS[COUNT - i - 1],
pageHeight * 3
)
}
break
case LB:
ctx.rotate(Math.PI * 2 - effectAngle)
ctx.translate(0, -pageHeight * 1.5)
for (var i = 0; i < COUNT; i+=1) {
effectOffset += vectorPeace * COEFFS[COUNT - i - 1]
ctx.drawImage(
canvasRendering,
pageWidth - vectorPeace * (i + 1),
0,
vectorPeace,
pageHeight * 3,
-effectOffset,
0,
vectorPeace * COEFFS[COUNT - i - 1],
pageHeight * 3
)
}
break
case RT:
ctx.rotate(-effectAngle)
ctx.translate(0, -pageHeight * 1.5)
for (var i = 0; i < COUNT; i+=1) {
effectOffset += vectorPeace * COEFFS[COUNT - i - 1]
ctx.drawImage(
canvasRendering,
pageWidth * 2.5 + vectorPeace * (i + 1),
0,
vectorPeace,
pageHeight * 3,
effectOffset,
0,
vectorPeace * COEFFS[COUNT - i - 1],
pageHeight * 3
)
}
break
case RB:
ctx.rotate(effectAngle)
ctx.translate(0, -pageHeight * 1.5)
for (var i = 0; i < COUNT; i+=1) {
effectOffset += vectorPeace * COEFFS[COUNT - i - 1]
ctx.drawImage(
canvasRendering,
pageWidth * 2.5 + vectorPeace * (i + 1),
0,
vectorPeace,
pageHeight * 3,
effectOffset,
0,
vectorPeace * COEFFS[COUNT - i - 1],
pageHeight * 3
)
}
break
}
ctx.restore()
ctx.save()
ctx.translate(x, y)
ctx.beginPath()
ctx.moveTo(bottomBandPoint_x - y, bottomBandPoint_y - y)
ctx.arc(pagingVector_x, pagingVector_y, 4, 0, 2 * Math.PI, false)
ctx.arc(topBandPoint_x - x, topBandPoint_y - y, 4, 0, 2 * Math.PI, false)
ctx.arc(bottomBandPoint_x - x, bottomBandPoint_y - y, 4, 0, 2 * Math.PI, false)
ctx.setLineDash([3, 3])
ctx.strokeStyle = '#333'
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
ctx.translate(x, y)
ctx.beginPath()
ctx.font = '10px Georgia'
//ctx.fillText('angle: ' + effectAngle, effectTopPoint_x - x, effectTopPoint_y - y - 30)
ctx.arc(effectTopPoint_x - x, effectTopPoint_y - y, 4, 0, 2 * Math.PI, false)
ctx.strokeStyle = '#ff0000'
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
ctx.translate(x, y)
ctx.beginPath()
ctx.arc(effectBottomPoint_x - x, effectBottomPoint_y - y, 4, 0, 2 * Math.PI, false)
ctx.strokeStyle = '#ff0001'
ctx.stroke()
ctx.closePath()
ctx.restore()
ctx.save()
ctx.translate(x, y)
ctx.beginPath()
ctx.arc(effectPoint_x, effectPoint_y, 4, 0, 2 * Math.PI, false)
ctx.strokeStyle = '#ff0001'
ctx.stroke()
ctx.closePath()
ctx.restore()
//
// var secondCanvas = document.getElementById('secondCanvas')
// var secCtx = secondCanvas.getContext('2d')
//
// secCtx.save()
// secCtx.translate(x, y)
// secCtx.clearRect(0, 0, secCtx.canvas.width, secCtx.canvas.height)
// secCtx.drawImage(D, 0, 0)
// secCtx.drawImage(A, pageWidth, 0)
// secCtx.restore()
}
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
var c = document.createElement('canvas')
c.setAttribute('id', 'canvas-rendering')
document.body.appendChild(c);
var canvasRendering = document.getElementById('canvas-rendering')
var canvasRenderingContex = canvasRendering.getContext('2d')
var bookWidth = 640
var bookHeight = 480
var bookX = 150
var bookY = 150
var fingerOffset = {x: 0, y: 0}
canvasRendering.width = bookWidth * 2
canvasRendering.height = bookHeight * 3
const A = new Image(320, 480)
A.src = './src/IMG_1.jpg'
const B = new Image(320, 480)
B.src = './src/IMG_2.jpg'
const C = new Image(320, 480)
C.src = './src/IMG_3.jpg'
const D = new Image(320, 480)
D.src = './src/IMG_4.jpg'
canvas.addEventListener('mousemove', function(event) {
drawPaging(ctx, bookX, bookY, fingerOffset.x, fingerOffset.y, event.clientX, event.clientY, A, B, C, D, 320, 480)
})
canvas.addEventListener('click', function(event) {
fingerOffset = {x: event.clientX, y: event.clientY}
drawPaging(ctx, bookX, bookY, fingerOffset.x, fingerOffset.y, event.clientX, event.clientY, A, B, C, D, 320, 480)
})
function paint(canvas, bookOffsetX, bookOffsetY, pageWidth, pageHeight, effectPoint_x, effectPoint_y, middlePointAngle, corner, pagingVector_length) {
canvasRenderingContex.clearRect(0, 0, canvasRenderingContex.canvas.width, canvasRenderingContex.canvas.height)
console.log(-effectPoint_x)
switch (corner) {
case LT:
canvasRenderingContex.save()
canvasRenderingContex.translate(pageWidth, pageHeight * 1.5)
canvasRenderingContex.rotate(-middlePointAngle)
canvasRenderingContex.drawImage(canvas, -effectPoint_x - bookOffsetX, -effectPoint_y - bookOffsetY)
canvasRenderingContex.restore()
break
case LB:
canvasRenderingContex.save()
canvasRenderingContex.translate(pageWidth, pageHeight * 1.5)
canvasRenderingContex.rotate(middlePointAngle)
canvasRenderingContex.drawImage(canvas, -effectPoint_x - bookOffsetX, -effectPoint_y - bookOffsetY)
canvasRenderingContex.restore()
break
case RB:
canvasRenderingContex.save()
canvasRenderingContex.translate(pageWidth * 2.5, pageHeight * 1.5)
canvasRenderingContex.rotate(-middlePointAngle)
canvasRenderingContex.drawImage(canvas, -effectPoint_x - bookOffsetX, -effectPoint_y - bookOffsetY)
canvasRenderingContex.restore()
break
case RT:
canvasRenderingContex.save()
canvasRenderingContex.translate(pageWidth * 2.5, pageHeight * 1.5)
canvasRenderingContex.rotate(middlePointAngle)
canvasRenderingContex.drawImage(canvas, -effectPoint_x - bookOffsetX, -effectPoint_y - bookOffsetY)
canvasRenderingContex.restore()
break
}
return canvasRendering
}
*/
<file_sep>/trash/leftTopCorner.js
function getLeftTopCornerPoints(startPoint, endPoint, pageWidth, pageHeight) {
var offsetPagingVector = {
x: endPoint.x,
y: endPoint.y - startPoint.y
}
offsetPagingVector.length = calcVectorLength(offsetPagingVector)
var A = {
a: offsetPagingVector.y,
b: offsetPagingVector.length
}
A.beta = Math.acos(A.a / A.b)
var B = {
a: startPoint.y,
beta: A.beta
}
B.b = Math.cos(B.beta) * B.a
var C = {
a: B.b,
beta: Math.PI * 0.5 - B.beta
}
C.b = C.a * Math.cos(C.beta)
var D = {
b: B.b,
beta: B.beta
}
D.a = D.b * Math.cos(D.beta)
/* Найдем координаты части вектора pagingVector */
B.x = C.b //rename
B.y = D.a //
/* ---- */
var pagingVector = {
x: 2 * B.x + offsetPagingVector.x, // rename
y: 2 * B.y + offsetPagingVector.y, //rename
length: offsetPagingVector.length + 2 * B.b
}
var boundingVector = {
x: pagingVector.x - pageWidth,
y: pagingVector.y
}
boundingVector.length = calcVectorLength(boundingVector)
pagingVector.beta = Math.acos(pagingVector.y / pagingVector.length)
if (boundingVector.length > pageWidth) {
var ratio = (pageWidth / boundingVector.length)
boundingVector.x = boundingVector.x * ratio
boundingVector.y = boundingVector.y * ratio
pagingVector.x = boundingVector.x + pageWidth
pagingVector.y = boundingVector.y
pagingVector.beta = Math.acos(pagingVector.y / pagingVector.length)
pagingVector.length = calcVectorLength(pagingVector)
}
var E = {
a: pagingVector.y,
b: pagingVector.length,
c: pagingVector.x
}
E.beta = Math.acos(E.a / E.b)
var G = {
b: 0.5 * pagingVector.length,
beta: E.beta
}
G.a = G.b / Math.cos(G.beta)
var F = {
a: 0.5 * pagingVector.length,
beta: Math.PI * 0.5 - G.beta
}
F.b = F.a / Math.cos(F.beta)
var bottomBandPoint = {
x: 0,
y: G.a
}
var topBandPoint = {
x: F.b,
y: 0
}
if (bottomBandPoint.y > pageHeight) {
var H = {
a: bottomBandPoint.y - pageHeight,
alpha: Math.PI * 0.5 - pagingVector.beta
}
H.b = H.a * Math.tan(H.alpha)
bottomBandPoint.x = H.b
bottomBandPoint.y = pageHeight
}
return {
topBandPoint,
bottomBandPoint,
pagingVector
}
}
function calcVectorLength(vector) {
return Math.sqrt(vector.x * vector.x + vector.y * vector.y)
}
<file_sep>/README.md
# Book engine
created with:
HTML5 Canvas + JavaScript ES5 ES6
<file_sep>/trash/test.js
// console.time('new')
// for (var i = 0; i < 1000000; i++) {
// getAnyCornerPoints2(Math.random() * 1000, Math.random() * 1000, Math.random() * 1000, Math.random() * 1000, Math.random() * 1000)
// }
// console.timeEnd('new')
//
// console.time('old')
// for (var i = 0; i < 1000000; i++) {
// getAnyCornerPoints(Math.random() * 1000, Math.random() * 1000, Math.random() * 1000, Math.random() * 1000, Math.random() * 1000)
// }
// console.timeEnd('old')
//
// // const RT = 1
// // const RB = 2
// // const R = 3
// // const LT = 4
// // const LB = 5
// // const L = 6
//
// function getAnyCornerPoints(startPoint_x, startPoint_y, endPoint_x, endPoint_y, pageWidth, pageHeight) {
// var bookWidth = pageWidth << 1
// var CORNER
//
//
// if (startPoint_x > pageWidth) {
// if (endPoint_y > startPoint_y) {
// endPoint_x = bookWidth - endPoint_x
// CORNER = RT
// } else {
// endPoint_x = bookWidth - endPoint_x
// startPoint_y = pageHeight - startPoint_y
// endPoint_y = pageHeight - endPoint_y
// CORNER = RB
// }
// if (startPoint_y == endPoint_y) {
// CORNER = R
// }
// } else {
// if (endPoint_y > startPoint_y) {
// CORNER = LT
// } else {
// startPoint_x = 0
// startPoint_y = pageHeight - startPoint_y
// endPoint_y = pageHeight - endPoint_y
// CORNER = LB
// }
// if (startPoint_y == endPoint_y) {
// CORNER = L
// }
// }
// /*------------------------------------------------------------------------------------------------------------------------------------------------------*/
// endPoint_y = endPoint_y - startPoint_y
// var offsetPagingVector_length_or_G_cosBeta = Math.sqrt(endPoint_x * endPoint_x + endPoint_y * endPoint_y)
//
// var boundingVector_x_or_B_cosBeta_or_G_minusBeta = endPoint_y / offsetPagingVector_length_or_G_cosBeta
// var bottomBandPoint_x_or_B_b_x2 = boundingVector_x_or_B_cosBeta_or_G_minusBeta * startPoint_y * 2
//
// /* Координаты части вектора pagingVector */
//
// var pagingVector_x = bottomBandPoint_x_or_B_b_x2 * Math.cos(Math.PI * 0.5 - Math.acos(boundingVector_x_or_B_cosBeta_or_G_minusBeta)) + endPoint_x
// var pagingVector_y = bottomBandPoint_x_or_B_b_x2 * boundingVector_x_or_B_cosBeta_or_G_minusBeta + endPoint_y
//
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = pagingVector_x - pageWidth
// startPoint_y = Math.sqrt(boundingVector_x_or_B_cosBeta_or_G_minusBeta * boundingVector_x_or_B_cosBeta_or_G_minusBeta + pagingVector_y * pagingVector_y)
//
// if (startPoint_y > pageWidth) {
//
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = boundingVector_x_or_B_cosBeta_or_G_minusBeta * (pageWidth / startPoint_y)
//
// pagingVector_x = boundingVector_x_or_B_cosBeta_or_G_minusBeta + pageWidth
// pagingVector_y = pagingVector_y * (pageWidth / startPoint_y)
//
// endPoint_y = Math.sqrt(pagingVector_x * pagingVector_x + pagingVector_y * pagingVector_y)
// } else {
// endPoint_y = offsetPagingVector_length_or_G_cosBeta + bottomBandPoint_x_or_B_b_x2
// }
//
// offsetPagingVector_length_or_G_cosBeta = pagingVector_y / endPoint_y
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = Math.PI * 0.5 - Math.acos(offsetPagingVector_length_or_G_cosBeta)
//
// bottomBandPoint_x_or_B_b_x2 = 0
// startPoint_y = 0.5 * endPoint_y / offsetPagingVector_length_or_G_cosBeta
//
// if (startPoint_y > pageHeight) {
// bottomBandPoint_x_or_B_b_x2 = (startPoint_y - pageHeight) * Math.tan(boundingVector_x_or_B_cosBeta_or_G_minusBeta)
// startPoint_y = pageHeight
// }
//
// topBandPoint_x = 0.5 * endPoint_y / Math.cos(boundingVector_x_or_B_cosBeta_or_G_minusBeta)
// topBandPoint_y = 0
// bottomBandPoint_x = bottomBandPoint_x_or_B_b_x2
// bottomBandPoint_y = startPoint_y
// /*------------------------------------------------------------------------------------------------------------------------------------------------------*/
// switch (CORNER) {
// case RT:
// topBandPoint_x = bookWidth - topBandPoint_x
// bottomBandPoint_x = bookWidth - bottomBandPoint_x
// pagingVector_x = bookWidth - pagingVector_x
// break;
//
// case RB:
// topBandPoint_x = bookWidth - topBandPoint_x
// topBandPoint_y = pageHeight
// bottomBandPoint_x = bookWidth - bottomBandPoint_x
// bottomBandPoint_y = pageHeight - bottomBandPoint_y
// pagingVector_x = bookWidth - pagingVector_x
// pagingVector_y = pageHeight - pagingVector_y
// break;
//
// case R:
// pagingVector_x = bookWidth - endPoint_x
// pagingVector_y = 0
// topBandPoint_x = pagingVector_x + endPoint_x * 0.5
// topBandPoint_y = pagingVector_y
// bottomBandPoint_x = topBandPoint_x
// bottomBandPoint_y = pageHeight
// break;
//
// case LB:
// topBandPoint_y = pageHeight
// bottomBandPoint_y = pageHeight - bottomBandPoint_y
// pagingVector_y = pageHeight - pagingVector_y
// break;
//
// case L:
// topBandPoint_x = endPoint_x * 0.5
// topBandPoint_y = 0
// bottomBandPoint_x = topBandPoint_x
// bottomBandPoint_y = pageHeight
// pagingVector_y = 0
// break;
// }
//
// return {
// topBandPoint_x,
// topBandPoint_y,
// bottomBandPoint_x,
// bottomBandPoint_y,
// pagingVector_x,
// pagingVector_y
// }
// }
//
// function getAnyCornerPoints2(startPoint_x, startPoint_y, endPoint_x, endPoint_y, pageWidth, pageHeight) {
// var bookWidth = pageWidth << 1
// var CORNER
// if (startPoint_x > pageWidth) {
// if (endPoint_y > startPoint_y) {
// endPoint_x = bookWidth - endPoint_x
// CORNER = RT
// } else {
// endPoint_x = bookWidth - endPoint_x
// startPoint_y = pageHeight - startPoint_y
// endPoint_y = pageHeight - endPoint_y
// CORNER = RB
// }
// if (startPoint_y == endPoint_y) {
// CORNER = R
// }
// } else {
// if (endPoint_y > startPoint_y) {
// CORNER = LT
// } else {
// startPoint_x = 0
// startPoint_y = pageHeight - startPoint_y
// endPoint_y = pageHeight - endPoint_y
// CORNER = LB
// }
// if (startPoint_y == endPoint_y) {
// CORNER = L
// }
// }
// /*------------------------------------------------------------------------------------------------------------------------------------------------------*/
// endPoint_y = endPoint_y - startPoint_y
// var offsetPagingVector_length_or_G_cosBeta = Math.sqrt(endPoint_x * endPoint_x + endPoint_y * endPoint_y)
//
// var boundingVector_x_or_B_cosBeta_or_G_minusBeta = endPoint_y / offsetPagingVector_length_or_G_cosBeta
// var bottomBandPoint_x_or_B_b_x2 = boundingVector_x_or_B_cosBeta_or_G_minusBeta * startPoint_y * 2
//
// /* Координаты части вектора pagingVector */
//
// var pagingVector_x = bottomBandPoint_x_or_B_b_x2 * Math.cos(Math.PI * 0.5 - Math.acos(boundingVector_x_or_B_cosBeta_or_G_minusBeta)) + endPoint_x
// var pagingVector_y = bottomBandPoint_x_or_B_b_x2 * boundingVector_x_or_B_cosBeta_or_G_minusBeta + endPoint_y
//
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = pagingVector_x - pageWidth
// startPoint_y = Math.sqrt(boundingVector_x_or_B_cosBeta_or_G_minusBeta * boundingVector_x_or_B_cosBeta_or_G_minusBeta + pagingVector_y * pagingVector_y)
//
// if (startPoint_y > pageWidth) {
//
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = boundingVector_x_or_B_cosBeta_or_G_minusBeta * (pageWidth / startPoint_y)
//
// pagingVector_x = boundingVector_x_or_B_cosBeta_or_G_minusBeta + pageWidth
// pagingVector_y = pagingVector_y * (pageWidth / startPoint_y)
//
// endPoint_y = Math.sqrt(pagingVector_x * pagingVector_x + pagingVector_y * pagingVector_y)
// } else {
// endPoint_y = offsetPagingVector_length_or_G_cosBeta + bottomBandPoint_x_or_B_b_x2
// }
//
// offsetPagingVector_length_or_G_cosBeta = pagingVector_y / endPoint_y
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = Math.PI * 0.5 - Math.acos(offsetPagingVector_length_or_G_cosBeta)
//
// bottomBandPoint_x_or_B_b_x2 = 0
// startPoint_y = 0.5 * endPoint_y / offsetPagingVector_length_or_G_cosBeta
//
// if (startPoint_y > pageHeight) {
// bottomBandPoint_x_or_B_b_x2 = (startPoint_y - pageHeight) * Math.tan(boundingVector_x_or_B_cosBeta_or_G_minusBeta)
// startPoint_y = pageHeight
// }
//
// topBandPoint_x = 0.5 * endPoint_y / Math.cos(boundingVector_x_or_B_cosBeta_or_G_minusBeta)
// topBandPoint_y = 0
// bottomBandPoint_x = bottomBandPoint_x_or_B_b_x2
// bottomBandPoint_y = startPoint_y
// /*------------------------------------------------------------------------------------------------------------------------------------------------------*/
// if(CORNER == RT) {
// topBandPoint_x = bookWidth - topBandPoint_x
// bottomBandPoint_x = bookWidth - bottomBandPoint_x
// pagingVector_x = bookWidth - pagingVector_x
// } else if(CORNER == RB) {
// topBandPoint_x = bookWidth - topBandPoint_x
// topBandPoint_y = pageHeight
// bottomBandPoint_x = bookWidth - bottomBandPoint_x
// bottomBandPoint_y = pageHeight - bottomBandPoint_y
// pagingVector_x = bookWidth - pagingVector_x
// pagingVector_y = pageHeight - pagingVector_y
// } else if (CORNER == R) {
// pagingVector_x = bookWidth - endPoint_x
// pagingVector_y = 0
// topBandPoint_x = pagingVector_x + endPoint_x * 0.5
// topBandPoint_y = pagingVector_y
// bottomBandPoint_x = topBandPoint_x
// bottomBandPoint_y = pageHeight
// } else if(CORNER == LB) {
// topBandPoint_y = pageHeight
// bottomBandPoint_y = pageHeight - bottomBandPoint_y
// pagingVector_y = pageHeight - pagingVector_y
// } else if (CORNER == L) {
// topBandPoint_x = endPoint_x * 0.5
// topBandPoint_y = 0
// bottomBandPoint_x = topBandPoint_x
// bottomBandPoint_y = pageHeight
// pagingVector_y = 0
// }
//
// return {
// topBandPoint_x,
// topBandPoint_y,
// bottomBandPoint_x,
// bottomBandPoint_y,
// pagingVector_x,
// pagingVector_y
// }
// }
<file_sep>/trash/testing.js
function intersection(AX1, AY1, AX2, AY2, BX1, BY1, BX2, BY2) {
AX1 = ((AX1 * AY2 - AX2 * AY1) * (BX2 - BX1) - (BX1 * BY2 - BX2 * BY1) * (AX2 - AX1)) / ((AY1 - AY2) * (BX2 - BX1) - (BY1 - BY2) * (AX2 - AX1))
AY1 = ((BY1 - BY2) * AX1 - (BX1 * BY2 - BX2 * BY1)) / (BX2 - BX1)
AX1 *= -1
return {
x: AX1,
y: AY1
}
}
console.log({x: 1, y: 2}, intersection(-3, 0, 5, 4, 0, 5, 2, -1))
console.log({x: -3, y: 3}, intersection(0, 5, -3, 3, -3, 3, 3, 2))
console.log({x: 3, y: 2}, intersection(0, 4, 6, 0, 3, 2, 5, 4))
<file_sep>/js/getAnyCornerPoints.js
const LT = 1
const RB = 2
const RT = 3
const LB = 4
const R = 5
const L = 6
function getAnyCornerPoints(startPoint_x, startPoint_y, endPoint_x, endPoint_y, pageWidth, pageHeight) {
var bookWidth = pageWidth << 1
// var pageCorner = pageWidth / 10
var CORNER
if (startPoint_x > pageWidth) {
if (endPoint_y > startPoint_y) {
endPoint_x = bookWidth - endPoint_x
CORNER = RT
} else {
endPoint_x = bookWidth - endPoint_x
startPoint_y = pageHeight - startPoint_y
endPoint_y = pageHeight - endPoint_y
CORNER = RB
}
if (startPoint_y == endPoint_y) {
CORNER = R
}
} else {
if (endPoint_y > startPoint_y) {
CORNER = LT
} else {
startPoint_x = 0
startPoint_y = pageHeight - startPoint_y
endPoint_y = pageHeight - endPoint_y
CORNER = LB
}
if (startPoint_y == endPoint_y) {
CORNER = L
}
}
/*------------------------------------------------------------------------------------------------------------------*/
endPoint_y = endPoint_y - startPoint_y
// if (endPoint_x < pageCorner){
// endPoint_x = pageCorner
// endPoint_y = pageCorner
// }
// console.log(endPoint_x, endPoint_y)
/*
Все ньюансы, которые приводят к ошибкам сгиба, и неправильной отрисовке, можно исправить поставив exceeptions на каждый из случаев, например, как в книге Ibooks
*/
var offsetPagingVector_length = Math.sqrt(endPoint_x * endPoint_x + endPoint_y * endPoint_y)
if (endPoint_x == 0 && endPoint_y == 0) {
offsetPagingVector_length = 1
}
var A_beta = Math.acos(endPoint_y / offsetPagingVector_length)
var B_b = Math.cos(A_beta) * startPoint_y
var pagingVector_x = 2 * B_b * Math.cos(Math.PI * 0.5 - A_beta) + endPoint_x
var pagingVector_y = 2 * B_b * Math.cos(A_beta) + endPoint_y
var pagingVector_length = offsetPagingVector_length + 2 * B_b
var boundingVector_radius = pageWidth / Math.cos(Math.PI * 0.25)
var boundingVector_x = pagingVector_x - pageWidth
var boundingVector_y = pagingVector_y + pageWidth
var boundingVector_length = Math.sqrt(boundingVector_x * boundingVector_x + boundingVector_y * boundingVector_y)
var pagingVector_beta = Math.acos(pagingVector_y / pagingVector_length)
if (boundingVector_length > boundingVector_radius) {
var ratio = (boundingVector_radius / boundingVector_length)
boundingVector_x = boundingVector_x * ratio
boundingVector_y = boundingVector_y * ratio
pagingVector_x = boundingVector_x + pageWidth
pagingVector_y = boundingVector_y - pageWidth
pagingVector_beta = Math.acos(pagingVector_y / pagingVector_length)
pagingVector_length = Math.sqrt(pagingVector_x * pagingVector_x + pagingVector_y * pagingVector_y)
}
var E_a = pagingVector_y
var E_b = pagingVector_length
var E_c = pagingVector_x
var E_beta = Math.acos(E_a / E_b)
var G_b = 0.5 * pagingVector_length
var G_beta = E_beta
var G_a = G_b / Math.cos(G_beta)
var F_a = 0.5 * pagingVector_length
var F_beta = Math.PI * 0.5 - G_beta
var F_b = F_a / Math.cos(F_beta)
var bottomBandPoint_x = 0
var bottomBandPoint_y = G_a
var topBandPoint_x = F_b
var topBandPoint_y = 0
var effectTopPoint_x = topBandPoint_x << 1
var effectTopPoint_y = 0
for (var i = 1; i <= COUNT; i += 1) {
COEFFS[i - 1] = Math.pow(i / COUNT, 0.35 + ((effectTopPoint_x) / pageWidth) * ((effectTopPoint_x) / pageWidth))
}
if (effectTopPoint_x > pageWidth) {
effectTopPoint_x = pageWidth
}
var effectBottomPoint_x = 0
var effectBottomPoint_y = bottomBandPoint_y << 1
if (effectBottomPoint_y > pageHeight) {
var ratio = effectBottomPoint_y / (effectBottomPoint_y - pageHeight)
effectBottomPoint_x = effectTopPoint_x / ratio
effectBottomPoint_y = pageHeight
}
if (effectBottomPoint_x > pageWidth) {
effectBottomPoint_x = pageWidth
}
var I_a = effectBottomPoint_y
var I_b = effectTopPoint_x - effectBottomPoint_x
var effectPoint_x = pagingVector_x
var effectPoint_y = pagingVector_y
var effectAngle = Math.atan2(I_b, I_a)
var effectPoint_length = pagingVector_length
if (effectTopPoint_x == pageWidth) {
effectPoint_x = ((0 * pagingVector_y - pagingVector_x * 0) * (effectBottomPoint_x - effectTopPoint_x) - (effectTopPoint_x * effectBottomPoint_y - effectBottomPoint_x * effectTopPoint_y) * (pagingVector_x - 0)) / ((0 - pagingVector_y) * (effectBottomPoint_x - effectTopPoint_x) - (effectTopPoint_y - effectBottomPoint_y) * (pagingVector_x - 0))
effectPoint_y = ((effectTopPoint_y - effectBottomPoint_y) * effectPoint_x - (effectTopPoint_x * effectBottomPoint_y - effectBottomPoint_x * effectTopPoint_y)) / (effectBottomPoint_x - effectTopPoint_x)
effectPoint_x *= -1
effectPoint_length = Math.sqrt(effectPoint_x * effectPoint_x + effectPoint_y * effectPoint_y)
}
var ratio
if (bottomBandPoint_y > pageHeight) {
var H_a = bottomBandPoint_y - pageHeight
ratio = bottomBandPoint_y / H_a
bottomBandPoint_x = topBandPoint_x / ratio
bottomBandPoint_y = pageHeight
}
var angle = (Math.PI - Math.acos(Math.cos(G_beta)) * 2) * (CORNER < RT ? 1 : -1)
var botTriangle_c = Math.abs(Math.cos(Math.PI * 0.5 - angle)) * pageHeight
var botTriangle_b = Math.cos(angle) * pageHeight
var topTriangle_a = Math.sqrt(((pagingVector_x - topBandPoint_x) * (pagingVector_x - topBandPoint_x)) + ((pagingVector_y - topBandPoint_y) * (pagingVector_y - topBandPoint_y)))
var topTriangle_b = pagingVector_y
var topTriangle_c = Math.sqrt((topTriangle_a * topTriangle_a) - (topTriangle_b * topTriangle_b))
var bottomPoint_x = topBandPoint_x + (topTriangle_c - botTriangle_c)
var bottomPoint_y = topTriangle_b + botTriangle_b
/*------------------------------------------------------------------------------------------------------------------------------------------------------*/
// endPoint_y = endPoint_y - startPoint_y
// var offsetPagingVector_length_or_G_cosBeta = Math.sqrt(endPoint_x * endPoint_x + endPoint_y * endPoint_y)
//
// var boundingVector_x_or_B_cosBeta_or_G_minusBeta = endPoint_y / offsetPagingVector_length_or_G_cosBeta
// var bottomBandPoint_x_or_B_b_x2 = boundingVector_x_or_B_cosBeta_or_G_minusBeta * startPoint_y * 2
//
// /* Координаты части вектора pagingVector */
//
// var pagingVector_x = bottomBandPoint_x_or_B_b_x2 * Math.cos(Math.PI * 0.5 - Math.acos(boundingVector_x_or_B_cosBeta_or_G_minusBeta)) + endPoint_x
// var pagingVector_y = bottomBandPoint_x_or_B_b_x2 * boundingVector_x_or_B_cosBeta_or_G_minusBeta + endPoint_y
//
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = pagingVector_x - pageWidth
// startPoint_y = Math.sqrt(boundingVector_x_or_B_cosBeta_or_G_minusBeta * boundingVector_x_or_B_cosBeta_or_G_minusBeta + pagingVector_y * pagingVector_y)
//
// if (startPoint_y > pageWidth) {
//
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = boundingVector_x_or_B_cosBeta_or_G_minusBeta * (pageWidth / startPoint_y)
//
// pagingVector_x = boundingVector_x_or_B_cosBeta_or_G_minusBeta + pageWidth
// pagingVector_y = pagingVector_y * (pageWidth / startPoint_y)
//
// endPoint_y = Math.sqrt(pagingVector_x * pagingVector_x + pagingVector_y * pagingVector_y)
// } else {
// endPoint_y = offsetPagingVector_length_or_G_cosBeta + bottomBandPoint_x_or_B_b_x2
// }
//
// offsetPagingVector_length_or_G_cosBeta = pagingVector_y / endPoint_y
// boundingVector_x_or_B_cosBeta_or_G_minusBeta = Math.PI * 0.5 - Math.acos(offsetPagingVector_length_or_G_cosBeta)
//
// bottomBandPoint_x_or_B_b_x2 = 0
// startPoint_y = 0.5 * endPoint_y / offsetPagingVector_length_or_G_cosBeta
//
// if (startPoint_y > pageHeight) {
// bottomBandPoint_x_or_B_b_x2 = (startPoint_y - pageHeight) * Math.tan(boundingVector_x_or_B_cosBeta_or_G_minusBeta)
// startPoint_y = pageHeight
// }
//
// topBandPoint_x = 0.5 * endPoint_y / Math.cos(boundingVector_x_or_B_cosBeta_or_G_minusBeta)
// topBandPoint_y = 0
// bottomBandPoint_x = bottomBandPoint_x_or_B_b_x2
// bottomBandPoint_y = startPoint_y
/*------------------------------------------------------------------------------------------------------------------------------------------------------*/
switch (CORNER) {
case RT:
topBandPoint_x = bookWidth - topBandPoint_x
bottomBandPoint_x = bookWidth - bottomBandPoint_x
pagingVector_x = bookWidth - pagingVector_x
effectTopPoint_x = bookWidth - effectTopPoint_x
effectBottomPoint_x = bookWidth - effectBottomPoint_x
effectPoint_x = bookWidth - effectPoint_x
bottomPoint_x = bookWidth - bottomPoint_x
break
case RB:
bottomBandPoint_x_or_B_b_x2 = topBandPoint_x
topBandPoint_x = bookWidth - bottomBandPoint_x
topBandPoint_y = pageHeight - bottomBandPoint_y
bottomBandPoint_x = bookWidth - bottomBandPoint_x_or_B_b_x2
bottomBandPoint_y = pageHeight
pagingVector_x = bookWidth - pagingVector_x
pagingVector_y = pageHeight - pagingVector_y
bottomBandPoint_x_or_B_b_x2 = effectTopPoint_x
effectTopPoint_x = bookWidth - effectBottomPoint_x
effectTopPoint_y = pageHeight - effectBottomPoint_y
effectBottomPoint_x = bookWidth - bottomBandPoint_x_or_B_b_x2
effectBottomPoint_y = pageHeight
effectPoint_x = bookWidth - effectPoint_x
effectPoint_y = pageHeight - effectPoint_y
bottomPoint_x = bookWidth - bottomPoint_x
bottomPoint_y = pageHeight - bottomPoint_y
break;
case R:
pagingVector_x = bookWidth - endPoint_x
pagingVector_y = 0
topBandPoint_x = pagingVector_x + endPoint_x * 0.5
topBandPoint_y = pagingVector_y
bottomBandPoint_x = topBandPoint_x
bottomBandPoint_y = pageHeight
effectTopPoint_x = bookWidth - effectPoint_x
effectTopPoint_y = 0
effectPoint_x = effectTopPoint_x
effectPoint_y = 0
effectBottomPoint_x = effectTopPoint_x
effectBottomPoint_y = pageHeight
effectAngle = Math.atan2(effectTopPoint_x - effectBottomPoint_x, effectBottomPoint_y)
bottomPoint_x = bookWidth - bottomPoint_x
CORNER = RT
break;
case LB:
bottomBandPoint_x_or_B_b_x2 = topBandPoint_x
bottomPoint_y = pageHeight - bottomPoint_y
topBandPoint_x = bottomBandPoint_x
topBandPoint_y = pageHeight - bottomBandPoint_y
bottomBandPoint_x = bottomBandPoint_x_or_B_b_x2
bottomBandPoint_y = pageHeight
pagingVector_y = pageHeight - pagingVector_y
bottomBandPoint_x_or_B_b_x2 = effectTopPoint_x
effectTopPoint_x = effectBottomPoint_x
effectTopPoint_y = pageHeight - effectBottomPoint_y
effectBottomPoint_x = bottomBandPoint_x_or_B_b_x2
effectBottomPoint_y = pageHeight
effectPoint_y = pageHeight - effectPoint_y
break;
case L:
topBandPoint_x = endPoint_x * 0.5
topBandPoint_y = 0
bottomBandPoint_x = topBandPoint_x
bottomBandPoint_y = pageHeight
pagingVector_y = 0
effectTopPoint_x = effectTopPoint_x
effectTopPoint_y = 0
effectPoint_x = effectTopPoint_x
effectPoint_y = 0
effectBottomPoint_x = effectTopPoint_x
effectBottomPoint_y = pageHeight
effectAngle = Math.atan2(effectTopPoint_x - effectBottomPoint_x, effectBottomPoint_y)
CORNER = LT
break;
}
var J_h //change position of variable declaration
switch (CORNER) {
case RB:
case LB:
var J_a = Math.sqrt(((topBandPoint_x - effectTopPoint_x) * (topBandPoint_x - effectTopPoint_x)) + ((topBandPoint_y - effectTopPoint_y) * (topBandPoint_y - effectTopPoint_y)))
var J_b = Math.sqrt(((effectBottomPoint_x - topBandPoint_x) * (effectBottomPoint_x - topBandPoint_x)) + ((effectBottomPoint_y - topBandPoint_y) * (effectBottomPoint_y - topBandPoint_y)))
var J_c = Math.sqrt(((effectTopPoint_x - effectBottomPoint_x) * (effectTopPoint_x - effectBottomPoint_x)) + ((effectTopPoint_y - effectBottomPoint_y) * (effectTopPoint_y - effectBottomPoint_y)))
var p = (J_a + J_b + J_c) * 0.5
J_h = ((Math.sqrt(p * (p - J_a) * (p - J_b) * (p - J_c))) << 1) / J_c
break
case RT:
case LT:
var J_a = Math.sqrt((bottomBandPoint_x - effectTopPoint_x) * (bottomBandPoint_x - effectTopPoint_x) + (bottomBandPoint_y - effectTopPoint_y) * (bottomBandPoint_y - effectTopPoint_y))
var J_b = Math.sqrt((effectBottomPoint_x - bottomBandPoint_x) * (effectBottomPoint_x - bottomBandPoint_x) + (effectBottomPoint_y - bottomBandPoint_y) * (effectBottomPoint_y - bottomBandPoint_y))
var J_c = Math.sqrt((effectBottomPoint_x - effectTopPoint_x) * (effectBottomPoint_x - effectTopPoint_x) + (effectBottomPoint_y - effectTopPoint_y) * (effectBottomPoint_y - effectTopPoint_y))
var p = (J_a + J_b + J_c) * 0.5
J_h = ((Math.sqrt(p * (p - J_a) * (p - J_b) * (p - J_c))) << 1) / J_c
break
}
return {
topBandPoint_x,
topBandPoint_y,
bottomBandPoint_x,
bottomBandPoint_y,
pagingVector_x,
pagingVector_y,
effectTopPoint_x,
effectTopPoint_y,
effectBottomPoint_x,
effectBottomPoint_y,
effectPoint_x,
effectPoint_y,
corner: CORNER,
angle: angle,
effectAngle,
pagingVector_length,
effectPoint_length,
J_h,
ratio,
bottomPoint_x,
bottomPoint_y
}
}
| c4989ec7f424034afa21ecbefbd0ec4b6b0c90e3 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | NailKhalimov/book-engine-canvas-animation | 43de7a5d590e5208a1c879dabd7c0bd31cfc465c | 351802b169691bfa68d1bbee7189f92cbfcb298e |
refs/heads/master | <file_sep>## Author: <NAME>
## Contributor: <NAME>
## Date Created: 11 April 2019
## Objective: Download most recent AACT database snapshot,
## Create visuals for SCT 2019 conference talk
## Output:
## Modification Log:
## 04/16/19 MF First pass comments
##
install.packages(c("RPostgreSQL", "tidyverse", "lubridate", "survival", "data.table"));
library(RPostgreSQL)
library(tidyverse)
library(lubridate)
library(survival)
library(data.table)
#connecting to the AACT database
drv <-dbDriver('PostgreSQL')
con <- dbConnect(drv, dbname="aact",
host="aact-db.ctti-clinicaltrials.org",
port=5432, user="kehaoz", password="<PASSWORD>")
#Select relevent variables and creating some trials level summaries from trials that completed.
#Key variable ACT: likely ACT status, which is adopted and modified from Anderson et al. NEJM 2015
Dat<-dbGetQuery(con,
"SELECT a.nct_id,a.results_first_submitted_date,a.is_fda_regulated_drug, a.is_fda_regulated_device,a.overall_status,
a.primary_completion_date,a.completion_date,a.completion_date_type, a.study_type,a.verification_date,a.phase,
a.plan_to_share_ipd,a.plan_to_share_ipd_description,a.has_dmc,a.disposition_first_submitted_date,
a.is_us_export,d.first_results_pending,dthaeYN,AEasYN,AEtfYN,baseYN,outcomeYN,aeYN,analysisYN,POcount,SOcount,oPOPYN,oPOPcount,
raceYN,basecount,
CASE WHEN (b.us_site=1
AND a.study_type='Interventional' AND riskyInternvention=1 AND
((a.phase NOT IN ('Early Phase 1','Phase 1','N/A'))
OR (c.primary_purpose != 'Device Feasibility'))) THEN 1 ELSE 0 END AS ACT
FROM studies a
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS us_site
FROM Countries WHERE
name IN ('United States','American Samoa','Guam','Northern Mariana Islands', 'Puerto Rico','U.S. Virgin Islands') AND removed IS NULL ) b
ON a.nct_id=b.nct_id
LEFT JOIN Designs c ON a.nct_id=c.nct_id
LEFT JOIN (SELECT nct_id,min(event_date) AS first_results_pending
FROM Pending_Results GROUP BY nct_id) d ON a.nct_id=d.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS riskyInternvention
FROM Interventions
WHERE intervention_type in ('Drug','Diagnostic Test',
'Device','Biological','Combination Product','Genetic','Radiation')) e ON a.nct_id=e.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS dthaeYN FROM Reported_Events
WHERE adverse_event_term in ('Total, all-cause mortality','Death','death')) f ON a.nct_id=f.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS AEasYN FROM Reported_Events
WHERE default_assessment!='') g ON a.nct_id=g.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS AEtfYN FROM Reported_Events
WHERE time_frame!='') ga ON a.nct_id=ga.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS baseYN FROM Baseline_Measurements) h ON a.nct_id=h.nct_id
LEFT JOIN (SELECT nct_id, COUNT(DISTINCT title) AS baseCount FROM Baseline_Measurements GROUP BY nct_id) ha ON a.nct_id=ha.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS raceYN FROM Baseline_Measurements
WHERE title in ('Race/Ethnicity, Customized','Ethnicity (NIH/OMB)','Race (NIH/OMB)')) hb ON a.nct_id=hb.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS outcomeYN FROM Outcomes) i ON a.nct_id=i.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS oPOPYN FROM Outcomes WHERE population!='') ia ON a.nct_id=ia.nct_id
LEFT JOIN (SELECT nct_id, COUNT(DISTINCT population) AS oPOPcount FROM Outcomes GROUP BY nct_id) ib ON a.nct_id=ib.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS aeYN FROM Reported_Events) j ON a.nct_id=j.nct_id
LEFT JOIN (SELECT DISTINCT nct_id, 1 AS analysisYN FROM Outcome_Analyses) k ON a.nct_id=k.nct_id
LEFT JOIN (SELECT nct_id, count(id) AS POcount FROM Outcomes WHERE outcome_type='Primary' GROUP BY nct_id) l ON a.nct_id=l.nct_id
LEFT JOIN (SELECT nct_id, count(id) AS SOcount FROM Outcomes WHERE outcome_type='Secondary' GROUP BY nct_id) m ON a.nct_id=m.nct_id
WHERE a.overall_status IN ('Completed','Terminated')")
#probable funding source adopted from Califf et al. JAMA 2012
funding<-dbGetQuery(con,"SELECT a.nct_id,/*a.agency_class AS lead_class, a.name AS lead_name, b.NIHcol,c.Industrycol, */
CASE WHEN (a.agency_class='NIH' OR b.NIHcol=1) THEN 'NIH'
WHEN (a.agency_class='Industry' OR c.Industrycol=1) THEN 'Industry'
ELSE 'Other' END AS funding_class
FROM Sponsors a
LEFT JOIN (select DISTINCT nct_id, 1 AS NIHcol FROM Sponsors WHERE agency_class='NIH') b ON a.nct_id=b.nct_id
LEFT JOIN (select DISTINCT nct_id, 1 AS Industrycol FROM Sponsors WHERE agency_class='Industry') c ON a.nct_id=c.nct_id
WHERE a.lead_or_collaborator='lead'")
ACT<-as_data_frame(Dat)
## Original data as data.table
TCA <- data.table( Dat )
#derive more variables, including whether result is submitted and time from completion to submission
ACT2<-mutate(ACT,
were_results_reported=if_else(is.na(first_results_pending)==F,T,is.na(results_first_submitted_date)==F),
resultdt=if_else(is.na(results_first_submitted_date)==F,results_first_submitted_date,
if_else(is.na(first_results_pending)==F,first_results_pending,Sys.Date())),
completedt=if_else(is.na(primary_completion_date)==F,primary_completion_date,
if_else(is.na(completion_date)==F,completion_date,verification_date)),
completion_yr=format(as.Date(completedt),"%Y"),
year1_due=as.factor(as.numeric(completion_yr)+1),
t2result=as.duration(completedt %--% resultdt)/dyears(1),
t2result_m=ceiling(as.duration(completedt %--% resultdt)/dyears(1)*12),
socount=if_else(is.na(socount),0,socount),
pocount=if_else(is.na(pocount),0,pocount)) %>%
filter(completedt<ymd(Sys.Date()-years(1))) %>% left_join(as_data_frame(funding))
#some summaries
ACT2 %>% filter(completion_yr %in% c(2008:2017)) %>%
summarise(totn=n(),actp=sum(act)*100/n(),nactp=sum(act==0)*100/n())
ACT2 %>% filter(completion_yr %in% c(2008:2017)) %>% group_by(act) %>%
summarise(resultp=sum(were_results_reported)*100/n())
ACT2 %>% filter(completion_yr %in% c(2008:2017)) %>% group_by(overall_status) %>%
summarise(n())
#summaries by year for trials completed at least one year ago.
year1_<-ACT2 %>% filter(completedt<ymd(Sys.Date()-years(1)) & completion_yr>=2008) %>%
group_by(act,completion_yr) %>%
summarise(totn=n(),
resultn=sum(were_results_reported==T),
yr1result=sum(t2result<=1&were_results_reported==T)/totn * 100,
m12result=sum(t2result_m<=12&were_results_reported==T)/totn * 100,
t2result_sum=mean(t2result,na.rm=T),
dthaep=sum(dthaeyn,na.rm=T)*100/ resultn,
fda.reg=sum(is_fda_regulated_drug==T|is_fda_regulated_drug==T,na.rm=T),
fda.reg_NA=sum(is.na(is_fda_regulated_drug)&is.na(is_fda_regulated_drug)),
export=sum(is_us_export==T, na.rm=T),
ipd=sum(plan_to_share_ipd=='Yes',na.rm=T),
ipd_p=sum(plan_to_share_ipd=='Yes',na.rm=T)/totn)
#plot 12 month submission rate by year
ggplot(year1_,aes(y=m12result, x= completion_yr,group=act))+
geom_point(aes(colour = factor(act),shape =factor(act)))+
labs(y='results submitted to \nCT.gov within 1 yr (%)',x='year completed')+
scale_colour_manual(name = "Likely ACT",
labels = c("No",'Yes'),
values = c("blue", "red")) +
scale_shape_manual(name = "Likely ACT",
labels = c("No","Yes"),
values = c(19, 17))
#cumulative rate by ACT status
ACT_m<-filter(ACT2,completion_yr %in% c(2008:2018))
km1<-survfit(Surv(t2result_m,were_results_reported)~act, data=ACT_m)
plot(km1,xlim=c(0,60),ylim=c(0,60),col=c('blue','red'),fun = function(x) (1-x)*100,
xlab='Months after Primary Completion Date',ylab='% Trials',
main='Cumulative Percentage of Clinical Trials \nThat Reported Results to CT.gov',
lwd=3,axes = FALSE)
axis(side = 1, at = 12*c(0,1,2,3,4,5))
axis(side = 2, at = 10*c(0,1:6))
abline(v=12,lty=3)
legend("topleft", inset=0.01,legend=c("Yes", "No"),
col=c("red", "blue"),title = 'Likely ACT',lty=c(1,1),lwd=c(3,3))
##among trials with results, were key results summarized
ACT2 %>% filter(is.na(results_first_submitted_date)==F & completion_yr %in% c(2008:2017)) %>%
group_by(act,completion_yr) %>%
summarise(resultn=n(),
dthaeYNp=sum(dthaeyn,na.rm=T)/n(),
AEasYNp=sum(aeasyn,na.rm=T)/n(),
baseYNp=sum(baseyn,na.rm=T)/n(),
basecount50=quantile(basecount,probs=0.10,na.rm=T),
outcomeYNp=sum(outcomeyn,na.rm=T)/n(),
aeYNp=sum(aeyn,na.rm=T)/n(),
analysisYNp=sum(analysisyn,na.rm=T)/n(),
raceYNp=sum(raceyn,na.rm=T)/n(),
oPopYNp=sum(opopyn,na.rm=T)/n(),
analysisYNp=sum(analysisyn,na.rm=T)/n(),
OPopcount50=quantile(opopcount,probs=0.50,na.rm=T),
pocount90=quantile(pocount,probs=0.90,na.rm=T)
)
<file_sep># clinical-trials-reporting
Evolving practices of reporting in ClinicalTrials.gov
| ccfa8d3e2ec4bed10d1c2960120e85be60ff1af9 | [
"Markdown",
"R"
] | 2 | R | how-many/clinical-trials-reporting | fa1a6036d3a4506a7e8350ef4dbd8b6f51f78b2d | 20343eba2ead01c8add422968e01bd25aaec912c |
refs/heads/master | <file_sep>"""
File containing samples of code philosophy
author: <NAME>
file: sample.py
date: 24 Mar 2015
"""
#Import our libraries
import sample_library
def ask_for_string():
"""
Function that obtains string from user.
"""
#Get a string from the user
user_string = raw_input('Please enter a single word containing only letters of the alphabet:')
#Verify input
#Check that it contains only alpha characters.
if (user_string.isalpha() ):
#Make sure it's only one word
if ( user_string.find('') ):
print('Input is more than single word.')
else:
return user_string
return False
def demonstrate_rot13_cipher(provided_string):
"""
This function takes the provided string, and encodes it using Pythons provided rot13 cipher, then decodes it the same way.
Then the function takes the provided string, and encodes it using the user provided rot13 cipher, then decodes it the same way.
The string pairs are then returned as a dictionary of dictionaries.
"""
#Pass through library functions
encoded_string = sample_library.rot13_encode_easy_way(provided_string)
decoded_string = sample_library.rot13_decode_easy_way(encoded_string)
#Pass through user functions
encoded_string2 = sample_library.rot13_encode_hard_way(provided_string)
decoded_string2 = sample_library.rot13_decode_hard_way(encoded_string2)
return { 'library' : {'encoded_string' : encoded_string, 'decoded_string' : decoded_string}, 'user' : {'encoded_string' : encoded_string2, 'decoded_string' : decoded_string2} }
#Main Execution
if __name__ == "__main__":
user_string = ask_for_string()
if ( not user_string ):
print('String provided was either more than one word, or contained non-alpha characters. Please try again.')
exit()
#Pass our user string to the function that will generate our encoded/decoded strings
examples = demonstrate_rot13_cipher(user_string)
print('Original string: %s' % user_string)
print('Library encoded string: %s' % examples['library']['encoded_string'])
print('Library decoded string: %s' % examples['library']['decoded_string'])
print('User encoded string: %s' % examples['user']['encoded_string'])
print('User decoded string: %s' % examples['user']['encoded_string'])<file_sep># code-sample
A collection of code samples, intended to exhibit my coding philosophy.
As I create new code, or re-factor old code, there are a couple of things that I like to focus on.
These are;
* Documentation
* Descriptive variable/function names
* Code Reusability
I feel this creates an emphasis on the maintainability of code. Having dealt with code that is decades old, being able to quickly discern the intentions of a previous developer is a boon to those currently seeking to fix or improve said code.
This sample contains two files:
* sample.py
* sample_library.pu
The first file [sample.py](sample.py) asks for user input, does some brief sanity checking on that input, and then passes it to a function which then makes calls to the code established in [sample_library.py](sample_library.py).
In particular the code will take the user input, and then pass it through two ROT13 ciphers, one provided by Python and one created by me.
Afterwards, the program outputs the original input along with both versions of the encoded/decoded string(which should be the same).
<file_sep>"""
Library for code samples
author: <NAME>
file: sample_library.py
date: 24 Mar 2015
"""
#Import included libraries
import codecs
def rot13_encode_easy_way(string_to_encode):
"""
This function encodes a string using the Python provided rot13 cipher.
"""
encoded_string = codecs.encode(string_to_encode, 'rot13')
return encoded_string
def rot13_decode_easy_way(string_to_decode):
"""
This function decodes a string using the Python provided rot13 cipher.
"""
decoded_string = codecs.decode(string_to_decode, 'rot13')
return decoded_string
def rot13_encode_hard_way(string_to_encode):
"""
This function encodes a string using a rot13 cipher.
"""
encoded_string = ''
for char in string_to_encode:
new_char = ord(char) + 13
#Branch of case of letter
if( char.isupper() ):
#Is new_char now out of bounds for uppercase letters?
if ( new_char > 90 ):
#How far past the end are we?
new_char = new_char - 90
#If we add 1, it should be A/65
new_char = 64 + new_char
else:
#Is new_char now out of bounds for lowercase letters?
if ( new_char > 122 ):
#How far past the end are we?
new_char = new_char - 122
#If we add 1, it should be a/97
new_char = 96 + new_char
encoded_string += chr(new_char)
return encoded_string
def rot13_decode_hard_way(string_to_decode):
"""
This function decodes a string using the a rot13 cipher.
"""
decoded_string = ''
for char in string_to_decode:
new_char = ord(char) - 13
#Branch of case of letter
if( char.isupper() ):
#Is new_char now out of bounds for uppercase letters?
if ( new_char < 65 ):
#How far past the end are we?
new_char = 65- new_char
#If we subtract 1, it should be Z/90
new_char = 91 - new_char
else:
#Is new_char now out of bounds for lowercase letters?
if ( new_char < 97 ):
#How far past the end are we?
new_char = 97 - new_char
#If we subtract 1, it should be z/122
new_char = 123 - new_char
decoded_string += chr(new_char)
return decoded_string
#Use for testing
if __name__ == "__main__":
encoded_string = rot13_encode_easy_way('foObar')
print('Encoded string: %s' % encoded_string)
decoded_string = rot13_decode_easy_way(encoded_string)
print('Decoded string: %s' % decoded_string)
encoded_string2 = rot13_encode_hard_way('foObar')
print('Encoded string: %s' % encoded_string2)
decoded_string2 = rot13_decode_hard_way(encoded_string2)
print('Decoded string: %s' % decoded_string2) | f0ea6eabdf4ed462630d6ec176c431c294b64622 | [
"Markdown",
"Python"
] | 3 | Python | gryffon/code-sample | 353f7e1ec0331190c04f31203c578aa4ece1a970 | e5dcce753aa89a5d9b93a02f1bc6a12c496c285a |
refs/heads/master | <file_sep>using AutoMapper;
using MBookLibrary.Data.Entities;
using MBookLibrary.Models;
using MBookLibrary.Models.Externals;
using System;
using System.Collections.Generic;
using System.Text;
namespace MBookLibrary.Business
{
public class BookProfile : Profile
{
public BookProfile()
{
CreateMap<Book, BookModel>().ReverseMap();
CreateMap<BookDetails, Book>();
}
}
}
<file_sep>using MBookLibrary.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace MBookLibrary.Data.Entities
{
public abstract class EntityBase
{
public int Id { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public Nullable<int> ModifierUserId { get; set; }
public Nullable<System.DateTime> CanceledDate { get; set; }
public Nullable<int> CancelUserId { get; set; }
public EntityStatus State { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace MBookLibrary.Data.Entities
{
public class Book :EntityBase
{
public string ISBN { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
}
}
<file_sep>using System;
using MBookLibrary.Models.Externals;
namespace MBookLibrary.Externals
{
public interface IBookDetailService
{
void Init();
BookDetails GetBookDetails(string isbnCode);
}
}
<file_sep>using System;
using System.Collections.Generic;
using AutoMapper;
using MBookLibrary.Data.Entities;
using MBookLibrary.Data.Repository;
using MBookLibrary.Models;
using System.Linq;
using MBookLibrary.Externals;
using MBookLibrary.Models.Externals;
namespace MBookLibrary.Business
{
public class BookService : ServiceBase, IBookService
{
private IMapper mapper;
private IBookRepository repository;
public BookService(IMapper mapper, IBookRepository repository)
{
this.mapper = mapper;
this.repository = repository;
}
public int Add(BookModel bookModel)
{
var bookDetailsFactory = new BookDetailsFactory<OpenLibraryBookService>();
var details = bookDetailsFactory.GetBookDetails(bookModel.ISBN);
Book book = mapper.Map<BookDetails, Book>(details);
repository.Add(book);
return book.Id;
}
public void Delete(int Id)
{
repository.DeleteById(Id);
}
public List<BookModel> Find(BookSearchCriteriaModel criteria)
{
return mapper.Map<List<Book>, List<BookModel>>(repository.FindBy(x => x.ISBN == criteria.ISBN || x.Author.Contains(criteria.Author) || x.Genre.Contains(criteria.Genre) || x.Title.Contains(criteria.Title)).ToList());
}
public List<BookModel> GetAll()
{
return mapper.Map<List<Book>, List<BookModel>>(repository.GetAll().ToList());
}
public BookModel GetById(int Id)
{
return mapper.Map<Book, BookModel>(repository.GetAll().FirstOrDefault(x=>x.Id == Id));
}
public void Update(BookModel bookModel)
{
Book book = mapper.Map<BookModel, Book>(bookModel);
repository.Update(book);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using MBookLibrary.Business;
using MBookLibrary.Data.EF;
using MBookLibrary.Data.Entities;
using MBookLibrary.Data.Repository;
using MBookLibrary.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
namespace MBookLibrary.Service
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Book API", Version = "v1" });
});
services
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<BookContext>((serviceProvider, options) =>
options.UseInMemoryDatabase("MBookLibrary")
.UseInternalServiceProvider(serviceProvider));
services.AddTransient<IBookService, BookService>();
services.AddTransient<IBookRepository, BookRepository>();
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseSwagger();
app.UseCors(MyAllowSpecificOrigins);
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Book API V1");
});
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { IBook } from '../../models/book';
import { IBookFilter } from '../../models/book-filter';
import { BookService } from '../../services/book.service';
@Component({
selector: 'app-book-list',
templateUrl: './book-list.component.html',
styleUrls: ['./book-list.component.css']
})
export class BookListComponent implements OnInit {
pageTitle = 'Book List';
imageWidth = 50;
imageMargin = 2;
errorMessage = '';
_listFilter: IBookFilter = { isbn : '', title : '', author : '', genre : '' };
get listFilter(): IBookFilter {
return this._listFilter;
}
set listFilter(value: IBookFilter) {
this._listFilter = value;
}
books: IBook[] = [];
constructor(private bookService: BookService) {
}
performFilter(filterBy: IBookFilter) {
this.bookService.getBooks(filterBy).subscribe(
books => {
this.books = books;
},
error => this.errorMessage = <any>error
);
}
ngOnInit(): void {
let filterBy: IBookFilter = { isbn: '', title: '', author: '', genre: '' };
this.performFilter(filterBy);
}
}
<file_sep>export interface IBookFilter {
title: string;
author: string;
genre: string;
isbn: string;
}
<file_sep>using MBookLibrary.Data.Entities;
using MBookLibrary.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace MBookLibrary.Business
{
public interface IBookService
{
int Add(BookModel book);
void Update(BookModel book);
List<BookModel> GetAll();
BookModel GetById(int Id);
List<BookModel> Find(BookSearchCriteriaModel criteria);
void Delete(int Id);
}
}
<file_sep>using System;
using MBookLibrary.Models.Externals;
namespace MBookLibrary.Externals
{
public class BookDetailsFactory<T> where T : IBookDetailService
{
public BookDetailsFactory()
{
}
public BookDetails GetBookDetails(string isbnCode) {
IBookDetailService detailService = null;
if (typeof(T) == typeof(OpenLibraryBookService))
detailService = new OpenLibraryBookService();
if (detailService != null)
{
detailService.Init();
return detailService.GetBookDetails(isbnCode);
}
return null;
}
}
}
<file_sep>using System;
namespace MBookLibrary.Models.Externals
{
public class BookDetails
{
public string ISBN { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace MBookLibrary.Common
{
public enum EntityStatus : int
{
Undefined = 0,
Active = 1,
Deleted = 2
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MBookLibrary.Business;
using MBookLibrary.Models;
using Microsoft.AspNetCore.Mvc;
namespace MBookLibrary.Service.Controllers
{
[Route("api/books")]
[ApiController]
public class BooksController : ControllerBase
{
private readonly IBookService _service;
public BooksController(IBookService service)
{
_service = service;
}
// GET api/values
[HttpPost("find")]
public ActionResult<List<BookModel>> Find([FromBody]BookSearchCriteriaModel criteriaModel)
{
return _service.Find(criteriaModel);
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<BookModel> Get(int id)
{
return _service.GetById(id);
}
// POST api/values
[HttpPost("add")]
public void Post([FromBody] BookModel bookModel)
{
_service.Add(bookModel);
}
// PUT api/values/5
[HttpPut("update")]
public void Put([FromBody] BookModel bookModel)
{
_service.Update(bookModel);
}
// DELETE api/values/5
[HttpDelete("delete/{id}")]
public void Delete(int id)
{
_service.Delete(id);
}
}
}
<file_sep>using MBookLibrary.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace MBookLibrary.Data.Repository
{
public interface IBookRepository
{
IQueryable<Book> GetAll();
IQueryable<Book> FindBy(Expression<Func<Book, bool>> predicate);
void Add(Book entity);
void Update(Book entity);
void Delete(Book entity);
void DeleteById(int id);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace MBookLibrary.Business
{
public abstract class ServiceBase
{
}
}
<file_sep>using System;
using MBookLibrary.Models.Externals;
namespace MBookLibrary.Externals
{
public class OpenLibraryBookService : IBookDetailService
{
public OpenLibraryBookService()
{
}
public void Init()
{
throw new NotImplementedException();
}
public BookDetails GetBookDetails(string isbnCode)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
namespace MBookLibrary.Models
{
public class BookSearchCriteriaModel : ModelBase
{
public string ISBN { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace MBookLibrary.Models
{
public abstract class ModelBase
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using MBookLibrary.Business;
using MBookLibrary.Models;
using MBookLibrary.Service.Controllers;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace MBookLibrary.Service.Test
{
public class BooksControllerUnitTest
{
[Fact]
public void TestFirstBook()
{
// Arrange
var mockRepo = new Mock<IBookService>();
mockRepo.Setup(repo => repo.GetById(1))
.Returns(GetFirstBook());
var controller = new BooksController(mockRepo.Object);
//Act
var result = controller.Get(1);
//Assert
var viewResult = Assert.IsType<ActionResult<BookModel>>(result);
var model = Assert.IsAssignableFrom<BookModel>(viewResult);
Assert.Equal("First Book", model.Title);
}
private BookModel GetFirstBook()
{
return new BookModel() { Id = 1, Title = "First Book" };
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace MBookLibrary.Models
{
public class BookModel
{
public int Id { get; set; }
public string ISBN { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
}
}
<file_sep>using MBookLibrary.Common;
using MBookLibrary.Data.EF;
using MBookLibrary.Data.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Linq.Expressions;
namespace MBookLibrary.Data.Repository
{
public class BookRepository : IBookRepository
{
private BookContext context;
public BookRepository(BookContext context)
{
this.context = context;
}
#region IBookRepository Member(s)
public virtual IQueryable<Book> GetAll()
{
IQueryable<Book> query = context.Set<Book>().Where(x => x.State == EntityStatus.Active);
return query;
}
public virtual Book GetById(int id)
{
return context.Set<Book>().FirstOrDefault(x => x.Id == id);
}
public IQueryable<Book> FindBy(System.Linq.Expressions.Expression<Func<Book, bool>> predicate)
{
IQueryable<Book> query = GetAll().Where(predicate);
return query;
}
public Book FirstOrDefault(System.Linq.Expressions.Expression<Func<Book, bool>> predicate)
{
return context.Set<Book>().Where(x => x.State == EntityStatus.Active).FirstOrDefault(predicate);
}
public virtual void Add(Book book)
{
book.State = EntityStatus.Active;
book.Id = context.Books.Count() + 1;
context.Set<Book>().Add(book);
Save();
}
public virtual void Delete(Book book)
{
book.CanceledDate = DateTime.Now;
book.State = EntityStatus.Deleted;
Save();
}
public virtual void DeleteById(int id)
{
Book book = context.Set<Book>().FirstOrDefault(x => x.Id == id);
if (book != null)
{
Delete(book);
}
}
public void Update(Book book)
{
context.Entry(book).State = EntityState.Modified;
Save();
}
public virtual void Save()
{
foreach (var item in context.ChangeTracker.Entries<Book>())
{
if (item.State == EntityState.Added || item.State == EntityState.Modified)
{
if (item.Entity.State != EntityStatus.Deleted)
{
item.Entity.ModifiedDate = DateTime.Now;
}
}
}
context.SaveChanges();
}
#endregion
#region IDisposable Member(s)
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| c020ec3110b83ce9301062bf93bdd5c7d3d8855e | [
"C#",
"TypeScript"
] | 21 | C# | ibrahimuylas/MBookLibrary | 880335af1ba0dd263bf09c41201641554436e6ed | 6452f4327b322f824ca40a588f3adfc2c9bbf478 |
refs/heads/master | <file_sep>
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class ProxyServer implements Runnable{
public static void main(String[] args) throws IOException {
String setup = "";
String filepath = args[0];
File file = new File("setup.txt"); //creates a new file instance
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
setup += line;
}
}
int port;
String [] words = new String[4];
String path = "";
//System.out.println(setup);
port= Integer.parseInt(setup.substring(11,15));
//System.out.println(port);
words[0] = setup.substring(21,26);
words[1] = setup.substring(27,35);
words[2] = setup.substring(36,43);
words[3] = setup.substring(44,55);
/*System.out.println(words[0]);
System.out.println(words[1]);
System.out.println(words[2]);
System.out.println(words[3]);*/
path = setup.substring(65,72);
//System.out.println(path);
// Stworzenie instancji klasy Proxy ktory zaczyna nasłuchiwać
ProxyServer myProxyServer = new ProxyServer(port);
myProxyServer.listen(path,words);
}
private ServerSocket serverSocket;
/**
* Semafor dla proxy
*/
private volatile boolean running = true;
/**
* Struktura danych dla ciągłego wyszukiwania pozycji w pamięci podręcznej.
* Klucz: URL żądanej strony/obrazka.
* Wartość: Plik w pamięci masowej powiązany z tym kluczem.
*/
static HashMap<String, File> vcvbxb;
/**
* ArrayLista wątków, które są obecnie uruchamiane i serwisowane.
* Lista ta jest wymagana, aby dołączyć do wszystkich wątków po zamknięciu serwera
*/
static ArrayList<Thread> czxczcxz;
/**
* Stworzenie Serwera Proxy
* @param port numer portu na ktorym bedzie sluchal serwer
*/
public ProxyServer(int port) {
czxczcxz = new ArrayList<>();
vcvbxb = new HashMap<>();
new Thread(this).start();
try{
// Load in cached sites from file
File dsadsa = new File("cachedSites.txt");
if(!dsadsa.exists()){
System.out.println("No cached sites found - creating new file");
dsadsa.createNewFile();
} else {
FileInputStream fileInputStream = new FileInputStream(dsadsa);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
vcvbxb = (HashMap<String,File>)objectInputStream.readObject();
fileInputStream.close();
objectInputStream.close();
}
} catch (IOException e) {
System.out.println("Error loading previously cached sites file");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Class not found loading in preivously cached sites file");
e.printStackTrace();
}
try {
serverSocket = new ServerSocket(port);
System.out.println("Listening on Port " + serverSocket.getLocalPort() + "..");
running = true;
}
catch (SocketException se) {
System.out.println("Socket Exception when connecting to client");
se.printStackTrace();
}
catch (SocketTimeoutException ste) {
System.out.println("Timeout occured while connecting to client");
}
catch (IOException io) {
System.out.println("IO exception when connecting to client");
}
}
/**
* Przesłuchuje port i akceptuje nowe połączenia gniazd.
* Tworzy nowy wątek do obsługi żądania i przekazuje mu połączenie z gniazdem i kontynuuje odsłuchiwanie.
*/
public void listen(String path,String words[]){
while(running){
try {
Socket socket = serverSocket.accept();
Thread thread = new Thread(new Polaczenia(socket,path,words));
czxczcxz.add(thread);
thread.start();
} catch (SocketException e) {
System.out.println("Server closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Zapisuje zbuforowane strony do pliku, aby można je było ponownie załadować w późniejszym czasie.
* Łączy również wszystkie wątki klasy Polaczenia, które są obecnie serwisowane.
*/
private void closeServer(){
System.out.println("\nClosing Server..");
running = false;
try{
FileOutputStream fileOutputStream = new FileOutputStream("cachedSites.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(vcvbxb);
objectOutputStream.close();
fileOutputStream.close();
System.out.println("Cached Sites written");
try{
// Close all servicing threads
for(Thread thread : czxczcxz){
if(thread.isAlive()){
System.out.print("Waiting on "+ thread.getId()+" to close..");
thread.join();
System.out.println(" closed");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Error saving cache sites");
e.printStackTrace();
}
// Close Server Socket
try{
System.out.println("Terminating Connection");
serverSocket.close();
} catch (Exception e) {
System.out.println("Exception closing proxy's server socket");
e.printStackTrace();
}
}
/**
* Szuka pliku w cache'u
* @param url
*/
public static File getCache(String url){
return vcvbxb.get(url);
}
/**
* Dodaje nowe strony do cache'a
* @param urlString
* @param fileToCache
*/
public static void addCache(String urlString, File fileToCache){
vcvbxb.put(urlString, fileToCache);
}
/**
* Tworzy interfejs zarządzania, który może dynamicznie aktualizować konfiguracje proxy
*
* close : closing server
*
*/
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
String command;
System.out.println("Enter \"close\" to shut down server");
while(running){
command = scanner.nextLine();
if(command.equals("close")){
running = false;
closeServer();
}
}
scanner.close();
}
}
<file_sep># ProxyServerJava
Http/Https Proxy Server written in Java 8
To start server just run start.bat file. cached sites will be stored under c:/cached/
if you want to change it just edit start.bat on the first line
Source Code is obfuscated.
| 7b2e31ced667017e4cf1f759a861734a46704c7e | [
"Markdown",
"Java"
] | 2 | Java | kacrat99/ProxyServerJava | e77f2db920d63f354fa41b4c21be1f2bd70f01b7 | 46741dd1d8e05fe51e464c71ffeef0d65c018b45 |
refs/heads/master | <file_sep>platform :ios, '12.4'
target 'route-checker' do
use_frameworks!
pod 'TinyConstraints'
pod 'IBAnimatable'
pod 'Alertift'
pod 'Toast-Swift'
pod 'FontAwesome.swift'
pod 'Alamofire'
end
<file_sep>//
// ViewController.swift
// route-checker
//
// Created by <NAME> on 2020/09/17.
// Copyright © 2020 <EMAIL>. All rights reserved.
//
import UIKit
import MapKit;
import IBAnimatable;
class ViewController: UIViewController {
@IBOutlet weak var button: AnimatableButton!
@IBOutlet weak var mapView: MKMapView!
private var locationManager:CLLocationManager?;
private var locations:[CLLocation] = [];
private var coordinates:[CLLocationCoordinate2D] = [];
private var isRecording:Bool = false;
private var polyLines:[MKPolyline] = [];
internal
override func viewDidLoad() {
super.viewDidLoad()
if locationManager != nil { return }
locationManager = CLLocationManager()
locationManager!.delegate = self
locationManager!.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager!.startUpdatingLocation()
}
// tracking user location
mapView.showsCompass = true;
mapView.userTrackingMode = .follow;
mapView.showsUserLocation = true
mapView.zoomLevel = 19;
mapView.delegate = self;
self.button.addTarget(self, action: #selector(self.onButtonTap), for: .touchUpInside);
self.button.backgroundColor = .white;
self.button.setTitleColor(.red, for: .normal);
self.button.borderColor = .red;
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first! //このタッチイベントの場合確実に1つ以上タッチ点があるので`!`つけてOKです
let location = touch.location(in: self.view) //in: には対象となるビューを入れます
self.update(location);
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first! //このタッチイベントの場合確実に1つ以上タッチ点があるので`!`つけてOKです
let location = touch.location(in: self.view) //in: には対象となるビューを入れます
event?.coalescedTouches(for: touch);
self.update(location);
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first! //このタッチイベントの場合確実に1つ以上タッチ点があるので`!`つけてOKです
let location = touch.location(in: self.view) //in: には対象となるビューを入れます
self.update(location);
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first! //このタッチイベントの場合確実に1つ以上タッチ点があるので`!`つけてOKです
let location = touch.location(in: self.view) //in: には対象となるビューを入れます
self.update(location);
if (self.isRecording) {
self.updateLine();
}
}
func update(_ location:CGPoint) {
if (!self.isRecording) {return;}
var coord = self.mapView.convert(location, toCoordinateFrom: self.view);
self.coordinates.append(coord);
print(self.coordinates.count);
return;
}
func updateLine() {
let polyLine = MKPolyline(coordinates:self.coordinates , count: self.coordinates.count);
// let polyLine = MKPolyline(coordinates:self.locations.map{$0.coordinate} , count: self.locations.count);
self.mapView.removeOverlays(self.mapView.overlays);
self.mapView.addOverlay(polyLine);
}
@objc func onButtonTap() {
if (!self.isRecording) {
self.start();
}else{
self.stop();
}
}
private func start() {
if (self.isRecording) { return; }
self.isRecording = true;
mapView.isUserInteractionEnabled = false;
self.locations = [];
self.coordinates = [];
self.updateLine();
self.button.backgroundColor = .red;
self.button.setTitleColor(.white, for: .normal);
self.button.borderColor = .white;
self.mapView.userTrackingMode = .none;
}
private func stop() {
if (!self.isRecording) { return; }
self.isRecording = false;
mapView.isUserInteractionEnabled = true;
self.button.backgroundColor = .white;
self.button.setTitleColor(.red, for: .normal);
self.button.borderColor = .red;
self.mapView.userTrackingMode = .follow;
}
}
extension ViewController:MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let polyline = overlay as? MKPolyline {
let polylineRenderer = MKPolylineRenderer(polyline: polyline)
polylineRenderer.strokeColor = .blue
polylineRenderer.lineWidth = 2.0
return polylineRenderer
}
return MKOverlayRenderer()
}
}
extension ViewController:CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
manager.requestWhenInUseAuthorization()
case .restricted, .denied:
break
case .authorizedAlways, .authorizedWhenInUse:
break
@unknown default:
fatalError()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// mapView.userTrackingMode = .follow
guard let newLocation = locations.last else {
return
}
// if (self.isRecording) {
// self.locations += locations;
//
//
// var coordinateInput:[CLLocationCoordinate2D] = ;
//
//// if (self.polyLines.count > 1) {
//// self.mapView.removeOverlay(self.polyLines.remove(at: 0));
//// }
//
// if (self.polyLines.count == 0) {
//
// }else{
// self.mapView.exchangeOverlay(self.polyLines.first!, with: polyLine);
//
// self.polyLines.remove(at: 0);
// }
// self.polyLines.append(polyLine);
//
// DispatchQueue.main.async {
// }
// }
// let location:CLLocationCoordinate2D
// = CLLocationCoordinate2DMake(newLocation.coordinate.latitude, newLocation.coordinate.longitude);
// var region:MKCoordinateRegion = mapView.region
// region.center = location
// mapView.setRegion(region,animated:true);
// let latitude = "".appendingFormat("%.4f", location.latitude)
// let longitude = "".appendingFormat("%.4f", location.longitude)
// latLabel.text = "latitude: " + latitude
// lngLabel.text = "longitude: " + longitude
// update annotation
// mapView.removeAnnotations(mapView.annotations)
//
// let annotation = MKPointAnnotation()
// annotation.coordinate = newLocation.coordinate
// mapView.addAnnotation(annotation)
// mapView.selectAnnotation(annotation, animated: true)
//
// // Showing annotation zooms the map automatically.
// mapView.showAnnotations(mapView.annotations, animated: true);
// mapView.zoomLevel = 14;
}
}
extension MKMapView {
var zoomLevel: Int {
get {
return Int(log2(360 * (Double(self.frame.size.width/256) / self.region.span.longitudeDelta)) + 1);
}
set (newZoomLevel){
setCenterCoordinate(coordinate:self.centerCoordinate, zoomLevel: newZoomLevel, animated: false)
}
}
private func setCenterCoordinate(coordinate: CLLocationCoordinate2D, zoomLevel: Int, animated: Bool) {
let span = MKCoordinateSpan(latitudeDelta: 0, longitudeDelta: 360 / pow(2, Double(zoomLevel)) * Double(self.frame.size.width) / 256)
setRegion(MKCoordinateRegion(center: coordinate, span: span), animated: animated)
}
}
| 5d823bf1c33287302e47fb4657bfe1f024828913 | [
"Swift",
"Ruby"
] | 2 | Ruby | atrasc-uchida/route-checker | 8d869de4b40217f4b75370ae6f4e8cfdfba7d713 | f47cf427a4590e744cab59769da9be0993f8746f |
refs/heads/main | <repo_name>AntoineBarnoin/CSF-Projet-objet-perdu<file_sep>/Arduino Code/CSF.ino
#include <Wire.h>
#include <SPI.h>
#include "i2c.h"
#include "i2c_BMP280.h"
#include "i2c_MMA8451.h"
#include <LoRa.h>
BMP280 bmp280;
MMA8451 mma8451;
int txPower = 14; // from 0 to 20, default is 14
int spreadingFactor = 9; // from 7 to 12, default is 12
long signalBandwidth = 125E3; // 7.8E3, 10.4E3, 15.6E3, 20.8E3, 31.25E3,41.7E3,62.5E3,125E3,250E3,500e3, default is 125E3
int codingRateDenominator=5; // Numerator is 4, and denominator from 5 to 8, default is 5
int preambleLength=8; // from 2 to 20, default is 8
float x = 0;
float y = 0;
float z = 0;
int t = 0;
float altitude = 0;
#define SS 10
#define RST 8
#define DI0 3
#define BAND 865E6 // Here you define the frequency carrier
void setup() {
Serial.begin(115200);
if (bmp280.initialize()) Serial.println("Sensor found");
else
{
Serial.println("Sensor missing");
while (1) {}
}
bmp280.setEnabled(0);
bmp280.triggerMeasurement();
bmp280.awaitMeasurement();
float temperature;
bmp280.getTemperature(temperature);
float Pascal;
bmp280.getPressure(Pascal);
static float metres, metersolde;
bmp280.getAltitude(metres);
metersolde = (metersolde * 10 + metres)/11;
bmp280.triggerMeasurement();
Serial.print("La pression de référence est: ");
Serial.print(Pascal);
Serial.println(" Pa");
altitude = Pascal;
SPI.begin();
if (mma8451.initialize());
else
{
Serial.println("Sensor missing");
while(1) {};
}
LoRa.setPins(SS,RST,DI0);
if (!LoRa.begin(BAND)) {
Serial.println("Starting LoRa failed!");
while (1);
}
LoRa.setTxPower(txPower,1);
LoRa.setSpreadingFactor(spreadingFactor);
LoRa.setSignalBandwidth(signalBandwidth);
LoRa.setCodingRate4(codingRateDenominator);
LoRa.setPreambleLength(preambleLength);
}
void loop()
{
LoRa.beginPacket();
bmp280.awaitMeasurement();
float temperature;
bmp280.getTemperature(temperature);
float pascal;
bmp280.getPressure(pascal);
static float metres, metersolde;
bmp280.getAltitude(metres);
metersolde = (metersolde * 10 + metres)/11;
bmp280.triggerMeasurement();
Serial.print(" HeightPT1: ");
Serial.print(metersolde);
Serial.print(" m; Height: ");
Serial.print(metres);
Serial.print(" Pressure: ");
Serial.println(pascal);
Serial.print(" Pa; T: ");
Serial.print(temperature);
Serial.println(" C");
if (altitude < pascal){
LoRa.println("L'objet est plus bas que vous.");
}
else{
LoRa.println("L'objet est plus haut que vous.");
}
static float xyz_g[3];
mma8451.getMeasurement(xyz_g);
if ((x!=xyz_g[0])|(y!=xyz_g[1])|(z!=xyz_g[2])) {
LoRa.println("L'objet est en mouvement");
}
x = xyz_g[0];
y = xyz_g[1];
z = xyz_g[2];
delay(1000);
LoRa.endPacket();
}
<file_sep>/README.md
# CSF-Projet-objet-perdu
| 2abe39b33a7e7f6a3f4e047d9e97a095376bf38e | [
"Markdown",
"C++"
] | 2 | C++ | AntoineBarnoin/CSF-Projet-objet-perdu | 629900c2e9a3cb161b3db8d8883480fe74538e78 | 0e9e19ea3bb0842f69ced7a050b17e871f8d592f |
refs/heads/master | <file_sep># Discord UI Clone | Rocketseat
Discord layout created using ReactJS.
## Libraries
- Styled components
- Styled Icons
## CSS
- Flexbox
- Gridlayout
## Challenges
- [x] Hide icons and just show when the mouse is hovering.
## Improves
- Only the channel title can be selected (or have a white text) when the mouse is hovering or the channel is selected.
- Removed bold effect just in nicknames of user list of server.
- Fixed bug in avatar icon of message on zoom.
- Added verify tag in flag of bot.
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
To know more about Rocketseat company, [click here](https://rocketseat.com.br/).
<file_sep>import styled from 'styled-components';
// SL - Server List
// SN - Server Name
// CI - Channel Info
// CL - Channel List
// CD - Channel Data
// UL - User List
// UI - User Info
/**
* A única parte responsiva da aplicação é o container responsável pelas
* mensagens, logo ela fica com tanho em auto para se ajustar conforme
* tamanho da tela
*/
export const Grid = styled.div`
display: grid;
grid-template-columns: 71px 240px auto 240px;
grid-template-rows: 46px auto 52px;
grid-template-areas:
'SL SN CI CI'
'SL CL CD UL'
'SL UI CD UL';
height: 100vh;
`;
| 9ee0a9d71bf2cc3a7e8a27d3c3e71fb26e7baaf8 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | willz3/discord-front-clone | ff44766fa0a0956217eb58d8fc3172aec109ed81 | e63295c092b0b624290152b74ec7fb107f19b837 |
refs/heads/master | <repo_name>SnowpitData/AvscienceServer-2.0<file_sep>/README.md
# AvscienceServer-2.0
New version of snow pilot data services, JSON and XML.
This is the newest version of the snow pilot data services.
These data services will run on a J2EE server such as Tomcat and access the snow pilot MySQL DB.
The data services abstract the snow pilot db and data model,
and produce and consume xml and json documents to interface various clients with the snow pilot
database.
These data services use the Snow Pilot Data Objects library, which are a java implmenetation of the the snow pilot data model.
<file_sep>/src/avscience/server/DAO.java
package avscience.server;
import java.sql.*;
import java.util.*;
import java.io.*;
import avscience.ppc.*;
import java.security.MessageDigest;
public class DAO {
private final static String DBUrl = "jdbc:mysql:///avscience_dev";
java.util.Date startDate = new java.util.Date(114, 4, 19);
public DAO() {
System.out.println("DAO() StartDate: " + startDate.toString());
loadDriver();
}
public static void setNewsProps(String newNews) {
Properties props = getNewsProps();
props.setProperty("current_news", newNews);
try {
File file = new File("news.properties");
FileOutputStream fout = new FileOutputStream(file);
props.save(fout, "new_change");
} catch (Exception e) {
System.out.println(e.toString());
}
}
static Properties getNewsProps() {
Properties props = new Properties();
try {
File file = new File("news.properties");
FileInputStream fin = new FileInputStream(file);
props.load(fin);
} catch (Exception e) {
System.out.println(e.toString());
}
return props;
}
public String getNews() {
System.out.println("getNews()");
Properties props = getNewsProps();
String news = props.getProperty("current_news");
return news;
}
public void addPitXML(String serial, String xml) {
System.out.println("addPitXML");
String query = "UPDATE PIT_TABLE SET PIT_XML = ? WHERE SYSTEM_SERIAL = ?";
try {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, xml);
ps.setString(2, serial);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("PIT XML added.");
} else {
System.out.println("PIT XML NOT added!!");
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
public boolean checkBuild(avscience.ppc.PitObs pit) {
int bld = pit.getBuild();
/// build # on whick pit changed to top/bottom instead of start/end
if (bld >= 563) {
return true;
} else {
return false;
}
}
public void writeECPTTestPits() {
File pitfile = new File("/Users/markkahrl/ISSW2014_PitData.csv");
File joinfile = new File("/Users/markkahrl/JoinData.csv");
File testfile = new File("/Users/markkahrl/CT_TestData.csv");
StringBuffer pitBuffer = new StringBuffer();
StringBuffer joinBuffer = new StringBuffer();
StringBuffer testBuffer = new StringBuffer();
pitBuffer.append("SERIAL ; OBSERVER ; LOCATION ; MTN_RANGE ; STATE ; ELV ; ELV_UOM ; LAT ; LONG ; ASPECT ; INCLINE ; PRECIP ; SKY ; WINDSPEED ; WIND_DIR ; WIND_LOADING ; AIR_TEMP ; AIR_TEMP_UOM ; STABILITY ; MEASURE_FROM ; DATE ; DEPTH_UNITS ; DENSITY_UNITS ; PI_DEPTH \n");
joinBuffer.append("pit_serial,ecScore , CTScore,ECT ShearQuality , CT ShearQuality, Total depth,depth to problematic layer , number of taps, Release type,length of cut ,length of column , slope angle, depth units \n");
testBuffer.append("pit_serial, Score, CTScore \n");
Hashtable pits = getAllPits();
Enumeration e = pits.keys();
while (e.hasMoreElements()) {
String serial = (String) e.nextElement();
String dat = (String) pits.get(serial);
avscience.ppc.PitObs pit = null;
try
{
pit = new avscience.ppc.PitObs(dat);
}
catch(Exception ee)
{
System.out.println(ee.toString());
continue;
}
avscience.ppc.Location loc = pit.getLocation();
if (loc == null) {
loc = new avscience.ppc.Location();
}
System.out.println("writing tests for pit: " + serial);
java.util.Enumeration tests = pit.getShearTests();
boolean hasCTTest = false;
boolean hasECPTTest = false;
while (tests.hasMoreElements()) {
avscience.ppc.ShearTestResult result = (avscience.ppc.ShearTestResult) tests.nextElement();
String code = result.getCode().trim();
String score = result.getScore().trim();
System.out.println("Pit:: " + serial + " code " + code + " Score: " + score);
if (code.equals("CT")) {
hasCTTest = true;
}
if (score.equals("ECTP")) {
hasECPTTest = true;
}
}
if (true) /// if (hasCTTest & hasECPTTest)
{
avscience.ppc.Layer l = pit.getPILayer();
System.out.println("writing data for pit: " + serial);
pitBuffer.append(serial + " ; ");
// pitBuffer.append(u.getFirst() + " " + u.getLast() + " ; ");
pitBuffer.append(loc.getName() + " ; ");
pitBuffer.append(loc.getRange() + " ; ");
pitBuffer.append(loc.getState() + " ; ");
pitBuffer.append(loc.getElv() + " ; ");
pitBuffer.append(pit.getPrefs().getElvUnits() + " ; ");
pitBuffer.append(loc.getLat() + " ; ");
pitBuffer.append(loc.getLongitude() + " ; ");
pitBuffer.append(pit.getAspect() + " ; ");
pitBuffer.append(pit.getIncline() + " ; ");
pitBuffer.append(pit.getPrecip() + " ; ");
pitBuffer.append(pit.getSky() + " ; ");
pitBuffer.append(pit.getWindspeed() + " ; ");
pitBuffer.append(pit.getWinDir() + " ; ");
pitBuffer.append(pit.getWindLoading() + " ; ");
pitBuffer.append(pit.getAirTemp() + " ; ");
pitBuffer.append(pit.getPrefs().getTempUnits() + " ; ");
pitBuffer.append(pit.getStability() + " ; ");
pitBuffer.append(pit.getMeasureFrom() + " ; ");
pitBuffer.append(pit.getDate() + " ; ");
// pitBuffer.append(pit.getTime() + " ; ");
/// pitBuffer.append(pit.getPitNotes()+", ");
pitBuffer.append(pit.getPrefs().getDepthUnits() + " ; ");
pitBuffer.append(pit.getPrefs().getRhoUnits() + " ;");
pitBuffer.append(pit.iDepth + "\n");
////////
System.out.println("writing tests for pit: " + serial);
tests = pit.getShearTests();
avscience.ppc.ShearTestResult ectTest = null;
avscience.ppc.ShearTestResult ctTest = null;
String numberOfTaps = null;
String releaseType = null;
String lengthOfCut = null;
String lengthOfColumn = null;
while (tests.hasMoreElements()) {
avscience.ppc.ShearTestResult result = (avscience.ppc.ShearTestResult) tests.nextElement();
String code = result.getCode();
String score = result.getScore();
String rt = result.getReleaseType();
rt = rt.trim();
if (rt.length() > 0) {
releaseType = rt;
}
/////
String nt = result.numberOfTaps;
nt = nt.trim();
if (nt.length() > 0) {
numberOfTaps = nt;
}
String lc = result.lengthOfCut;
lc = lc.trim();
if (lc.length() > 0) {
lengthOfCut = lc;
}
String lcc = result.lengthOfColumn;
lcc = lcc.trim();
if (lcc.length() > 0) {
lengthOfColumn = lcc;
}
// int scr = new java.lang.Integer(score).intValue();
int ecScore = result.getECScoreAsInt();
int ctScore = result.getCTScoreAsInt();
if (ectTest != null) {
if (ecScore != 0) {
if (ecScore < ectTest.getECScoreAsInt()) {
ectTest = result;
}
}
}
if (score.equals("ECTP") & ectTest == null) {
ectTest = result;
}
if (ctTest != null) {
if (ctScore != 0) {
if (ctScore > ctTest.getCTScoreAsInt()) {
ctTest = result;
}
}
}
if (score.equals("ECTP") & ectTest == null) {
ectTest = result;
}
if (code.equals("CT") & ctTest == null) {
ctTest = result;
}
////
if (code.equals("CT")) {
testBuffer.append(serial + ", " + result.getScore() + ", " + result.getCTScore() + "\n");
}
}
// joinBuffer.append(serial+", "+ectTest.getECScore()+", "+ctTest.getCTScore()+", "+ectTest.getQuality()+", "+ctTest.getQuality()+", "+getMaxDepth(pit)+", "+pit.iDepth+", "+numberOfTaps+", "+releaseType+", "+lengthOfCut+", "+lengthOfColumn+", "+pit.getIncline()+", " +pit.getUser().getDepthUnits()+"\n");
}
}
FileOutputStream out = null;
PrintWriter writer = null;
try {
out = new FileOutputStream(testfile);
writer = new PrintWriter(out);
} catch (Exception ex) {
System.out.println(ex.toString());
}
try {
writer.print(testBuffer.toString());
writer.flush();
writer.close();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public int getMaxDepth(avscience.ppc.PitObs pit) {
System.out.println("getMaxDepth");
int max = 0;
if (pit == null) {
System.out.println("PIT IS NULL.");
return 0;
}
System.out.println("max depth layers.");
java.util.Enumeration e = null;
if (pit.hasLayers()) {
e = pit.getLayers();
if (e != null) {
while (e.hasMoreElements()) {
avscience.ppc.Layer l = (avscience.ppc.Layer) e.nextElement();
int end = l.getEndDepthInt();
if (end > max) {
max = end;
}
int start = l.getStartDepthInt();
if (start > max) {
max = start;
}
}
}
}
System.out.println("max depth tests.");
if (max == 0) {
e = pit.getShearTests();
if (e != null) {
while (e.hasMoreElements()) {
avscience.ppc.ShearTestResult result = (avscience.ppc.ShearTestResult) e.nextElement();
int depth = result.getDepthValueInt();
if (depth > max) {
max = depth;
}
}
}
// max+=6;
}
return max;
}
void writePitToFile(avscience.ppc.PitObs pit) {
///avscience.ppc.User u = pit.getUser();
FileOutputStream out = null;
PrintWriter writer = null;
File file = new File("TestPitFile.txt");
try {
out = new FileOutputStream(file);
writer = new PrintWriter(out);
} catch (Exception ex) {
System.out.println(ex.toString());
}
StringBuffer buffer = new StringBuffer();
avscience.ppc.Location loc = pit.getLocation();
buffer.append(pit.getDateString() + "\n");
// buffer.append("Observer ," + u.getFirst() + " " + u.getLast() + "\n");
buffer.append("Location ," + loc.getName() + "\n");
buffer.append("Mtn Range ," + loc.getRange() + "\n");
buffer.append("State/Prov ," + loc.getState() + "\n");
buffer.append("Elevation " + pit.getPrefs().getElvUnits() + " ," + loc.getElv() + "\n");
buffer.append("Lat. ," + loc.getLat() + "\n");
buffer.append("Long. ," + loc.getLongitude() + "\n");
Hashtable labels = getPitLabels();
// avscience.util.Hashtable atts = pit.attributes;
Enumeration e = labels.keys();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
String v ="";
try
{
v = (String) pit.get(s);
}
catch(Exception ee)
{
System.out.println(ee.toString());
}
String l = (String) labels.get(s);
s = l + " ," + v + "\n";
if (!(s.trim().equals("null"))) {
buffer.append(s);
}
}
buffer.append("Activities: \n");
java.util.Enumeration ee = pit.getActivities().elements();
while (ee.hasMoreElements()) {
String s = (String) ee.nextElement();
buffer.append(s + "\n");
}
if (file == null) {
return;
}
try {
out = new FileOutputStream(file);
writer = new PrintWriter(out);
} catch (Exception ex) {
System.out.println(ex.toString());
}
try {
writer.print(buffer.toString());
writer.flush();
writer.close();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public LinkedHashMap getPitsFromQuery(String whereclause) {
System.out.println("getPitsFromQuery(): " + whereclause);
LinkedHashMap v = new LinkedHashMap();
String[][] pits = getPitListArrayFromQuery(whereclause, false);
for (int i = 0; i < pits[1].length; i++) {
String serial = pits[1][i];
String data = getPPCPit(serial);
v.put(serial, data);
}
return v;
}
public String[][] getPitStringArrayFromQuery(String whereclause) {
System.out.println("getPitsFromQuery(): " + whereclause);
String[][] pits = getPitListArrayFromQuery(whereclause, false);
String[][] rpits = new String[3][pits[1].length];
for (int i = 0; i < pits[1].length; i++) {
String serial = pits[1][i];
String data = getPPCPit(serial);
String name = pits[0][i];
rpits[0][i] = serial;
rpits[1][i] = name;
rpits[2][i] = data;
}
return rpits;
}
Hashtable getPitLabels() {
Hashtable attributes = new Hashtable();
attributes.put("aspect", "Aspect");
attributes.put("incline", "Slope Angle");
attributes.put("precip", "Precipitation");
attributes.put("sky", "Sky Cover");
attributes.put("windspeed", "Wind Speed");
attributes.put("winDir", "Wind Direction");
attributes.put("windLoading", "Wind Loading");
attributes.put("airTemp", "Air Temperature");
attributes.put("stability", "Stability on simular slopes");
attributes.put("measureFrom", "Measure from: ");
attributes.put("date", "Date");
attributes.put("time", "Time");
attributes.put("pitNotes", "Notes");
return attributes;
}
private void loadDriver() {
System.out.println("Load Driver..");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
System.out.println("Unable to Load Driver: " + e.toString());
}
}
private Connection getConnection() throws SQLException {
System.out.println("get Connection..");
return DriverManager.getConnection(DBUrl, "root", "port");
}
boolean hasUser(User u) {
String userName = u.getUserName();
boolean has = false;
String query = "SELECT * FROM USER_TABLE WHERE USERNAME ='" + userName + "' AND EMAIL = '"+u.getEmail()+"'";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
has = true;
}
} catch (Exception e) {
System.out.println(e.toString());
}
return has;
}
public boolean addUser(User user) {
boolean add = false;
if (!hasUser(user)) {
add = true;
System.out.println("dao: Adding user: ");
String query = "INSERT INTO USER_TABLE (USERNAME, EMAIL, PROF, AFFIL, FIRST, LAST, PHONE) VALUES (?,?,?,?,?,?,?)";
try {
Connection conn = getConnection();
if (conn == null) {
System.out.println("Connection null::");
} else {
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, user.getUserName());
stmt.setString(2, user.getEmail());
stmt.setBoolean(3, user.getProf());
stmt.setString(4, user.getAffil());
stmt.setString(5, user.getFirst());
stmt.setString(6, user.getLast());
stmt.setString(7, user.getPhone());
int r = stmt.executeUpdate();
if (r > 0) {
System.out.println("User added.");
} else {
System.out.println("User not added.");
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
return add;
}
public void updateUser(User user) {
deleteUser(user);
addUser(user);
}
public void deleteUser(User user) {
String query = "DELETE FROM USER_TABLE WHERE USERNAME = '" + user.getUserName() + "'";
try {
Statement stmt = getConnection().createStatement();
stmt.executeUpdate(query);
} catch (Exception e) {
System.out.println(e.toString());
}
}
public boolean userExist(String userName) {
boolean exist = false;
String query = "SELECT * FROM USER_TABLE WHERE USERNAME ='" + userName + "'";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
exist = true;
}
} catch (Exception e) {
System.out.println(e.toString());
}
return exist;
}
public boolean authWebUser(String userName, String email) {
System.out.println("authWebUser");
System.out.println("user: " + userName);
System.out.println("email: " + email);
boolean auth = false;
String query = "SELECT * FROM USER_TABLE WHERE USERNAME ='" + userName + "' AND EMAIL = '" + email + "'";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
auth = true;
}
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("Auth: " + auth);
return auth;
}
public boolean authDataUser(String userName, String email) {
System.out.println("authWebUser");
System.out.println("user: " + userName);
System.out.println("email: " + email);
boolean auth = false;
String query = "SELECT * FROM USER_TABLE WHERE USERNAME ='" + userName + "' AND EMAIL = '" + email + "'";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
boolean duser = rs.getBoolean("DATAUSER");
auth = duser;
}
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("Auth: " + auth);
return auth;
}
public boolean authSuperUser(String userName, String email) {
System.out.println("authSuperUser");
System.out.println("user: " + userName);
System.out.println("email: " + email);
boolean auth = false;
String query = "SELECT * FROM USER_TABLE WHERE USERNAME ='" + userName + "' AND EMAIL = '" + email + "'";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println("SU: " + rs.getBoolean("SUPERUSER"));
if (rs.getBoolean("SUPERUSER")) {
auth = true;
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("Auth: " + auth);
return auth;
}
private boolean xmlExistsAndUnAltered(String xml)
{
String query = "SELECT PIT_XML FROM PIT_TABLE WHERE PIT_XML = ?";
PreparedStatement stmt = null;
try
{
stmt = getConnection().prepareStatement(query);
stmt.setString(1, xml);
ResultSet rs = stmt.executeQuery();
return rs.next();
}
catch(Exception e)
{
System.out.println(e.toString());
}
return false;
}
private boolean pitUnAltered(String data) {
System.out.println("pitUnAltered()");
boolean un = false;
avscience.ppc.PitObs pit = null;
try
{
pit = new avscience.ppc.PitObs(data);
}
catch(Exception ex)
{
System.out.println(ex.toString());
return false;
}
String name = pit.getName();
String ser = pit.getSerial();
System.out.println("pit: " + name);
if (ser.trim().length() > 0) {
String query = "SELECT PIT_DATA FROM PIT_TABLE WHERE PIT_NAME = ? AND LOCAL_SERIAL = ?";
PreparedStatement stmt = null;
String s = "";
if ((name != null) && (name.trim().length() > 0)) {
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, ser);
ResultSet rs = stmt.executeQuery();
System.out.println("Query executed:");
if (rs.next()) {
System.out.println("Result::");
s = rs.getString("PIT_DATA");
}
un = s.equals(data);
} catch (Throwable e) {
System.out.println(e.toString());
}
}
} else {
System.out.println("no local serial for pit: " + name);
String query = "SELECT PIT_DATA FROM PIT_TABLE WHERE PIT_NAME = ?";
PreparedStatement stmt = null;
String s = "";
if ((name != null) && (name.trim().length() > 0)) {
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
System.out.println("Query executed:");
if (rs.next()) {
System.out.println("Result::");
s = rs.getString("PIT_DATA");
}
un = s.equals(data);
} catch (Throwable e) {
System.out.println(e.toString());
}
}
}
System.out.println("pit unaltered?: " + un);
return un;
}
private boolean occUnAltered(String data) {
System.out.println("occUnAltered");
boolean unaltered = false;
String query = "SELECT SERIAL FROM OCC_TABLE WHERE OCC_DATA = ?";
PreparedStatement stmt = null;
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, data);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
unaltered = true;
}
} catch (Exception e) {
System.out.println(e.toString());
}
return unaltered;
}
public String removeDelims(String s) {
System.out.println("s: " + s);
String d = "'";
char delim = d.charAt(0);
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == delim) {
chars[i] = ' ';
}
}
String result = new String(chars);
System.out.println("result: " + result);
return result;
}
public String generateSerial(PitObs pit)
{
String s = pit.toString();
byte[] bts = s.getBytes();
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] res = md.digest(bts);
long sum = 0;
StringBuffer buffer = new StringBuffer();
for (int i = 0; i<res.length; i++)
{
sum += Math.abs(res[i]);
}
return (sum+"-"+(int)res[0]+(int)res[1]+":"+System.currentTimeMillis());
}
catch(Exception e)
{
System.out.println(e.toString());
return s;
}
}
public int writePitToDB(avscience.ppc.PitObs pit, String xml)
{
if (xmlExistsAndUnAltered(xml))
{
System.out.println("Pit XML already in DB");
return 0;
}
addUser(pit.getUser());
if (pit.getUserHash()==null) pit.setUserhash(pit.getUser());
String system_serial = null;
int retValue = -1;
System.out.println("writePitToDB::PitObs");
if (pit == null)
{
System.out.println("Pit is null !!! ");
return -1;
}
String data = pit.toString();
if (pitPresent(pit))
{
System.out.println("Pit already in DB");
if (pitUnAltered(data))
{
return 0;
}
else
{
system_serial = pit.getSystemSerial();
System.out.println("deleting pit:");
deletePit(pit.getSystemSerial());
}
}
if (system_serial == null)
{
system_serial = generateSerial(pit);
pit.setSystemSerial(system_serial);
}
System.out.println("writing pit to DB : " + pit.getName());
String query = "INSERT INTO PIT_TABLE (PIT_DATA, AIR_TEMP, ASPECT, CROWN_OBS, DATE_TEXT, TIMESTAMP, INCLINE, LOC_NAME, LOC_ID, STATE, MTN_RANGE, LAT, LONGITUDE, NORTH, WEST, ELEVATION, USERHASH, WINDLOADING, PIT_NAME, HASLAYERS, LOCAL_SERIAL, PRECIP, SKY_COVER, WIND_SPEED, WIND_DIR, STABILITY, SHARE, ACTIVITIES, TEST_PIT, PLATFORM, SYSTEM_SERIAL, LAST_UPDATED, PIT_XML, AVIPIT, AVILOC, ILAYER, IDEPTH, SKI_AREA_PIT, BC_PIT, SURFACE_PEN, BOOT_SKI) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
/// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 34 35 36 37 38 39 40 41
String pit_name = pit.generateName();
pit.setName(pit_name);
try {
Connection conn = getConnection();
if (conn == null) {
System.out.println("Connection null::");
return -1;
}
PreparedStatement stmt = conn.prepareStatement(query);
long ptime = 0;
ptime = pit.getTimestamp();
stmt.setString(1, data);
float temp = -999.9f;
System.out.println("setting air temp");
try {
if ((pit.getAirTemp() != null) && (pit.getAirTemp().trim().length() > 0)) {
temp = stringToFloat(pit.getAirTemp());
if (pit.getPrefs().getTempUnits().equals("F")) {
temp = FtoC(temp);
}
}
// air temp C
stmt.setFloat(2, temp);
} catch (Exception e) {
System.out.println(e.toString());
stmt.setFloat(2, -999.9f);
}
System.out.println("setting aspect");
try {
stmt.setInt(3, stringToInt(pit.getAspect()));
} catch (Exception e) {
System.out.println(e.toString());
stmt.setInt(3, -999);
}
// is Crown obs?
System.out.println("setting crown obs");
boolean co = pit.getCrownObs();
stmt.setBoolean(4, co);
/// date of pit
System.out.println("setting datestring");
stmt.setString(5, pit.getDateString());
// date entered here
System.out.println("setting timestamp");
stmt.setDate(6, new java.sql.Date(System.currentTimeMillis()));
// incline
System.out.println("setting incline");
try {
String incl = pit.getIncline();
System.out.println("incline: " + incl);
stmt.setInt(7, stringToInt(incl));
} catch (Exception e) {
System.out.println(e.toString());
stmt.setInt(7, -999);
}
// location
System.out.println("getting loc");
avscience.ppc.Location loc = pit.getLocation();
System.out.println("Locname : " + loc.getName().trim());
String ln = loc.getName().trim();
ln.replaceAll("'", "");
System.out.println("setting locname");
stmt.setString(8, ln);
System.out.println("setting locID");
stmt.setString(9, loc.getID().trim());
System.out.println("setting state");
stmt.setString(10, loc.getState().trim());
System.out.println("setting range");
stmt.setString(11, loc.getRange().trim());
System.out.println("setting lat");
float lat = -999.9f;
try {
lat = stringToFloat(loc.getLat());
stmt.setFloat(12, lat);
} catch (Exception e) {
stmt.setFloat(12, -999.9f);
System.out.println(e.toString());
}
System.out.println("setting long");
float longitude = -999.9f;
try {
longitude = stringToFloat(loc.getLongitude());
stmt.setFloat(13, longitude);
} catch (Exception e) {
stmt.setFloat(13, -999.9f);
System.out.println(e.toString());
}
System.out.println("setting lat type");
stmt.setBoolean(14, loc.getLatType().equals("N"));
System.out.println("setting long type");
stmt.setBoolean(15, loc.getLongType().equals("W"));
System.out.println("setting elv");
try {
System.out.println("elv: " + loc.getElv());
int e = stringToInt(loc.getElv());
System.out.println("elevation: " + e);
if (pit.getPrefs().getElvUnits().equals("ft")) {
e = ft_to_m(e);
}
stmt.setInt(16, e);
} catch (Exception ex) {
System.out.println(ex.toString());
stmt.setInt(16, -999);
}
// user name
System.out.println("setting username");
stmt.setString(17, pit.getUserHash());
stmt.setString(18, pit.getWindLoading());
// name
// String pn = pit.getName().trim();
// pn.replaceAll("'", "");
System.out.println("setting name");
stmt.setString(19, pit_name);
System.out.println("setting has layers");
stmt.setBoolean(20, pit.hasLayers());
System.out.println("setting serial.");
stmt.setString(21, pit.getSerial());
System.out.println("setting wind loading:");
stmt.setString(22, pit.getPrecip());
stmt.setString(23, pit.getSky());
stmt.setString(24, pit.getWindspeed());
stmt.setString(25, pit.getWinDir());
stmt.setString(26, pit.getStability());
stmt.setBoolean(27, pit.getPrefs().getShare());
Timestamp ots = new Timestamp(pit.getTimestamp());
StringBuffer buffer = new StringBuffer(" ");
try {
// System.out.println("setting activities: ");
if (pit.getActivities() != null) {
// System.out.println("# activities: " + pit.getActivities().size());
java.util.Enumeration e = pit.getActivities().elements();
if (e != null) {
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
//System.out.println("acts: " + s);
buffer.append(" : " + s + " : ");
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("Setting activities:");
stmt.setString(28, buffer.toString());
boolean testPit = false;
System.out.println("Setting Test Pit?:");
if (pit.testPit != null) {
if (pit.testPit.trim().equals("true")) {
testPit = true;
}
stmt.setBoolean(29, testPit);
} else {
stmt.setBoolean(29, false);
}
System.out.println("Setting software version:");
if (pit.version != null) {
stmt.setString(30, pit.version);
} else {
stmt.setString(30, "");
}
System.out.println("System serial: "+pit.getSystemSerial());
stmt.setString(31, pit.getSystemSerial());
stmt.setTimestamp(32, new Timestamp(System.currentTimeMillis()));
stmt.setString(33, xml);
stmt.setBoolean(34, pit.isAviPit());
stmt.setString(35, pit.aviLoc);
try
{
stmt.setInt(36, new Integer(pit.iLayerNumber).intValue());
}
catch(Exception ex)
{
stmt.setInt(36, 0);
}
try
{
stmt.setDouble(37, new Double(pit.iDepth).doubleValue());
}
catch(Exception ee)
{
stmt.setDouble(37, 0.0);
}
stmt.setBoolean(38, pit.isSkiAreaPit());
stmt.setBoolean(39, pit.isBCPit());
try
{
stmt.setDouble(40, new Double(pit.getSurfacePen()).doubleValue());
}
catch(Exception exx)
{
stmt.setDouble(40,0.0);
}
stmt.setString(41, pit.getSkiBoot());
System.out.println("execute query:");
retValue = stmt.executeUpdate();
System.out.println("Update executed!");
if ( retValue > 0 ) System.out.println("Pit added to DB !!!!!!");
conn.close();
} catch (Exception e) {
System.out.println(e.toString());
}
writeLayersToDB(pit);
writeTestsToDB(pit);
return retValue;
}
void writeLayersToDB(avscience.ppc.PitObs pit)
{
System.out.println("Write Layers to DB:");
String serial = pit.getSystemSerial();
int numLayers = pit.getLayersVector().size();
System.out.println("Writing "+numLayers+" to DB.");
Enumeration le = pit.getLayers();
while (le.hasMoreElements())
{
avscience.ppc.Layer l = (avscience.ppc.Layer) le.nextElement();
writeLayerToDB(l, serial);
}
}
void writeTestsToDB(avscience.ppc.PitObs pit)
{
System.out.println("Write Tests to DB:");
String serial = pit.getSystemSerial();
Enumeration le = pit.getShearTests();
while (le.hasMoreElements())
{
avscience.ppc.ShearTestResult test = (avscience.ppc.ShearTestResult) le.nextElement();
writeTestToDB(test, serial);
}
}
void writeTestToDB(avscience.ppc.ShearTestResult test, String serial)
{
System.out.println("Write Test to DB: for pit: "+serial);
String query = "INSERT INTO TEST_TABLE (LABEL, CODE, SCORE, QUALITY, DEPTH, CT_SCORE, EC_SCORE, DEPTH_UNITS, DATE_STRING,"
+ " RELEASE_TYPE, FRACTURE_CHAR, FRACTURE_CAT, NUMBER_OF_TAPS, LENGTH_OF_CUT, LENGTH_OF_COLUMN, COMMENTS, PIT_SERIAL)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = getConnection();
stmt = conn.prepareStatement(query);
System.out.println("Setting test string");
stmt.setString(1, test.toString());
System.out.println("setting test code");
stmt.setString(2, test.getCode());
System.out.println("setting test score");
stmt.setString(3, test.getScore());
System.out.println("setting test quality");
stmt.setString(4, test.getQuality());
System.out.println("setting depth");
stmt.setDouble(5, test.getDepthValue());
System.out.println("setting ct score");
stmt.setInt(6, test.getCTScoreAsInt());
System.out.println("setting ec score");
stmt.setInt(7, test.getECScoreAsInt());
System.out.println("setting depth units");
stmt.setString(8, test.getDepthUnits());
System.out.println("setting test date");
stmt.setString(9, test.getDateString());
System.out.println("setting releaseType");
stmt.setString(10, test.getReleaseType());
System.out.println("setting test character");
stmt.setString(11, test.character);
System.out.println("setting fracture cat");
stmt.setString(12, test.fractureCat);
System.out.println("setting number of taps");
stmt.setInt(13, test.getNumberOfTaps());
System.out.println("setting length of cut");
stmt.setInt(14, test.getLengthOfCut());
System.out.println("setting length of column");
stmt.setInt(15, test.getLengthOfColumn());
System.out.println("setting test comments");
stmt.setString(16, test.getComments());
System.out.println("setting serial: "+serial);
stmt.setString(17, serial);
int rw = stmt.executeUpdate();
if (rw > 0 ) System.out.println("TEST added !!");
else System.out.println("Error adding TEST");
conn.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
void deletePitLayers(String serial)
{
String query = "DELETE FROM LAYER_TABLE WHERE PIT_SERIAL = ?";
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = getConnection();
stmt = conn.prepareStatement(query);
stmt.setString(1, serial);
int rws = stmt.executeUpdate();
System.out.println(rws+" layers deleted for pit: "+serial);
conn.close();
}
catch (Exception e) {
System.out.println(e.toString());
}
}
void deletePitTests(avscience.ppc.PitObs pit)
{
/// long serial = getDBSerial(pit);
// deletePitTests(serial);
}
void deletePitTests(String serial)
{
String query = "DELETE FROM TEST_TABLE WHERE PIT_SERIAL = ?";
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = getConnection();
stmt = conn.prepareStatement(query);
stmt.setString(1, serial);
int rws = stmt.executeUpdate();
System.out.println(rws+" tests deleted for pit: "+serial);
conn.close();
}
catch (Exception e) {
System.out.println(e.toString());
}
}
void writeLayerToDB(avscience.ppc.Layer layer, String serial)
{
System.out.println("Write Layer to DB: for pit: "+serial);
String query = "INSERT INTO LAYER_TABLE (START_DEPTH, END_DEPTH, LAYER_NUMBER, WATER_CONTENT, GRAIN_TYPE1, GRAIN_TYPE2, GRAIN_SIZE1, "
+ "GRAIN_SIZE2, GRAIN_SIZE_UNITS1, GRAIN_SIZE_UNITS2, GRAIN_SUFFIX1, GRAIN_SUFFIX2, HARDNESS1, HARDNESS2, HSUFFIX1, HSUFFIX2, "
+ "DENSITY1, DENSITY2, FROM_TOP, MULTIPLE_HARDNESS, MULTIPLE_DENSITY, MULTIPLE_GRAIN_SIZE, MULTIPLE_GRAIN_TYPE, PIT_SERIAL, "
+ "COMMENTS) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = getConnection();
stmt = conn.prepareStatement(query);
stmt.setDouble(1, layer.getStartDepth());
stmt.setDouble(2, layer.getEndDepth());
stmt.setInt(3, layer.getLayerNumber());
stmt.setString(4, layer.getWaterContent());
stmt.setString(5, layer.getGrainType1());
stmt.setString(6, layer.getGrainType2());
stmt.setDouble(7, layer.getGrainSize1_Dbl());
stmt.setDouble(8, layer.getGrainSize2_Dbl());
stmt.setString(9, layer.getGrainSizeUnits1());
stmt.setString(10, layer.getGrainSizeUnits2());
stmt.setString(11, layer.getGrainSuffix());
stmt.setString(12, layer.getGrainSuffix1());
stmt.setString(13, layer.getHardness1());
stmt.setString(14, layer.getHardness2());
stmt.setString(15, layer.getHSuffix1());
stmt.setString(16, layer.getHSuffix2());
stmt.setDouble(17, layer.getDensity1_Dbl());
stmt.setDouble(18, layer.getDensity2__Dbl());
int ftop = 0;
if (layer.getFromTop()) ftop=1;
stmt.setInt(19, ftop);
int mltHrd=0;
int mltGt=0;
int mltGs=0;
int mltRho=0;
if (layer.getMultDensityBool()) mltRho=1;
if (layer.getMultGrainSizeBool()) mltGs=1;
if (layer.getMultGrainTypeBool()) mltGt=1;
if (layer.getMultHardnessBool()) mltHrd=1;
stmt.setInt(20, mltHrd);
stmt.setInt(21, mltRho);
stmt.setInt(22, mltGs);
stmt.setInt(23, mltGt);
stmt.setString(24, serial);
stmt.setString(25, layer.getComments());
int rw = stmt.executeUpdate();
if (rw > 0 ) System.out.println("Layer added.");
else System.out.println("Error adding layer");
conn.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void writeOccToDB(String data) {
System.out.println("writeOccToDB");
avscience.ppc.AvOccurence occ = null;
try
{
occ = new avscience.ppc.AvOccurence(data);
}
catch(Exception e)
{
occ = new avscience.ppc.AvOccurence();
System.out.println(e.toString());
}
String pn = occ.getPitName();
pn = removeDelims(pn);
occ.setPitName(pn);
if (occPresent(occ)) {
System.out.println("Occ already in DB");
if (occUnAltered(data)) {
return;
} else {
System.out.println("Deleting occ..");
deleteOcc(occ);
}
}
System.out.println("writing occ to DB : " + occ.getPitName());
String query = "INSERT INTO OCC_TABLE (OCC_DATA, OBS_DATE, TIMESTAMP, ELV_START, ELV_DEPOSIT, ASPECT, TYPE, TRIGGER_TYPE, TRIGGER_CODE, US_SIZE, CDN_SIZE, AVG_FRACTURE_DEPTH, MAX_FRACTURE_DEPTH, WEAK_LAYER_TYPE, WEAK_LAYER_HARDNESS, SNOW_PACK_TYPE, FRACTURE_WIDTH, FRACTURE_LENGTH, AV_LENGTH, AVG_START_ANGLE, MAX_START_ANGLE, MIN_START_ANGLE, ALPHA_ANGLE, DEPTH_DEPOSIT, LOC_NAME, LOC_ID, STATE, MTN_RANGE, LAT, LONGITUDE, NORTH, WEST, USERNAME, NAME, LOCAL_SERIAL, SHARE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
Connection conn = getConnection();
if (conn == null) {
System.out.println("Connection null::");
} else {
PreparedStatement stmt = conn.prepareStatement(query);
// String data = occ.dataString();
// data = URLEncoder.encode(data, "UTF-8");
stmt.setString(1, data);
String ser = occ.getSerial();
System.out.println("Occ Serial: " + ser);
String pdata = "";
java.sql.Date odate = null;
long otime = 0;
avscience.ppc.PitObs pit = null;
if ((ser != null) && (ser.trim().length() > 0)) {
System.out.println("getPitBySerial: " + ser);
pdata = getPitByLocalSerial(ser);
if ((pdata != null) && (pdata.trim().length() > 1)) {
System.out.println("getting pit by local serial.");
pit = new avscience.ppc.PitObs(pdata);
if (pit != null) {
otime = pit.getTimestamp();
}
} else {
System.out.println("Can't get Pit: " + ser + " by serial.");
}
} else {
String wdata = getPit(pn);
// = wpit.dataString();
if ((wdata != null) && (wdata.trim().length() > 1)) {
pit = new avscience.ppc.PitObs(wdata);
} else {
System.out.println("Can't get Pit: " + pn + " by Name.");
}
}
if (pit == null) {
System.out.println("Pit is null..");
}
//else if (pit.getUser() == null) {
// System.out.println("Pit user is null.");
// }
System.out.println("setting dates.");
if (otime > 1) {
odate = new java.sql.Date(otime);
}
System.out.println("Date: " + odate.toString());
stmt.setDate(2, odate);
///stmt.setDate(2, new java.sql.Date(System.currentTimeMillis()));
stmt.setDate(3, new java.sql.Date(System.currentTimeMillis()));
//
System.out.println("setting elevation.");
int elvStart = 0;
if (occ.getElvStart().trim().length() > 0) {
elvStart = stringToInt(occ.getElvStart());
}
if (pit.getPrefs().getElvUnits().equals("ft")) {
elvStart = ft_to_m(elvStart);
}
stmt.setInt(4, elvStart);
System.out.println("setting elevation.");
int elvDep = 0;
if (occ.getElvDeposit().trim().length() > 0) {
elvDep = stringToInt(occ.getElvDeposit());
}
if (pit.getPrefs().getElvUnits().equals("ft")) {
elvDep = ft_to_m(elvDep);
}
stmt.setInt(5, elvDep);
System.out.println("setting aspect");
int aspect = 0;
if (occ.getAspect().trim().length() > 0) {
aspect = stringToInt(occ.getAspect());
}
stmt.setInt(6, aspect);
stmt.setString(7, occ.getType().trim());
stmt.setString(8, occ.getTriggerType().trim());
stmt.setString(9, occ.getTriggerCode().trim());
stmt.setString(10, occ.getUSSize());
String cs = occ.getCASize().trim();
System.out.println("CASize: " + cs);
if (cs.lastIndexOf('D') > -1) {
cs = cs.substring(1, cs.length());
}
System.out.println("cs: " + cs);
float csize = 0;
if (cs.trim().length() > 0) {
csize = (new Float(cs)).floatValue();
}
stmt.setFloat(11, csize);
int aDepth = stringToInt(occ.getAvgFractureDepth());
if (pit.getPrefs().getDepthUnits().equals("in")) {
aDepth = in_to_cm(aDepth);
}
stmt.setInt(12, aDepth);
int mDepth = stringToInt(occ.getMaxFractureDepth());
if (pit.getPrefs().getDepthUnits().equals("in")) {
mDepth = in_to_cm(mDepth);
}
stmt.setInt(13, mDepth);
System.out.println("setting layer types");
stmt.setString(14, occ.getWeakLayerType().trim());
stmt.setString(15, occ.getWeakLayerHardness().trim());
stmt.setString(16, occ.getSnowPackType().trim());
int fw = stringToInt(occ.getFractureWidth());
if (pit.getPrefs().getElvUnits().equals("ft")) {
fw = ft_to_m(fw);
}
stmt.setInt(17, fw);
int fl = stringToInt(occ.getFractureLength());
if (pit.getPrefs().getElvUnits().equals("ft")) {
fl = ft_to_m(fl);
}
stmt.setInt(18, fl);
int al = stringToInt(occ.getLengthOfAvalanche());
if (pit.getPrefs().getElvUnits().equals("ft")) {
al = ft_to_m(al);
}
stmt.setInt(19, al);
System.out.println("setting angles");
stmt.setInt(20, stringToInt(occ.getAvgStartAngle()));
stmt.setInt(21, stringToInt(occ.getMaxStartAngle()));
stmt.setInt(22, stringToInt(occ.getMinStartAngle()));
stmt.setInt(23, stringToInt(occ.getAlphaAngle()));
int d = stringToInt(occ.getDepthOfDeposit());
if (pit.getPrefs().getElvUnits().equals("ft")) {
d = ft_to_m(d);
}
stmt.setInt(24, d);
System.out.println("setting location");
avscience.ppc.Location loc = pit.getLocation();
String ln = loc.getName().trim();
ln.replaceAll("'", "");
stmt.setString(25, ln);
stmt.setString(26, loc.getID().trim());
stmt.setString(27, loc.getState().trim());
stmt.setString(28, loc.getRange().trim());
float lat = -999.9f;
lat = stringToFloat(loc.getLat());
stmt.setFloat(29, lat);
float longitude = -999.9f;
System.out.println("setting lat/lon.");
longitude = stringToFloat(loc.getLongitude());
stmt.setFloat(30, longitude);
stmt.setBoolean(31, loc.getLatType().equals("N"));
stmt.setBoolean(32, loc.getLongType().equals("W"));
stmt.setString(33, pit.getUserHash().trim());
pn = pit.getName().trim();
pn.replaceAll("'", "");
stmt.setString(34, pn);
stmt.setString(35, occ.getSerial());
boolean share = false;
stmt.setBoolean(36, pit.getPrefs().getShare());
System.out.println("executing occ update: ");
stmt.executeUpdate();
conn.close();
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
private int stringToInt(String s) {
s = s.trim();
System.out.println("stringToInt() " + s);
int i = -999;
if ((s != null) && (s.trim().length() > 0)) {
try {
// s = makeNumeric(s);
if (s.trim().length() > 0) {
i = (new java.lang.Integer(s)).intValue();
i = java.lang.Math.abs(i);
}
} catch (Exception e) {
System.out.println("stringToInt: " + e.toString());
}
}
return i;
}
private float stringToFloat(String s) {
s = s.trim();
float f = -999.9f;
try {
if (s.trim().length() > 0) {
f = (new java.lang.Float(s)).floatValue();
}
} catch (Exception e) {
System.out.println("stringTofloat: " + e.toString());
}
return f;
}
private String makeNumeric(String s) {
System.out.println("makeNumeric: " + s);
int length = s.length();
char[] chars = new char[length];
Vector digs = new Vector();
int j = 0;
for (int i = 0; i < length; i++) {
char c = chars[i];
Character C = new Character(c);
if (Character.isDigit(C.charValue())) {
digs.add(j, C);
j++;
}
}
length = digs.size();
char[] newChars = new char[length];
for (int i = 0; i < length; i++) {
newChars[i] = ((Character) digs.elementAt(i)).charValue();
}
return new String(newChars);
}
private int in_to_cm(int in) {
return (int) java.lang.Math.rint(in * 2.54);
}
/* private boolean pitPresent(avscience.wba.PitObs pit) {
System.out.println("pitPresent");
String name = pit.getName();
String user = pit.getUser().getName();
if (name == null) {
name = "";
}
if (user == null) {
user = "";
}
String query = "SELECT * FROM PIT_TABLE WHERE PIT_NAME = ? AND USERNAME = ?";
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = getConnection();
stmt = conn.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, user);
ResultSet rs = stmt.executeQuery();
conn.close();
if (rs.next()) {
return true;
} else {
return false;
}
} catch (Exception e) {
System.out.println(e.toString());
}
return false;
}*/
public void updateRanges() {
String query = "SELECT SERIAL, PIT_DATA FROM PIT_TABLE";
Statement stmt = null;
String serial = "";
// String name = "";
String data = "";
Connection conn = null;
try {
conn = getConnection();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
// name = rs.getString("PIT_NAME");
serial = rs.getString("SERIAL");
data = rs.getString("PIT_DATA");
avscience.ppc.PitObs pit = new avscience.ppc.PitObs(data);
String rng = pit.getLocation().getRange();
System.out.println("Setting range for pit: " + serial + " to " + rng);
try {
String q2 = "UPDATE PIT_TABLE SET MTN_RANGE = ? WHERE SERIAL = ?";
PreparedStatement stmt1 = conn.prepareStatement(q2);
stmt1.setString(1, rng);
stmt1.setString(2, serial);
stmt1.executeUpdate();
} catch (Exception e) {
System.out.println(e.toString());
}
}
conn.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
/* public void updateObsTimes() {
String query = "SELECT SERIAL, PIT_DATA FROM PIT_TABLE";
Statement stmt = null;
String serial = "";
// String name = "";
String data = "";
Connection conn = null;
try {
conn = getConnection();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
serial = rs.getString("SERIAL");
data = rs.getString("PIT_DATA");
avscience.ppc.PitObs pit = new avscience.ppc.PitObs(data);
////
java.sql.Date pdate = null;
long ptime = 0;
ptime = pit.getTimestamp();
if (ptime > 1) {
pdate = new java.sql.Date(ptime);
} else {
String s = pit.getDateString();
System.out.println("datestring: " + s);
String dt = pit.getDate();
String tt = pit.getTime();
if (dt.trim().length() > 5) {
pdate = getDateTime(dt, tt);
} else {
pdate = getDate(s);
}
if (pdate == null) {
pdate = new java.sql.Date(System.currentTimeMillis());
}
}
///////
System.out.println("Setting obs_datetime for pit: " + serial);
try {
String q2 = "UPDATE PIT_TABLE SET OBS_DATETIME = ? WHERE SERIAL = ?";
PreparedStatement stmt1 = conn.prepareStatement(q2);
Timestamp ots = new Timestamp(pdate.getTime());
stmt1.setTimestamp(1, ots);
stmt1.setString(2, serial);
stmt1.executeUpdate();
} catch (Exception e) {
System.out.println(e.toString());
}
}
conn.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}*/
private String getDBSerial(avscience.ppc.PitObs pit)
{
String name = pit.getName();
String user = pit.getUserHash();
String ser = pit.getSerial();
return getDBSerial(name, user, ser);
}
private String getDBSerial(String name, String user, String ser)
{
String serial = "";
System.out.println("getDBSerial");
String query = "SELECT * FROM PIT_TABLE WHERE PIT_NAME = ? AND USEHASH = ? AND LOCAL_SERIAL = ?";
PreparedStatement stmt = null;
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, user);
stmt.setString(3, ser);
ResultSet rs = stmt.executeQuery();
if (rs.next()) serial = rs.getString("SYSTEM_SERIAL");
} catch (Exception e) {
System.out.println(e.toString());
}
return serial;
}
private boolean pitPresent(avscience.ppc.PitObs pit) {
System.out.println("pitPresent");
String name = pit.getName();
String user = pit.getUserHash();
String ser = pit.getSerial();
String query = "SELECT * FROM PIT_TABLE WHERE PIT_NAME = ? AND USERHASH = ? AND LOCAL_SERIAL = ?";
PreparedStatement stmt = null;
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, user);
stmt.setString(3, ser);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return true;
} else {
return false;
}
} catch (Exception e) {
System.out.println(e.toString());
}
return false;
}
private boolean occPresent(avscience.ppc.AvOccurence occ) {
System.out.println("occPresent()");
String name = occ.getPitName();
String serial = occ.getSerial();
if (name == null) {
name = "";
}
if (serial == null) {
serial = "";
}
String query = "SELECT * FROM OCC_TABLE WHERE NAME = ? AND LOCAL_SERIAL = ?";
PreparedStatement stmt = null;
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, serial);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return true;
} else {
return false;
}
} catch (Exception e) {
System.out.println(e.toString());
}
return false;
}
private float FtoC(float t) {
t = t - 32;
float c = t * (5 / 9);
return c;
}
private int ft_to_m(int ft) {
return (int) java.lang.Math.rint(ft / 3.29f);
}
/*public java.sql.Date getDateTime(String dt, String time) {
String yr = "0";
String mnth = "0";
String dy = "0";
String hr = "0";
String min = "0";
if (!(dt.trim().length() < 8)) {
yr = dt.substring(0, 4);
mnth = dt.substring(4, 6);
dy = dt.substring(6, 8);
}
if (!(time.trim().length() < 4)) {
hr = time.substring(0, 2);
min = time.substring(2, 4);
}
int y = new java.lang.Integer(yr).intValue();
int m = new java.lang.Integer(mnth).intValue() - 1;
int d = new java.lang.Integer(dy).intValue();
int h = new java.lang.Integer(hr).intValue();
int mn = new java.lang.Integer(min).intValue();
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.set(y, m, d, h, mn);
long ts = cal.getTimeInMillis();
System.out.println("date/time: " + new java.sql.Date(ts).toString());
return new java.sql.Date(ts);
}*/
/*private java.sql.Date getDate(String date) {
System.out.println("getDate(): " + date);
// if ( date == null ) return;
String tm = "";
date = date.trim();
if (date.length() > 12) {
tm = date.substring(11, date.length());
}
System.out.println("time: " + tm);
if (date.length() > 10) {
date = date.substring(0, 10);
}
long time = 0;
int month = 0;
int day = 0;
int year = 0;
Calendar cal = Calendar.getInstance();
int start = 0;
int end = 0;
if (date.length() > 6) {
end = date.indexOf("/");
String m = date.substring(0, end);
if ((m != null) && (m.trim().length() > 0)) {
month = (new java.lang.Integer(m)).intValue();
}
start = end + 1;
end = date.indexOf(" ", start);
if (end > 1) {
day = (new java.lang.Integer(date.substring(start, end))).intValue();
year = (new java.lang.Integer(date.substring(date.length() - 4, date.length()))).intValue();
} else {
year = new java.lang.Integer(date.substring(date.length() - 4, date.length())).intValue();
// month = new java.lang.Integer(date.substring(4, 6)).intValue();
day = new java.lang.Integer(date.substring(3, 5)).intValue();
}
}
int hr = 0;
int mn = 0;
int sc = 0;
if (tm.trim().length() > 6) {
try {
String h = "";
String min = "";
String s = "";
start = 0;
end = tm.indexOf(":", start);
if (end > 0) {
h = tm.substring(start, end);
}
start = end + 1;
end = tm.indexOf(":", start);
if (end > 0) {
min = tm.substring(start, end);
}
start = end + 1;
s = tm.substring(start, start + 2);
String ap = tm.substring(tm.length() - 2, tm.length());
hr = new java.lang.Integer(h).intValue();
if (ap.equals("PM")) {
hr += 12;
}
mn = new java.lang.Integer(min).intValue();
sc = new java.lang.Integer(s).intValue();
} catch (Exception e) {
System.out.println(e.toString());
}
}
month -= month;
if (month > 11) {
month = 11;
}
cal.set(year, month, day, hr, mn, sc);
time = cal.getTimeInMillis();
System.out.println("date/time: " + new java.sql.Date(time).toString());
return new java.sql.Date(time);
}
public String cleanString(String s) {
if (s.trim().length() < 2) {
return s;
}
try {
char[] chars = s.toCharArray();
int l = chars.length;
for (int jj = 0; jj < l; jj++) {
int idx = jj;
//logger.println("idx: "+idx);
if ((idx < l) && (idx > 0)) {
char test = chars[idx];
if (test <= 0) {
chars[idx] = ' ';
}
}
}
String tmp = "";
tmp = new String(chars);
if ((tmp != null) && (tmp.trim().length() > 5)) {
s = tmp;
}
} catch (Throwable e) {
System.out.println("cleanString failed: " + e.toString());
}
return s;
}*/
public String[][] getPitListArray(boolean datefilter) {
Vector serials = new Vector();
Vector names = new Vector();
String query = "SELECT CROWN_OBS, TIMESTAMP, PIT_NAME, SHARE, SYSTEM_SERIAL FROM PIT_TABLE WHERE SHARE > 0 ORDER BY TIMESTAMP DESC";
Statement stmt = null;
Connection conn;
try {
conn = getConnection();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
int i = 0;
while (rs.next()) {
java.util.Date pitDate = rs.getDate("TIMESTAMP");
if ((datefilter) && (pitDate.after(startDate))) {
if (!rs.getBoolean("CROWN_OBS")) {
String serial = rs.getString("SYSTEM_SERIAL");
String name = rs.getString("PIT_NAME");
serials.insertElementAt(serial, i);
names.insertElementAt(name, i);
i++;
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
String[][] list = new String[2][serials.size()];
int i = 0;
Iterator e = serials.iterator();
Iterator ee = names.iterator();
while (e.hasNext()) {
String ser = (String) e.next();
String nm = (String) ee.next();
list[0][i] = nm;
list[1][i] = ser;
i++;
}
return list;
}
public String[][] getPitListArrayFromQuery(String whereclause, boolean datefilter) {
System.out.println("getPitListArrayFromQuery() " + whereclause);
Vector serials = new Vector();
Vector names = new Vector();
String query = "SELECT CROWN_OBS, OBS_DATETIME, PIT_NAME, SERIAL ,SHARE FROM PIT_TABLE " + whereclause + " AND SHARE > 0 ORDER BY OBS_DATETIME DESC";
System.out.println("Query: " + query);
Statement stmt = null;
Connection conn;
int i = 0;
try {
conn = getConnection();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
java.util.Date pitDate = rs.getDate("OBS_DATETIME");
if (datefilter && (pitDate.after(startDate))) {
if (!rs.getBoolean("CROWN_OBS")) {
String serial = rs.getString("SYSTEM_SERIAL");
String name = rs.getString("PIT_NAME");
serials.insertElementAt(serial, i);
names.insertElementAt(name, i);
i++;
}
} else if (!datefilter) {
if (!rs.getBoolean("CROWN_OBS")) {
String serial = rs.getString("SYSTEM_SERIAL");
String name = rs.getString("PIT_NAME");
serials.insertElementAt(serial, i);
names.insertElementAt(name, i);
i++;
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
String[][] list = new String[2][serials.size()];
i = 0;
Enumeration e = serials.elements();
Enumeration ee = names.elements();
while (e.hasMoreElements()) {
String ser = (String) e.nextElement();
String nm = (String) ee.nextElement();
list[0][i] = nm;
list[1][i] = ser;
i++;
}
return list;
}
public Hashtable getAllPits() {
System.out.println("getAllPits()");
Hashtable v = new Hashtable();
String query = "SELECT SYSTEM_SERIAL, PIT_DATA FROM PIT_TABLE";
try {
Statement stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String dat = rs.getString("PIT_DATA");
String serial = rs.getString("SYSTEM_SERIAL");
if ((dat != null) && (dat.trim().length() > 5)) {
v.put(serial, dat);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("No of PITS: " + v.size());
return v;
}
public Vector getPitListFromQuery(String whereclause) throws Exception {
System.out.println("DAO pitlist query");
Vector v = new Vector();
String query = "SELECT PIT_NAME, TIMESTAMP, SHARE FROM PIT_TABLE " + whereclause + " AND SHARE > 0 ORDER BY TIMESTAMP DESC";
System.out.println("QUERY:: " + query);
Statement stmt = null;
whereclause = "";
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
java.util.Date pitDate = rs.getDate("OBS_DATETIME");
// if (pitDate.after(startDate)) {
String s = rs.getString(1);
v.add(s);
// }
}
} catch (Exception e) {
whereclause = e.toString();
System.out.println(e.toString());
throw e;
}
return v;
}
public Vector getOccListFromQuery(String whereclause) throws Exception {
System.out.println("DAO occlist query");
Vector v = new Vector();
String query = "SELECT NAME, TIMESTAMP, SHARE FROM OCC_TABLE " + whereclause + " AND SHARE > 0 ORDER BY TIMESTAMP";
System.out.println("QUERY: " + query);
Statement stmt = null;
whereclause = "";
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString(1);
v.add(s);
}
} catch (Exception e) {
whereclause = e.toString();
System.out.println(e.toString());
throw e;
}
return v;
}
public String[][] getOccListArrayFromQuery(String whereclause, boolean datefilter) throws Exception {
System.out.println("DaO occlist query " + whereclause);
Vector names = new Vector();
Vector serials = new Vector();
String query = "SELECT NAME, TIMESTAMP, OBS_DATE, SERIAL, SHARE FROM OCC_TABLE " + whereclause + " AND SHARE > 0 ORDER BY TIMESTAMP";
System.out.println("QUERY: " + query);
Statement stmt = null;
whereclause = "";
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
int i = 0;
while (rs.next()) {
java.util.Date date = rs.getDate("OBS_DATE");
if ((datefilter) && (date.after(startDate))) {
String serial = "" + rs.getInt("SERIAL");
String name = rs.getString("NAME");
serials.insertElementAt(serial, i);
names.insertElementAt(name, i);
i++;
} else if (!datefilter) {
String serial = "" + rs.getInt("SERIAL");
String name = rs.getString("NAME");
serials.insertElementAt(serial, i);
names.insertElementAt(name, i);
i++;
}
}
} catch (Exception e) {
whereclause = e.toString();
System.out.println(e.toString());
throw e;
}
System.out.println(serials.size() + " OCCs retieved.");
String[][] list = new String[2][serials.size()];
int i = 0;
Enumeration e = serials.elements();
Enumeration ee = names.elements();
while (e.hasMoreElements()) {
String ser = (String) e.nextElement();
String nm = (String) ee.nextElement();
list[0][i] = nm;
list[1][i] = ser;
i++;
}
return list;
}
public String[][] getOccListArray(boolean datefilter) {
Vector names = new Vector();
Vector serials = new Vector();
String query = "SELECT NAME, TIMESTAMP, SERIAL, OBS_DATE, SHARE FROM OCC_TABLE WHERE SHARE > 0 ORDER BY TIMESTAMP";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
int i = 0;
while (rs.next()) {
java.util.Date date = rs.getDate("OBS_DATE");
if ((datefilter) && (date.after(startDate))) {
String serial = "" + rs.getInt("SERIAL");
String name = rs.getString("NAME");
serials.insertElementAt(serial, i);
names.insertElementAt(name, i);
i++;
} else if (!datefilter) {
String serial = "" + rs.getInt("SERIAL");
String name = rs.getString("NAME");
serials.insertElementAt(serial, i);
names.insertElementAt(name, i);
i++;
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
String[][] list = new String[2][serials.size()];
int i = 0;
Enumeration e = serials.elements();
Enumeration ee = names.elements();
while (e.hasMoreElements()) {
String ser = (String) e.nextElement();
String nm = (String) ee.nextElement();
list[0][i] = nm;
list[1][i] = ser;
i++;
}
return list;
}
public Vector getOccList() {
Vector v = new Vector();
String query = "SELECT NAME, TIMESTAMP, SHARE FROM OCC_TABLE WHERE SHARE > 0 ORDER BY TIMESTAMP";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString(1);
v.add(s);
}
} catch (Exception e) {
System.out.println(e.toString());
}
return v;
}
public Vector getLocationList() {
Vector v = new Vector();
String query = "SELECT DISTINCT LOC_NAME FROM PIT_TABLE ORDER BY LOC_NAME";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString(1);
v.add(s);
}
} catch (Exception e) {
System.out.println(e.toString());
}
return v;
}
public Vector getRangeList() {
Vector v = new Vector();
String query = "SELECT DISTINCT MTN_RANGE, OBS_DATETIME FROM PIT_TABLE ORDER BY MTN_RANGE ASC";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
java.util.Date pitDate = rs.getDate("OBS_DATETIME");
if (pitDate.after(startDate)) {
String s = rs.getString(1);
s = s.trim();
if ((s.trim().length() > 0) && (!(v.contains(s)))) {
v.add(s);
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
return v;
}
public Vector getRangeListAll()
{
Vector v = new Vector();
String query = "SELECT DISTINCT MTN_RANGE FROM PIT_TABLE ORDER BY MTN_RANGE ASC";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString(1);
s = s.trim();
if ((s.trim().length() > 0) && (!(v.contains(s)))) {
v.add(s);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
return v;
}
public Vector getStateList() {
Vector v = new Vector();
String query = "SELECT DISTINCT STATE, OBS_DATETIME FROM PIT_TABLE ORDER BY STATE ASC";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
java.util.Date pitDate = rs.getDate("OBS_DATETIME");
if (pitDate.after(startDate)) {
String s = rs.getString(1);
s = s.trim();
if ((s.trim().length() > 0) && (!(v.contains(s)))) {
v.add(s);
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
return v;
}
////////////////
public Vector getStateListAll() {
Vector v = new Vector();
String query = "SELECT DISTINCT STATE FROM PIT_TABLE ORDER BY STATE ASC";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
// java.util.Date pitDate = rs.getDate("OBS_DATE");
String s = rs.getString(1);
s = s.trim();
if ((s.trim().length() > 0) && (!(v.contains(s)))) {
v.add(s);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
return v;
}
////////////////////
public Vector getPitList(String user) {
Vector v = new Vector();
String query = "SELECT PIT_NAME, OBS_DATETIME FROM PIT_TABLE WHERE USERHASH ='" + user + "' AND SHARE > 0 ORDER BY OBS_DATETIME DESC";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString(1);
v.add(s);
}
} catch (Exception e) {
System.out.println(e.toString());
}
return v;
}
public Vector getOccList(String user) {
Vector v = new Vector();
String query = "SELECT NAME, TIMESTAMP FROM OCC_TABLE WHERE USERNAME ='" + user + "' ORDER BY TIMESTAMP";
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString(1);
v.add(s);
}
} catch (Exception e) {
System.out.println(e.toString());
}
return v;
}
public void deletePit(String dbserial) {
String query = "DELETE FROM PIT_TABLE WHERE SYSTEM_SERIAL = " + dbserial;
try {
Statement stmt = getConnection().createStatement();
stmt.executeUpdate(query);
} catch (Exception e) {
System.out.println(e.toString());
}
deletePitLayers(dbserial);
deletePitTests(dbserial);
}
public boolean deleteOcc(String user, String serial, String name) {
System.out.println("deleteOcc. " + serial + " " + name);
boolean del = false;
String query = null;
if ((serial != null) && (serial.trim().length() > 1)) {
query = "DELETE FROM OCC_TABLE WHERE LOCAL_SERIAL = '" + serial + "' AND USERNAME = '" + user + "'";
} else {
query = "DELETE FROM OCC_TABLE WHERE PIT_NAME = '" + name + "' AND USERNAME = '" + user + "'";
}
try {
Statement stmt = getConnection().createStatement();
int n = stmt.executeUpdate(query);
if (n > 0) {
System.out.println("OCC deleted: " + serial);
del = true;
}
} catch (Exception e) {
System.out.println(e.toString());
}
// deletePit(user, serial, name);
return del;
}
private void deleteOcc(avscience.ppc.AvOccurence occ) {
System.out.println("DELETE OCC. ");
String name = occ.getPitName();
String serial = occ.getSerial();
System.out.println("OCC SERIAL: " + serial);
avscience.ppc.PitObs pit = null;
if ((serial == null) || (serial.trim().length() < 2)) {
System.out.println("getting pit by name: " + name);
String data = getPit(name);
try
{
pit = new avscience.ppc.PitObs(data);
}
catch(Exception ex)
{
System.out.println(ex.toString());
return;
}
// name = pit.getDBName();
} else {
System.out.println("getting pit by serial: " + serial);
String data = getPitByLocalSerial(serial);
try
{
pit = new avscience.ppc.PitObs(data);
}
catch(Exception ex)
{
System.out.println(ex.toString());
return;
}
}
String user = pit.getUserHash();
deleteOcc(user, serial, name);
}
public String getPit(String name) {
System.out.println("DAO: getting WBA pit: " + name);
// avscience.wba.PitObs pit = null;
String s = "";
String query = "SELECT PIT_DATA FROM PIT_TABLE WHERE PIT_NAME = ?";
PreparedStatement stmt = null;
if ((name != null) && (name.trim().length() > 0)) {
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("pit in DB");
s = rs.getString("PIT_DATA");
if (s != null) {
break;
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
return s;
}
public String getPitByLocalSerial(String ser) {
System.out.println("getPitByLocalSerial()");
String s = "";
String query = "SELECT PIT_DATA FROM PIT_TABLE WHERE LOCAL_SERIAL = ?";
PreparedStatement stmt = null;
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, ser);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("PIT in DB");
s = rs.getString("PIT_DATA");
// System.out.println("Data: "+s);
}
} catch (Exception e) {
System.out.println(e.toString());
}
return s;
}
public String getPPCOcc(String serial) {
System.out.println("DAO: getting PPC occ: # " + serial);
// avscience.ppc.PitObs pit = null;
String query = "SELECT OCC_DATA FROM OCC_TABLE WHERE SERIAL = ?";
PreparedStatement stmt = null;
String s = "";
if ((serial != null) && (serial.trim().length() > 0)) {
int ser = 0;
ser = new java.lang.Integer(serial).intValue();
try {
stmt = getConnection().prepareStatement(query);
stmt.setInt(1, ser);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("OCC in DB");
// System.out.println("Data: "+s);
s = rs.getString("OCC_DATA");
} else {
System.out.println("PPC OCC query failed:.");
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
return s;
}
public String getPitXML(String ser)
{
String query = "SELECT PIT_XML FROM PIT_TABLE WHERE SYSTEM_SERIAL = ?";
PreparedStatement stmt = null;
String xml = "none";
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, ser);
ResultSet rs = stmt.executeQuery();
if (rs.next())
{
xml = rs.getString("PIT_XML");
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
return xml;
}
public String getPPCPit(String serial) {
System.out.println("DAO: getting PPC pit: # " + serial);
// avscience.ppc.PitObs pit = null;
String query = "SELECT PIT_DATA FROM PIT_TABLE WHERE SYSTEM_SERIAL = ?";
PreparedStatement stmt = null;
String s = "";
if ((serial != null) && (serial.trim().length() > 0)) {
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, serial);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("pit in DB");
// System.out.println("Data: "+s);
s = rs.getString("PIT_DATA");
System.out.println("PIT Data: " + s);
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
//System.out.println("Data: " + s);
return s;
}
public avscience.ppc.AvOccurence getOcc(String name) {
System.out.println("DAO: getting occ: " + name);
avscience.ppc.AvOccurence occ = null;
String query = "SELECT OCC_DATA FROM OCC_TABLE WHERE NAME = ?";
PreparedStatement stmt = null;
if ((name != null) && (name.trim().length() > 0)) {
try {
stmt = getConnection().prepareStatement(query);
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("occ in DB.");
String data = rs.getString("OCC_DATA");
if ((data != null) && (data.trim().length() > 0)) {
occ = new avscience.ppc.AvOccurence(data);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
return occ;
}
/*public void tallyTests() {
System.out.println("TallyTests()");
String[] queries = new String[10];
String[] years = {"2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012"};
String[] types = ShearTests.getInstance().getShearTestDescriptions();
int[] total = new int[years.length];
int[][] testTotal = new int[years.length][types.length];
int[] prof = new int[years.length];
int[] testPits = new int[years.length];
int[] ectNotes = new int[years.length];
int[] pstNotes = new int[years.length];
queries[0] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2003-01-01' AND OBS_DATE < '2004-01-01' ORDER BY OBS_DATE DESC";
queries[1] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2004-01-01' AND OBS_DATE < '2005-01-01' ORDER BY OBS_DATE DESC";
queries[2] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2005-01-01' AND OBS_DATE < '2006-01-01' ORDER BY OBS_DATE DESC";
queries[3] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2006-01-01' AND OBS_DATE < '2007-01-01' ORDER BY OBS_DATE DESC";
queries[4] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2007-01-01' AND OBS_DATE < '2008-01-01' ORDER BY OBS_DATE DESC";
queries[5] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2008-01-01' AND OBS_DATE < '2009-01-01' ORDER BY OBS_DATE DESC";
queries[6] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2009-01-01' AND OBS_DATE < '2010-01-01' ORDER BY OBS_DATE DESC";
queries[7] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2010-01-01' AND OBS_DATE < '2011-01-01' ORDER BY OBS_DATE DESC";
queries[8] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2011-01-01' AND OBS_DATE < '2012-01-01' ORDER BY OBS_DATE DESC";
queries[9] = "SELECT SERIAL, OBS_DATE FROM PIT_TABLE WHERE OBS_DATE >= '2012-01-01' ORDER BY OBS_DATE DESC";
for (int i = 0; i < queries.length; i++) {
System.out.println("Getting tests for query: " + queries[i]);
Statement stmt = null;
try {
stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery(queries[i]);
while (rs.next()) {
String s = rs.getString("SERIAL");
String data = getPPCPit(s);
avscience.ppc.PitObs pit = new avscience.ppc.PitObs(data);
if (pit.getPitNotes().contains("ECT")) {
ectNotes[i]++;
}
if (pit.getPitNotes().contains("PST")) {
pstNotes[i]++;
}
Enumeration tests = pit.getShearTests();
if (tests != null) {
if (tests.hasMoreElements()) {
testPits[i]++;
try {
avscience.ppc.User u = pit.getUser();
boolean prf = u.getProf();
if (prf) {
prof[i]++;
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
for (int j = 0; j < types.length; j++) {
tests = pit.getShearTests();
if (tests != null) {
while (tests.hasMoreElements()) {
avscience.ppc.ShearTestResult result = (avscience.ppc.ShearTestResult) tests.nextElement();
String cd = result.getCode();
String type = ShearTests.getInstance().getShearTestByCode(cd).getType();
if (types[j].equals(type)) {
testTotal[i][j]++;
break;
}
}
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
System.out.println("Writing test tally results to file:");
FileOutputStream out = null;
PrintWriter writer = null;
File file = new File("TestSummaryByYear.txt");
try {
out = new FileOutputStream(file);
writer = new PrintWriter(out);
} catch (Exception ex) {
System.out.println(ex.toString());
}
StringBuffer buffer = new StringBuffer();
buffer.append(" ,");
for (int i = 0; i < years.length; i++) {
buffer.append(years[i]);
buffer.append(",");
}
buffer.append("\n");
buffer.append("Pits with tests: ,");
for (int i = 0; i < testPits.length; i++) {
buffer.append(testPits[i]);
buffer.append(",");
}
buffer.append("\n");
buffer.append("Pits by professional: ,");
for (int i = 0; i < prof.length; i++) {
buffer.append(prof[i]);
buffer.append(",");
}
buffer.append("\n");
for (int i = 0; i < types.length; i++) {
buffer.append(types[i]);
buffer.append(",");
for (int j = 0; j < years.length; j++) {
buffer.append(testTotal[j][i]);
buffer.append(",");
}
buffer.append("\n");
}
buffer.append(",");
for (int i = 0; i < total.length; i++) {
buffer.append(total[i]);
buffer.append(",");
}
buffer.append("\n");
buffer.append("ECT in notes,");
for (int i = 0; i < ectNotes.length; i++) {
buffer.append(ectNotes[i]);
buffer.append(",");
}
buffer.append("\n");
buffer.append("PST in notes,");
for (int i = 0; i < pstNotes.length; i++) {
buffer.append(pstNotes[i]);
buffer.append(",");
}
buffer.append("\n");
try {
writer.print(buffer.toString());
writer.flush();
writer.close();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}*/
}<file_sep>/src/avscience/PitListServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
public class PitListServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
String action=request.getParameter("action");
if (action==null)action="";
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
doGet(request, response);
}
} | d35d4016109da19a7fd5a137717d418cd16d809b | [
"Markdown",
"Java"
] | 3 | Markdown | SnowpitData/AvscienceServer-2.0 | eacc0aa6f540cdeed773c95b01a18b4999c9d8ea | 252ff367ef872d8f009ff91153789abdd1b34838 |
refs/heads/master | <repo_name>Feemic/Color_trace<file_sep>/README.md
# Color_trace
the file named ColorBlobDetectionView.java is the opencv original source file.
the other files is changed to rejust the "Portrait Full Screen".
<file_sep>/ColorTrace.java
package com.example.healthdemo.activity;
import android.Manifest;
import android.app.FragmentManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.healthdemo.R;
import com.example.healthdemo.common.Data;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuParams;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import java.util.List;
/**
* Created by Feemic on 2016/8/8.
*/
public class ColorTrace extends AppCompatActivity implements View.OnTouchListener, CameraBridgeViewBase.CvCameraViewListener2
{
private FragmentManager fragmentManager;
private ContextMenuDialogFragment mMenuDialogFragment;
private static final String TAG = "OCVSample::Activity";
private boolean mIsColorSelected = false;
private Mat mRgba;
private Mat mRgbaF;
private Mat mRgbaT;
private Scalar mBlobColorRgba;
private Scalar mBlobColorHsv;
private ColorBlobDetector mDetector;
private Mat mSpectrum;
private Size SPECTRUM_SIZE;
private Scalar CONTOUR_COLOR;
public int sport_count;
public int flag,ok_flag;
private ImageButton back,buttonok;
private Context mContext;
private CameraBridgeViewBase mOpenCvCameraView;
//the camara prio
private static final int TAKE_PHOTO_REQUEST_CODE = 1;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this)
{
@Override
public void onManagerConnected(int status)
{
switch (status)
{
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
mOpenCvCameraView.setOnTouchListener(ColorTrace.this);
}
break;
default:
{
super.onManagerConnected(status);
}
break;
}
}
};
public ColorTrace()
{
Log.i(TAG, "Instantiated new " + this.getClass());
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "called onCreate");
mContext = this;
sport_count=0;
flag=0;
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.camera_layout);
fragmentManager = getFragmentManager();
initToolbar();
initMenuFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setBackgroundColor(getResources().getColor(R.color.lotine_background));
if(Build.VERSION.SDK_INT>=23){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
TAKE_PHOTO_REQUEST_CODE);
}
}
if (Build.VERSION.SDK_INT >= 21)
{
getWindow().setStatusBarColor(getResources().getColor(R.color.lotine_background));
}
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.surface_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
// mOpenCvCameraView.setCameraIndex(this);
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public void onResume()
{
super.onResume();
if (!OpenCVLoader.initDebug())
{
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
}
else
{
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy()
{
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height)
{
mRgba = new Mat(height, width, CvType.CV_8UC4);
mDetector = new ColorBlobDetector();
mSpectrum = new Mat();
mBlobColorRgba = new Scalar(255);
mBlobColorHsv = new Scalar(255);
SPECTRUM_SIZE = new Size(200, 64);
CONTOUR_COLOR = new Scalar(255,0,0,255);
this.mRgbaF = new Mat(height, width, CvType.CV_8UC4);
this.mRgbaT = new Mat(height, width, CvType.CV_8UC4);
}
public void onCameraViewStopped()
{
mRgba.release();
}
public boolean onTouch(View v, MotionEvent event)
{
int cols = mRgba.cols();
int rows = mRgba.rows();
// int xOffset = (mOpenCvCameraView.getWidth() - cols) / 2;
//int yOffset = (mOpenCvCameraView.getHeight() - rows) / 2;
int x = (int)(event.getX()/mOpenCvCameraView.getWidth()*cols);
int y = (int)(event.getY()/mOpenCvCameraView.getHeight()*rows);
Log.i(TAG, "Touch image coordinates: (" + x + ", " + y + ")");
if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) return false;
Rect touchedRect = new Rect();
touchedRect.x = (x>4) ? x-4 : 0;
touchedRect.y = (y>4) ? y-4 : 0;
touchedRect.width = (x+4 < cols) ? x + 4 - touchedRect.x : cols - touchedRect.x;
touchedRect.height = (y+4 < rows) ? y + 4 - touchedRect.y : rows - touchedRect.y;
Mat touchedRegionRgba = mRgba.submat(touchedRect);
Mat touchedRegionHsv = new Mat();
Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);
// Calculate average color of touched region
mBlobColorHsv = Core.sumElems(touchedRegionHsv);
int pointCount = touchedRect.width*touchedRect.height;
for (int i = 0; i < mBlobColorHsv.val.length; i++)
mBlobColorHsv.val[i] /= pointCount
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setBackgroundColor(Color.rgb((int) this.mBlobColorRgba.val[0], (int) this.mBlobColorRgba.val[1], (int) this.mBlobColorRgba.val[2]));
if (Build.VERSION.SDK_INT >= 21)
{
getWindow().setStatusBarColor(Color.rgb((int)this.mBlobColorRgba.val[0], (int)this.mBlobColorRgba.val[1], (int) this.mBlobColorRgba.val[2]));
}
Log.e(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");
mDetector.setHsvColor(mBlobColorHsv);
Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);
mIsColorSelected = true;
touchedRegionRgba.release();
touchedRegionHsv.release();
return false; // don't need subsequent touch events
}
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame)
{
mRgba = inputFrame.rgba();
Object localObject;
Core.transpose(this.mRgba, this.mRgbaT);
Imgproc.resize(this.mRgbaT, this.mRgbaF, this.mRgbaF.size(), 0.0D, 0.0D, 0);
Core.flip(this.mRgbaF, this.mRgba, 1);
if (mIsColorSelected)
{
mDetector.process(mRgba);
List<MatOfPoint> contours = mDetector.getContours();
Log.v(TAG, "Contours count: " + contours.size());
Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR);
localObject = new Message();
Bundle localBundle = new Bundle();
if (contours.size() != 0)
{
Log.e("coutonrs.size!=0","!=1");
Moments localMoments = Imgproc.moments((Mat)contours.get(0), false);
int i = (int)(localMoments.get_m10() / localMoments.get_m00());
int j = (int)(localMoments.get_m01() / localMoments.get_m00());
int k = (int)((MatOfPoint)contours.get(0)).size().area();
localBundle.putInt("x", j);
localBundle.putInt("y", i);
localBundle.putInt("size", k);
Log.e("x:",i+"y:"+j+"size:"+k);
((Message)localObject).what = 0;
((Message)localObject).setData(localBundle)
/*Mat colorLabel = mRgba.submat(0, 38, 0, 800); //间距为0,写38行,800列
colorLabel.setTo(mBlobColorRgba);*/
//Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
// mSpectrum.copyTo(spectrumLabel);
}
return mRgba;
}
private Scalar converScalarHsv2Rgba(Scalar hsvColor)
{
Mat pointMatRgba = new Mat();
Mat pointMatHsv = new Mat(1, 1, CvType.CV_8UC3, hsvColor);
Imgproc.cvtColor(pointMatHsv, pointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);
return new Scalar(pointMatRgba.get(0, 0));
}
private void initMenuFragment()
{
MenuParams menuParams = new MenuParams();
menuParams.setClosableOutside(false);
}
@Override
public boolean onCreateOptionsMenu(final Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
@Override
public void onBackPressed()
{
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded())
{
mMenuDialogFragment.dismiss();
}
else
{
finish();
}
}
}
| 22a695d6f917662d998681a017039f0cd1adf1df | [
"Markdown",
"Java"
] | 2 | Markdown | Feemic/Color_trace | 1387dfcf1513d9298e0ac92b1ed878a4c15416f9 | 4ecbd1e3ef2de4ac138b9bb3e02219b4cd339166 |
refs/heads/master | <file_sep>package projet_java;
public class GestionProtoAnnuaire {
private Utilisateur user = new Utilisateur();
public String analyserTraiter(String req) {
String[] requete = req.split("#");
if(requete[0].equalsIgnoreCase("CREATE"))
{
if (requete.length==8 )
{
return ("CREATIONOK");
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("CONSULTINFOPERSO"))
{
if (requete.length==2 ) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String reponse = user.consulterInfoPerso(numFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFINFOPERSONOM"))
{
if (requete.length==3) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String nom = requete[2];
String reponse = user.modificationInformationNom(numFiche, nom);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFINFOPERSOPRENOM"))
{
if (requete.length==3) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String prenom = requete[2];
String reponse = user.modificationInformationPrenom(numFiche, prenom);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFINFOPERSOTEL"))
{
if (requete.length==3) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String tel = requete[2];
String rep = user.modificationInformationTel(numFiche, tel);
return(rep);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFINFOPERSOFORMATION"))
{
if (requete.length==3) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String formation = requete[2];
String reponse = user.modificationInformationFormation(numFiche, formation);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFINFOPERSOANDIPLOME"))
{
if (requete.length==3) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String anneeDiplome = requete[2];
String reponse = user.modificationInformationAnneeDiplome(numFiche, anneeDiplome);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFINFOPERSOMAIL"))
{
if (requete.length==3) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String mail = requete[2];
String reponse = user.modificationInformationMail(numFiche, mail);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFINFOPERSOMDP"))
{
if (requete.length==3) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String mdp = requete[2];
String reponse = user.modificationInformationMotDePasse(numFiche, mdp);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFINFOPERSOCOMPETENCE"))
{
if (requete.length==3) /* ne pas oublier de modif suivant le nb de parametre */
{
String numFiche = requete[1];
String competence = requete[2];
String reponse = user.modificationInformationCompetence(numFiche, competence);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("RECHERCHENOM"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String nom = requete[1];
String reponse = user.rechercheNom(nom);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("RECHERCHEPRENOM"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String prenom = requete[1];
String reponse = user.recherchePrenom(prenom);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("RECHERCHEMAIL"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String mail = requete[1];
String reponse = user.rechercheMail(mail);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("RECHERCHEFORMATION"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String formation = requete[1];
String reponse = user.rechercheFormation(formation);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("RECHERCHEANDIPLOME"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String anneeDiplome = requete[1];
String reponse = user.rechercheAnneeDiplome(anneeDiplome);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("RECHERCHECOMPETENCE"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String competence = requete[1];
String reponse = user.rechercheCompetence(competence);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("VISIBILITENOM"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.visibiliteNom(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFVISINOM"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.modifVisibiliteNom(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("VISIBILITEPRENOM"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.visibilitePrenom(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFVISIPRENOM"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.modifVisibilitePrenom(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("VISIBILITETEL"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.visibiliteTel(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFVISITEL"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.modifVisibiliteTel(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("VISIBILITEFORM"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.visibiliteFormation(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFVISIFORM"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.modifVisibiliteFormation(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("VISIBILITEANDIPLOME"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.visibiliteAnneeDiplome(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFVISIANDIPLOME"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.modifVisibiliteAnneeDiplome(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("VISIBILITECOMPETENCE"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.visibiliteCompetence(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
else if(requete[0].equalsIgnoreCase("MODIFVISICOMPETENCE"))
{
if (requete.length==2) /* ne pas oublier de modif suivant le nb de parametre */
{
String NumFiche = requete[1];
String reponse = user.modifVisibiliteCompetence(NumFiche);
return(reponse);
}
else
{
return("ERREUR : REQUETE MAL FORMEE");
}
}
return("ERREURSRVAnnuaire");
}
}
| c7bb94cd815510e86667dbb3a7e9107b442ca8c4 | [
"Java"
] | 1 | Java | loicprojetjava/Projet_JAVA | b05b75d37a463168bbfdf3e66213ea22a8e4c213 | 0a0551d88bd780352216c92743438bedd0f1e83d |
refs/heads/master | <file_sep>export interface Destination {
PointX : number,
PointY : number,
Id : number
}
<file_sep>import { SettingsService } from './settings.service';
import { Destination } from './destination';
import * as _ from 'underscore';
export class Path {
path: Destination[] = <Destination[]>[];
constructor(private settingsService: SettingsService, private prePopulate: Boolean = true) {
if (prePopulate)
this.path = _.shuffle(this.settingsService.AllDestinations);
}
private getDist(startDest: Destination, endDest: Destination): number {
let xd = startDest.PointX - endDest.PointX;
let yd = startDest.PointY - endDest.PointY;
return Math.sqrt(xd * xd + yd * yd);
}
public Fitness(): number {
let fitness = 0;
for (let i = 0; i < this.path.length - 1; i++) {
let startDest = this.path[i];
let endDest = this.path[i + 1];
let dist = this.getDist(startDest, endDest);
fitness = fitness + dist;
}
// calculate back to base
fitness = fitness + this.getDist(this.path[0], this.path[this.path.length - 1]);
return fitness;
}
get ToString(): String {
let output = "";
for(let d of this.path)
{
output += d.Id + " "
}
return output
}
}
<file_sep>ng build -prod
cp -R dist/* /Users/wai/Dropbox/Apps/Azure/travelSalesmanapp
az appservice web source-control sync --name travelSalesmanapp --resource-group travelSalesmanrg
open http://travelSalesmanapp.azurewebsites.net
<file_sep><div class="wrapper">
<div class="box a">
<p>
<label class="label">Number of dots</label>
<input (change)="onSettingChange()" [disabled]="NotInMode(['new', 'generated'])" class="slider" type="range" max="150" min="1" [(ngModel)]="settingService.RouteLength"
/> {{settingService.RouteLength}}
</p>
<p>
<label class="label">Total Population</label>
<input (change)="onSettingChange()" [disabled]="NotInMode(['new', 'generated'])" class="slider" type="range" max="300" min="1" [(ngModel)]="settingService.TotalPopulation"
/> {{settingService.TotalPopulation}}
</p>
<p>
<label class="label">No Of Generations to run</label>
<input (change)="onSettingChange()" [disabled]="NotInMode(['new', 'generated'])" class="slider" type="range" max="100000" min="1" [(ngModel)]="settingService.NoOfGenerations"
/> {{settingService.NoOfGenerations}}
</p>
<p>
<label class="label">Mutation Rate</label>
<input (change)="onSettingChange()" class="slider" type="range" max="1" min="0" step="0.01" [(ngModel)]="settingService.MutationRate" /> {{settingService.MutationRate}}
</p>
<p>
<label class="label">Tournament Size</label>
<input (change)="onSettingChange()" class="slider" type="range" max="30" min="2" step="1" [(ngModel)]="settingService.tournamentSize" /> {{settingService.tournamentSize}}
</p>
<p>
<label class="label"> Is Elitist </label>
<input (change)="onSettingChange()" type="checkbox" [(ngModel)]="settingService.IsElitist" />
</p>
<p> <label class="label"> Number of possible pathways </label> {{noOfCombinations}}</p>
<p> <label class="label"> Number of pathways to calculate </label> {{noOfTests | number}}</p>
<p> best distance is : {{bestDistance | number}} </p>
<p> generation : {{currentGeneration}} </p>
<p> mode : {{mode}}</p>
<p>
<button [disabled]="NotInMode(['new', 'generated', 'stop'])" (click)="onGenerate()">Generate</button>
<button [disabled]="NotInMode(['generated', 'stop'])" (click)="onStart()">Start</button>
<button [disabled]="NotInMode(['run'])" (click)="onStop()">Stop</button>
</p>
<p> paths </p>
<p *ngFor="let p of sortedPaths, let i=index">
{{i}} ({{p.Fitness() | number : '1.0-0' }}) :
{{p.ToString}}
</p>
</div>
<div class="box b">
<canvas #myCanvas height="600" width="400" style="border:1px solid #000000;"></canvas>
</div>
</div><file_sep>import { Path } from 'app/path';
import { SettingsService } from './../settings.service';
import { CalculateService } from './../calculate.service';
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { Destination } from "app/destination";
import * as _ from 'underscore';
import { Router, ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, AfterViewInit {
constructor(public settingService: SettingsService, private calculateService: CalculateService,
private activatedRoute: ActivatedRoute) { }
canvasWidth: number = 400;
canvasHeight: number = 600;
context: CanvasRenderingContext2D;
@ViewChild("myCanvas") myCanvas;
destinations: Destination[] = [];
bestRoute: Destination[];
mode: String = "new";
NotInMode(acceptableModes: String[]): Boolean {
return acceptableModes.indexOf(this.mode) < 0;
}
ngOnInit() {
}
ngAfterViewInit() {
this.activatedRoute.queryParams.subscribe((params: Params) => {
try {
let dotsValue = params['dots'];
if (dotsValue) {
let obj = JSON.parse(dotsValue);
this.destinations = obj;
let canvas = this.myCanvas.nativeElement;
this.context = canvas.getContext("2d");
this.drawDots();
this.mode = "generated";
this.settingService.TotalPopulation = params["TotalPopulation"] as number;
this.settingService.NoOfGenerations = params["NoOfGenerations"] as number;
this.settingService.tournamentSize = params["tournamentSize"] as number;
this.settingService.IsElitist = params["IsElitist"] as Boolean;
this.settingService.MutationRate = params["MutationRate"] as number;
this.settingService.RouteLength = params["RouteLength"] as number;
}
}
catch(ex)
{
console.log(ex);
}
});
}
onSettingChange()
{
this.saveToQueryString();
}
bestDistance: number;
currentGeneration: number;
sortedPaths: Path[];
get noOfCombinations(): number {
return this.rFact(this.settingService.RouteLength - 1) / 2;
}
get noOfTests(): number {
return this.settingService.NoOfGenerations * this.settingService.TotalPopulation;
}
private rFact(num): number {
if (num === 0)
{ return 1; }
else
{ return num * this.rFact(num - 1); }
}
onGenerate() {
let canvas = this.myCanvas.nativeElement;
this.context = canvas.getContext("2d");
this.destinations = [];
for (let i = 0; i < this.settingService.RouteLength; i++) {
let _x = Math.floor(Math.random() * this.canvasWidth);
let _y = Math.floor(Math.random() * this.canvasHeight);
let dot = <Destination>{ PointX: _x, PointY: _y, Id: i }
this.destinations.push(dot);
}
this.saveToQueryString();
this.drawDots();
this.mode = "generated";
}
onStop() {
this.calculateService.toStop = true;
this.mode = "stop";
//this.calculateService.broadcast.unsubscribe();
}
onStart() {
this.mode = "run";
this.calculateService.toStop = false;
this.calculateService.broadcast.
subscribe(
data => {
this.drawDots();
this.plotBestRoute(data.FittestPath().path);
this.bestDistance = data.FittestPath().Fitness();
this.currentGeneration = data.generationNumber;
this.sortedPaths = data.PathsSortedByFitness();
});
this.calculateService.CalculateBestRoute(this.destinations);
}
private setFromQueryString() {
}
private saveToQueryString() {
let currentURL = [location.protocol, '//', location.host].join('');
let dots = JSON.stringify(this.destinations)
let queryString = "?dots=" + dots;
queryString += "&TotalPopulation=" + this.settingService.TotalPopulation;
queryString += "&NoOfGenerations=" + this.settingService.NoOfGenerations;
queryString += "&tournamentSize=" + this.settingService.tournamentSize;
queryString += "&IsElitist=" + this.settingService.IsElitist;
queryString += "&MutationRate=" + this.settingService.MutationRate;
queryString += "&RouteLength=" + this.settingService.RouteLength;
window.history.replaceState({}, "", currentURL + queryString);
}
private drawDots() {
this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
for (let dot of this.destinations) {
this.context.fillRect(dot.PointX, dot.PointY, 5, 5);
}
}
private plotBestRoute(route: Destination[]) {
this.context.beginPath();
let isStart: Boolean = true;
for (let d of route) {
if (isStart) {
this.context.moveTo(d.PointX, d.PointY);
isStart = false;
}
else {
this.context.lineTo(d.PointX, d.PointY);
}
}
// plot back to beginning
this.context.lineTo(route[0].PointX, route[0].PointY);
this.context.stroke();
}
}
<file_sep>import { SettingsService } from './settings.service';
import { Destination } from 'app/destination';
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Rx";
import { Path } from "app/path";
import { Generation } from "app/generation";
import { Subject } from "rxjs/Subject";
@Injectable()
export class CalculateService {
constructor(private settingsService: SettingsService) { }
public broadcast: Subject<Generation> = new Subject<Generation>();
public toStop = false;
public CalculateBestRoute(destinations: Destination[]) {
// store all destinations
this.settingsService.AllDestinations = destinations;
let paths: Path[] = <Path[]>[];
// generate a whole lot of generated paths
for (let i = 0; i < this.settingsService.TotalPopulation; i++) {
paths.push(new Path(this.settingsService, true));
}
// create a new generation for these paths
let currG = new Generation(this.settingsService);
currG.paths = paths;
let savedTimeouts = [];
// start to evolve
for (let i = 0; i < this.settingsService.NoOfGenerations; i++) {
savedTimeouts.push(setTimeout(() => {
// stop taking up resources when i hit stop
if (this.toStop) {
for(let t of savedTimeouts)
{
clearTimeout(t);
}
return;
}
// create the nex generation
let newG = new Generation(this.settingsService);
newG.generationNumber = i;
// if we want to have eliteism.
if(this.settingsService.IsElitist)
newG.paths.push(currG.FittestPath());
// get new generation of routes
for (let j = this.settingsService.IsElitist ? 1 : 0; j < this.settingsService.TotalPopulation; j++) {
// select two routes via tournament selection
let parent1 = currG.RunTournament();
let parent2 = currG.RunTournament();
// run crossover
let crossOverPath = this.settingsService.RunCrossOver(parent1, parent2);
newG.paths.push(crossOverPath);
}
currG = newG;
this.broadcast.next(newG);
}, 1));
}
}
}
<file_sep>import { Path } from './path';
import { Destination } from './destination';
import { Injectable } from '@angular/core';
import * as _ from 'underscore';
@Injectable()
export class SettingsService {
constructor() { }
public TotalPopulation: number = 20;
public NoOfGenerations: number = 25000;
public AllDestinations: Destination[];
public tournamentSize: number = 15;
public IsElitist: Boolean = true;
public MutationRate: number = 0.1;
public RouteLength: number = 16;
public HalfRouteLength(): number {
return Math.floor(this.RouteLength / 2);
}
public RunCrossOver(parent1: Path, parent2: Path): Path {
let parent1Section = Math.floor(Math.random() * (this.HalfRouteLength() - 1));
let subSetOfParent1 = <Destination[]>[];
for (let i = parent1Section; i < parent1Section + this.HalfRouteLength(); i++) {
subSetOfParent1.push(parent1.path[i]);
}
let parent2NonParent1Dest = <Destination[]>[];
parent2NonParent1Dest = _.filter(parent2.path, (p2) => _.every(subSetOfParent1,
(p1) => {
return p1.Id != p2.Id;
}));
let newRoute = new Path(this, false);
for (let i = 0; i < this.RouteLength; i++) {
// if current i is in the starting section of parent 1, use parent 1
if (i >= parent1Section && i < parent1Section + this.HalfRouteLength()) {
newRoute.path.push(parent1.path[i]);
}
else {
// if not, check if parent2's destination at i is a destination in parent1's startingsection,
let p = parent2NonParent1Dest.shift();
newRoute.path.push(p);
}
}
if (Math.random() < this.MutationRate) {
// let noOfPathMutated = Math.floor(Math.random() * this.HalfRouteLength());
let noOfPathMutated = 1;
for (let i = 0; i < noOfPathMutated; i++) {
let random1 = Math.floor(Math.random() * this.RouteLength);
let random2 = Math.floor(Math.random() * this.RouteLength);
let middleRoute = newRoute.path[random1];
newRoute.path[random1] = newRoute.path[random2];
newRoute.path[random2] = middleRoute;
}
}
return newRoute;
}
}
<file_sep>import { Path } from './path';
import { SettingsService } from './settings.service';
import * as _ from 'underscore';
export class Generation {
paths: Path[] = <Path[]>[];
generationNumber: number;
constructor(private settingsService: SettingsService) { }
public RunTournament(): Path {
// randomly pick tournaments
let contestants = _.first(_.shuffle(this.paths), this.settingsService.tournamentSize);
// get the best two to be the first parents
return _.sortBy(contestants, (p) => p.Fitness())[0];
}
public FittestPath(): Path {
let sorted = _.sortBy(this.paths, (p) => p.Fitness());
return sorted[0];
}
public AverageFitness(): number {
return _.reduce(this.paths, function (memo, num) {
return memo + num.Fitness();
}, 0) / this.paths.length;
}
public UnFittestPath(): Path {
let sorted = _.sortBy(this.paths, (p) => p.Fitness() * -1);
return sorted[0];
}
public PathsSortedByFitness() : Path[]
{
return _.sortBy(this.paths, (p) => p.Fitness());
}
}
| 50ae295fdabffa0d2ae329edcfcc1e1cd882d8a0 | [
"TypeScript",
"HTML",
"Shell"
] | 8 | TypeScript | waiholiu/travelsalesmen | 4a34aed05fd1e787d23bbdb86cc341243c565ed2 | 3e4828cb53bd3b85579b06f2652eb0c7791055df |
refs/heads/master | <file_sep>package com.example.pesc.hello;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class ResultActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
SharedPreferences sharedpreferences = getSharedPreferences("pessoa", this.MODE_PRIVATE);
String nome= sharedpreferences.getString("nome", null);
Pessoa pessoa = (Pessoa) getIntent().getSerializableExtra("pessoa");
TextView nomeView = (TextView) findViewById(R.id.nomeView);
TextView emailView = (TextView) findViewById(R.id.emailView);
TextView senhaView = (TextView) findViewById(R.id.senhaView);
nomeView.setText(nome);
emailView.setText(pessoa.getEmail());
senhaView.setText(pessoa.getSenha());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_result, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.example.pesc.hello;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by PESC on 28/05/2015.
*/
public class DBHelper extends SQLiteOpenHelper {
//version number to upgrade database version
//each time if you Add, Edit table, you need to change the
//version number.
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "bancoDados.db";
SQLiteDatabase db;
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = getWritableDatabase();
}
public SQLiteDatabase getDb(){
return db;
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("Database", "onCreate");
String CREATE_TABLE_PESSOA = "CREATE TABLE " + Pessoa.TABLE + "("
+ Pessoa.NOME + " TEXT, "
+ Pessoa.SENHA + " TEXT, "
+ Pessoa.EMAIL + " TEXT )";
db.execSQL(CREATE_TABLE_PESSOA);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("Database" , "OldVersion: " + oldVersion);
Log.d("Database" , "NewVersion: " + newVersion);
// Drop older table if existed, all data will be gone!!!
//db.execSQL("DROP TABLE IF EXISTS " + Pessoa.TABLE);
switch (newVersion) {
case 2:
db.execSQL("ALTER TABLE " + Pessoa.TABLE + " ADD COLUMN profissao TEXT;");
break;
case 3:
db.execSQL("ALTER TABLE " + Pessoa.TABLE + " ADD COLUMN profissao2 TEXT;");
break;
}
}
}
| 255894ce391d25d2e07f40baae299a171a3e1072 | [
"Java"
] | 2 | Java | capgovWorkshop/antonio_constantino | 5257f485ceed3282316e7fd8cbfc1241806074b2 | 912700477bf973f13c54ee232ab0ca2a3048ea4a |
refs/heads/master | <file_sep>"""
Monte Carlo timestep calculator for PoMs-MC
"""
# Import generic packages, and then append the specific directory path - needs to be edited by user
import sys
import numpy as np
sys.path.append("/Users/u5707688/Documents/ISM_positron_prop/Adiabatic_ISM")
# Import the PoMs_MC user packages:
# Import the parameter set for this external timestep
import param
##################################################
# #
# PoMs_MC: TIMESTEP INITIALIZATION ROUTINE #
# Song suggestion: "Better" - The Screaming Jets #
# #
##################################################
# Import the external simulation timestep and the next timestep (or just set it for the test)
dt_ext = 10**3
dt_ext1 = dt_ext
#Calculate the energy-set timestep
def dt_en(energy, rate_ion, rate_pla):
return energy/(rate_ion+rate_pla)
dt_e = dt_en(param.e_mcp, param.ion, param.pla)
print(dt_e)
#calculate the interaction probability set timestep
def denom(sig_Hex, sig_Hi, sig_Hcx, n_H, n_He, sig_Heex, sig_Hei, sig_Hecx, energy):
beta = np.sqrt(1-(1/(1+((energy)/param.mp)))**2)
sumxs = n_H*(sig_Hex+sig_Hi+sig_Hcx) + n_He*(sig_Heex+sig_Hei+sig_Hecx)
return sumxs*beta*param.c
if denom(param.xsec_Hex, param.xsec_Hi, param.xsec_Hc, param.n_H, param.n_He, param.xsec_Heex, param.xsec_Hei,param.xsec_Hec, param.e_mcp) == 0:
dt_int = inf
else:
dt_int = 0.01/denom(param.xsec_Hex, param.xsec_Hi, param.xsec_Hc, param.n_H, param.n_He, param.xsec_Heex, param.xsec_Hei, param.xsec_Hec, param.e_mcp)
print(dt_int)
# Calculate the Monte Carlo timestep and print it
dt_MC = min(dt_ext, dt_ext1, dt_e, dt_int)
dt_remain = dt_ext-dt_MC
print(dt_MC, dt_ext)<file_sep>"""
Welcome to PoMs-MC (Positron Microphysics Monte Carlo): A Monte Carlo positron annihilation spectrum calculator for generalized positron transport
Created by <NAME>, Australian National University
Collaborators: <NAME>, <NAME>, <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
#
# import He-positron cross-sections
# Data from Murphy et al. 2005
#
arr_He_ion = np.loadtxt("He_process/heion_xsec.txt",skiprows=0)
arr_He_ex = np.loadtxt("He_process/heex_xsec.txt",skiprows=0)
arr_He_cx = np.loadtxt("He_process/hece_xsec.txt",skiprows=0)
#
# import H-positron cross-sections
# ex and io from Murphy 2005. NEED TO UPDATE CHARGE EXCHANGE: currently from Kernoghan+1992
#
arr_H_ion = np.loadtxt("H_process/ion_xsec.txt",skiprows=0)
arr_H_ex = np.loadtxt("H_process/ex_xsec.txt",skiprows=0)
arr_H_cx = np.loadtxt("H_process/cx_xsec.txt",skiprows=0)
#
# if you would like to plot the raw cross-sections for these processes, please uncomment the following
#
##Helium cross-sections - Log-Log plot
#
#plt.figure
#plt.plot(np.log10(arr_He_ion[:,0]),np.log10(arr_He_ion[:,1]), 'r-' ,lw = 2, label = 'He Ionization')
#plt.plot(np.log10(arr_He_ex[:,0]), np.log10(arr_He_ex[:,1]), 'b--',lw = 2, label = 'He exitation')
#plt.plot(np.log10(arr_He_cx[:,0]), np.log10(arr_He_cx[:,1]), 'c:', lw = 2, label = 'He charge exchange')
#plt.title("Helium-positron process cross-sections")
#plt.xlabel("log(E/eV)")
#plt.ylabel("log($\sigma$/$\mathrm{cm}^2$)")
#plt.legend(loc = 'best')
#plt.ylim([-17.5,-15])
#plt.show()
#
##Hydrogen cross-sections - Log-Log plot
#
#plt.figure
#plt.plot(np.log10(arr_H_ion[:,0]),np.log10(arr_H_ion[:,1]), 'r-' ,lw = 2, label = 'H Ionization')
#plt.plot(np.log10(arr_H_ex[:,0]), np.log10(arr_H_ex[:,1]), 'b--',lw = 2, label = 'H exitation')
#plt.plot(np.log10(arr_H_cx[:,0]), np.log10(arr_H_cx[:,1]), 'c:', lw = 2, label = 'H charge exchange')
#plt.title("Hydrogen-positron process cross-sections")
#plt.xlabel("log(E/eV)")
#plt.ylabel("log($\sigma$/$\mathrm{cm}^2$)")
#plt.legend(loc = 'best')
#plt.ylim([-17.5,-15])
#plt.show()
<file_sep>"""
Constants required for MC simulation
"""
import sys
sys.path.append("/Users/u5707688/Documents/ISM_positron_prop/Adiabatic_ISM")
# initialize required constants
#
kbev = 8.6E-5 # Boltzmann constant in units eV/K
ec = 4.8E-19 # Electron charge in cgs units
hbar = 1.05E-27 # h/2pi in cgs units
kberg = 1.3E-16 # Boltzmann constant in cgs units
me = 9.11E-28 # Electron mass in cgs units
mp = 511*10**3 # positron rest mass in units eV/c^2
c = 3*10**10 # speed of light in cgs<file_sep>"""
Discrete energy loss module for PoMs-MC
"""
<file_sep>"""
user-defined special functions
Author: <NAME>, Australian National University
"""
import numpy as np
def find_nearest(array, value):
idx = (np.abs(array-value)).argmin()
return idx, array[idx]
#arr = np.zeros((2,10))
#for i in range(1,10):
# arr[0][i] = i
#for i in range(1,10):
# arr[1][i] = np.random.random(1)
#
#print(arr)
#v = 0.5
#q = find_nearest(arr[1,:],v)
#print(q, arr[0,q[0]])
<file_sep>"""
Welcome to PoMs-MC (Positron Microphysics Monte Carlo): A Monte Carlo positron annihilation spectrum calculator for generalized positron transport
Created by <NAME>, Australian National University
Collaborators: <NAME>, <NAME>, <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
#
# import reaction rates
#
arr_df = np.loadtxt("rates_data/rate_dfree.txt",skiprows=0)
arr_hcx = np.loadtxt("rates_data/rate_hcx.txt",skiprows=0)
arr_hdb = np.loadtxt("rates_data/rate_hdab.txt",skiprows=0)
arr_hedb = np.loadtxt("rates_data/rate_hedab.txt",skiprows=0)
arr_rr = np.loadtxt("rates_data/rate_rr.txt",skiprows=0)
plt.figure
plt.plot(np.log10(arr_df[:,1]),np.log10(arr_df[:,0]), 'r-' ,lw = 2, label = 'Direct free')
plt.plot(np.log10(arr_hcx[:,1]), np.log10(arr_hcx[:,0]), 'b--',lw = 2, label = 'Charge exchange w/ H')
plt.plot(np.log10(arr_hdb[:,0]), np.log10(arr_hdb[:,1]), 'c:', lw = 2, label = 'Direct bound H')
plt.plot(np.log10(arr_hedb[:,0]), np.log10(arr_hedb[:,1]), 'y-', lw = 2, label = 'Direct bound He')
plt.plot(np.log10(arr_rr[:,0]), np.log10(arr_rr[:,1]), 'g-', lw = 2, label = 'Direct bound H')
plt.title("reaction rates/target density")
plt.xlabel("log(T/K)")
plt.ylabel("log($\mathrm{cm}^3$/$\mathrm{s}$)")
plt.legend(loc = 'best')
plt.xlim([2,8])
plt.show()<file_sep>"""
Parameter initialization and storage for PoMs-MC
"""
# Import generic packages, and then append the specific directory path - needs to be edited by user
import sys
import numpy as np
sys.path.append("/Users/u5707688/Documents/ISM_positron_prop/Adiabatic_ISM")
###################################################
# #
# PoMs_MC: PARAMETER INITIALIZATION #
# Song suggestion: "<NAME>" #
# - <NAME> Birds #
# #
###################################################
# Initialization routine
# Initialize the arrays which will store the various parameters at each MC timestep
# Slap this all into one single giant array at some stage - means redefining where shit goes
arr_epacket = []
arr_nH = [0.1,1]
arr_nHe = []
arr_xH = []
arr_temperature = []
#arr_dts = []
arr_dtMC = []
# This array stores the time since the beginning of the simulation
timing_sim = []
# Here, the routine to import these parameters from the PLUTO source files will go
arr_nHsim = [1]*10
# Initialize the first parameters for the simulation, including case to prevent appending or overwriting arrays which contain information
def initialize_MC(e, H, He, xH, temperature):
if not arr_epacket:
init_e = e
arr_epacket.append(init_e)
if not arr_nH:
init_nH = H
arr_nH.append(init_nH)
if not arr_nHe:
init_nHe = He
arr_nHe.append(init_nHe)
if not arr_xH:
init_xH = xH
arr_xH.append(init_xH)
if not arr_temperature:
init_temperature = temperature
arr_temperature.append(init_temperature)
if not timing_sim:
timing_sim.append(0)
return print('parameters initialized')
#initialize_MC(1,1,0.1,1,7000)
#There is no initialization for the Monte Carlo timestep dtMC - this is set and updated through the timestep
#module. DO NOT EDIT arr_dtMC THROUGH THIS MODULE. LEAVE IT ALONE! BAD ASTRO! NO BISCUIT!
# These functions update the parameters for each timestep and they scare me a lot. Be nice
# Only the dynamic parameters - the packet energy and the MC timestep update. The others are fixed by the parent
# Simulation
def update_epacket(current_energy, energy_lost):
temp = current_energy-energy_lost
return arr_epacket.append(temp)
#OH MY GOD IT ACTUALLY WORKS! WOW!
##############################################
# DON'T BE AFRAID TO FAIL -- #
# BE AFRAID NOT TO TRY #
##############################################
#update_epacket(arr_epacket[0],10)
#print(arr_epacket)
def update_dtMC(dt_sim, dtMC):
temp = dt_sim-dtMC
if temp <= 0:
arr_dtMC.append(init_dts)
else:
return arr_dtMC.append(temp)
# Interpolate to find the value of n_H at the end of the current Monte Carlo timestep
def update_nH(time, nH):
t_arrtemp = [timing_sim[len(timing_sim)-1],timing_sim[len(timing_sim)-1]+timestep.dt_ext]
nH_arrtemp = [arr_nHsim[len(timing_sim)-1], arr_nHsim[len(timing_sim)]]
inter = interp1d(time,nH)
return arr_nH.append(inter(timingsim[len(timing_sim)-1]+timestep.dt_MC))
# Function to update the simulation timing at the end of the MC timestep
def update_timing(dt_MC):
return timing_sim.append(timing_sim[len(timing_sim)-1]+dt_MC)
<file_sep>"""
Parameter settings and import for PoMs-MC
"""
import sys
import numpy as np
sys.path.append("/Users/u5707688/Documents/ISM_positron_prop/Adiabatic_ISM")
# Import the PoMs_MC user packages
# To import the cross-sections, we import the cross-section array module
import cross_sections
#import par_init
# We import the special user-defined functions written for use in PoMs_MC
import test
import energy_loss
import constants as const
##################################################
# #
# PoMs_MC: PARAMETER SETTING AND IMPORT #
# Song suggestion: "<NAME>" #
# - <NAME> #
# #
##################################################
# import x-secs, energy loss, packet energy, n_e, n_H, x_H
# Temp MCP packet energy in eV, electron density, H number density and ionization
# fraction for test
# Need to think of a crafty way to update this at each timestep
# Read in for the initialize/update parameters module
e_mcp = 600
n_e = 1
n_H = 1
n_He = 0
x_H = 0.7
Z = 1
Temperature = 7000
# You can check that the cross-sections have imported correctly by uncommenting
# the following line if you are loading different cross-section files.
# Free advice: don't be a weenie. Leave the input files alone.
#print(cross_sections.arr_H_ion)
# To calculate the adaptive timestep, we need to know the cross-sections for
# various processes xsec_ij where i is the process and j is the target density.
# The cross-sections are a function of energy.
# Ver 1.0 does not interpolate between gridpoints. This will be updated in ver 2.0
# HYDROGEN
def Hxsec(e_mcp):
temp = test.find_nearest(cross_sections.arr_H_ion[:,0], e_mcp)
if abs(temp[1]-e_mcp)>50:
xsec_Hi = 0
else:
xsec_Hi = cross_sections.arr_H_ion[temp[0],1]
temp = test.find_nearest(cross_sections.arr_H_ex[:,0], e_mcp)
if abs(temp[1]-e_mcp)>50:
xsec_Hex = 0
else:
xsec_Hex = cross_sections.arr_H_ex[temp[0],1]
temp = test.find_nearest(cross_sections.arr_H_cx[:,0], e_mcp)
if abs(temp[1]-e_mcp)>50:
xsec_Hc = 0
else:
xsec_Hc = cross_sections.arr_H_cx[temp[0],1]
return [xsec_Hi, xsec_Hex, xsec_Hc]
# HELIUM
def Hexsec(e_mcp):
if n_He==0:
return [0,0,0]
else:
temp = test.find_nearest(cross_sections.arr_He_ion[:,0], e_mcp)
if abs(temp[1]-e_mcp)>50:
xsec_Hei = 0
else:
xsec_Hei = cross_sections.arr_He_ion[temp[0],1]
temp = test.find_nearest(cross_sections.arr_He_ex[:,0], e_mcp)
if abs(temp[1]-e_mcp)>50:
xsec_Heex = 0
else:
xsec_Heex = cross_sections.arr_He_ex[temp[0],1]
temp = test.find_nearest(cross_sections.arr_He_cx[:,0], e_mcp)
if abs(temp[1]-e_mcp)>50:
xsec_Hec = 0
else:
xsec_Hec = cross_sections.arr_He_cx[temp[0],1]
return [xsec_Hei, xsec_Heex, xsec_Hec]
# A redundant debugging line to make sure the functions work
#print(Hxsec(600), Hexsec(600))
# calculate the energy loss rates in eV/s
def eloss_rate(n_e, n_H, n_He, Z, e_mcp, Temperature, B, x_H):
ion = energy_loss.dE_io(n_H, e_mcp, Z)
pla = energy_loss.dE_pl(e_mcp, n_e, Temperature)
syn = energy_loss.dE_sy(B, e_mcp)
brion = energy_loss.dE_br(e_mcp, Z, x_H*n_H)
brneu = energy_loss.dE_brn(e_mcp, n_H)
return [ion, pla, syn, brion, brneu, ion + pla + syn + brion + brneu]
# parameter to store energy loss rate in eV/s
de_conts = eloss_rate(n_e,n_H,n_He, Z, e_mcp, Temperature, 50,x_H)[5]
# calculates the positron velocity in cm s^-1 in terms of energy
def p_vel(energy):
return np.sqrt(1-(1/(1+((energy)/const.mp)))**2)*const.c
print(p_vel(e_mcp))
# A redundant debugging line to make sure the functions work
#print(eloss_rate(1,1,0.1,1, 700, 8000, 50, 0.7))
<file_sep>Welcome to PoMS-MC: POsitron MicrophysicS Monte Carlo simulator!
Created by <NAME>, Australian National University 2016
email: fiona(.)panther(at)anu(.)edu(.)au
PoMS-MC is an open-source, user-friendly Monte Carlo simulator to produce annihilation spectra and radiation skymaps of annihilating positrons in astrophysical environments.
PoMS-MC makes no assumptions about the transport of positrons (in contrast with previous positron annihilation MC simulations). The user is free to import their own transport data (e.g. hydrodynamic simulations of SN, MHD simulations of solar flares or ISM transport). We will also provide a grid of simple MHD models for the user to experiment with.
<file_sep>"""
Welcome to PoMs-MC (Positron Microphysics Monte Carlo): A Monte Carlo positron annihilation spectrum calculator for generalized positron transport
Created by <NAME>, Australian National University
Collaborators: <NAME>, <NAME>, <NAME>
"""
import sys
import scipy
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pylab
from scipy.integrate import quad
sys.path.append("/Users/u5707688/Documents/ISM_positron_prop/Adiabatic_ISM")
import constants as const
#
# initialize the formulae to calculate the energy loss processes
#
# ~~GLOSSARY~~
# dE_io - ionization continuum losses
# dE_pl - plasma losses
# dE_sy - synchrotron losses
# dE_br - bremsstrahlung losses
# dE_ic - inverse Compton losses
#
# ionization continuum losses (ref. Prantzos et al. 2011)
def dE_io(nn, energy, Z):
gamma = 1+((energy)/(const.mp))
beta = np.sqrt(1-(1/(1+((energy)/const.mp)))**2)
return (7.1*10**-9)*(nn*Z/beta)*(np.log((gamma-1)*((gamma*beta*const.mp)**2)/(2*13.6**2))+1/8)
# test the function works!
#print(dE_io(1,10**3,1))
# plasma continuum losses (ref. Huba 2004 (NRL Plasma Formulary))
def dE_pl(energy, ne, temperature):
u = np.sqrt(2*energy/const.me)-np.sqrt((8*const.kbev*temperature)/(np.pi*const.me))
rmax = np.sqrt(const.kberg*temperature/(4*np.pi*ne*(const.ec**2)))
rmin = np.max((const.ec**2/(const.me*u**2)),const.hbar/(2*const.me*u))
cl = np.log(rmax/rmin)
beta = np.sqrt(1-(1/(1+((energy)/const.mp)))**2)
funcint = lambda x: x**(1/2)*np.exp(-x)-(energy/(const.kbev*temperature))**(1/2)*np.exp(-energy/const.kbev*temperature)
integ = quad(funcint,0,(energy/(const.kbev*temperature)))
return (1.7*10**-8)*(ne/beta)*cl*integ[0]
# test the function works!
#print(dE_pl(10**3,1,8000))
# synchrotron losses (ref Blumenthal & Gould 1970)
# PLEASE NOTE: SPECIFY B IN MICROGAUSS!
def dE_sy(B, energy):
gamma = 1+((energy)/(const.mp))
beta = np.sqrt(1-(1/(1+((energy)/const.mp)))**2)
return (9.9*10**-16)*B**2*gamma**2*beta**2*(2/3)
# test the function works!
#print(dE_sy(50, 10**3))
# Bremsstrahlung losses (ref. Ginzburg 1979) for fully ionized gas
def dE_br(energy, Z, ni):
gamma = 1+((energy)/(const.mp))
return(3.6*10**-11)*Z*(Z+1)*ni*gamma*(np.log(2*gamma)-(1/3))
# Bremsstrahlung losses for neutral H gas
def dE_brn(energy, nn):
gamma = 1+((energy)/(const.mp))
return (4.1*10**-10)*nn*gamma
# Inverse compton losses (ref. Blumenthal & Gould 1970)
# note this function needs some work! In certain environments it is possible to
# calculate the radiation energy density urad. This could be an add-on module
#def dE_ic(urad, energy):
# gamma = 1+((energy)/(mp))
# beta = np.sqrt(1-(1/(1+((energy)/mp)))**2)
# return (2.6*10**-14)*urad*gamma**2*beta**2
# Adiabatic energy losses/gain. Function of change in gas density between
# timesteps
| 41d002c7ea432e3528ce1a8ec546856c13fdfc7c | [
"Markdown",
"Python"
] | 10 | Python | fipanther/PoMS_MC | 326da10baa85d0388a4762a549f33bc3c8155ced | 4ccb223f5d5af066a088fbdc0e12d84e6c522e9c |
refs/heads/master | <repo_name>DenizDalkilic10/MyLinuxShell<file_sep>/README.md
# MyLinuxShell
A personalized linux shell for single and compound commands
Bilshell has only one builtin function, "exit".
When it is entered as a single command, exit(1) is called.
If it is used in a compound command like "exit | sort" the shell will ask for a new input.
<file_sep>/bilshell.c
#define _GNU_SOURCE
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#define TOKEN_DIVIDER " \t\r\n\a"
#define READ_LINE_BUFFER_SIZE 1024 // dynamic allocation used if the buffer size is exceeded
int processHandler(char ** firstCommand, char ** secondCommand, int bytesToTransfer)
{
pid_t cp1_id, cp2_id;
int pipeMC1[2], pipeMC2[2]; //pipeMC1 = Main - CHild1 pipe , pipeMC2 = Main - Child2 pipe
int isCompoundCommand;
if (firstCommand[0] == NULL) { // An empty command was entered.
return 1;
}
else if(secondCommand == NULL)
{
isCompoundCommand = 0;
if (strcmp(firstCommand[0],"exit") == 0) // if the user types "exit" the program terminates
{
exit(1);
}
}
else{
isCompoundCommand = 1;
}
/////////Pipe 1 is being created////////
if(isCompoundCommand){ // this will be true if the command is compound command with "|"
if(pipe(pipeMC1) == -1){
perror("Pipe between Main and Child 1 failed");
exit(EXIT_FAILURE);
}
fcntl(pipeMC1[0],F_SETPIPE_SZ,1024*1024); //new pipe size
fcntl(pipeMC1[1],F_SETPIPE_SZ,1024*1024); //new pipe size
//printf("New Pipe Size %d\n",b );
}
//printf("BulletPoint\n");
cp1_id = fork(); //child process 1
if (cp1_id == 0) {
if(isCompoundCommand){
dup2(pipeMC1[1],1); //redirection of standart output
}
//the command is a single command
if (execvp(firstCommand[0], firstCommand) == -1) {
printf("Error in firstCommand\n");
exit(1);
}
}
else if (cp1_id < 0) {
printf("Error during first process creation");
} else { //main process
wait(NULL);
if (isCompoundCommand)
{
char oneReadValue [bytesToTransfer]; //forms a buffer according to the size of the bytesToRead
ssize_t readSize;
ssize_t totalBytesRead = 0;
int totalReadOperations = 0;
close(pipeMC1[1]);
////////Pipe 2 is being created////////
if(pipe(pipeMC2) == -1){
perror("Pipe between Main and Child 2 failed");
exit(1);
}
fcntl(pipeMC2[0],F_SETPIPE_SZ,1024*1024); //new pipe size
fcntl(pipeMC2[1],F_SETPIPE_SZ,1024*1024); //new pipe size
/////////////////////////////////////// Data Transfer Between Pipes Handled By Main Process ///////////////////////////////////////////////
while((readSize = read(pipeMC1[0],oneReadValue, bytesToTransfer)) > 0){ // main reads from pipe 1 and writes to pipe 2
totalBytesRead += readSize;
totalReadOperations++;
write(pipeMC2[1], oneReadValue, readSize); //read doğru çalışıyo burdan sonrasını check et bi yerde segmentation fault alıyosunnnnn!!!!!!
}
/////////////////////////////////////// Data Transfer Between Pipes Handled By Main Process ///////////////////////////////////////////////
close(pipeMC2[1]); //closing the write end of pipe 2
cp2_id = fork();
//printf("CHILD 2 FORKED\n");
if (cp2_id == 0) { //second child
dup2(pipeMC2[0],0); //redirection of standart input
close(pipeMC2[0]); //closes the read end of Main - CHild2 pipe
if (execvp(secondCommand[0], secondCommand) == -1) {
//printf("%s\n",secondCommand[0]);
printf("Error in secondCommand\n");
exit(1);
}
}
else if (cp2_id < 0) {
printf("Error during second process creation");
} else {
wait(NULL); // wait for the child to terminate
printf("\nCharacter Count: %ld\n", totalBytesRead);
printf("Read Call Count: %d\n\n", totalReadOperations);
}
}
}
return 1;
}
char **createArguments(char *line)
{
int bufsize = 64;
char **wordArray = malloc(bufsize * sizeof(char*));
char *word = NULL;
word = strtok(line, TOKEN_DIVIDER);
int i = 0;
while (word != NULL) {
wordArray[i++] = word;
if (i >= bufsize) {
bufsize += 64;
wordArray = realloc(wordArray, bufsize * sizeof(char*));
}
word = strtok(NULL, TOKEN_DIVIDER);
}
wordArray[i] = NULL;
return wordArray;
}
void shellCore(char * file, int bytesToTransfer)
{
char *line = NULL; // the command in interactive mode
char * firstCommand = NULL; // the first command in bash mode
char * secondCommand = NULL; // the second command in bash mode
char **args = NULL; // used for interactive mode for keeping tokens of one single command
char ** argsOfFirstCommand = NULL; // used for bash mode
char ** argsOfSecondCommand = NULL; // used for bash mode
size_t len = 0;
ssize_t read = 0;
int success = 1; // integer for keeping the success value of operations
int fd = 0; // file descriptor
int interactiveMode = 0; // identifies the mode of the shell
int isCompoundCommand = 0; // identifies the type of the given command
const char tok[2] = "|"; // used for dividing compound commands into tokens
if(file == NULL){
interactiveMode = 1;
}
if(!interactiveMode){ //if bash mode is active
if ( ( fd = open (file, O_RDONLY) ) < 0 ) {
exit (1);
}
FILE * fp = fdopen(fd,"r"); // opens the input file, fp points to beginning of the file
do {
read = getline(&line, &len, fp); //for reading from input file
if(read > 1){
firstCommand = strtok(line,tok); //if not null, and if null it is a single command
if (firstCommand != NULL)
{
secondCommand = strtok(NULL,tok);
if (secondCommand != NULL){
isCompoundCommand = 1;
}
else
{
isCompoundCommand = 0;
}
}
if(isCompoundCommand){
//printf("Compound Command detected...\n");
argsOfFirstCommand = createArguments(firstCommand);
argsOfSecondCommand = createArguments(secondCommand);
success = processHandler(argsOfFirstCommand,argsOfSecondCommand,bytesToTransfer);
if(argsOfFirstCommand != NULL){
free(argsOfFirstCommand);
}
if(argsOfSecondCommand != NULL){
free(argsOfSecondCommand);
}
}
else{
//printf("Single Command detected...\n");
args = createArguments(line);
success = processHandler(args,NULL,bytesToTransfer);
if(args != NULL){
free(args); //bu değişti
}
}
}
} while (success && read != -1);
free(line);
fclose(fp);
}
else if (interactiveMode){
do {
printf("bilshell-$: ");
read = getline(&line,&len,stdin);//readLine(); // reads an input from the user
if(read > 1){ //if the command is not empty
firstCommand = strtok(line,tok); //if not null, and if null it is a single command
if (firstCommand != NULL)
{
secondCommand = strtok(NULL,tok);
if (secondCommand != NULL){
isCompoundCommand = 1;
}
else
{
isCompoundCommand = 0;
}
}
if(isCompoundCommand){
//printf("Compound Command detected...\n");
argsOfFirstCommand = createArguments(firstCommand);
argsOfSecondCommand = createArguments(secondCommand);
success = processHandler(argsOfFirstCommand,argsOfSecondCommand,bytesToTransfer);
if(argsOfFirstCommand != NULL){
free(argsOfFirstCommand);
}
if(argsOfSecondCommand != NULL){
free(argsOfSecondCommand);
}
}
else{
//printf("Single Command detected...\n");
args = createArguments(line);
success = processHandler(args,NULL,bytesToTransfer);
if(args != NULL){
free(args); //bu değişti
}
}
}
} while (success && read != -1);
free(line);
}
}
int main(int argc, char * argv[])
{
int bytesToTransfer = atoi(argv[1]);
if (bytesToTransfer == 0 || bytesToTransfer > 4096){
printf("Illegal number of bytesToTransfer: %d\n",bytesToTransfer);
printf("Exiting from bilshell...");
exit(1);
}
else{
printf("Bytes to transfer in each operation: %d \n", bytesToTransfer);
}
if(argv[2] == NULL){
printf("No input file\n");
printf("\n********Interactive Mode Activated************\n");
}
else{
printf("Input File Name Is: %s \n",argv[2]);
printf("\n********Bash Mode Activated************\n");
printf("\nPLease wait...Reading the file...\n");
}
shellCore(argv[2], bytesToTransfer); //pass input file as an argument
return EXIT_SUCCESS;
}
<file_sep>/Makefile
all: bilshell
bilshell: bilshell.c
gcc -Wall -g -o bilshell bilshell.c
clean:
rm -fr bilshell bilshell.o *~
| 4d11915263050789d8b6d4ddd260ae5f920cb9e6 | [
"Markdown",
"C",
"Makefile"
] | 3 | Markdown | DenizDalkilic10/MyLinuxShell | 1d7b4c49e9bc12bcb40f6f683a76122b9043b8ec | ad1cff72e603860afe3994f2664b77b533b787c0 |
refs/heads/master | <file_sep>import os
import random
from threading import Lock
from flask import Flask, jsonify, render_template, request, session, redirect, url_for, flash
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.secret_key = "my secret key"
app.config["SESSION_TYPE"] = "filesystem"
mutex = Lock()
DEFAULT_STATIC_PATH = "/static"
IMG_PATH_TO_TAG = {
"01foto.jpg": "OCCHIALI",
"02foto.jpg": "SVEGLIA",
"03foto.jpg": "CUCCHIAINO",
"04foto.jpg": "BICCHIERE",
"05foto.jpg": "PIATTO",
"06foto.jpg": "MELA",
"07foto.jpg": "BOTTIGLIA",
"08foto.jpg": "TAZZA",
"09foto.jpg": "CHIAVI",
"10foto.jpg": "CIPOLLA",
"11foto.jpg": "COLTELLO",
"12foto.jpg": "CREMA",
"13foto.jpg": "CUCINA",
"14foto.jpg": "CUSCINO",
"15foto.jpg": "DENTIFRICIO",
"16foto.jpg": "DOCCIA",
"17foto.jpg": "FORCHETTA",
"18foto.jpg": "FOTO",
"19foto.jpg": "FRIGO",
"20foto.jpg": "LAMPADA",
"21foto.jpg": "LATTE",
"22foto.jpg": "LIBRO",
"23foto.jpg": "MIELE",
"24foto.jpg": "PANTOFOLE",
"25foto.jpg": "POMODORI",
"26foto.jpg": "PROFUMO",
"27foto.jpg": "QUADRO",
"28foto.jpg": "RUBINETTO",
"29foto.jpg": "SAPONE",
"30foto.jpg": "SEDIA",
"31foto.jpg": "SHAMPOO",
"32foto.jpg": "SPAZZOLINO",
"33foto.jpg": "SPECCHIO",
"34foto.jpg": "SPUGNA",
"35foto.jpg": "TEA",
"36foto.jpg": "TELEFONO",
"37foto.jpg": "TELEVISIONE",
"38foto.jpg": "UOVA",
"39foto.jpg": "VASO",
}
@app.route("/")
def root_handler():
img_data = _get_random_img()
session["tag"] = img_data["tag"]
session["path"] = img_data["path"]
return render_template("index.html", **img_data)
@app.route("/reload")
def reload_handler():
img_data = _get_random_img()
session["tag"] = img_data["tag"]
session["path"] = img_data["path"]
return jsonify(img_data)
@app.route("/upload", methods=["GET", "POST"])
def upload_handler():
if request.method == "GET":
return render_template("upload.html")
if request.method == "POST":
if "file" not in request.files:
flash("Selezionare un file")
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == "":
flash('No selected file')
return redirect(request.url)
if file:
filename = secure_filename(file.filename)
print(filename)
# file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return render_template("upload.html")
@app.route("/name", methods=["GET"])
def name_handler():
if request.args.get("tag").upper() == session["tag"]:
img_data = _get_random_img()
session["tag"] = img_data["tag"]
session["path"] = img_data["path"]
return jsonify(img_data)
else:
return jsonify({"tag": session["tag"], "path": session["path"]})
def _get_random_img():
images = [f for f in os.listdir("static") if f.endswith(".jpg")]
img = images[random.randint(0, len(images) - 1)]
path = os.path.join(DEFAULT_STATIC_PATH, img)
mutex.acquire()
tag = IMG_PATH_TO_TAG[img]
mutex.release()
return {
"path": path,
"tag": tag,
}
if __name__ == '__main__':
app.run()
| bf75968cf18196bb71e70982cae12cc2707f0610 | [
"Python"
] | 1 | Python | lorep86/aphasiaWebapp | e4ad83a5542472caef33915699a965e98edd040b | 3b708c4013c2495e6b06db4804ce04427986bf4c |
refs/heads/master | <file_sep>from PySide2 import QtWidgets, QtCore, QtGui
### char formats
__varTypeFormat = QtGui.QTextCharFormat()
#__varTypeFormat.setFontWeight(QtGui.QFont.Bold)
__varTypeFormat.setForeground(QtCore.Qt.magenta)
__varCommentFormat = QtGui.QTextCharFormat()
__varCommentFormat.setForeground(QtCore.Qt.yellow)
### patterns
__varTypePatterns = ["int", "float", "string", "vector"
, "matrix", "matrix3", "vector4", "vector2", "matrix2"]
__varTypePatterns = ["\\b" + pattern + "\\b" for pattern in __varTypePatterns]
__singleLinePattern = ["//"]
__singleLinePattern = [pattern + "*" for pattern in __singleLinePattern]
__multilinePatternsStart = ["/\\*"]
__multilinePatternsEnd = ["\\*/"]
# ("pattern", format)
vexRules = []
[vexRules.append((pattern, __varTypeFormat)) for pattern in __varTypePatterns]
singleLineRules = []
[singleLineRules.append((pattern, __varCommentFormat)) for pattern in __singleLinePattern]
multiLineRules = []
[multiLineRules.append((start, end, __varCommentFormat)) for (start, end) in zip(__multilinePatternsStart, __multilinePatternsEnd)]
<file_sep>from PySide2 import QtWidgets, QtCore, QtGui
from kaToolsExpressionPicker import syntaxRules
reload(syntaxRules)
class vexSyntaxHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, parent = None):
super(vexSyntaxHighlighter, self).__init__(parent)
def highlightBlock(self, text):
for pattern, charFormat in syntaxRules.vexRules:
expression = QtCore.QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, charFormat)
index = expression.indexIn(text, index + length)
for pattern, charFormat in syntaxRules.singleLineRules:
expression = QtCore.QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = len(text)
self.setFormat(index, length - index, charFormat)
index = expression.indexIn(text, index + length)
for start, end, charFormat in syntaxRules.multiLineRules:
startExp = QtCore.QRegExp(start)
endExp = QtCore.QRegExp(end)
startIndex = 0
self.setCurrentBlockState(0)
if self.previousBlockState() != 1:
startIndex = startExp.indexIn(text)
while startIndex >= 0:
#print "start index: ", startIndex
endIndex = endExp.indexIn(text, startIndex)
#print "end index: ", endIndex
if endIndex == -1:
self.setCurrentBlockState(1)
commentLength = len(text) - startIndex
else :# if endIndex >= startIndex:
commentLength = endIndex - startIndex + endExp.matchedLength()
self.setFormat(startIndex, commentLength, charFormat)
startIndex = startExp.indexIn(text, startIndex + commentLength)
<file_sep># -*- coding: utf-8 -*-
import hou
#import xml.etree.ElementTree as ET
import sys
#import xml.parsers.expat as ep
import lxml.etree as let
import re
import os
class categoryData:
parent = None
name = ''
myselfData = None
parentData = None
def __init__(self, parent = None, myself = None):
self.myselfData = myself
self.parentData = parent
if parent != None :
if "name" in parent.keys():
self.parent = parent.attrib[("name")]
if myself != None:
self.name = myself.attrib[("name")]
class expressionData(categoryData):
expression=''
categories = []
def __init__(self, parent = None, myself = None):
self.myselfData = myself
self.parentData = parent
if parent != None:
self.parent = parent.attrib[("name")]
if myself != None:
self.name = myself.attrib[("name")]
self.expression = myself.text
class presetXML:
parser = ""
menus = []
inSet=False
inExp=False
expression=''
XMLPath=''
tree2 = let.ElementTree()
kwargs = None
expressions = []
categories = []
def __init__(self, kwargs=None):
scriptPath = __file__
validPath = ""
while True:
if os.path.split(scriptPath)[1] != "":
scriptPath = os.path.split(scriptPath)[0]
if scriptPath == "":
break
else:
if os.path.exists(scriptPath + '/expressions.xml'):
validPath = scriptPath + '/expressions.xml'
else:
break
self.XMLPath = validPath
parser = let.XMLParser(resolve_entities=False, remove_blank_text=True, strip_cdata=False)
self.tree2 = let.parse(self.XMLPath, parser)
self.kwargs = kwargs
self.readAll()
###########################################################################
def findCategory(self, root):
categories = list(root)
for child in categories:
if child.tag == "category":
category = categoryData(root, child)
self.categories.append(category)
#print category
self.findCategory(child)
elif child.tag == "expression":
expression = expressionData(root, child)
self.expressions.append(expression)
def getParents(self, data):
parentName = data.parentData
#print parentName
if parentName != None:
for category in self.categories:
if category.myselfData == parentName:
categoryList = self.getParents(category)
categoryList.append(parentName.attrib[("name")])
return categoryList
#print "done2"
return []
else:
#print "done"
return []
def readAll(self):
root = self.tree2.getroot()
self.expressions = []
self.categories = []
self.findCategory(root)
#print [e.name for e in self.categories]
#print [e.parent for e in self.categories]
#print [self.getParents(e) for e in self.expressions]
#print [e.name for e in self.expressions]
pass
def saveXML(self, saveCategory, saveName, exp):
root = self.tree2.getroot()
categories = saveCategory.split("/")
name = saveName
expression = exp
expression = let.CDATA(expression)
expressionElement = let.Element("expression")
expressionElement.set("name", name)
expressionElement.text = expression
parent = root
rootPath = "."
for i in range(len(categories)):
rootPath = rootPath + "/category"
foundCategories = parent.findall(rootPath + "[@name='" + categories[i] + "']")
#print rootPath
if len(foundCategories) >0:
parent = foundCategories[0]
#print "found", parent.attrib[("name")]
else:
categoryElement = let.Element("category")
categoryElement.set("name", categories[i])
parent.append(categoryElement)
parent = categoryElement
#print "not found", parent.attrib[("name")]
parent.append(expressionElement)
self.tree2.write(self.XMLPath, encoding="utf-8", method="xml", pretty_print = True)
def findWhereToAdd(self, element):
if element.tag != "expression":
exsistingCategories = list(element)
pass
def exportExpression(self, kwargs):
expression = self.getExpression(kwargs)
return expression
def exportCategory(self, kwargs):
category = self.getCategory(kwargs)
return category
def paste(self, kwargs):
expression = self.getExpression(kwargs)
kwargs["parms"][0].set(kwargs["parms"][0].eval() + expression)
def getExpression(self, kwargs):
root = self.tree2.getroot()
expression = root.find("./set[@name='" + kwargs["selectedlabel"] +"']").find('expression').text
return expression
def getCategory(self, kwargs):
root = self.tree2.getroot()
category = ""
try:
category = root.find("./set[@name='" + kwargs["selectedlabel"] +"']").attrib[("category")]
#print category
except KeyError:
#print "no category"
category = "no category"
return category
def makeMenus(self):
root = self.tree2.getroot()
self.menus = []
for menuset in root:
if menuset.tag == "set":
self.menus.append(menuset.attrib[("name")])
self.menus.append(menuset.attrib[("name")])
return self.menus
def updateExpression(self, categoryList, name, newName, newExp):
root = self.tree2.getroot()
length = len(name)
if length==0:
return
element = self.getElement(categoryList, name)
#print element
if element != None:
element.set("name", newName)
element.text = newExp
self.updateXMLFile()
def deleteExpression(self, categoryList, name):
root = self.tree2.getroot()
length = len(name)
if length==0:
return
element = self.getElement(categoryList, name)
parent = None
if element != None:
for data in self.expressions:
if data.myselfData == element:
parent = data.parentData
break
if parent != None:
parent.remove(element)
self.updateXMLFile()
def getElement(self, categoryList, name):
root = self.tree2.getroot()
element = None
rootPath = "."
for i in range(len(categoryList)):
rootPath = rootPath + "/category"
rootPath = rootPath + "[@name='" + categoryList[i] + "']"
foundCategories = root.findall(rootPath + "/expression[@name='" + name + "']")
if len(foundCategories) >0:
element = foundCategories[0]
else:
foundCategories = root.findall(rootPath + "/category[@name='" + name + "']")
if len(foundCategories) >0:
element = foundCategories[0]
return element
def updateXMLFile(self):
self.tree2.write(self.XMLPath, encoding="utf-8", method="xml", pretty_print = True)
def sortXML(self):
root = self.tree2.getroot()
#print "sort"
self.sortOneLevel(root)
self.updateXMLFile()
pass
def sortOneLevel(self, parent):
parent[:] = sorted(parent, key=lambda child:child.get("name"))
parent[:] = sorted(parent, key=lambda child:child.tag)
for child in parent:
self.sortOneLevel(child)
<file_sep>from PySide2 import QtWidgets, QtCore, QtGui
import hou
class saveDialog(QtWidgets.QDialog):
def __init__(self, parent = None, f=0):
super(saveDialog, self).__init__(parent, f)
self.setFocus()
layout = QtWidgets.QVBoxLayout()
catLayout = QtWidgets.QHBoxLayout()
nameLayout = QtWidgets.QHBoxLayout()
buttonLayout = QtWidgets.QHBoxLayout()
cautionLabel = QtWidgets.QLabel("Use \"/\" to make sub directories. (e.g. aaa/bbb)")
catLabel = QtWidgets.QLabel("Category: ")
nameLabel = QtWidgets.QLabel("Name : ")
self.catTextLine = QtWidgets.QLineEdit()
self.nameTextLine = QtWidgets.QLineEdit()
okButton = QtWidgets.QPushButton("OK")
cancelButton = QtWidgets.QPushButton("Cancel")
catLayout.addWidget(catLabel)
catLayout.addWidget(self.catTextLine)
nameLayout.addWidget(nameLabel)
nameLayout.addWidget(self.nameTextLine)
buttonLayout.addStretch()
buttonLayout.addWidget(okButton)
buttonLayout.addWidget(cancelButton)
layout.addWidget(cautionLabel)
layout.addLayout(catLayout)
layout.addLayout(nameLayout)
layout.addLayout(buttonLayout)
self.setLayout(layout)
self.catTextLine.setFocus()
okButton.clicked.connect(self.accept)
cancelButton.clicked.connect(self.reject)
self.setStyleSheet(hou.qt.styleSheet())
def getCatandName(self):
return self.catTextLine.text(), self.nameTextLine.text()
<file_sep>import hou
import toolutils
from PySide2 import QtWidgets, QtCore, QtGui
from kaToolsExpressionPicker import addExpression, stylesheet, vexSyntaxHighlighter
from kaToolsExpressionPicker.widgets import expressionTreeWidget, snippet, saveDialog, snippetDialog
reload(addExpression)
reload(stylesheet)
reload(expressionTreeWidget)
reload(snippet)
reload(saveDialog)
reload(snippetDialog)
class editFlags:
__edit = 0
__clear = 1
__current = 0
def __init__(self, init = 0):
self.setFlag(init)
pass
def flag(self):
return self.__current
def setFlag(self, val):
self.__current = val
def edit(self):
return self.__edit
def clear(self):
return self.__clear
class pickerWidget1(QtWidgets.QFrame):
def __init__(self, parent = None):
super(pickerWidget, self).__init__(parent)
layout = QtWidgets.QVBoxLayout()
view = QtWidgets.QTreeView()
view.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
model = QtGui.QStandardItemModel()
model.setHorizontalHeaderLabels(['col1', 'col2', 'col3'])
view.setModel(model)
#view.setUniformRowHeights(True)
for i in range(3):
parent1 = QtGui.QStandardItem('Family {}. Some long status text for sp'.format(i))
for j in range(3):
child1 = QtGui.QStandardItem('Child {}'.format(i*3+j))
child2 = QtGui.QStandardItem('row: {}, col: {}'.format(i, j+1))
child3 = QtGui.QStandardItem('row: {}, col: {}'.format(i, j+2))
parent1.appendRow([child1, child2, child3])
model.appendRow(parent1)
# span container columns
view.setFirstColumnSpanned(i, view.rootIndex(), True)
layout.addWidget(view)
self.setLayout(layout)
class pickerWidget(QtWidgets.QFrame):
prevClicked = QtWidgets.QTreeWidgetItem()
flag = editFlags()
def __init__(self, parent = None):
#super(pickerWidget, self).__init__(parent)
QtWidgets.QFrame.__init__(self, parent)
self.draggedItem = None
layout = QtWidgets.QVBoxLayout()
#layout.setContentsMargins(0,0,0,0)
self.splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
### set up buttons
buttonLayout = QtWidgets.QHBoxLayout()
self.refreshButton = QtWidgets.QPushButton("Refresh")
self.sortButton = QtWidgets.QPushButton("Sort")
self.saveButton = QtWidgets.QPushButton("Save")
self.deleteButton = QtWidgets.QPushButton("Delete")
buttonLayout.addWidget(self.refreshButton)
buttonLayout.addWidget(self.sortButton)
buttonLayout.addWidget(self.saveButton)
buttonLayout.addWidget(self.deleteButton)
self.refreshButton.clicked.connect(self.onRefreshClicked)
self.refreshButton.clicked.connect(self.onSortClicked)
self.saveButton.clicked.connect(self.onSaveClicked)
self.deleteButton.clicked.connect(self.onDeleteClicked)
### set up tree widget
self.treeWidget = expressionTreeWidget.expressionTreeWidget()
self.treeWidget.setColumnCount(2)
self.treeWidget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.treeWidget.setColumnWidth(0, 150)
self.treeWidget.setColumnWidth(1, 800)
self.treeWidget.setAutoScroll(False)
self.treeWidget.setHeaderLabels(["Name", "Expression"])
self.treeWidget.itemClicked.connect(self.onItemClicked)
self.treeWidget.itemDoubleClicked.connect(self.onItemDoubleClicked)
searchLayout = QtWidgets.QHBoxLayout()
self.staticSearchText = QtWidgets.QLabel()
self.staticSearchText.setText("Filter : ")
self.searchTextArea = QtWidgets.QLineEdit()
self.clearFilterButton = QtWidgets.QPushButton("Clear")
self.searchTextArea.textEdited.connect(self.onSearchTextEdited)
self.searchTextArea.editingFinished.connect(self.onEditFinished)
self.clearFilterButton.clicked.connect(self.onClearFilterClicked)
searchLayout.addWidget(self.staticSearchText)
searchLayout.addWidget(self.searchTextArea)
searchLayout.addWidget(self.clearFilterButton)
labelLayout = QtWidgets.QHBoxLayout()
self.pathLabel = QtWidgets.QLabel()
self.pathLabel.setStyleSheet(stylesheet.styles["initial"])
self.pathLabel.setText("Drop parameter above:")
#self.pathLabel.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum))
self.clearButton = QtWidgets.QPushButton("Clear")
self.clearButton.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed))
labelLayout.addWidget(self.pathLabel)
#labelLayout.addStretch(0)
labelLayout.addWidget(self.clearButton)
self.clearButton.clicked.connect(self.onClearClicked)
self.textArea = snippet.snippet(pathLabel = self.pathLabel)
cursor = self.textArea.textCursor()
font = QtGui.QFont()
font.setPointSize(12)
self.textArea.setCurrentFont(font)
layout.addLayout(buttonLayout)
layout.addLayout(searchLayout)
layout.addWidget(self.splitter)
self.splitter.addWidget(self.treeWidget)
self.splitter.addWidget(self.textArea)
layout.addLayout(labelLayout)
self.setLayout(layout)
self.splitter.setSizes([250,100])
self.preset = addExpression.presetXML()
self.updateTree()
self.setStyleSheet(hou.qt.styleSheet())
def closeEvent(self, event):
if hou.parm(self.pathLabel.text()) !=None:
self.textArea.removeCallBack(hou.parm(self.pathLabel.text()).node())
super(pickerWidget,self).closeEvent(event)
def onSelectionChanged(self, selection):
node = None
if len(selection) > 0:
for each in selection:
if each.networkItemType() == hou.networkItemType.Node:
node = each
break
if node != None:
self.textArea.autoConnect(node)
pass
def onItemDoubleClicked(self, item, column):
#self.treeWidget.editItem(item, column)
newName = item.text(0)
newExp = item.text(1)
snippetDia = snippetDialog.snippetDialog(parent = self, text=item.text(column))
result = snippetDia.exec_()
if result == QtWidgets.QDialog.Accepted:
if column == 0:
newName = snippetDia.getNewText()
elif column == 1:
newExp = snippetDia.getNewText()
categoryList = self.getParentItems(item)
#print categoryList
self.preset = addExpression.presetXML()
self.preset.updateExpression(categoryList, item.text(0), newName, newExp)
self.onRefreshClicked()
def onItemClicked(self, item, column):
'''
if item.isSelected() == True:
if self.prevClicked is item:
selectecNodes = hou.selectedNodes()
selectecNode = None
if len(selectecNodes) == 0:
return
selectecNode = selectecNodes[0]
if selectecNode.type() == hou.sopNodeTypeCategory().nodeTypes()["attribwrangle"]:
self.draggedItem = item.text(1)
parmText = selectecNode.parm("snippet").eval()
selectecNode.parm("snippet").set(parmText + self.draggedItem)
self.prevClicked = item
'''
if item.childCount()>0:
if item.isExpanded() == False:
item.setExpanded(True)
else:
item.setExpanded(False)
def onRefreshClicked(self):
self.preset = addExpression.presetXML()
#menus = self.importXmlMenus()
#menus, categories = self.importExpressions(menus)
self.updateTree()
def onSortClicked(self):
self.preset.sortXML()
self.onRefreshClicked()
def onSaveClicked(self):
savedia = saveDialog.saveDialog()
result = savedia.exec_()
if result == QtWidgets.QDialog.Accepted:
category, name = savedia.getCatandName()
self.preset = addExpression.presetXML()
self.preset.saveXML(category, name, self.textArea.toPlainText())
self.onRefreshClicked()
def onDeleteClicked(self):
items = self.treeWidget.selectedItems()
if len(items)>0:
for item in items:
categoryList = self.getParentItems(item)
name = item.text(0)
self.preset.deleteExpression(categoryList, name)
self.onRefreshClicked()
def getParentItems(self, item):
if isinstance(item, QtWidgets.QTreeWidgetItem):
parentItem = item.parent()
if isinstance(parentItem, QtWidgets.QTreeWidgetItem):
categoryList = self.getParentItems(parentItem)
categoryList.append(parentItem.text(0))
return categoryList
else:
return []
else:
return []
def onSearchTextEdited(self, text):
allItems = self.treeWidget.findItems("", QtCore.Qt.MatchStartsWith | QtCore.Qt.MatchRecursive)
for item in allItems:
item.setHidden(False)
if text != "":
for i in range(self.treeWidget.topLevelItemCount()):
child = self.treeWidget.topLevelItem(i)
if text in child.text(0):
pass
else:
self.setVisiblity(text, child)
def setVisiblity(self, text, rootItem):
if text in rootItem.text(0):
return 1
else:
count = rootItem.childCount()
found = 0
if count > 0:
for i in range(count):
found += self.setVisiblity(text, rootItem.child(i))
if found>0:
#rootItem.setHidden(True)
return 1
else:
rootItem.setHidden(True)
return 0
else:
rootItem.setHidden(True)
return 0
def onEditFinished(self):
self.treeWidget.setFocus()
def onClearFilterClicked(self):
self.searchTextArea.setText("")
self.onSearchTextEdited("")
def onClearClicked(self):
self.pathLabel.setText("Cleared.")
self.flag.setFlag(self.flag.clear())
self.textArea.setText("")
self.pathLabel.setStyleSheet(stylesheet.styles["initial"])
def rrrr(self):
print "resize"
allItems = self.treeWidget.findItems("", QtCore.Qt.MatchStartsWith | QtCore.Qt.MatchRecursive)
for item in allItems:
count = item.childCount()
if count==0:
print item.expArea.toPlainText()
print item.expArea.viewport().size()
item.setSizeHint(1, item.expArea.document().size().toSize()*1.1)
item.expArea.setFixedHeight(item.expArea.document().size().height())
pass
############################################################
def clear(self):
'''
length = self.treeWidget.topLevelItemCount()
if length > 0:
for i in range(0, length):
#print i
self.clearItems(self.treeWidget.topLevelItem(0))
self.treeWidget.takeTopLevelItem(0)
'''
self.treeWidget.clear()
def clearItems(self, item):
#print item
length = item.childCount()
if length > 0:
for i in range(0, length):
item.child(0)
item.removeChild(item.child(0))
parent.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled) #QtCore.Qt.ItemIsEditable |
def updateTree(self):
while True:
try:
if self.treeWidget.itemPressed is not None:
self.treeWidget.itemPressed.disconnect()
except Exception:
#print Exception
break
while True:
try:
if self.treeWidget.itemDoubleClicked is not None:
self.treeWidget.itemDoubleClicked.disconnect()
except Exception:
#print Exception
break
while True:
try:
if self.treeWidget.itemClicked is not None:
self.treeWidget.itemClicked.disconnect()
except Exception:
#print Exception
break
self.clear()
font = None
for expression in self.preset.expressions:
categories = self.preset.getParents(expression)
#print expression.name, categories
parent = self.treeWidget
for i, categoryName in enumerate(categories):
items = []
if isinstance(parent, expressionTreeWidget.expressionTreeWidget):
items = parent.findItems(categoryName, QtCore.Qt.MatchCaseSensitive, 0)
#print "parent is tree"
elif isinstance(parent, QtWidgets.QTreeWidgetItem):
#print "parent is item" , parent.text(0)
for i in range(parent.childCount()):
if parent.child(i).text(0) == categoryName:
items.append(parent.child(i))
if len(items) == 0:
parent = QtWidgets.QTreeWidgetItem(parent)
parent.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled) #QtCore.Qt.ItemIsEditable |
parent.setText(0, categoryName)
parent.setExpanded(False)
font = parent.font(0)
font.setPointSize(11)
font.setBold(True)
parent.setFont(0, font)
else:
parent = items[0]
font = parent.font(0)
#child = expTreeItem(parent)
child = QtWidgets.QTreeWidgetItem(parent)
child.setText(0, expression.name)
#child.expArea.setText(expression.expression)
child.setText(1, expression.expression)
child.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled) #QtCore.Qt.ItemIsEditable |
child.setToolTip(1, expression.expression)
font.setPointSize(10)
font.setBold(False)
for column in range (child.columnCount()):
child.setFont(column, font)
#self.treeWidget.itemPressed.connect(self.onItemPressed)
self.treeWidget.itemDoubleClicked.connect(self.onItemDoubleClicked)
self.treeWidget.itemClicked.connect(self.onItemClicked)
pass
class expTreeItem(QtWidgets.QTreeWidgetItem):
def __init__(self, parent=None):
super(expTreeItem, self).__init__(parent)
self.expArea = QtWidgets.QTextBrowser()
#self.expArea.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed , QtWidgets.QSizePolicy.Fixed ))
#self.expArea.setMinimumHeight(10)
vexSyntax = vexSyntaxHighlighter.vexSyntaxHighlighter(self.expArea.document())
self.expArea.setReadOnly(True)
#self.expArea.setEnabled(False)
#self.expArea.setMouseTracking(False)
self.expArea.setTextInteractionFlags(QtCore.Qt.NoTextInteraction )
self.expArea.setStyleSheet(stylesheet.styles["templateAreaAlt"])
self.expArea.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.treeWidget().setItemWidget(self, 1, self.expArea)
self.setSizeHint(1, QtCore.QSize(10, 800))
pass
def text(self, column):
return self.expArea.toPlainText()
<file_sep># kaToolsExpressionPicker
Thank you for visiting my tool!
This is module-based expression editor.
We can write vex/python code by drag & drop....plus a little bit of editing.
If you use one function over and over again, save it as a module, and you can grab it whenever you want from the list view!
## Update v0.1.022
- Syntax highlighting! (Partially...)
- Clear button for filtering.
- reconstruct some part.
## Update v0.1.018
- You can double-click something on a list and edit a code or name.
- Bit better layout.
## Update v0.1.017
- If you press tab in the text area, cursor still keeps the position (It doesn't go away).
- Not completely, but even when you edit code on a parameter, text area on this tool is updated (You need to set focus to somewhere from the parameter).
### Installation
Put this repository somewhere and add its path to both:
- HOUDINI_PATH,
- HOUDINI_PYTHON_PANEL_PATH
in houdini.env.
(e.g. rename "kaToolsExpressionPicker-release" "kaToolsExpressionPicker", move it to "C:/Users/foo/Documents/houdini16.0" and then, on Windows:
HOUDINI_PATH="C:/Users/foo/Documents/houdini16.0/kaToolsExpressionPicker;"
HOUDINI_PYTHON_PANEL_PATH="C:/Users/foo/Documents/houdini16.0/kaToolsExpressionPicker;")
### Once you donwload it, I reccomend moving "expression.xml" to parent folder.
** On Windows, if that file path is below: **
** "C:/Users/foo/Documents/houdini16.0/kaToolsExpressionPicker/expression.xml", **
** then move it parent like below: **
** "C:/Users/foo/Documents/houdini16.0/expression.xml". **
** This tool looks up original file path or above. (e.g. it looks up even : "C:/expression.xml") **
** In this way, you don't lose expression-modules you have made when you update this tool. **
### Instructions
1. Type whatever code you might re-use.
2. Hit "Save".
3. Type Category and name, and press OK.
4. On the list, now you can see expressions you have saved.
5. Drag and Drop a parameter (e.g. "snippet" parameter in "attribwrangle")
6.Drag and drop expressions from the list onto text area.
7. You can edit code in the text area, Houdini shows result tight away.
(Sorry, but no auto completion or syntax highlighting.)
### Extra:
- When you have a bunch of expressions, you can filter expressions and categories.
- If you want to sort expressions, hit "sort".
- If you want to delete a expression you have in the list, select it and hit "delete".
### Shortcuts
(text area)
- Ctrl + Shift + "+": zoom in
- Ctrl + "-" : zoom out
### Bug....ish
- Drag and drop inside the list doesn't really work. It looks like you can re-arrange the order, but if you hit refresh, the list goes back to the previous order.
If you have any questions, feedbacks and/or ideas that may enhance usability of this tool, feel free to send a message to:
<EMAIL>
<NAME>
<file_sep>from PySide2 import QtWidgets, QtCore, QtGui
from kaToolsExpressionPicker.widgets import snippet
import hou
reload(snippet)
class snippetDialog(QtWidgets.QDialog):
def __init__(self, parent = None, f=0, text = ""):
super(snippetDialog, self).__init__(parent, f)
layout = QtWidgets.QVBoxLayout()
self.snippetTextArea = snippet.snippet(parent = parent)
self.snippetTextArea.setText(text)
buttonLayout = QtWidgets.QHBoxLayout()
okButton = QtWidgets.QPushButton("OK")
cancelButton = QtWidgets.QPushButton("Cancel")
buttonLayout.addStretch()
buttonLayout.addWidget(okButton)
buttonLayout.addWidget(cancelButton)
layout.addWidget(self.snippetTextArea)
layout.addLayout(buttonLayout)
self.setLayout(layout)
self.setFocus()
self.snippetTextArea.setFocus()
okButton.clicked.connect(self.accept)
cancelButton.clicked.connect(self.reject)
self.setStyleSheet(hou.qt.styleSheet())
def getNewText(self):
return self.snippetTextArea.toPlainText()<file_sep>import hou
from PySide2 import QtWidgets, QtCore, QtGui
from kaToolsExpressionPicker import stylesheet
reload(stylesheet)
class expressionTreeWidget(QtWidgets.QTreeWidget):
selected = []
mimeData = QtCore.QMimeData()
def __init__(self, parent=None):
QtWidgets.QTreeWidget.__init__(self, parent)
self.setItemsExpandable(True)
self.setDragEnabled(True)
self.setDropIndicatorShown(True)
self.setAcceptDrops(True)
#self.setDragDropMode(self.DragDrop)
self.setDragDropMode(self.InternalMove)
self.setAlternatingRowColors(True)
self.setUniformRowHeights(False)
self.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
self.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
self.setStyleSheet(stylesheet.styles["tree"])
def mousePressEvent(self, event):
super(expressionTreeWidget, self).mousePressEvent(event)
self.selected = self.selectedItems()
for item in self.selected:
item.setSelected(False)
self.selected = self.itemAt(event.pos())
if self.selected is not None:
self.selected.setSelected(True)
if isinstance(self.selected, QtWidgets.QTreeWidgetItem):
self.mimeData = QtCore.QMimeData()
#mimeData.setData("application/treeItem", "1")
#self.mimeData.setData("text/plain", self.selected[0].text(0))
self.mimeData.setText(self.selected.text(1))
#print "mouse press", self.mimeData.text()
pass
def mouseReleaseEvent(self, event):
super(expressionTreeWidget, self).mouseReleaseEvent(event)
#print "release: ", event
pass
'''
return_val = super( QtWidgets.QTreeWidget, self ).mouseReleaseEvent( event )
#print "mouse release"
#print hou.ui.curDesktop().paneTabUnderCursor().type()
widget = QtWidgets.QApplication.instance().widgetAt(event.globalX(), event.globalY())
if widget:
self.searchChildren(widget)
'''
def mouseMoveEvent(self, event):
#super(expressionTreeWidget, self).mouseMoveEvent(event)
#print "move: ", event
if self.selected is not None:
drag = QtGui.QDrag(self)
drag.setMimeData(self.mimeData)
drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction, QtCore.Qt.CopyAction)
def searchChildren(self, parent):
for child in parent.children():
if child:
if isinstance(child, QtGui.QTextFrame):
pass
self.searchChildren(child)
def dragEnterEvent(self, event):
#super(expressionTreeWidget, self).dragEnterEvent(event)
event.acceptProposedAction()
#print "dragenter: ", event.mimeData().text()
pass
def dragMoveEvent(self, event):
#super(expressionTreeWidget, self).dragMoveEvent(event)
#print "drag move"
event.acceptProposedAction()
pass
def dropEvent(self, event):
#if event.mimeData().hasFormat(self.mimeTypes()[0]):
#print "drop: ", event.mimeData().formats()
super(expressionTreeWidget, self).dropEvent(event)
<file_sep>styles = {"valid" : "font: 16pt; background-color: #3e5062"
, "invalid" : "font: 16pt; background-color: #990000"
, "initial" : "font: 16pt; background-color: #222222"
, "snippet" : "font: 15pt; background-color: #222222"
, "tree" : "QTreeWidget{border-style:solid; border-color : 'black';border-width:3px} QTreeWidget:item{ padding : 10px 5px 10px 5px; background-color: #3a3a3a} QTreeWidget:item:alternate{color: #B3B3B3; background-color: #2d2d2d}"#spacing: 4px;margin: 5px 5px 5px 5px;
, "templateArea" : "background-color: #3a3a3a"
, "templateAreaAlt" : "background-color: #2d2d2d"}<file_sep>import hou
from PySide2 import QtWidgets, QtCore, QtGui
from kaToolsExpressionPicker import stylesheet, vexSyntaxHighlighter
reload(stylesheet)
reload(vexSyntaxHighlighter)
class snippet(QtWidgets.QTextEdit):
currentSize = 12
parent = None
def __init__(self, parent=None, pathLabel = None):
super(snippet, self).__init__(parent)
self.parent = parent
self.pathLabel = pathLabel
#self.setFontPointSize(12)
self.setTabStopWidth(20)
self.setAcceptRichText(True)
self.setMouseTracking(True)
if self.pathLabel != None:
self.textChanged.connect(self.onSnippetTextEdited)
vexSyntax = vexSyntaxHighlighter.vexSyntaxHighlighter(self.document())
def autoConnect(self,node):
print (node.type())
parm = node.parm("snippet")
if parm != None:
if hou.parm(self.pathLabel.text()) !=None:
self.removeCallBack(hou.parm(self.pathLabel.text()).node())
if isinstance(parm.eval(),str):
self.pathLabel.setText(parm.path())
self.setText(parm.eval())
self.pathLabel.setStyleSheet(stylesheet.styles["valid"])
self.setUpCallback(parm.node())
else:
print("not valid")
else:
print("not valid2")
def dragEnterEvent(self, event):
super(snippet, self).dragEnterEvent(event)
#print "enter to text area", event.type()
#event.accept()
event.acceptProposedAction()
def dragMoveEvent(self, event):
super(snippet, self).dragMoveEvent(event)
#print "drag move", event.mimeData().formats()
#event.accept()
event.acceptProposedAction()
def dropEvent(self, event):
text = event.mimeData().text()
#print event.mimeData().formats()
parm = hou.parm(text)
if parm != None:
if hou.parm(self.pathLabel.text()) !=None:
self.removeCallBack(hou.parm(self.pathLabel.text()).node())
if isinstance(parm.eval(),str):
mime = QtCore.QMimeData()
mime.setText("")
newEvent = QtGui.QDropEvent(event.pos(), event.dropAction(), mime, event.mouseButtons(), event.keyboardModifiers())
super(snippet, self).dropEvent(newEvent)
self.pathLabel.setText(text)
self.setText(parm.eval())
self.pathLabel.setStyleSheet(stylesheet.styles["valid"])
self.setUpCallback(parm.node())
else:
mime = QtCore.QMimeData()
mime.setText("")
newEvent = QtGui.QDropEvent(event.pos(), event.dropAction(), mime, event.mouseButtons(), event.keyboardModifiers())
super(snippet, self).dropEvent(newEvent)
self.pathLabel.setText("Invalid. Only String Parameter is acceptable:")
self.pathLabel.setStyleSheet(stylesheet.styles["invalid"])
else:
###
### droped info is not path to parm
###
if hou.parm(self.pathLabel.text()) != None:
###
### parm is already set
###
if hou.node(text) == None:
###
### dropping a template
###
self.dropTemplate(event)
if hou.parm(self.pathLabel.text()).name() == "snippet":
self.parmCreate(hou.parm(self.pathLabel.text()).node())
else:
###
### dropping node or something
###
if hou.parm(self.pathLabel.text()) !=None:
self.removeCallBack(hou.parm(self.pathLabel.text()).node())
mime = QtCore.QMimeData()
mime.setText("")
newEvent = QtGui.QDropEvent(event.pos(), event.dropAction(), mime, event.mouseButtons(), event.keyboardModifiers())
super(snippet, self).dropEvent(newEvent)
self.pathLabel.setText("Invalid. Drop a parameter:")
self.pathLabel.setStyleSheet(stylesheet.styles["invalid"])
else:
###
### parm is not set
###
self.dropTemplate(event)
self.pathLabel.setText("Invalid. Drop a parameter first:")
self.pathLabel.setStyleSheet(stylesheet.styles["invalid"])
def dropTemplate(self, event):
#print self.currentSize
#currentSize = self.fontPointSize()
super(snippet, self).dropEvent(event)
cursor = self.textCursor()
self.selectAll()
self.setFontPointSize(self.currentSize)
self.setTextCursor(cursor)
def mouseMoveEvent(self, event):
#print "mouse move"
super(snippet, self).mouseMoveEvent(event)
self.setFocus()
def keyPressEvent(self, event):
super(snippet, self).keyPressEvent(event)
text = self.toPlainText()
if "\t" in text:
doc = self.document()
cursor = doc.find("\t")
cursor.deleteChar()
cursor.insertText(" ")
if event.key() == QtCore.Qt.Key_Plus:
if event.modifiers() == QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier:
#print "press contol plus"
cursor = self.textCursor()
self.selectAll()
self.setFontPointSize(self.fontPointSize()+2)
self.currentSize = self.fontPointSize()
self.setTextCursor(cursor)
elif event.key() == QtCore.Qt.Key_Minus:
if event.modifiers() == QtCore.Qt.ControlModifier :
#print "press contol minus"
cursor = self.textCursor()
self.selectAll()
self.setFontPointSize(self.fontPointSize()-2)
self.currentSize = self.fontPointSize()
self.setTextCursor(cursor)
def onSnippetTextEdited (self):
#print "edit in", self.currentSize
currentText = self.toPlainText()
parm = hou.parm(self.pathLabel.text())
if parm != None:
parm.set(currentText)
self.pathLabel.setStyleSheet(stylesheet.styles["valid"])
else:
self.pathLabel.setText("Drag & Drop a parameter above:")
self.pathLabel.setStyleSheet(stylesheet.styles["invalid"])
if currentText == "" or currentText.startswith("\n"):
font = QtGui.QFont()
font.setPointSize(self.currentSize)
self.setCurrentFont(font)
pass
else:
#self.currentSize = self.fontPointSize()
pass
def parmCreate(self, node):
try:
import vexpressionmenu
parmname = 'snippet'
vexpressionmenu.createSpareParmsFromChCalls(node, parmname)
except error:
print "cannot create parms"
def onParmChanged(self, **kwargs):
try:
linkedParm = hou.parm(self.pathLabel.text())
parms = kwargs["parm_tuple"]
for parm in parms:
if linkedParm.name() == parm.name():
if self.toPlainText() != parm.eval():
self.setText(parm.eval())
break
except error:
print error
def setUpCallback(self, node):
self.removeCallBack(node)
#print "add"
node.addEventCallback((hou.nodeEventType.ParmTupleChanged,), self.onParmChanged)
def removeCallBack(self, node):
#print "remove event handler", node.name()
node.removeAllEventCallbacks()
| 809ab5e7379248a9c6d62ba4363794b98367e8a4 | [
"Markdown",
"Python"
] | 10 | Python | genchansansan/kaToolsExpressionPicker | b279c373a8178ea5732693b7d356c8cc625b5f8f | 558d5f75285eff99dfe08e48394f3f10c1feaeb0 |
refs/heads/main | <repo_name>lbideau/the-domain-name-generator<file_sep>/src/app.js
/* eslint-disable */
import "bootstrap";
import "./style.css";
import "./assets/img/rigo-baby.jpg";
import "./assets/img/4geeks.ico";
window.onload = function() {
//write your code here
var pronoun = ["the", "our"];
var adj = ["great", "big"];
var noun = ["jogger", "racon"];
for(let i=0; i<pronoun.length; i++ ){
for(let j=0; j<adj.length; j++){
for(let k=0; k<noun.length; k++){
let random = pronoun[i] + adj[j] + noun[k] + ".com";
console.log(random);
}
}
}
console.log("Hello Rigo from the console!");
};
| a15b6a49826763cafbb436052ddf7182bd10d368 | [
"JavaScript"
] | 1 | JavaScript | lbideau/the-domain-name-generator | 9fa8856ccae34001cb1ac30e338f74f8b7e3618a | 3ec0231bdf7488090cb7235144591445a407a622 |
refs/heads/master | <repo_name>HeriklesVinicyus/SysZonaAzul<file_sep>/src/java/br/edu/ifpe/infraestrutura/fachada/Fachada.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.edu.ifpe.infraestrutura.fachada;
import br.edu.ifpe.infraestrutura.repositorios.implementacao.FabricaRepositorios;
import br.edu.ifpe.infraestrutura.repositorios.implementacao.RepositorioVagaImplMemo;
import br.edu.ifpe.infraestrutura.repositorios.implementacao.RepositorioVeiculoImplMemo;
import br.edu.ifpe.infraestrutura.repositorios.interfaces.RepositorioGenerico;
import br.edu.ifpe.negocio.Vaga;
import br.edu.ifpe.negocio.Veiculo;
import java.util.List;
/**
*
* @author 1860915
*/
public class Fachada {
private static Fachada myself = null;
private RepositorioGenerico<Veiculo,String> repositorioVeiculo = null;
private RepositorioGenerico<Vaga,Integer> repositorioVaga = null;
private Fachada(){
this.repositorioVeiculo = FabricaRepositorios.fabricaRepositorios(FabricaRepositorios.OBJETOVEICULO
, FabricaRepositorios.ARMAZENAMENTOMEMO);
this.repositorioVaga = FabricaRepositorios.fabricaRepositorios(FabricaRepositorios.OBJETOVAGA,
FabricaRepositorios.ARMAZENAMENTOMEMO);
}
public static Fachada getInstance(){
if(myself==null)
myself = new Fachada();
return myself;
}
public void inserir(Veiculo veiculo){
this.repositorioVeiculo.inserir(veiculo);
}
public void inserir(Vaga vaga){
this.repositorioVaga.inserir(vaga);
}
public void alterar(Veiculo veiculo){
this.repositorioVeiculo.alterar(veiculo);
}
public void alterar(Vaga vaga){
this.repositorioVaga.alterar(vaga);
}
public Veiculo recuperarVeiculo(String placa){
return this.repositorioVeiculo.recuperar(placa+"");
}
public Vaga recuperarVaga(int codigo){
return this.repositorioVaga.recuperar(codigo);
}
public void excluir(Veiculo v){
this.repositorioVeiculo.excluir(v);
}
public void excluir(Vaga v){
this.repositorioVaga.excluir(v);
}
public List<Veiculo> recuperarVeiculos(){
return this.repositorioVeiculo.recuperarTodos();
}
public List<Vaga> recuperarVaga(){
return this.repositorioVaga.recuperarTodos();
}
}
<file_sep>/src/java/br/edu/ifpe/apresentacao/servlets/ApresentaVagaServlet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.ifpe.apresentacao.servlets;
import br.edu.ifpe.infraestrutura.fachada.Fachada;
import br.edu.ifpe.negocio.Vaga;
import br.edu.ifpe.negocio.Veiculo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author 20161D13GR0082
*/
@WebServlet(name = "ApresentaVagaServlet", urlPatterns = {"/ApresentaVagaServlet"})
public class ApresentaVagaServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Vaga> vaga = Fachada.getInstance().recuperarVaga();
//List<Vaga> listaVaga = Fachada.getInstance().recuperarVagas();
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ApresentaVagaServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Lista de merda!</h1>");
out.println("<a href='index.html'>página inicial</a>");
out.println("<table border='1'");
out.println("<tr><th>Codico</th><th>Localização</th><th>Observação</th><th>Opções</th></tr>");
for (Vaga v : vaga) {
out.println("<tr>");
out.println("<td>" + v.getCodigo() + "</td>");
out.println("<td>" + v.getLocalizacao() + "</td>");
out.println("<td>" + v.getObservacao() + "</td>");
out.println("<td><a href='VisualizaVagaServlet?codigo=" + v.getCodigo() + "'"
+ ">visualizar</a> <a href='ApresentaVagaAlteracaoServlet?codigo=" + v.getCodigo() + "'>"
+ "alterar</a> <a href='DeletarVagaServlet?codigo="+v.getCodigo()+"'>Deletar</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/src/java/br/edu/ifpe/negocio/Ticket.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.edu.ifpe.negocio;
import java.util.Date;
/**
*
* @author 1860915
*/
public class Ticket {
private int numero;
private Veiculo veiculo;
private Vaga vaga;
private Date entrada;
private Date saida;
private boolean estaPago;
private double valor;
public Ticket(int numero, Veiculo veiculo, Vaga vaga, boolean estaPago) {
this.numero = numero;
this.veiculo = veiculo;
this.vaga = vaga;
this.estaPago = estaPago;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public Veiculo getVeiculo() {
return veiculo;
}
public void setVeiculo(Veiculo veiculo) {
this.veiculo = veiculo;
}
public Vaga getVaga() {
return vaga;
}
public void setVaga(Vaga vaga) {
this.vaga = vaga;
}
public Date getEntrada() {
return entrada;
}
public void setEntrada(Date entrada) {
this.entrada = entrada;
}
public Date getSaida() {
return saida;
}
public boolean isEstaPago() {
return estaPago;
}
public void setEstaPago(boolean estaPago) {
this.estaPago = estaPago;
}
public double getValor() {
return valor;
}
public void fecharTicket(double valorTarifa){
this.saida = new Date();
long horasPassadas = (long) (Math.ceil((double)this.saida.getTime() -
(double)this.entrada.getTime())/((double)(60*60*1000)));
this.valor = valorTarifa*horasPassadas;
this.estaPago = true;
}
}
<file_sep>/src/java/br/edu/ifpe/apresentacao/servlets/CadastroTicketServlet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.edu.ifpe.apresentacao.servlets;
import br.edu.ifpe.infraestrutura.fachada.Fachada;
import br.edu.ifpe.negocio.Vaga;
import br.edu.ifpe.negocio.Veiculo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author 1860915
*/
@WebServlet(name = "CadastroTicketServlet", urlPatterns = {"/CadastroTicketServlet"})
public class CadastroTicketServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
List<Veiculo> veiculos = Fachada.getInstance().recuperarVeiculos();
session.setAttribute("veiculos", veiculos);
List<Vaga> vagas = Fachada.getInstance().recuperarVaga();
session.setAttribute("vagas", vagas);
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet CadastroTicketServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Cadastrar Ticket</h1>");
out.println("<form method='post' action='CadastrarTicketServlet'>"
+ "Número:<input type='text' name='numero'/><br/>"
+ "Veiculo: <select name='veiculo'> ");
for(Veiculo v:veiculos){
out.println("<option value='"+veiculos.indexOf(v)+"'>"+v.getPlaca()+"</option>");
}
out.println( "</select><br/>"
+ "Número da Vaga: <select name='vaga'>");
for(int i=0;i<vagas.size();i++){
out.println("<option value='"+i+"'>"+vagas.get(i).getCodigo()+"</option>");
}
out.println("</select><br/>"
+ "<input type='submit' value='cadastrar'/>"
+ "</form>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 4ebc9909d739944124733bc75986d59b7d0eb69b | [
"Java"
] | 4 | Java | HeriklesVinicyus/SysZonaAzul | d80df6bfe637892e0611424baffd6f5435f69321 | 5dac1e6a89705b24c287d41d08c0eafd5e80def5 |
refs/heads/main | <file_sep>import React, {useEffect, useState} from 'react';
import {
SafeAreaView,
ScrollView,
Text,
TextInput,
TouchableHighlight,
TouchableOpacity,
View,
Button,
} from 'react-native';
import ToDoListItem from './ToDoListItem';
const ToDo = () => {
const [idCounter, setIdCounter] = useState(0);
const [items, setItems] = useState([]);
const [item, setItem] = useState(null);
useEffect(() => {}, [items]);
const handleAddItemClick = () => {
if (item === null) {
return;
}
setItems((prev) => [{id: idCounter, name: item, done: false}, ...prev]);
setItem(null);
setIdCounter(idCounter + 1);
};
const renderItems = () => {
return items.map((i) => {
return (
<ToDoListItem
handleToDoItemDone={handleToDoItemDone}
item={i}
key={i.id}
/>
);
});
};
const handleToDoItemDone = (itemId) => {
const itemIndex = items.findIndex((i) => i.id === itemId);
items[itemIndex].done = !items[itemIndex].done;
setItems((prev) => [...items]);
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 1}}>
<TextInput
onChangeText={(value) => setItem(value)}
value={item}
placeholder={'todo item...'}
style={{
borderBottomWidth: 2,
borderColor: '#009788',
width: '100%',
paddingLeft: 150,
}}
/>
</View>
<View
style={{
flex: 5,
alignItems: 'center',
justifyContent: 'center',
}}>
<ScrollView>{renderItems()}</ScrollView>
</View>
<TouchableOpacity
onPress={handleAddItemClick}
style={{
width: '100%',
backgroundColor: '#009788',
height: 60,
flex: 1,
position: 'absolute',
bottom: 0,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text style={{color: 'white', fontSize: 24}}>Add</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
export default ToDo;
<file_sep># todo-app-mobile
A react-native based mobile to-do app

| 4f6a2b8bdc8a110ef6c2b688fc0654cb0410051e | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ssozuer/todo-app-mobile | f37d51c73645842f956e65adfe3f19b435e220b7 | 06361db40b0cb224ae4f114ee0fec7ddee0ec21d |
refs/heads/master | <file_sep>package arrayelementneighbours;
import java.util.ArrayList;
import java.util.List;
/**
* Created by bathoryalex on 16/10/17.
*/
public class Neighbours
{
static final int[][] D = new int[][]{
{-1,-1}, {-1, 0}, {-1,1}, {0,-1},
{ 0, 1}, { 1,-1}, { 1,0}, {1, 1}
};
static int [][] field = new int[][]{
{ 2, 4, 8, 3},
{-5, 6, 7, 9, 1, -8},
{10},
{11, 2, 7},
{12, 20, -1},
{ 1, 2, 4}
};
public static Integer[] getNeighbours(int i, int j)
{
List<Integer> result = new ArrayList<>();
for (int[] dir : D)
{
int di = i + dir[0];
int dj = j + dir[1];
if (di >= 0 && di < field.length)
{
if (dj >= 0 && dj < field[di].length)
{
result.add(field[di][dj]);
}
}
}
return result.toArray(new Integer[result.size()]);
}
public static void main(String[] args)
{
getNeighbours(2,3);
}
}<file_sep>package guessthenumber;
import java.util.Scanner;
/**
* Created by bathoryalex on 16/10/12.
*/
public class NumberGuesser
{
public static void guess()
{
int randomNumber = (int) (Math.random() * 100);
Scanner input = new Scanner(System.in);
int yourGuessNumber;
System.out.println("Enter your guess between 1 and 100!");
yourGuessNumber = input.nextInt();
while (yourGuessNumber > 100 || yourGuessNumber < 1)
{
System.out.println("Enter your guess again (between 1 and 100)!");
yourGuessNumber = input.nextInt();
}
while (yourGuessNumber != randomNumber)
{
if (yourGuessNumber < randomNumber)
{
System.out.println("Your guess is lower than mine!");
yourGuessNumber = input.nextInt();
}
else if (yourGuessNumber > randomNumber)
{
System.out.println("Your guess is greater than mine!");
yourGuessNumber = input.nextInt();
}
}
System.out.println("Congrats, you guessed it!");
}
public static void main(String[] args)
{
guess();
}
}
<file_sep># PracticeRoom
Practicing Java algorythms
<file_sep>package mixcharactersinsideword;
import java.util.Random;
/**
* Created by bathoryalex on 16/10/18.
*/
public class WordCharMixer
{
public static String mixWordCharacters(String yourSentence)
{
String[] words = yourSentence.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words)
{
if(word.length() > 3)
{
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
word = shuffleWord(word.substring(1, word.length() - 1));
word = firstChar + word + lastChar;
}
result.append(word);
result.append(" ");
}
return result.toString();
}
public static String shuffleWord(String word)
{
Random rand = new Random();
String result = word;
for (int i = 0; i < result.length() ; i++)
{
result = swapCharacters(result, i, rand.nextInt(result.length()));
}
return result;
}
public static String swapCharacters(String word, int i, int j)
{
if (i == j)
{
return word;
}
char[] chars = word.toCharArray();
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
String result = new String(chars);
return result;
}
public static void main(String[] args)
{
String text="A fentiekből világosan látszik hogy itt nem tiszta minden hiszen hogyan is " +
"lenne képes ugyanaz a GPU ugyanarra ötven százalékkal kisebb fogyasztással";
System.out.println(mixWordCharacters(text));
}
}<file_sep>package randomintegersinanarray;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by bathoryalex on 16/10/13.
*/
public class ArraySplitter
{
public static int[] generateNumbers(int n)
{
int[] generatedNumbers = new int[n];
for (int i = 0; i < generatedNumbers.length; i++)
{
generatedNumbers[i] = (int) (Math.random() * 20);
}
return generatedNumbers;
}
public static Integer[][] arraySplitter(int[] array)
{
List<Integer[]> resultList = new ArrayList<>();
List<Integer> subList = new ArrayList<>();
for (int i : array)
{
if(!subList.contains(i))
{
subList.add(i);
}
else
{
Integer[] subArray = subList.toArray(new Integer[1]);
resultList.add(subArray);
subList.clear();
subList.add(i);
}
}
Integer[] subArray = subList.toArray(new Integer[1]);
resultList.add(subArray);
return resultList.toArray(new Integer[1][]);
}
public static void main(String[] args)
{
int[] randoms = generateNumbers(30);
System.out.println(Arrays.toString(randoms));
System.out.println("----------");
Integer[][] splitted = arraySplitter(randoms);
for (Integer[]i : splitted)
{
System.out.println(Arrays.toString(i));
}
}
} | 3ded8c1455cb060392f71632f43626b23a7c6381 | [
"Markdown",
"Java"
] | 5 | Java | bathoryalex/PracticeRoom | 43dc35a580b5c6c670a0fd51da65b9ccbc8e50cc | 16d25d1cc401a85d49bd3db46c61adc952b6abd9 |
refs/heads/master | <repo_name>jmpereztorres/spotifire-back<file_sep>/src/main/java/com/spotifire/core/utils/SpotifireUtils.java
package com.spotifire.core.utils;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.spotifire.persistence.pojo.Location;
import com.spotifire.persistence.pojo.Report;
public final class SpotifireUtils {
private static final Logger LOGGER = LogManager.getLogger(SpotifireUtils.class);
private SpotifireUtils() {
throw new IllegalAccessError("Utility class");
}
/**
* Get last item
*
* @param a
* @param b
* @return
*/
public static <T> T getLastItem(T a, T b) {
return b != null ? b : a;
}
/**
* Checks if a collection is not null or empty
*
* @param collection
* @return boolean
*/
public static boolean isNotNullNorEmpty(Collection<?> collection) {
return collection != null && !collection.isEmpty();
}
/**
* Call reflection method not to generate duplicated try catch blocks
*
* @param pojoFrom
* @param methodName
* @param valueToSet
* @param parametrizedArgs
* @return
*/
public static Object callReflectionMethod(Object pojoFrom, String methodName, Object valueToSet, Class<?>... parametrizedArgs) {
Object res = null;
try {
// with arguments
if (parametrizedArgs != null) {
res = pojoFrom.getClass().getDeclaredMethod(methodName, parametrizedArgs).invoke(pojoFrom, valueToSet);
// without arguments
} else {
res = pojoFrom.getClass().getDeclaredMethod(methodName).invoke(pojoFrom);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
| SecurityException e) {
LOGGER.error(e.getMessage(), e);
}
return res;
}
public static double distance(double lat1, double lat2, double lon1, double lon2, double el1, double el2) {
final int R = 6371;
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // -> meters
double height = el1 - el2;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return Math.sqrt(distance);
}
public static double distance(Location location1, Location location2) {
return distance(location1.getLatitude(), location2.getLatitude(), location1.getLongitude(), location2.getLongitude(), 0d, 0d);
}
public static Date parseDateFromCsvFile(String fieldValue, String pattern) {
Date res = null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
res = sdf.parse(fieldValue);
} catch (java.text.ParseException e) {
System.out.println(e.getMessage());
}
return res;
}
public static Location getCentralReportLocation(List<Report> reportList) {
if (reportList.size() == 1) {
return reportList.get(0).getLocation();
}
double x = 0;
double y = 0;
double z = 0;
for (Report report : reportList) {
double latitude = report.getLocation().getLatitude() * Math.PI / 180;
double longitude = report.getLocation().getLongitude() * Math.PI / 180;
x += Math.cos(latitude) * Math.cos(longitude);
y += Math.cos(latitude) * Math.sin(longitude);
z += Math.sin(latitude);
}
double total = reportList.size();
x = x / total;
y = y / total;
z = z / total;
double centralLongitude = Math.atan2(y, x);
double centralSquareRoot = Math.sqrt(x * x + y * y);
double centralLatitude = Math.atan2(z, centralSquareRoot);
Location center = new Location();
center.setLatitude(centralLatitude * 180 / Math.PI);
center.setLongitude(centralLongitude * 180 / Math.PI);
return center;
}
}
<file_sep>/src/main/java/com/spotifire/web/rest/dto/NasaFireDTO.java
package com.spotifire.web.rest.dto;
import java.util.Date;
import com.spotifire.persistence.pojo.Location;
public class NasaFireDTO {
private Date creationDate;
private Location location;
public NasaFireDTO() {
super();
}
public Date getCreationDate() {
return this.creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Location getLocation() {
return this.location;
}
public void setLocation(Location location) {
this.location = location;
}
}
<file_sep>/src/main/java/com/spotifire/exception/SpotifireCodeException.java
package com.spotifire.exception;
public enum SpotifireCodeException {
CAUSED_BY("error.CAUSED_BY"), SESSION_EXPIRED("error.SESSION_EXPIRED"), NULL_DATA("error.NULL_DATA");
private String code;
public String getCode() {
return code;
}
private SpotifireCodeException(String code) {
this.code = code;
}
}<file_sep>/src/main/java/com/spotifire/web/rest/client/NasaFirmsClientManager.java
package com.spotifire.web.rest.client;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.spotifire.core.service.IReportService;
import com.spotifire.core.utils.SpotifireUtils;
import com.spotifire.persistence.constants.ReportType;
import com.spotifire.persistence.constants.SourceType;
import com.spotifire.persistence.constants.SpotifireConstants;
import com.spotifire.persistence.pojo.Location;
import com.spotifire.persistence.pojo.Report;
import com.spotifire.persistence.repository.ITransactionalRepository;
@Service
public class NasaFirmsClientManager implements INasaFirmsClientService {
private static final Logger LOGGER = LogManager.getLogger(NasaFirmsClientManager.class);
@Autowired
private ITransactionalRepository transactionalRepository;
@Autowired
private IReportService reportService;
@Autowired
@Qualifier("nasaRestTemplate")
private RestTemplate trustedRestTemplate;
@Override
public void fetchData() throws URISyntaxException {
URI uriPetition = new URI(SpotifireConstants.NASA_FIRMS_URL);
ResponseEntity<String> response = trustedRestTemplate.exchange(uriPetition, HttpMethod.GET, null, String.class);
List<Report> reportList = new ArrayList<>();
String[] lines = response.getBody().split("\n");
if (lines != null) {
Arrays.asList(lines).forEach(line -> {
String[] columns = line.split(SpotifireConstants.OPERATOR_COMMA);
Report report = new Report();
if (columns != null) {
report.setCreationDate(
SpotifireUtils.parseDateFromCsvFile(columns[5] + columns[6], SpotifireConstants.NASA_FIRMS_DATE_PATTERN));
report.setType(ReportType.FIRE);
report.setScore(
scoreSatelliteDataRow(Double.valueOf(columns[2]), Double.valueOf(columns[10]), Double.valueOf(columns[11])));
report.setLocation(new Location(Double.valueOf(columns[0]), Double.valueOf(columns[1])));
report.setSource(SourceType.NASA);
}
reportList.add(report);
});
}
reportList.stream().forEach(this.reportService::processReport);
}
private static int scoreSatelliteDataRow(double brightness1, double brightness2, double power) {
double maxBrightness1 = 503.2;
double minBrightness1 = 300.0;
double maxBrightness2 = 400.1;
double minBrightness2 = 264.9;
double maxPower = 400.1;
double minPower = 2;
double coeficienBrightness1 = 0.3045;
double coeficienBrightness2 = 0.1297;
double coeficientPower = 0.1747;
double calculationBrightness1 = calculateCuadraticMinimum(brightness1, maxBrightness1, minBrightness1) * coeficienBrightness1;
double calculationBrightness2 = calculateCuadraticMinimum(brightness2, maxBrightness2, minBrightness2) * coeficienBrightness2;
double calculationPower = calculateCuadraticMinimum(power, maxPower, minPower) * coeficientPower;
return (int) (calculationBrightness1 + calculationBrightness2 + calculationPower) * 100;
}
private static double calculateCuadraticMinimum(double input, double maximum, double minimum) {
return (input - minimum) / (maximum - minimum);
}
}
<file_sep>/src/main/java/com/spotifire/web/rest/dto/AddressDTO.java
package com.spotifire.web.rest.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AddressDTO {
private String village;
private String town;
private String suburb;
private String region;
private String county;
private String state;
private String postcode;
private String country;
@JsonProperty("country_code")
private String countryCode;
public AddressDTO() {
super();
}
public String getVillage() {
return village;
}
public void setVillage(String village) {
this.village = village;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getSuburb() {
return suburb;
}
public void setSuburb(String suburb) {
this.suburb = suburb;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AddressDTO [village=").append(village).append(", town=").append(town).append(", suburb=").append(suburb)
.append(", region=").append(region).append(", county=").append(county).append(", state=").append(state)
.append(", postcode=").append(postcode).append(", country=").append(country).append(", countryCode=").append(countryCode)
.append("]");
return builder.toString();
}
}
<file_sep>/src/main/java/com/spotifire/web/rest/dto/FireDTO.java
package com.spotifire.web.rest.dto;
import java.util.List;
import com.spotifire.persistence.pojo.Evidence;
public class FireDTO {
private List<Evidence> evidences;
private List<Evidence> alerts;
private List<NasaFireDTO> nasaFires;
public FireDTO() {
super();
}
public List<Evidence> getEvidences() {
return this.evidences;
}
public void setEvidences(List<Evidence> evidences) {
this.evidences = evidences;
}
public List<NasaFireDTO> getNasaFires() {
return this.nasaFires;
}
public void setNasaFires(List<NasaFireDTO> nasaFires) {
this.nasaFires = nasaFires;
}
public List<Evidence> getAlerts() {
return alerts;
}
public void setAlerts(List<Evidence> alerts) {
this.alerts = alerts;
}
}
<file_sep>/src/main/java/com/spotifire/persistence/constants/AlertLevel.java
package com.spotifire.persistence.constants;
import com.fasterxml.jackson.annotation.JsonProperty;
public enum AlertLevel {
@JsonProperty("FIRE")
FIRE,
@JsonProperty("ALERT")
ALERT;
}
<file_sep>/src/main/java/com/spotifire/core/utils/ImageUtils.java
package com.spotifire.core.utils;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public final class ImageUtils {
private static final Logger LOGGER = LogManager.getLogger(ImageUtils.class);
private ImageUtils() {
throw new IllegalAccessError("Utility class");
}
public static Integer scoringImage(byte[] image) {
Integer score = null;
ByteArrayInputStream bis = new ByteArrayInputStream(image);
BufferedImage imageInput;
try {
imageInput = ImageIO.read(bis);
int width = imageInput.getWidth();
int height = imageInput.getHeight();
int histogramReturn[][] = new int[3][256];
int pixel = 0;
int red = 0;
int green = 0;
int blue = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
pixel = imageInput.getRGB(i, j);
red = (pixel >> 16) & 0xFF;
green = (pixel >> 8) & 0xFF;
blue = pixel & 0xFF;
histogramReturn[0][red] += 1;
histogramReturn[1][green] += 1;
histogramReturn[2][blue] += 1;
}
}
score = analyzeFire(histogramReturn, width, height);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
System.out.println("Image score is: " + score);
return score;
}
private static int analyzeFire(int histogram[][], int width, int height) {
int meanHistogramRed = calculateHighMeanHistogram(histogram[0]);
int meanHistogramGreen = calculateHighMeanHistogram(histogram[1]);
int meanHistogramBlue = calculateHighMeanHistogram(histogram[2]);
double numberOfPixels = (double) width * height;
if ((numberOfPixels / 11000) > meanHistogramRed) {
meanHistogramRed = 0;
}
return calculateConfidence(meanHistogramRed, meanHistogramGreen, meanHistogramBlue);
}
private static int calculateHighMeanHistogram(int histogram[]) {
int meanCalculated = 0;
for (int i = 192; i < 256; i++) {
meanCalculated += histogram[i];
}
meanCalculated = meanCalculated / (256 - 192);
return meanCalculated;
}
private static int calculateConfidence(int red, int green, int blue) {
int confidence = 0;
if (red > (blue + green)) {
float difference = (float) (red - (blue + green)) / (red + blue + green);
if (difference > 0.1) {
if (difference < 0.9) {
confidence = (int) (difference * 100);
} else {
confidence = 99;
}
} else {
confidence = 0;
}
} else {
confidence = 0;
}
return confidence;
}
}
<file_sep>/src/test/java/com/spotifire/config/EmptyConfig.java
package com.spotifire.config;
import org.springframework.context.annotation.Configuration;
@Configuration
// @ComponentScan(basePackages = { "com.gmv.cts.business.manager", "com.gmv.cts.business.service", "com.gmv.business.base.core",
// "com.gmv.business.base.transactional", "com.gmv.business.base.wrapper" })
public class EmptyConfig {
}<file_sep>/src/main/java/com/spotifire/web/rest/dto/WeatherDTO.java
package com.spotifire.web.rest.dto;
public class WeatherDTO {
private double latitude;
private double longitude;
private int offset;
private CurrentlyWeatherDTO currently;
public WeatherDTO() {
super();
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public CurrentlyWeatherDTO getCurrently() {
return currently;
}
public void setCurrently(CurrentlyWeatherDTO currently) {
this.currently = currently;
}
@Override
public String toString() {
return "WeatherDTO [latitude=" + latitude + ", longitude=" + longitude + ", offset=" + offset + ", currently="
+ currently + "]";
}
}
<file_sep>/src/main/java/com/spotifire/web/rest/client/INasaFirmsClientService.java
package com.spotifire.web.rest.client;
import java.net.URISyntaxException;
public interface INasaFirmsClientService {
void fetchData() throws URISyntaxException;
}
<file_sep>/src/main/java/com/spotifire/core/service/IReportService.java
package com.spotifire.core.service;
import java.io.IOException;
import com.spotifire.persistence.pojo.Report;
import com.spotifire.web.rest.dto.FireDTO;
import com.spotifire.web.rest.dto.NotificationDTO;
import com.spotifire.web.rest.dto.ReportRequestDTO;
public interface IReportService {
Report processReport(Report report);
Report saveReport(Report report);
void parseReportAndSave(ReportRequestDTO reportRequest) throws IOException;
FireDTO findFiresByLocation(ReportRequestDTO reportRequestDTO);
FireDTO findTypedFiresByLocation(ReportRequestDTO reportRequestDTO);
NotificationDTO createPushNotification(ReportRequestDTO reportRequestDTO);
}
<file_sep>/README.md
# spotifire-back
NASA Space apps challenge: spotifire backend
<file_sep>/src/test/java/com/spotifire/spotifireback/CoreTest.java
package com.spotifire.spotifireback;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.stream.IntStream;
import javax.imageio.ImageIO;
import javax.transaction.Transactional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
import com.spotifire.SpotifireBackApplication;
import com.spotifire.core.service.IReportService;
import com.spotifire.persistence.constants.ReportType;
import com.spotifire.persistence.constants.SourceType;
import com.spotifire.persistence.constants.SpotifireConstants;
import com.spotifire.persistence.pojo.Author;
import com.spotifire.persistence.pojo.Evidence;
import com.spotifire.persistence.pojo.Location;
import com.spotifire.persistence.pojo.Report;
import com.spotifire.persistence.repository.ITransactionalRepository;
import com.spotifire.web.rest.dto.FireDTO;
import com.spotifire.web.rest.dto.ReportRequestDTO;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpotifireBackApplication.class)
@SpringBootTest
public class CoreTest {
private static final Logger LOGGER = LogManager.getLogger(CoreTest.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private ITransactionalRepository repo;
@Autowired
private IReportService reportService;
@Autowired
@Qualifier("nasaRestTemplate")
private RestTemplate nasaRestTemplate;
@Test
public void contextLoads() {
System.out.println("OK");
}
@Test
@Rollback(false)
public void fetchTwitter() {
Twitter twitter = new TwitterFactory().getInstance();
// Twitter Consumer key & Consumer Secret
twitter.setOAuthConsumer("l3socwjpwuFbis9sDX56PIIxP", "<KEY>");
// Twitter Access token & Access token Secret
twitter.setOAuthAccessToken(
new AccessToken("<KEY>", "<KEY>"));
Query query = new Query();
query.setQuery(SpotifireConstants.SPOTIFIRE_TWITTER_HASHTAG);
query.setCount(100);
List<Status> statuses = null;
try {
QueryResult queryResult = twitter.search(query);
statuses = queryResult.getTweets();
statuses.stream().forEach(tweet -> {
Report report = new Report();
report.setTwitterId(tweet.getId());
List<Report> persistedReports = this.repo.findByExample(report);
if (persistedReports == null || persistedReports.isEmpty()) {
// base data
report.setCreationDate(tweet.getCreatedAt());
report.setSource(SourceType.TWITTER);
report.setType(ReportType.FIRE);
report.setDescription(tweet.getText());
// location
if (tweet.getGeoLocation() != null) {
report.setLocation(new Location(tweet.getGeoLocation().getLatitude(), tweet.getGeoLocation().getLongitude()));
}
// author
Author authorExample = new Author();
authorExample.setAlias(tweet.getUser().getName());
authorExample.setSource(SourceType.TWITTER);
List<Author> persistedAuthors = this.repo.findByExample(authorExample);
report.setAuthor(persistedAuthors != null && !persistedAuthors.isEmpty() ? persistedAuthors.get(0) : authorExample);
// images
if (tweet.getMediaEntities() != null && tweet.getMediaEntities().length > 0
&& tweet.getMediaEntities()[0].getType().equals("photo")) {
try {
URL url = new URL(tweet.getMediaEntities()[0].getMediaURL());
BufferedImage image = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
baos.flush();
report.setHasImage(true);
report.setImage(baos.toByteArray());
} catch (IOException e) {
LOGGER.error("Error reading tweet image");
}
}
this.reportService.processReport(report);
}
});
} catch (Exception e) {
}
System.out.println("OK");
}
@Test
@Transactional
@Rollback(false)
public void fillDatabase() {
double range = 1d;
double latitudeBase = 39.4532f;
double altitudeBase = -0.4262f;
IntStream.range(0, 20).forEach(index -> {
Location location = new Location(Math.random() * range + latitudeBase, Math.random() * range + altitudeBase);
Evidence evidence = new Evidence();
evidence.setCreationDate(new Date());
evidence.setConfidence(68 + index % 3);
evidence.setImpact(60 + index % 5);
evidence.setType(ReportType.FIRE);
evidence.setLocation(location);
this.repo.save(evidence);
});
}
@Test
public void asdads() {
ReportRequestDTO reportRequest = new ReportRequestDTO();
FireDTO fireDTO = this.reportService.findFiresByLocation(reportRequest);
System.out.println("Test OK");
}
@Test
public void checkConfiguration() {
System.out.println("Testing checkConfiguration...");
this.repo.save(new Location());
System.out.println("Test OK");
}
}
<file_sep>/src/main/java/com/spotifire/persistence/pojo/Author.java
package com.spotifire.persistence.pojo;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.spotifire.persistence.constants.SourceType;
@Entity
@Table(name = "AUTHOR")
public class Author implements IPojo {
private static final long serialVersionUID = -1226244226635320029L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String alias;
private Date creationDate;
private SourceType source;
/**
* Default constructor
*/
public Author() {
super();
}
@Override
public Long getId() {
return this.id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public SourceType getSource() {
return this.source;
}
public void setSource(SourceType source) {
this.source = source;
}
public String getAlias() {
return this.alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public Date getCreationDate() {
return this.creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Author other = (Author) obj;
if (this.id == null) {
if (other.id != null) {
return false;
}
} else if (!this.id.equals(other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Author [id=").append(this.id).append(", alias=").append(this.alias).append(", creationDate=")
.append(this.creationDate).append(", source=").append(this.source).append("]");
return builder.toString();
}
}
<file_sep>/src/main/java/com/spotifire/web/rest/controller/FireController.java
package com.spotifire.web.rest.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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;
import com.spotifire.core.service.IReportService;
import com.spotifire.persistence.constants.SpotifireConstants;
import com.spotifire.web.rest.dto.FireDTO;
import com.spotifire.web.rest.dto.ReportRequestDTO;
@RestController
@RequestMapping(value = "/api/fires", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@CrossOrigin
public class FireController {
@Autowired
private IReportService reportService;
@RequestMapping(value = "", method = RequestMethod.POST, produces = { SpotifireConstants.REST_ACCEPT_APPLICATION_JSON_UTF_8 })
public ResponseEntity<FireDTO> getFireByLocation(@RequestBody ReportRequestDTO reportRequestDTO) {
System.out.println("getFireByLocation invokation " + reportRequestDTO.toString());
FireDTO fireDTO = this.reportService.findFiresByLocation(reportRequestDTO);
return new ResponseEntity<>(fireDTO, HttpStatus.OK);
}
@RequestMapping(value = "/typed", method = RequestMethod.POST, produces = { SpotifireConstants.REST_ACCEPT_APPLICATION_JSON_UTF_8 })
public ResponseEntity<FireDTO> getFireByLocationTyped(@RequestBody ReportRequestDTO reportRequestDTO) {
System.out.println("getFireByLocationTyped invokation " + reportRequestDTO.toString());
FireDTO fireDTO = this.reportService.findTypedFiresByLocation(reportRequestDTO);
return new ResponseEntity<>(fireDTO, HttpStatus.OK);
}
}
<file_sep>/src/main/java/com/spotifire/persistence/constants/ReportType.java
package com.spotifire.persistence.constants;
import com.fasterxml.jackson.annotation.JsonProperty;
public enum ReportType {
@JsonProperty("FIRE")
FIRE,
@JsonProperty("PREVENTION")
PREVENTION;
}
<file_sep>/src/main/java/com/spotifire/core/utils/WeatherUtils.java
package com.spotifire.core.utils;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.spotifire.web.rest.dto.WeatherDTO;
public final class WeatherUtils {
private static final Logger LOGGER = LogManager.getLogger(WeatherUtils.class);
private WeatherUtils() {
throw new IllegalAccessError("Utility class");
}
public Integer scoringWeather(double latitude, double longitude, long timeStamp) throws URISyntaxException {
// https://api.darksky.net/forecast/f0882429cb4afe2fb72984e427e6789f/37.035229,-6.435476,1499860800?units=si&exclude=flags?exclude=alerts?exclude=minutely
StringBuilder sb = new StringBuilder();
sb.append("https://api.darksky.net/forecast/f0882429cb4afe2fb72984e427e6789f/").append(latitude).append(",")
.append(longitude).append(",").append(timeStamp)
.append("?units=si&exclude=flags?exclude=alerts?exclude=minutely?exclude=hourly?exclude=daily");
URI uriPetition = new URI(sb.toString());
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<WeatherDTO> response = restTemplate.exchange(uriPetition, HttpMethod.GET, null,
WeatherDTO.class);
System.out.println(response.getStatusCode() + ":" + response.getBody());
int riskFactor = 0;
double humidity = response.getBody().getCurrently().getHumidity();
double precipIntensity = response.getBody().getCurrently().getPrecipIntensity();
double precipProbability = response.getBody().getCurrently().getPrecipProbability();
double windSpeed = response.getBody().getCurrently().getWindSpeed();
if (windSpeed > 11) { // 40 km/h
riskFactor += 0.2;
if (windSpeed > 27) { // 100 km/h
riskFactor += 0.2;
}
}
if (humidity < 0.5) {
riskFactor += 0.2;
if (humidity < 0.25) {
riskFactor += 0.2;
}
}
if (precipProbability > 0.2) {
if (precipProbability > 0.4) {
riskFactor -= 0.1;
if (precipProbability > 0.8) {
riskFactor -= 0.1;
}
}
} else {
riskFactor += 0.2;
}
if (precipIntensity > 1) {
riskFactor -= 0.1;
if (precipIntensity > 3) {
riskFactor -= 0.1;
if (precipIntensity > 5) {
riskFactor -= 0.1;
if (precipIntensity > 10) {
riskFactor = 0;
}
}
}
} else {
riskFactor += 0.1;
}
int riskFactorInt = riskFactor * 100;
return riskFactorInt;
}
}
<file_sep>/src/main/resources/application.properties
spring.datasource.url=${DATABASE_URL:jdbc:postgresql://ec2-54-217-214-201.eu-west-1.compute.amazonaws.com:5432/dblo32ol08co96?sslmode=verify-ca&sslfactory=org.postgresql.ssl.NonValidatingFactory}
spring.datasource.username=cbbcotreaudszd
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
server.port=${PORT:8080}
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB<file_sep>/src/main/java/com/spotifire/web/rest/client/WeatherDarkskyForecastClientManager.java
package com.spotifire.web.rest.client;
import java.net.URI;
import java.net.URISyntaxException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.spotifire.persistence.constants.SpotifireConstants;
import com.spotifire.web.rest.dto.WeatherDTO;
@Service
public class WeatherDarkskyForecastClientManager implements IWeatherClientService {
@Autowired
@Qualifier("restTemplate")
private RestTemplate restTemplate;
@Override
public int fetchWeatherData(double latitude, double longitude, long timestamp) throws URISyntaxException {
StringBuilder sb = new StringBuilder();
sb.append(SpotifireConstants.WEATHER_DARKSKY_FORECAST_BASE_URL).append(latitude).append(SpotifireConstants.OPERATOR_COMMA)
.append(longitude).append(SpotifireConstants.OPERATOR_COMMA).append(timestamp)
.append(SpotifireConstants.WEATHER_DARKSKY_FORECAST_BASE_URL_EXTRA_PARAMS);
URI uriPetition = new URI(sb.toString());
ResponseEntity<WeatherDTO> response = this.restTemplate.exchange(uriPetition, HttpMethod.GET, null, WeatherDTO.class);
int riskFactor = 0;
double humidity = response.getBody().getCurrently().getHumidity();
double precipIntensity = response.getBody().getCurrently().getPrecipIntensity();
double precipProbability = response.getBody().getCurrently().getPrecipProbability();
double windSpeed = response.getBody().getCurrently().getWindSpeed();
if (windSpeed > 11) { // 40 km/h
riskFactor += 0.2;
if (windSpeed > 27) { // 100 km/h
riskFactor += 0.2;
}
}
if (humidity < 0.5) {
riskFactor += 0.2;
if (humidity < 0.25) {
riskFactor += 0.2;
}
}
if (precipProbability > 0.2) {
if (precipProbability > 0.4) {
riskFactor -= 0.1;
if (precipProbability > 0.8) {
riskFactor -= 0.1;
}
}
} else {
riskFactor += 0.2;
}
if (precipIntensity > 1) {
riskFactor -= 0.1;
if (precipIntensity > 3) {
riskFactor -= 0.1;
if (precipIntensity > 5) {
riskFactor -= 0.1;
if (precipIntensity > 10) {
riskFactor = 0;
}
}
}
} else {
riskFactor += 0.1;
}
return riskFactor * 100;
}
}
<file_sep>/src/test/java/com/spotifire/spotifireback/MiscCodeTest.java
package com.spotifire.spotifireback;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.spotifire.config.EmptyConfig;
import com.spotifire.core.utils.SpotifireUtils;
import com.spotifire.persistence.constants.ReportType;
import com.spotifire.persistence.constants.SourceType;
import com.spotifire.persistence.constants.SpotifireConstants;
import com.spotifire.persistence.pojo.Location;
import com.spotifire.persistence.pojo.Report;
import com.spotifire.web.rest.dto.GeolocationDTO;
import com.spotifire.web.rest.dto.WeatherDTO;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { EmptyConfig.class }, loader = AnnotationConfigContextLoader.class)
public class MiscCodeTest {
private static final Logger LOGGER = LogManager.getLogger(MiscCodeTest.class);
@Test
public void checkConfiguration() {
System.out.println("Testing checkConfiguration...");
LOGGER.debug("EEEEES");
System.out.println("Test Init");
}
@Test
@Rollback(false)
public void publishTweet() throws RestClientException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("l3socwjpwuFbis9sDX56PIIxP", "<KEY>");
twitter.setOAuthAccessToken(
new AccessToken("<KEY>", "<KEY>"));
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(SpotifireConstants.GEOCODE_API_URL)
.queryParam(SpotifireConstants.GEOCODE_API_FORMAT_PARAM, SpotifireConstants.JSON_FORMAT)
.queryParam(SpotifireConstants.GEOCODE_API_LATITUDE_PARAM, 39.420143)
.queryParam(SpotifireConstants.GEOCODE_API_LONGITUDE_PARAM, -0.457176);
HttpEntity<GeolocationDTO> response = this.getNasaRestTemplate().exchange(builder.toUriString(), HttpMethod.GET, null,
GeolocationDTO.class);
if (response != null) {
GeolocationDTO geolocation = response.getBody();
String tweet = String.format(SpotifireConstants.TWEET_MESSAGE,
geolocation.getAddress().getVillage() != null ? geolocation.getAddress().getVillage()
: geolocation.getAddress().getTown(),
geolocation.getAddress().getCounty());
try {
StatusUpdate statusTweet = new StatusUpdate(tweet);
twitter.updateStatus(statusTweet);
} catch (TwitterException e) {
System.err.println(e.getMessage());
}
}
}
@Test
public void testSatelliteData() throws URISyntaxException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
System.out.println("Testing testSatelliteData...");
LOGGER.debug("EEEEES");
System.out.println("Test Init");
URI uriPetition = new URI("https://firms.modaps.eosdis.nasa.gov/data/active_fire/c6/csv/MODIS_C6_Europe_24h.csv");
RestTemplate nasaRestTemplate = this.getNasaRestTemplate();
ResponseEntity<String> response = nasaRestTemplate.exchange(uriPetition, HttpMethod.GET, null, String.class);
List<Report> reportList = new ArrayList<>();
String[] lines = response.getBody().split("\n");
if (lines != null) {
Arrays.asList(lines).forEach(line -> {
String[] columns = line.split(",");
Report report = new Report();
if (columns != null) {
report.setCreationDate(parseDateFromCsvFile(columns[5] + columns[6], "yyyy-MM-ddhhmm"));
report.setType(ReportType.FIRE);
report.setScore(this.scoringSatelliteData(Double.valueOf(columns[2]), Double.valueOf(columns[10]),
Double.valueOf(columns[11])));
report.setLocation(new Location(Double.valueOf(columns[0]), Double.valueOf(columns[1])));
}
reportList.add(report);
});
}
System.out.println("Test End");
}
private static Date parseDateFromCsvFile(String fieldValue, String pattern) {
Date res = null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
res = sdf.parse(fieldValue);
} catch (java.text.ParseException e) {
System.out.println(e.getMessage());
}
return res;
}
private RestTemplate getNasaRestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
private int scoringSatelliteData(double brightness1, double brightness2, double power) {
System.out.println("Testing scoringSatelliteData...");
LOGGER.debug("EEEEES");
System.out.println("Test Init");
double maxBrightness1 = 503.2;
double minBrightness1 = 300.0;
double maxBrightness2 = 400.1;
double minBrightness2 = 264.9;
double maxPower = 400.1;
double minPower = 2;
double coeficienBrightness1 = 0.3045;
double coeficienBrightness2 = 0.1297;
double coeficientPower = 0.1747;
double calculationBrightness1 = this.calculateCuadraticMinimum(brightness1, maxBrightness1, minBrightness1) * coeficienBrightness1;
double calculationBrightness2 = this.calculateCuadraticMinimum(brightness2, maxBrightness2, minBrightness2) * coeficienBrightness2;
double calculationPower = this.calculateCuadraticMinimum(power, maxPower, minPower) * coeficientPower;
int result = (int) (calculationBrightness1 + calculationBrightness2 + calculationPower) * 100;
System.out.printf("Scoring satellite data: %d \n", result);
return result;
}
private double calculateCuadraticMinimum(double input, double maximum, double minimum) {
return (input - minimum) / (maximum - minimum);
}
/**
* @throws URISyntaxException
*/
@Test
public void testAPIWeather() throws URISyntaxException {
// https://api.darksky.net/forecast/f0882429cb4afe2fb72984e427e6789f/37.035229,-6.435476,1499860800?units=si&exclude=flags?exclude=alerts?exclude=minutely
System.out.println("Testing testAPIWeather...");
System.out.println("Test Init");
double latitude = 37.035229f;
double longitude = -6.435476f;
long timeStamp = (new Date().getTime()) / 1000;
StringBuilder sb = new StringBuilder();
sb.append("https://api.darksky.net/forecast/f0882429cb4afe2fb72984e427e6789f/").append(latitude).append(",").append(longitude)
.append(",").append(timeStamp)
.append("?units=si&exclude=flags?exclude=alerts?exclude=minutely?exclude=hourly?exclude=daily");
URI uriPetition = new URI(sb.toString());
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<WeatherDTO> response = restTemplate.exchange(uriPetition, HttpMethod.GET, null, WeatherDTO.class);
System.out.println(response.getStatusCode() + ":" + response.getBody());
int riskFactor = 0;
double humidity = response.getBody().getCurrently().getHumidity();
double precipIntensity = response.getBody().getCurrently().getPrecipIntensity();
double precipProbability = response.getBody().getCurrently().getPrecipProbability();
double windSpeed = response.getBody().getCurrently().getWindSpeed();
if (windSpeed > 11) { // 40 km/h
riskFactor += 0.2;
if (windSpeed > 27) { // 100 km/h
riskFactor += 0.2;
}
}
if (humidity < 0.5) {
riskFactor += 0.2;
if (humidity < 0.25) {
riskFactor += 0.2;
}
}
if (precipProbability > 0.2) {
if (precipProbability > 0.4) {
riskFactor -= 0.1;
if (precipProbability > 0.8) {
riskFactor -= 0.1;
}
}
} else {
riskFactor += 0.2;
}
if (precipIntensity > 1) {
riskFactor -= 0.1;
if (precipIntensity > 3) {
riskFactor -= 0.1;
if (precipIntensity > 5) {
riskFactor -= 0.1;
if (precipIntensity > 10) {
riskFactor = 0;
}
}
}
} else {
riskFactor += 0.1;
}
int riskFactorInt = riskFactor * 100;
System.out.printf("riskFactor: %d \n", riskFactorInt);
System.out.println("Test End");
}
@Test
public void scoringImage() {
System.out.println("Testing scoringImage...");
BufferedImage imageInput = null;
File input_file = null;
try {
input_file = new File("C:/Users/Carlos/Desktop/imagenes/llamas/fotoTwitter.jpg");
imageInput = ImageIO.read(input_file);
System.out.println("Reading complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
int width = imageInput.getWidth();
int height = imageInput.getHeight();
BufferedImage imageOutputRed = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
BufferedImage imageOutputGreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
BufferedImage imageOutputBlue = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int histogramReturn[][] = new int[3][256];
int pixel = 0;
int pixelRed = 0;
int pixelGreen = 0;
int pixelBlue = 0;
int red = 0;
int green = 0;
int blue = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
pixelRed = 0;
pixelGreen = 0;
pixelBlue = 0;
pixel = imageInput.getRGB(i, j);
red = (pixel >> 16) & 0xFF;
green = (pixel >> 8) & 0xFF;
blue = pixel & 0xFF;
pixelRed = (red << 16);
pixelGreen = (green << 8);
pixelBlue = blue;
imageOutputRed.setRGB(i, j, pixelRed);
imageOutputGreen.setRGB(i, j, pixelGreen);
imageOutputBlue.setRGB(i, j, pixelBlue);
histogramReturn[0][red] += 1;
histogramReturn[1][green] += 1;
histogramReturn[2][blue] += 1;
}
}
try {
File outputfileRed = new File("imageTwitterRed.jpg");
ImageIO.write(imageOutputRed, "jpg", outputfileRed);
} catch (IOException e) {
}
try {
File outputfileGreen = new File("imageTwitterGreen.jpg");
ImageIO.write(imageOutputGreen, "jpg", outputfileGreen);
} catch (IOException e) {
}
try {
File outputfileBlue = new File("imageTwitterBlue.jpg");
ImageIO.write(imageOutputBlue, "jpg", outputfileBlue);
} catch (IOException e) {
}
int confidence = this.analyzeFire(histogramReturn, width, height);
System.out.println("Histogram Red.");
for (int i = 0; i < 256; i++) {
System.out.printf("%d : %d \n", i, histogramReturn[0][i]);
}
System.out.println("Histogram Green.");
for (int i = 0; i < 256; i++) {
System.out.printf("%d : %d \n", i, histogramReturn[1][i]);
}
System.out.println("Histogram Blue.");
for (int i = 0; i < 256; i++) {
System.out.printf("%d : %d \n", i, histogramReturn[2][i]);
}
System.out.printf("Confidence of the image being of a fire: %d \n", confidence);
System.out.println("Test OK");
}
private int analyzeFire(int histogram[][], int width, int height) {
int meanHistogramRed = this.calculateHighMeanHistogram(histogram[0], width, height);
int meanHistogramGreen = this.calculateHighMeanHistogram(histogram[1], width, height);
int meanHistogramBlue = this.calculateHighMeanHistogram(histogram[2], width, height);
double numberOfPixels = width * height;
System.out.printf("Histogram Red mean %d \n", meanHistogramRed);
if ((numberOfPixels / 11000) > meanHistogramRed) {
meanHistogramRed = 0;
}
System.out.printf("Histogram Red mean %d \n", meanHistogramRed);
System.out.printf("Histogram Green mean %d \n", meanHistogramGreen);
System.out.printf("Histogram Blue mean %d \n", meanHistogramBlue);
int confidence = this.calculateConfidence(meanHistogramRed, meanHistogramGreen, meanHistogramBlue);
return confidence;
}
private int calculateHighMeanHistogram(int histogram[], int width, int height) {
int meanCalculated = 0;
for (int i = 192; i < 256; i++) {
meanCalculated += histogram[i];
}
meanCalculated = meanCalculated / (256 - 192);
return meanCalculated;
}
private int calculateConfidence(int red, int green, int blue) {
int confidence = 0;
if (red > (blue + green)) {
float difference = (float) (red - (blue + green)) / (red + blue + green);
if (difference > 0.1) {
if (difference < 0.9) {
confidence = (int) (difference * 100);
} else {
confidence = 99;
}
} else {
confidence = 0;
}
} else {
confidence = 0;
}
return confidence;
}
private static Twitter getTwitterClient() {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("l3socwjpwuFbis9sDX56PIIxP", "<KEY>");
twitter.setOAuthAccessToken(
new AccessToken("<KEY>", "<KEY>"));
return twitter;
}
@Test
public void fetchTwitter() {
Twitter twitter = getTwitterClient();
Query query = new Query();
query.setQuery(SpotifireConstants.SPOTIFIRE_TWITTER_HASHTAG);
query.setCount(100);
List<Status> statuses = null;
try {
QueryResult queryResult = twitter.search(query);
statuses = queryResult.getTweets();
statuses.stream().filter(tweet -> Double.compare(tweet.getUser().getId(), 1053697168136122368L) != 0).forEach(tweet -> {
Report report = new Report();
report.setTwitterId(tweet.getId());
report.setCreationDate(tweet.getCreatedAt());
report.setSource(SourceType.TWITTER);
report.setType(ReportType.FIRE);
report.setDescription(tweet.getText());
if (tweet.getGeoLocation() != null) {
report.setLocation(new Location(tweet.getGeoLocation().getLatitude(), tweet.getGeoLocation().getLongitude()));
}
if (tweet.getMediaEntities() != null && tweet.getMediaEntities().length > 0
&& tweet.getMediaEntities()[0].getType().equals("photo")) {
try {
URL url = new URL(tweet.getMediaEntities()[0].getMediaURL());
BufferedImage image = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
baos.flush();
report.setHasImage(true);
report.setImage(baos.toByteArray());
} catch (IOException e) {
LOGGER.error("Error reading tweet image");
}
}
});
} catch (Exception e) {
}
}
@Test
public void testCentralLongitude() {
Report r1 = new Report();
Report r2 = new Report();
Report r3 = new Report();
Report r4 = new Report();
Report r5 = new Report();
Location l1 = new Location();
l1.setLatitude(42.9336785);
l1.setLongitude(-72.2272968);
r1.setLocation(l1);
Location l2 = new Location();
l2.setLatitude(42.9185950);
l2.setLongitude(-72.2249794);
r2.setLocation(l2);
Location l3 = new Location();
l3.setLatitude(42.9180293);
l3.setLongitude(-72.2531748);
r3.setLocation(l3);
Location l4 = new Location();
l4.setLatitude(42.9335843);
l4.setLongitude(-72.2560072);
r4.setLocation(l4);
Location l5 = new Location();
l5.setLatitude(42.9337728);
l5.setLongitude(-72.2284555);
r5.setLocation(l5);
List<Report> reportList = new ArrayList<>();
reportList.add(r1);
reportList.add(r2);
reportList.add(r3);
reportList.add(r4);
reportList.add(r5);
Location center = SpotifireUtils.getCentralReportLocation(reportList);
System.out.println(center.getLatitude());
System.out.println(center.getLongitude());
}
}
| 0c98e5b0e6940a53863da19fc0b2528b17f8c4fa | [
"Markdown",
"Java",
"INI"
] | 21 | Java | jmpereztorres/spotifire-back | 7fd2c9b86fd0141d59026005325add91bce7d5a1 | de6a4753924377d9845bed445d049717e90ae33d |
refs/heads/master | <file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/book-ajax', 'BookAjaxController@index');
Route::get('/book-ajax/get-book', 'BookAjaxController@books');
Route::get('/book-builder', 'BookBuilderController@index');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use Datatables;
class BookAjaxController extends Controller
{
public function index(){
return view('books-ajax.index');
}
public function books(){
$books = Book::select('title','author','publisher')->get();
return Datatables::of($books)->make(true);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use Datatables;
use Yajra\Datatables\Html\Builder;
class BookBuilderController extends Controller
{
public function index(Request $request, Builder $htmlBuilder)
{
if ($request->ajax()) {
$books = Book::select('title','author','publisher')->get();
return Datatables::of($books)->make(true);
}
$html = $htmlBuilder
->addColumn(['data' => 'title', 'name' => 'title', 'title' => 'Judul'])
->addColumn(['data' => 'author', 'name' => 'author', 'title' => 'Penulis'])
->addColumn(['data' => 'publisher', 'name' => 'publisher', 'title' => 'Penerbit']);
return view('books-builder.index', compact('html'));
}
}
| 32f80bbebb31477995616d13784ec24568816f18 | [
"PHP"
] | 3 | PHP | widihastomo/datatables-demo | 2b257570de8fed34eecb18ea92a44ad0fdc79819 | af81eaa2687c2afc16066d85bfdec599bc1de227 |
refs/heads/master | <repo_name>EXALLENGE/Muradkhanova_task2<file_sep>/viselica.py
import random
f = ['h', 'e', 'l', 'l']
c = ['h', 'o', 'p', 'e', 'l', 'e', 's', 's']
e = ['a', 'n', 'x', 'i', 'e', 't', 'y']
d = ['s', 'a', 'd', 'n', 'e', 's', 's']
s = ['a', 'n', 'g', 'e', 'l']
v = ['s', 'o', 'o', 'n']
g = [f, c, e, d, s, v]
a = random.choice(g)
b = ['*' for i in a]
mistake = 0
while mistake < 5:
print('Guess a letter:')
x = input().lower()
if x not in a:
mistake += 1
print('Missed, mistake', mistake, 'out of 5.')
print('The word: ', *b, sep='')
if x in a:
for i in range(0, a.count(x)):
k = a.index(x)
b[k] = x
a[k] = '+'
print('Hit!')
print('The word: ', *b, sep='')
if '*' not in b:
print('You won!')
break
if mistake == 5:
print('You lost!')
| 83c6d05c6f3110f5c248fc298b789a2259e44ffb | [
"Python"
] | 1 | Python | EXALLENGE/Muradkhanova_task2 | fdeaf2aef06b31efdb4204c3dd4a334db9d25e1e | 337733306577fa704fc61ad11587efcf28dd578e |
refs/heads/master | <repo_name>qbit-/tcc-scratch<file_sep>/report_for_gus/plot_t_norms_vs_u_cpd.py
import numpy as np
import time
import pickle
from pyscf.lib import logger
from pyscf import scf
from tcc.hubbard import hubbard_from_scf
from tcc.cc_solvers import (classic_solver, gradient_solver,
root_solver, residual_diis_solver)
from tcc.rccsd import RCCSD, RCCSD_UNIT
from tcc.rccsd_cpd import RCCSD_nCPD_LS_T_HUB
from tcc.cpd import cpd_normalize
# Set up parameters of the script
N = 10
U_VALUES = np.linspace(1, 10, num=20)
# RANKS_T = np.array([5, 7, 8, 10, 12, 20, 25, 40]).astype('int')
RANKS_T = np.array([11, 13, 15, 17, 19]).astype('int')
l1 = [1, ] * 4 + [3, ] * 13 + [5, ] * 3
l2 = [1, ] * 2 + [2, ] * 2 + [3, ] * 10 + [5, ] * 6
l3 = [1, ] * 2 + [2, ] * 2 + [3, ] * 5 + [5, ] * 5 + [7, ] * 6
l4 = [1, ] * 2 + [3, ] * 2 + [8, ] * 5 + [10, ] * 4 + [14, ] * 4 + [18, ] * 3
#LAMBDAS = [l1, l2, l3, l3, l3, l4, l4, l4]
LAMBDAS = [l4, l4, l4, l4, l4]
def run_scfs(N, us, filename):
scf_energies = []
scf_mos = []
scf_mo_energies = []
for idxu, u in enumerate(us):
rhf = hubbard_from_scf(scf.RHF, N, N, u, 'y')
rhf.scf()
scf_energies.append(rhf.e_tot)
scf_mos.append(rhf.mo_coeff)
scf_mo_energies.append(rhf.mo_energy)
results = tuple(
tuple([e_tot, mo_coeff, mo_energy])
for e_tot, mo_coeff, mo_energy
in zip(scf_energies, scf_mos, scf_mo_energies))
with open(filename, 'wb') as fp:
pickle.dump(results, fp)
def calc_solutions_diff_u_cpd():
"""
Run RCCSD-CPD for all corellation strengths
"""
# Set up parameters of the script
us = U_VALUES.copy()
lambdas = LAMBDAS.copy()
rankst = RANKS_T.copy()
results = np.array(us)
results_t1 = np.array(us)
results_t2 = np.array(us)
# Run all scfs here so we will have same starting points for CC
run_scfs(N, us, 'calculated/{}-site/scfs_different_u_t1.p'.format(N))
with open(
'calculated/{}-site/scfs_different_u_t1.p'.format(N), 'rb'
) as fp:
ref_scfs = pickle.load(fp)
for idxr, rank in enumerate(rankst):
t1_norms = []
energies = []
t2_norms = []
# timb = time.process_time()
solutions = []
for idxu, (u, curr_scf) in enumerate(zip(us, ref_scfs)):
tim = time.process_time()
rhf = hubbard_from_scf(scf.RHF, N, N, u, 'y')
rhf.max_cycle = 1
rhf.scf()
e_scf, mo_coeff, mo_energy = curr_scf
cc = RCCSD_nCPD_LS_T_HUB(rhf, rankt={'t2': rank},
mo_coeff=mo_coeff,
mo_energy=mo_energy)
converged = False
if idxu == 0:
converged, energy, amps = classic_solver(
cc, lam=lambdas[idxr][idxu], conv_tol_energy=1e-8,
conv_tol_amps=1e-7, max_cycle=50000,
verbose=logger.NOTE)
else:
converged, energy, amps = classic_solver(
cc, lam=lambdas[idxr][idxu], conv_tol_energy=1e-8,
conv_tol_amps=1e-8, max_cycle=60000,
verbose=logger.NOTE, amps=amps)
solutions.append((u, curr_scf, amps))
if np.isnan(energy):
Warning(
'Warning: N = {}, U = {} '
'Rank = {} did not converge'.format(N, u, rank)
)
energies.append(energy + e_scf)
norms = amps.map(np.linalg.norm)
if not np.isnan(energy):
t1_norms.append(norms.t1)
else:
t1_norms.append(np.nan)
if not np.isnan(energy):
t2_norms.append(amps.t2.xlam[0, 0])
else:
t2_norms.append(np.nan)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}\n'.format(
idxu + 1, len(us), rank, elapsed
))
results = np.column_stack((results, energies))
results_t1 = np.column_stack((results_t1, t1_norms))
results_t2 = np.column_stack((results_t2, t2_norms))
with open('amps_and_scf_rank_{}.p'.format(rank), 'wb') as fp:
pickle.dump(solutions, fp)
def calc_t1_norm_vs_u_cpd():
"""
Collect t1 from calculated solutions into a table
"""
# Set up parameters of the script
rankst = RANKS_T.copy()
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, rankst[0]), 'rb') as fp:
solutions = pickle.load(fp)
us = [sol[0] for sol in solutions]
results_t1 = us
for idxr, rank in enumerate(rankst):
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, rank), 'rb') as fp:
solutions = pickle.load(fp)
t1_norms = []
for idxu, (u, curr_scf, amps) in enumerate(solutions):
tim = time.process_time()
t1_norm = amps.map(np.linalg.norm).t1
t1_norms.append(t1_norm)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}\n'.format(
idxu + 1, len(solutions), rank, elapsed
))
results_t1 = np.column_stack((results_t1, t1_norms))
np.savetxt(
'calculated/{}-site/t1_norm_vs_u.txt'.format(N),
results_t1,
header='U ' + ' '.join('R={}'.format(rr) for rr in rankst)
)
us, *t1_l = np.loadtxt(
'calculated/{}-site/t1_norm_vs_u.txt'.format(N), unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, t1_l[0])
plt.xlabel('$U / t$')
plt.ylabel('$||T^{1}||$')
plt.title('$T^{1}$ norm behavior for different ranks')
fig.show()
def plot_t1_vs_u_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
rankst = RANKS_T.copy()
us, *t1_norms_l = np.loadtxt(
'calculated/{}-site/t1_norm_vs_u.txt'.format(N), unpack=True)
if len(t1_norms_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst) + 1))
fig, ax = plt.subplots()
rankst = rankst[[0, 1, 2, 3, 5, 6]] # Cut out some elements
t1_norms_l = t1_norms_l[:4] + t1_norms_l[5:]
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
if idxr == 8:
marker = '^'
ls = ''
else:
marker = None
ls = '-'
ax.plot(us, t1_norms_l[idxr],
color=color, ls=ls, marker=marker)
us_rccsd, t1_norms_rccsd_l = np.loadtxt(
'calculated/{}-site/t1_norm_vs_u_rccsd.txt'.format(N), unpack=True)
ax.plot(us_rccsd, t1_norms_rccsd_l,
color='k', ls='', marker='^')
plt.xlabel('$U / t$')
plt.ylabel('$||T^{1}||$')
plt.title(
'Spatial symmetry breaking for different ranks, {} sites'.format(N)
)
# plt.ylim(None, None)
# plt.xlim(1, 4)
plt.legend(
['R={}'.format(rank) for rank in rankst]
+ ['RCCSD', ],
loc='upper left'
)
fig.show()
fig.savefig('figures/t1_norms_vs_u_{}_sites.eps'.format(N))
def calc_t2_norm_vs_u_cpd():
"""
Collect t2 from calculated solutions into a table
"""
# Set up parameters of the script
from tcc.cpd import ncpd_rebuild
rankst = RANKS_T.copy()
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, rankst[0]), 'rb') as fp:
solutions = pickle.load(fp)
us = [sol[0] for sol in solutions]
results_t2 = us
t2names = ['xlam', 'x1', 'x2', 'x3', 'x4']
for idxr, rank in enumerate(rankst):
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, rank), 'rb') as fp:
solutions = pickle.load(fp)
t2_norms = []
for idxu, (u, curr_scf, amps) in enumerate(solutions):
tim = time.process_time()
t2f = ncpd_rebuild([amps.t2[name] for name in t2names])
t2_norm = np.linalg.norm(t2f)
t2_norms.append(t2_norm)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}\n'.format(
idxu + 1, len(solutions), rank, elapsed
))
results_t2 = np.column_stack((results_t2, t2_norms))
np.savetxt(
'calculated/{}-site/t2_norm_vs_u.txt'.format(N),
results_t2,
header='U ' + ' '.join('R={}'.format(rr) for rr in rankst)
)
us, *t2_l = np.loadtxt(
'calculated/{}-site/t2_norm_vs_u.txt'.format(N), unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, t2_l[0])
plt.xlabel('$U / t$')
plt.ylabel('$||T^{1}||$')
plt.title('$T^{1}$ norm behavior for different ranks')
fig.show()
def calc_t2_norm_vs_u_rccsd():
"""
Calculate norms of T2 in conventional RCCSD
"""
us = U_VALUES.copy()
lambdas = LAMBDAS.copy()
with open(
'calculated/{}-site/scfs_different_u_t1.p'.format(N), 'rb'
) as fp:
ref_scfs = pickle.load(fp)
t1_norms = []
energies = []
t2_norms = []
# timb = time.process_time()
solutions = []
amps = None
for idxu, (u, curr_scf) in enumerate(zip(us, ref_scfs)):
rhf = hubbard_from_scf(scf.RHF, N, N, u, 'y')
rhf.max_cycle = 1
rhf.scf()
e_scf, mo_coeff, mo_energy = curr_scf
cc = RCCSD_UNIT(rhf,
mo_coeff=mo_coeff,
mo_energy=mo_energy)
converged, energy, amps = residual_diis_solver(
cc, conv_tol_energy=1e-9,
conv_tol_res=1e-9,
max_cycle=10000,
verbose=logger.NOTE, amps=None, lam=14)
norms = amps.map(np.linalg.norm)
t1_norms.append(norms.t1)
t2_norms.append(norms.t2)
energies.append(energy)
solutions.append([u, curr_scf, amps])
print('Step {} out of {}'.format(idxu + 1, len(us)))
t1_norms = np.column_stack((us, t1_norms))
t2_norms = np.column_stack((us, t2_norms))
np.savetxt(
'calculated/{}-site/t1_norm_vs_u_rccsd.txt'.format(N),
t1_norms,
header='U |t1|'
)
np.savetxt(
'calculated/{}-site/t2_norm_vs_u_rccsd.txt'.format(N),
t2_norms,
header='U |t2|'
)
with open(
'calculated/{}-site/amps_and_scf_rccsd.p'.format(N),
'wb') as fp:
pickle.dump(solutions, fp)
us, *t2_l = np.loadtxt(
'calculated/{}-site/t2_norm_vs_u_rccsd.txt'.format(N), unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, t2_l[0])
plt.xlabel('$U / t$')
plt.ylabel('$||T^{2}||$')
plt.title('$T^{2}$ norm behavior for different ranks')
fig.show()
def plot_t2_vs_u_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
rankst = RANKS_T.copy()
us, *t2_norms_l = np.loadtxt(
'calculated/{}-site/t2_norm_vs_u.txt'.format(N), unpack=True)
if len(t2_norms_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst) + 1))
fig, ax = plt.subplots()
rankst_sel = rankst[[0, 1, 2, 3, 5, 6]] # Cut out some elements
t2_norms_l_sel = t2_norms_l[:4] + t2_norms_l[5:7]
for idxr, (rank, color) in enumerate(zip(rankst_sel, colors)):
if idxr == 6:
marker = '^'
ls = ''
else:
marker = None
ls = '-'
ax.plot(us, t2_norms_l_sel[idxr],
color=color, ls=ls, marker=marker)
us_rccsd, t2_norms_rccsd_l = np.loadtxt(
'calculated/{}-site/t2_norm_vs_u_rccsd.txt'.format(N), unpack=True)
ax.plot(us_rccsd, t2_norms_rccsd_l,
color='k', ls='', marker='^')
plt.xlabel('$U / t$')
plt.ylabel('$||T^{2}||$')
plt.title(
'$T^{{2}}$ amplitude norm for different ranks, {0} sites'.format(N)
)
# plt.ylim(None, None)
# plt.xlim(1, 4)
plt.legend(
['R={}'.format(rank) for rank in rankst_sel] +
['RCCSD', ],
loc='upper left'
)
fig.show()
fig.savefig('figures/t2_norms_vs_u_{}_sites.eps'.format(N))
if __name__ == '__main__':
calc_solutions_diff_u_cpd()
<file_sep>/seminar_talk_cpd_rccsd/plot_compare_thc_cpd_energy.py
import numpy as np
def plot_energy_vs_u_cpd_compare():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
N = 10
rankst = np.array([5, 8, 10, 12, 20, 30]).astype('int')
us, *energies_l = np.loadtxt(
'calculated/{}-site/t1_norm_vs_u_energies.txt'.format(N), unpack=True)
if len(energies_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst)))
fig, ax = plt.subplots()
rankst = rankst[[0, 2, 4, 5]] # Cut out some elements
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
ax.plot(us, energies_l[idxr],
color=color, marker=None)
us, *energies_thc_l = np.loadtxt(
'reference/{}-site/THCRCCSD.txt'.format(N), unpack=True)
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
ax.plot(us, energies_thc_l[idxr], '^',
color=color)
u_cc, e_cc = np.loadtxt(
'reference/{}-site/RCCSD.txt'.format(N), unpack=True)
ax.plot(u_cc, e_cc,
':k', marker=None)
plt.xlabel('$U / t$')
plt.ylabel('$E$, H')
plt.title(
'Comparing THC- and CPD-RCCSD, {} sites'.format(N)
)
plt.ylim(-10, None)
plt.xlim(1, 9)
plt.legend(
['R={}'.format(rank) for rank in rankst] +
['R={} (THC)'.format(rank) for rank in rankst] +
['RCCSD', ],
loc='upper left'
)
fig.show()
fig.savefig('figures/energies_vs_u_{}_sites_compare_thc.eps'.format(N))
<file_sep>/seminar_talk_cpd_rccsd/plot_lambdas_vs_r.py
import numpy as np
def plot_l_1_vs_u_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
N = 10
rankst = np.array([5, 7, 8, 10, 12, 20]).astype('int')
us, *lam_1_l = np.loadtxt(
'calculated/{}-site/lam_1_vs_u.txt'.format(N), unpack=True)
if len(lam_1_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst)+1))
fig, ax = plt.subplots()
rankst = rankst[:5] # Cut out some elements
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
ax.plot(us, lam_1_l[idxr],
color=color, marker=None)
plt.xlabel('$U / t$')
plt.ylabel('$\lambda^{1}$')
plt.title(
'Largest contribution in CPD of $T^2$ amplitudes, {} sites'.format(N)
)
# plt.ylim(None, None)
# plt.xlim(1, 4)
plt.legend(
['R={}'.format(rank) for rank in rankst],
loc='upper left'
)
fig.show()
fig.savefig('figures/lam_1_vs_u_{}_sites.eps'.format(N))
<file_sep>/report_for_gus/plot_residuals_vs_r.py
import numpy as np
import time
import pickle
from pyscf.lib import logger
from pyscf import scf
from tcc.hubbard import hubbard_from_scf
from tcc.cc_solvers import (classic_solver, root_solver)
from tcc.rccsd import RCCSD_UNIT
from tcc.rccsd_cpd import RCCSD_nCPD_LS_T_HUB
from tcc.cpd import cpd_normalize
# Set up parameters of the script
N = 10
RANKS_T = np.array([5, 7, 8, 10, 20, 25, 40]).astype('int')
def calc_resids_norm():
"""
Plot T1 norm of RCCSD-CPD for all corellation strengths
"""
# Set up parameters of the script
rankst = RANKS_T.copy()
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, rankst[0]), 'rb') as fp:
solutions = pickle.load(fp)
us = [sol[0] for sol in solutions]
results_r1 = us
results_r2 = us
for idxr, rank in enumerate(rankst):
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, rank), 'rb') as fp:
solutions = pickle.load(fp)
r1_norms = []
r2_norms = []
for idxu, (u, curr_scf, amps) in enumerate(solutions):
tim = time.process_time()
rhf = hubbard_from_scf(scf.RHF, N, N, u, 'y')
rhf.max_cycle = 1
rhf.scf()
e_scf, mo_coeff, mo_energy = curr_scf
cc = RCCSD_nCPD_LS_T_HUB(rhf, rankt={'t2': rank},
mo_coeff=mo_coeff,
mo_energy=mo_energy)
h = cc.create_ham()
res = cc.calc_residuals(h, amps)
norms = res.map(np.linalg.norm)
r1_norms.append(norms.t1)
r2_norms.append(norms.t2)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}\n'.format(
idxu + 1, len(solutions), rank, elapsed
))
results_r1 = np.column_stack((results_r1, r1_norms))
results_r2 = np.column_stack((results_r2, r2_norms))
np.savetxt(
'calculated/{}-site/r1_norm_vs_u.txt'.format(N),
results_r1,
header='U ' + ' '.join('R={}'.format(rr) for rr in rankst)
)
np.savetxt(
'calculated/{}-site/r2_norm_vs_u.txt'.format(N),
results_r2,
header='U ' + ' '.join('R={}'.format(rr) for rr in rankst)
)
us, *r1_norms_l = np.loadtxt(
'calculated/{}-site/r1_norm_vs_u.txt'.format(N), unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, r1_norms_l[0])
plt.xlabel('$U$')
plt.ylabel('$||r^{1}||$')
plt.title('R1 behavior for different ranks')
fig.show()
def plot_r1_vs_u_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
rankst = RANKS_T.copy()
us, *r1_norms_l = np.loadtxt(
'calculated/{}-site/r1_norm_vs_u.txt'.format(N), unpack=True)
if len(r1_norms_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst) + 1))
fig, ax = plt.subplots()
rankst = rankst # Cut out some elements
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
ax.semilogy(us, r1_norms_l[idxr],
color=color, marker=None)
plt.xlabel('$U / t$')
plt.ylabel('$||R^{1}||$')
plt.title(
'Singles residuals for different ranks, {} sites'.format(N)
)
# plt.ylim(None, None)
# plt.xlim(1, 4)
plt.legend(
['R={}'.format(rank) for rank in rankst],
loc='upper left'
)
fig.show()
fig.savefig('figures/r1_norms_vs_u_{}_sites.eps'.format(N))
def plot_r2_vs_u_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
rankst = RANKS_T.copy()
us, *r2_norms_l = np.loadtxt(
'calculated/{}-site/r2_norm_vs_u.txt'.format(N), unpack=True)
if len(r2_norms_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst) + 1))
fig, ax = plt.subplots()
rankst = rankst[:6] # Cut out some elements
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
if idxr == 6:
ls = ''
marker = '^'
else:
ls = '-'
marker = None
ax.plot(us, r2_norms_l[idxr],
color=color, marker=marker, ls=ls)
plt.xlabel('$U / t$')
plt.ylabel('$||R^{2}||$')
plt.title(
'Doubles residuals for different ranks, {} sites'.format(N)
)
# plt.ylim(None, None)
# plt.xlim(1, 4)
plt.legend(
['R={}'.format(rank) for rank in rankst],
loc='upper left'
)
fig.show()
fig.savefig('figures/r2_norms_vs_u_{}_sites.eps'.format(N))
if __name__ == '__main__':
pass
<file_sep>/report_for_gus/plot_energy_vs_u_cpd.py
"""
This script runs RCCSD_CPD calculation on a 1D Hubbard w/o PBC
for different ranks of the decomposition. The RCCSD_CPD code
is new (as of Oct 18 2017) with explicit symmetrization of CPD
amplitudes.
"""
import numpy as np
import time
import pickle
from pyscf.lib import logger
from pyscf import scf
from tcc.hubbard import hubbard_from_scf
from tcc.cc_solvers import (classic_solver, root_solver, step_solver)
from tcc.rccsd import RCCSD_UNIT
from tcc.rccsd_cpd import RCCSD_nCPD_LS_T_HUB
from tcc.rccsd_cpd import RCCSD_CPD_LS_T_HUB
# Set up script parameters
# USE_PBC = 'y'
# U_VALUES = np.linspace(1, 5.5, num=20)
# U_VALUES_REFERENCE = np.linspace(1, 4, num=20)
# N = 14
# RANKS_T = np.array([7, 14, 21, 28, ]).astype('int')
# l1 = [3, ] * 12 + [4, ] * 12 + [10, ] * 2
# LAMBDAS = [l1, l1, l1, l1]
USE_PBC = 'y'
U_VALUES = np.linspace(1, 10.0, num=20)
U_VALUES_REFERENCE = np.linspace(1, 10, num=20)
N = 10
RANKS_T = np.array([5, 8, 10, 11, 12]).astype('int')
# l1 = [3, ] * 9 + [7, ] * 8 + [10, ] * 3
l1 = [1, ] * 4 + [3, ] * 13 + [5, ] * 3
l2 = [1, ] * 4 + [3, ] * 10 + [5, ] * 6
l3 = [1, ] * 4 + [3, ] * 5 + [5, ] * 5 + [7, ] * 6
LAMBDAS = [l1, l2, l3, l3, l3]
# USE_PBC = 'y'
# U_VALUES = np.linspace(1, 14.0, num=20)
# U_VALUES_REFERENCE = np.linspace(1, 14, num=20)
# N = 6
# RANKS_T = np.array([3, 4, 5, 6, 7]).astype('int')
# l1 = [3, ] * 12 + [7, ] * 6 + [10, ] * 2
# l2 = [3, ] * 9 + [5, ] * 3 + [7, ] * 5 + [10, ] * 3
# LAMBDAS = [l1, l2, l1, l1, l1]
def run_scfs(N, us, filename):
scf_energies = []
scf_mos = []
scf_mo_energies = []
for idxu, u in enumerate(us):
rhf = hubbard_from_scf(scf.RHF, N, N, u, USE_PBC)
rhf.scf()
scf_energies.append(rhf.e_tot)
scf_mos.append(rhf.mo_coeff)
scf_mo_energies.append(rhf.mo_energy)
results = tuple(
tuple([e_tot, mo_coeff, mo_energy])
for e_tot, mo_coeff, mo_energy
in zip(scf_energies, scf_mos, scf_mo_energies))
with open(filename, 'wb') as fp:
pickle.dump(results, fp)
def calc_energy_vs_u_cpd():
"""
Plot energy of RCCSD-CPD for all corellation strengths
"""
# Set up parameters of the script
us = U_VALUES.copy()
lambdas = LAMBDAS.copy()
rankst = RANKS_T.copy()
results = np.array(us)
print('Running CC-CPD')
# Run all scfs here so we will have same starting points for CC
run_scfs(N, us, 'calculated/{}-site/scfs_different_u.p'.format(N))
with open('calculated/{}-site/scfs_different_u.p'.format(N), 'rb') as fp:
ref_scfs = pickle.load(fp)
for idxr, rank in enumerate(rankst):
energies = []
converged = False
# timb = time.process_time()
amps = None
for idxu, (u, curr_scf) in enumerate(zip(us, ref_scfs)):
tim = time.process_time()
rhf = hubbard_from_scf(scf.RHF, N, N, u, USE_PBC)
rhf.max_cycle = 1
rhf.scf()
e_scf, mo_coeff, mo_energy = curr_scf
cc = RCCSD_CPD_LS_T_HUB(rhf, rankt={'t2': rank},
mo_coeff=mo_coeff,
mo_energy=mo_energy)
if not converged:
amps = None
converged, energy, amps = classic_solver(
cc, lam=lambdas[idxr][idxu], conv_tol_energy=1e-8,
conv_tol_amps=1e-7, max_cycle=40000,
verbose=logger.NOTE)
# converged, energy, amps = step_solver(
# cc, beta=0.7, # (1 - 1. / lambdas[idxr][idxu]),
# conv_tol_energy=1e-8,
# conv_tol_amps=1e-7, max_cycle=20000,
# verbose=logger.NOTE)
if np.isnan(energy):
Warning(
'Warning: N = {}, U = {} '
'Rank = {} did not converge'.format(N, u, rank)
)
energies.append(energy + e_scf)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}\n'.format(
idxu + 1, len(us), rank, elapsed
))
results = np.column_stack((results, energies))
# elapsedb = time.process_time() - timb
# print('Batch {} out of {}, rank = {}, time: {}'.format(
# 0 + 1, len(rankst), rank, elapsedb))
np.savetxt(
'calculated/{}-site/energy_vs_u.txt'.format(N),
results,
header='U ' + ' '.join('R={}'.format(rr) for rr in rankst)
)
us, *energies_l = np.loadtxt(
'calculated/{}-site/energy_vs_u.txt'.format(N), unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, energies)
plt.xlabel('$U$')
plt.ylabel('$E$, H')
plt.title('Energy behavior for different ranks')
fig.show()
def plot_energy_vs_u_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
rankst = RANKS_T.copy()
us, *energies_l = np.loadtxt(
'calculated/{}-site/energy_vs_u.txt'.format(N), unpack=True)
if len(energies_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst)))
fig, ax = plt.subplots()
rankst = rankst # Cut out some elements
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
ax.plot(us, energies_l[idxr],
color=color, marker=None)
u_ref, e_ref = np.loadtxt(
'reference/{}-site/Exact'.format(N), unpack=True)
ax.plot(u_ref, e_ref,
color='k', marker=None)
u_cc, e_cc = np.loadtxt(
'reference/{}-site/RCCSD.txt'.format(N), unpack=True)
ax.plot(u_cc, e_cc,
':k', marker=None)
plt.xlabel('$U / t$')
plt.ylabel('$E$, H')
plt.title('Energy behavior for different ranks, {} sites'.format(N))
# plt.ylim(-14.5, -5.5) # 14 sites
# plt.xlim(1, 5.5)
plt.ylim(-12, 5) # 10 sites
plt.xlim(1, 9)
# plt.ylim(-12, 2) # 6 sites
# plt.xlim(1, 14)
plt.legend(
['R={}'.format(rank) for rank in rankst] + ['Exact', ] + ['RCCSD', ],
loc='upper left'
)
fig.show()
fig.savefig('figures/energy_vs_u_{}_sites.eps'.format(N))
def run_ccsd():
us = U_VALUES_REFERENCE.copy()
from tcc.cc_solvers import residual_diis_solver
energies = []
amps = None
for idxu, u in enumerate(us):
rhf = hubbard_from_scf(scf.RHF, N, N, u, USE_PBC)
rhf.scf()
scf_energy = rhf.e_tot
cc = RCCSD_UNIT(rhf)
converged, energy, amps = residual_diis_solver(cc,
conv_tol_energy=1e-6,
lam=15, amps=amps,
max_cycle=2000)
energies.append(scf_energy + energy)
np.savetxt(
'reference/{}-site/RCCSD.txt'.format(N),
np.column_stack((us, energies)),
header='U E_total'
)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, energies)
plt.xlabel('$U$')
plt.ylabel('$E$, H')
plt.title('Energy behavior for different ranks')
fig.show()
if __name__ == '__main__':
calc_energy_vs_u_cpd()
<file_sep>/report_for_gus/plot_residuals_vs_r_eq.py
"""
This script plots residuals of singles and doubles
in the weak correlation regime versus the rank of nCPD
decomposition for Hubbard model
"""
import pickle
import numpy as np
import time
from pyscf.lib import logger
from pyscf import scf
from tcc.hubbard import hubbard_from_scf
from tcc.cc_solvers import (classic_solver, root_solver)
from tcc.rccsd import RCCSD_UNIT
from tcc.rccsd_cpd import RCCSD_nCPD_LS_T_HUB
from tcc.cpd import ncpd_rebuild
# Set up parameters of the script
N = 10
U = 2
RANKS_T = np.round(N**np.linspace(0.2, 1.8, num=14)).astype('int')
def calc_residuals_vs_r_cpd_eq():
"""
Calculates t1 residuals in nCPD approximated and full CC
at weak correlation
"""
rankst = RANKS_T.copy()
rhf = hubbard_from_scf(scf.RHF, N, N, U, 'y')
rhf.max_cycle = 1
rhf.scf()
with open('calculated/{}-site/amps_and_scf_eq/rhf_results_u_{}.p'.format(N, U), 'rb') as fp:
curr_scf = pickle.load(fp)
e_scf, mo_coeff, mo_energy = curr_scf
with open('calculated/{}-site/amps_and_scf_eq/cc_results_u_{}.p'.format(N, U), 'wb') as fp:
energy_ref, _ = pickle.load(fp)
with open('calculated/{}-site/amps_and_scf_eq/energy_rank_amps_u_{}.p'.format(N, U), 'rb') as fp:
cc_solutions = pickle.load(fp)
r1_results = []
r2_results = []
t2names = ['xlam', 'x1', 'x2', 'x3', 'x4']
for idx, cc_solution in enumerate(cc_solutions):
tim = time.process_time()
energy, rank, amps = cc_solution
cc = RCCSD_nCPD_LS_T_HUB(rhf, rankt={'t2': rank})
h = cc.create_ham()
res_norms = cc.calc_residuals(h, amps).map(np.linalg.norm)
r1_results.append(res_norms.t1)
r2_results.append(res_norms.t2)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}'.format(
idx + 1, len(rankst), rank, elapsed
))
r1_results = np.column_stack((rankst, r1_results))
r2_results = np.column_stack((rankst, r2_results))
np.savetxt(
'calculated/{}-site/r1_vs_rank_u_{}.txt'.format(N, U),
r1_results, header='Rank |r1|', fmt=('%i', '%e',)
)
np.savetxt(
'calculated/{}-site/r2_vs_rank_u_{}.txt'.format(N, U),
r2_results, header='Rank |r2|', fmt=('%i', '%e',)
)
rankst, energies, deltas = np.loadtxt(
'calculated/{}-site/r1_vs_rank_u_{}.txt'.format(N, U), unpack=True)
# Plot
from matplotlib import pyplot as plt
plt.plot(np.log(rankst) / np.log(N), np.log10(np.abs(deltas)))
plt.xlabel('log$_N(R)$')
plt.ylabel('log($|r1|$)')
plt.title('Singles residual dependence on rank in weak correlation regime')
plt.show()
def plot_r1_vs_r_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set data to use
ns = [6, 10, 14, 18, 22]
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(ns)))
fig, ax = plt.subplots()
for n, color in zip(ns, colors):
rankst, _, deltas = np.loadtxt(
'calculated/{}-site/r1_vs_rank_u_{}.txt'.format(n), unpack=True)
ax.plot(np.log(rankst) / np.log(n), np.log10(np.abs(deltas)),
color=color, marker=None)
plt.ylim(-10, 0)
plt.xlabel('log$_N(R)$')
plt.ylabel('log($|r1|$)')
plt.title('Singles residual dependence on rank in weak correlation regime')
plt.legend(['{} sites'.format(n) for n in ns])
fig.show()
fig.savefig('figures/r1_vs_r_u_{}_cpd.eps'.format(U))
def plot_r2_vs_r_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set data to use
ns = [6, 10, 14, 18, 22]
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(ns)))
fig, ax = plt.subplots()
for n, color in zip(ns, colors):
rankst, _, deltas = np.loadtxt(
'calculated/{}-site/r2_vs_rank_u_{}.txt'.format(n), unpack=True)
ax.plot(np.log(rankst) / np.log(n), np.log10(np.abs(deltas)),
color=color, marker=None)
plt.ylim(-10, 0)
plt.xlabel('log$_N(R)$')
plt.ylabel('log($|r2|$)')
plt.title('Singles residual dependence on rank in weak correlation regime')
plt.legend(['{} sites'.format(n) for n in ns])
fig.show()
fig.savefig('figures/r2_vs_r_u_{}_cpd.eps'.format(U))
<file_sep>/report_for_gus/plot_lambdas_vs_r.py
import numpy as np
import pickle
import time
from tcc.hubbard import hubbard_from_scf
from pyscf import scf
from tcc.rccsd_cpd import RCCSD_nCPD_LS_T_HUB
from tcc.cpd import ncpd_renormalize
# Set up parameters of the script
N = 10
RANKS_T = np.array([5, 7, 8, 10, 20, 25, 40]).astype('int')
def calc_lam1_vs_u():
"""
Plot Lambda1 in RCCSD-CPD for all corellation strengths
"""
# Set up parameters of the script
rankst = RANKS_T.copy()
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, rankst[0]), 'rb') as fp:
solutions = pickle.load(fp)
us = [sol[0] for sol in solutions]
results_lam1 = us
for idxr, rank in enumerate(rankst):
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, rank), 'rb') as fp:
solutions = pickle.load(fp)
lam1 = []
for idxu, (u, curr_scf, amps) in enumerate(solutions):
tim = time.process_time()
t2names = ['xlam', 'x1', 'x2', 'x3', 'x4']
t2_cpd = ncpd_renormalize([amps.t2[key]
for key in t2names], sort=True)
lam1.append(t2_cpd[0][0, 0])
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}\n'.format(
idxu + 1, len(solutions), rank, elapsed
))
results_lam1 = np.column_stack((results_lam1, lam1))
np.savetxt(
'calculated/{}-site/lam1_vs_u.txt'.format(N),
results_lam1,
header='U ' + ' '.join('R={}'.format(rr) for rr in rankst)
)
us, *lam1_l = np.loadtxt(
'calculated/{}-site/lam1_vs_u.txt'.format(N), unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, lam1_l[0])
plt.xlabel('$U$')
plt.ylabel('$\lambda^{1}$')
plt.title('Largest mode behavior for different ranks')
fig.show()
def plot_lam1_vs_u():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
rankst = RANKS_T.copy()
us, *lam1_l = np.loadtxt(
'calculated/{}-site/lam1_vs_u.txt'.format(N), unpack=True)
if len(lam1_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst) + 1))
fig, ax = plt.subplots()
rankst = rankst # Cut out some elements
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
ax.plot(us, lam1_l[idxr],
color=color, marker=None)
us_rccsd, *lam1_rccsd = np.loadtxt(
'calculated/{}-site/lam1_lamN_vs_u_rccsd_vovo.txt'.format(N),
unpack=True)
ax.plot(us_rccsd, lam1_rccsd[-1],
color='k', marker='^', ls='')
plt.xlabel('$U / t$')
plt.ylabel('$\lambda^{1}$')
plt.title(
'Largest mode in CPD of $T^2$ amplitudes, {} sites'.format(N)
)
# plt.ylim(None, None)
# plt.xlim(1, 4)
plt.legend(
['R={}'.format(rank) for rank in rankst] +
['RCCSD (SVD in vovo order) '],
loc='upper left'
)
fig.show()
fig.savefig('figures/lam1_vs_u_{}_sites.eps'.format(N))
def calc_l1_ln_vs_u():
"""
Plot Lambda1-LambdaN in RCCSD-CPD for all corellation strengths
for selected rank
"""
# Set up parameters of the script
RANKT = 25
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, RANKT), 'rb') as fp:
solutions = pickle.load(fp)
us = [sol[0] for sol in solutions]
with open('calculated/{}-site/amps_and_scf/amps_and_scf_rank_{}.p'.format(N, RANKT), 'rb') as fp:
solutions = pickle.load(fp)
lambdas = np.zeros([0, RANKT])
for idxu, (u, curr_scf, amps) in enumerate(solutions):
tim = time.process_time()
t2names = ['xlam', 'x1', 'x2', 'x3', 'x4']
t2_cpd = ncpd_renormalize([amps.t2[key]
for key in t2names], sort=True)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}\n'.format(
idxu + 1, len(solutions), RANKT, elapsed))
lambdas = np.row_stack((lambdas, t2_cpd[0]))
results_lam1_lamN = np.column_stack((us, lambdas))
np.savetxt(
'calculated/{}-site/lam1_lamN_vs_u_rank_{}.txt'.format(N, RANKT),
results_lam1_lamN,
header='U ' + ' '.join('lam_{}'.format(rr)
for rr in range(1, RANKT + 1))
)
us, *lambdas_l = np.loadtxt(
'calculated/{}-site/lam1_lamN_vs_u_rank_{}.txt'.format(N, RANKT), unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, lambdas_l[0])
plt.xlabel('$U / t$')
plt.ylabel('$\lambda$')
plt.title('CPD spectrum behavior for different U, rank={}'.format(RANKT))
fig.show()
def calc_l1_ln_vs_u_rccsd():
"""
Plot Lambda1-LambdaN in RCCSD-CPD for all corellation strengths
for selected rank
"""
NUM_SVECS = 40
with open('calculated/{}-site/amps_and_scf_rccsd.p'.format(N), 'rb') as fp:
solutions = pickle.load(fp)
us = [sol[0] for sol in solutions]
with open('calculated/{}-site/amps_and_scf_rccsd.p'.format(N), 'rb') as fp:
solutions = pickle.load(fp)
s1_values = []
s2_values = []
for idxu, (u, curr_scf, amps) in enumerate(solutions):
tim = time.process_time()
shape = amps.t2.shape
t2m1 = amps.t2.transpose(
[0, 2, 1, 3]).reshape(
shape[0] * shape[2], shape[1] * shape[3])
s1 = np.linalg.svd(t2m1, compute_uv=False)
t2m2 = amps.t2.reshape(
shape[0] * shape[1], shape[2] * shape[3])
s2 = np.linalg.svd(t2m2, compute_uv=False)
elapsed = time.process_time() - tim
print('Step {} out of {}, time: {}\n'.format(
idxu + 1, len(solutions), elapsed))
s1_values.append(s1[:NUM_SVECS][::-1])
s2_values.append(s2[:NUM_SVECS][::-1])
results_lam1_lamN_vovo = np.column_stack((
np.array(us)[:, None], np.array(s1_values)))
results_lam1_lamN_vvoo = np.column_stack((
np.array(us)[:, None], np.array(s2_values)))
np.savetxt(
'calculated/{}-site/lam1_lamN_vs_u_rccsd_vovo.txt'.format(N),
results_lam1_lamN_vovo,
header='U '
+ ' '.join('S(vovo)_{}'.format(ii) for ii in range(1, NUM_SVECS + 1))
)
np.savetxt(
'calculated/{}-site/lam1_lamN_vs_u_rccsd_vvoo.txt'.format(N),
results_lam1_lamN_vvoo,
header='U '
+ ' '.join('S(vvoo)_{}'.format(ii) for ii in range(1, NUM_SVECS + 1))
)
us, *lambdas_l = np.loadtxt(
'calculated/{}-site/lam1_lamN_vs_u_rccsd_vovo.txt'.format(N),
unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(us, lambdas_l[0])
plt.xlabel('$U / t$')
plt.ylabel('$\lambda$')
plt.title('SVD spectrum behavior for different U')
fig.show()
def plot_l1_ln_vs_u_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set up parameters of the script
RANKT = 25
us, *lambdas_l = np.loadtxt(
'calculated/{}-site/lam1_lamN_vs_u_rank_{}.txt'.format(N, RANKT), unpack=True)
if len(lambdas_l) != RANKT:
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, RANKT))
fig, ax = plt.subplots()
STEP = 1
for rr, color in zip(range(0, len(colors), STEP), colors):
ax.plot(us, lambdas_l[rr],
color=color, marker=None)
plt.xlabel('$U / t$')
plt.ylabel('$\lambda$')
plt.title(
'CPD spectrum behavior for different U, rank={}'.format(RANKT)
)
# plt.ylim(None, None)
# plt.xlim(1, 4)
import itertools
plt.legend(
['$\lambda^{{ {0} }}$'.format(rr) for rr in range(1, RANKT + 1, STEP)],
loc='upper left', ncol=3
)
fig.show()
fig.savefig('figures/lam1_lamN_vs_u_{}_sites_rank_{}.eps'.format(N, RANKT))
def plot_l1_ln_vs_u_rccsd():
"""
Make plots
"""
ORDER = 'vvoo'
import matplotlib as mpl
from matplotlib import pyplot as plt
us, *lambdas_l = np.loadtxt(
'calculated/{}-site/lam1_lamN_vs_u_rccsd_{}.txt'.format(N, ORDER),
unpack=True)
nvecs = len(lambdas_l)
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, nvecs))
fig, ax = plt.subplots()
STEP = 1
for rr, color in zip(range(0, len(colors), STEP), colors):
ax.plot(us, lambdas_l[rr],
color=color, marker=None)
plt.xlabel('$U / t$')
plt.ylabel('$\lambda$')
plt.title(
'SVD spectrum behavior for different U, full RCCSD, {} order'.format(ORDER))
plt.legend(
['$\lambda^{{ {0} }}$'.format(rr) for rr in range(1, nvecs + 1, STEP)],
loc='upper left', ncol=3
)
# plt.xlim([None, 6.5])
fig.show()
fig.savefig('figures/lam1_lamN_vs_u_{}_sites_rccsd_{}.eps'.format(N, ORDER))
<file_sep>/seminar_talk_cpd_rccsd/run_pycc.py
from pyscf import gto, scf, cc
mol = gto.M(atom='H 0 0 0; H 0 0 1')
mf = scf.RHF(mol).run()
cc.CCSD(mf).run()
from pyscf import gto, scf, cc
mol = gto.M(atom='H 0 0 0; H 0 0 1')
mf = scf.RHF(mol).run()
cc.RCCSD(mf).run()
<file_sep>/seminar_talk_cpd_rccsd/plot_err_vs_r_cpd.py
import numpy as np
import time
from pyscf.lib import logger
def calc_err_vs_r_cpd():
"""
Plot error of RCCSD-CPD vs rank for weak corellation
"""
# Set up parameters of the script
N = 14
U = 2
rankst = np.round(N**np.linspace(0.2, 1.8, num=10)).astype('int')
# Run RHF calculations
from pyscf import scf
from tcc.hubbard import hubbard_from_scf
rhf = hubbard_from_scf(scf.RHF, N, N, U, 'y')
rhf.damp = -4.0
rhf.scf()
from tcc.cc_solvers import (classic_solver, root_solver)
from tcc.rccsd import RCCSD_UNIT
from tcc.rccsd_cpd import RCCSD_CPD_LS_T_HUB
from tensorly.decomposition import parafac
# Run reference calculation
cc_ref = RCCSD_UNIT(rhf)
_, energy_ref, amps_ref = root_solver(cc_ref, conv_tol=1e-10)
energies = []
deltas = []
for idx, rank in enumerate(rankst):
tim = time.process_time()
cc = RCCSD_CPD_LS_T_HUB(rhf, rankt=rank)
xs = parafac(
amps_ref.t2, rank, tol=1e-14
)
amps_guess = cc.types.AMPLITUDES_TYPE(
amps_ref.t1, *xs
)
converged, energy, amps = classic_solver(
cc, lam=1.8, conv_tol_energy=1e-14,
conv_tol_amps=1e-10, max_cycle=10000,
amps=amps_guess, verbose=logger.NOTE)
if not converged:
Warning(
'Warning: N = {}, U = {} '
'Rank = {} did not converge'.format(N, U, rank)
)
energies.append(energy)
deltas.append(energy - energy_ref)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}'.format(
idx + 1, len(rankst), rank, elapsed
))
results = np.column_stack((rankst, energies, deltas))
np.savetxt(
'calculated/{}-site/err_vs_rank.txt'.format(N),
results, header='Rank Energy Delta', fmt=('%i', '%e', '%e')
)
rankst, energies, deltas = np.loadtxt(
'calculated/{}-site/err_vs_rank.txt'.format(N), unpack=True)
# Plot
from matplotlib import pyplot as plt
plt.plot(np.log(rankst)/np.log(N), np.log10(np.abs(deltas)))
plt.xlabel('log$_N(R)$')
plt.ylabel('log($\Delta$)')
plt.title('Error dependence on rank in weak correlation regime')
plt.show()
def plot_err_vs_r_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
# Set data to use
ns = [6, 8, 10, 12, 14]
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(ns)))
fig, ax = plt.subplots()
for n, color in zip(ns, colors):
rankst, _, deltas = np.loadtxt(
'calculated/{}-site/err_vs_rank.txt'.format(n), unpack=True)
ax.plot(np.log(rankst)/np.log(n), np.log10(np.abs(deltas)),
color=color, marker=None)
plt.xlabel('log$_N(R)$')
plt.ylabel('log($\Delta$)')
plt.ylim(-10, 0)
plt.title('Error dependence on rank in weak correlation regime, U = 2')
plt.legend(['{} sites'.format(n) for n in ns])
fig.show()
fig.savefig('figures/err_vs_r_cpd.eps')
if __name__ == '__main__':
calc_err_vs_r_cpd()
<file_sep>/report_for_gus/plot_energy_vs_d_cpd.py
import numpy as np
import time
import pickle
from pyscf.lib import logger
from pyscf import scf
from tcc.hubbard import hubbard_from_scf
from tcc.cc_solvers import (classic_solver, residual_diis_solver)
from tcc.rccsd import RCCSD_UNIT
from tcc.rccsd_cpd import (RCCSD_CPD_LS_T,
RCCSD_nCPD_LS_T)
# Set up parameters of the script
# BASIS = 'sto-3g'
# DISTS = np.linspace(0.8, 2.4, num=25)
# LAMBDAS = [3, ] * 10 + [4, ] * 0 + [6, ] * 10 + [6, ] * 5
# RANKS_T = np.array([2, 4, 5, 6, 8]).astype('int')
BASIS = 'cc-pvdz'
DISTS = np.linspace(0.8, 2.4, num=25)
LAMBDAS = [3, ] * 10 + [4, ] * 0 + [6, ] * 10 + [6, ] * 5
RANKS_T = np.array([2, 3, 4, 5, 6, 8, 40]).astype('int')
DISTS_REFERENCE = np.linspace(0.8, 2.75, num=30)
LAMBDAS_REFERENCE = [3, ] * 10 + [4, ] * 5 + [6, ] * 10 + [6, ] * 5
def run_scfs(mols, filename):
scf_energies = []
scf_mos = []
scf_mo_energies = []
for idm, mol in enumerate(mols):
rhf = scf.density_fit(scf.RHF(mol))
rhf.scf()
scf_energies.append(rhf.e_tot)
scf_mos.append(rhf.mo_coeff)
scf_mo_energies.append(rhf.mo_energy)
results = tuple(
tuple([e_tot, mo_coeff, mo_energy])
for e_tot, mo_coeff, mo_energy
in zip(scf_energies, scf_mos, scf_mo_energies))
with open(filename, 'wb') as fp:
pickle.dump(results, fp)
def calc_energy_vs_d_cpd():
"""
Plot energy of RCCSD-CPD for different distances in dissociation of N2
"""
# Set up parameters of the script
basis = BASIS
dists = DISTS.copy()
lambdas = LAMBDAS.copy()
rankst = RANKS_T.copy()
def make_mol(dist):
from pyscf import gto
mol = gto.Mole()
mol.atom = [
[7, (0., 0., 0.)],
[7, (0., 0., dist)]]
mol.basis = {'N': basis}
mol.build()
return mol
mols = [make_mol(dist) for dist in dists]
results = np.array(dists)
# Run all scfs here so we will have same starting points for CC
run_scfs(mols, 'calculated/{}/scfs_different_dist.p'.format(basis))
with open('calculated/{}/scfs_different_dist.p'.format(basis), 'rb') as fp:
ref_scfs = pickle.load(fp)
for idxr, rank in enumerate(rankst):
lambdas = LAMBDAS.copy()
energies = []
converged = False
# timb = time.process_time()
for idxd, (dist, curr_scf) in enumerate(zip(dists, ref_scfs)):
tim = time.process_time()
rhf = scf.density_fit(scf.RHF(mols[idxd]))
rhf.max_cycle = 1
rhf.scf()
e_scf, mo_coeff, mo_energy = curr_scf
cc = RCCSD_nCPD_LS_T(rhf, rankt={'t2': rank},
mo_coeff=mo_coeff,
mo_energy=mo_energy)
if not converged:
amps = None
converged, energy, amps = classic_solver(
cc, lam=lambdas[idxd], conv_tol_energy=1e-8,
conv_tol_amps=1e-7, max_cycle=30000,
verbose=logger.NOTE, amps=amps)
if not converged:
Warning(
'Warning: D = {} Rank = {}'
' did not converge'.format(dist, rank)
)
energies.append(energy + e_scf)
elapsed = time.process_time() - tim
print('Step {} out of {}, rank = {}, time: {}\n'.format(
idxd + 1, len(dists), rank, elapsed
))
results = np.column_stack((results, energies))
# elapsedb = time.process_time() - timb
# print('Batch {} out of {}, rank = {}, time: {}'.format(
# 0 + 1, len(rankst), rank, elapsedb))
np.savetxt(
'calculated/{}/energy_vs_d.txt'.format(basis),
results,
header='Dist ' + ' '.join('R={}'.format(rr) for rr in rankst)
)
us, *energies_l = np.loadtxt(
'calculated/{}/energy_vs_d.txt'.format(basis), unpack=True)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(dists, energies, marker='o')
plt.xlabel('$D, \AA$')
plt.ylabel('$E$, H')
plt.title('Energy behavior for different ranks')
fig.show()
def plot_energy_vs_d_cpd():
"""
Make plots
"""
import matplotlib as mpl
from matplotlib import pyplot as plt
basis = BASIS
rankst = RANKS_T.copy()
us, *energies_l = np.loadtxt(
'calculated/{}/energy_vs_d.txt'.format(basis), unpack=True)
if len(energies_l) != len(rankst):
raise ValueError('Check what you plot')
cmap = mpl.cm.get_cmap('Set1')
colors = cmap(np.linspace(0, 1, len(rankst)))
fig, ax = plt.subplots()
rankst = rankst # Cut out some elements
for idxr, (rank, color) in enumerate(zip(rankst, colors)):
ax.plot(us, energies_l[idxr],
color=color, marker=None)
d_ref, e_ref = np.loadtxt(
'reference/{}/FCI.txt'.format(basis), unpack=True)
ax.plot(d_ref, e_ref,
color='k', marker=None)
d_cc, e_cc = np.loadtxt(
'reference/{}/gauRCCSD.txt'.format(basis), unpack=True)
ax.plot(d_cc, e_cc,
':k', marker=None)
plt.xlabel('$D, \AA$')
plt.ylabel('$E$, H')
plt.title('Energy behavior for different ranks, $N_2$ ({})'.format(basis))
# plt.ylim(-107.75, -107.2) # sto-3g
# plt.xlim(0.8, 2.2)
plt.legend(
['R={}'.format(rank) for rank in rankst] + ['Exact', ] + ['RCCSD', ],
loc='upper left'
)
fig.show()
fig.savefig('figures/energy_vs_d_{}.eps'.format(basis))
def run_ccsd():
basis = BASIS
dists = DISTS_REFERENCE.copy()
lambdas = LAMBDAS_REFERENCE.copy()
def make_mol(dist):
from pyscf import gto
mol = gto.Mole()
mol.atom = [
[7, (0., 0., 0.)],
[7, (0., 0., dist)]]
mol.basis = {'N': basis}
mol.build()
return mol
mols = [make_mol(dist) for dist in dists]
# Run all scfs here so we will have same starting points for CC
run_scfs(mols, 'reference/{}/scfs_different_dist.p'.format(basis))
with open('reference/{}/scfs_different_dist.p'.format(basis), 'rb') as fp:
ref_scfs = pickle.load(fp)
from tcc.rccsd_mul import RCCSD_MUL_RI
energies = []
amps = None
for idxd, (dist, curr_scf) in enumerate(zip(dists, ref_scfs)):
tim = time.process_time()
rhf = scf.density_fit(scf.RHF(mols[idxd]))
rhf.max_cycle = 1
rhf.scf()
e_scf, mo_coeff, mo_energy = curr_scf
cc = RCCSD_MUL_RI(rhf,
mo_coeff=mo_coeff,
mo_energy=mo_energy)
converged, energy, amps = residual_diis_solver(
cc, conv_tol_energy=1e-9, conv_tol_res=1e-8,
max_cycle=500,
verbose=logger.NOTE, amps=amps)
energies.append(energy + e_scf)
elapsed = time.process_time() - tim
print('Step {} out of {}, dist = {}, time: {}\n'.format(
idxd + 1, len(dists), dist, elapsed
))
np.savetxt(
'reference/{}/RCCSD.txt'.format(basis),
np.column_stack((dists, energies)),
header='U E_total'
)
# Plot
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
plt.plot(dists, energies)
plt.xlabel('$D, \AA$')
plt.ylabel('$E$, H')
plt.title('Energy in RCCSD (RI)')
fig.show()
if __name__ == '__main__':
calc_energy_vs_d_cpd()
<file_sep>/systems/run_system.py
#!/home/ilias/.local/bin/python3.6
"""
These scripts are for running molecular systems
with RCCSD-CPD
"""
import numpy as np
import pickle
import time
import sys
import os
from os.path import isfile, isdir
from pyscf import gto
from pyscf import scf
# Set up global parameters of the script
BASIS = 'cc-pvdz'
RANKS_T_FACTOR = [1, 1.5, 2]
def load_geom(workdir):
"""
Loads geometry from geom.dat in the specified directory
"""
atoms = []
with open(workdir + 'geom.xyz', 'r') as fp:
fp.readline() # Skip first two lines - ugly but works
fp.readline()
for line in fp:
elem, *coords = line.split()
atoms.append([elem, tuple(coords)])
return atoms
def build_rhf(workdir):
print('Running SCF')
if (not isfile(workdir + 'rhf_results.p')
or not isfile(workdir + 'rhf_results.p')):
mol = gto.Mole()
mol.atom = load_geom(workdir)
mol.basis = BASIS
mol.build()
rhf = scf.RHF(mol)
rhf = scf.density_fit(scf.RHF(mol))
rhf.scf()
rhf_results = tuple([rhf.e_tot, rhf.mo_coeff, rhf.mo_energy, mol.atom])
with open(workdir + 'rhf_results.p', 'wb') as fp:
pickle.dump(rhf_results, fp)
np.savetxt(
workdir + 'RHF.txt',
np.array([rhf.e_tot, ]),
header='Energy'
)
def run_cc_ref(workdir):
from pyscf.lib import logger
print('Running CC')
# Restore RHF object
with open(workdir + 'rhf_results.p', 'rb') as fp:
rhf_results = pickle.load(fp)
e_tot, mo_coeff, mo_energy, atom = rhf_results
mol = gto.Mole()
mol.atom = atom
mol.basis = BASIS
mol.build()
rhf = scf.density_fit(scf.RHF(mol))
rhf.max_cycle = 1
rhf.scf()
# Run RCCSD_RI
from tcc.rccsd import RCCSD_DIR_RI
from tcc.cc_solvers import residual_diis_solver
tim = time.process_time()
if (not isfile(workdir + 'ccsd_results.p')
or not isfile(workdir + 'RCCSD.txt')):
cc = RCCSD_DIR_RI(rhf,
mo_coeff=mo_coeff,
mo_energy=mo_energy)
converged, energy, amps = residual_diis_solver(
cc, conv_tol_energy=1e-9, conv_tol_res=1e-8,
max_cycle=500,
verbose=logger.INFO)
ccsd_results = [energy, amps]
with open(workdir + 'ccsd_results.p', 'wb') as fp:
pickle.dump(ccsd_results, fp)
np.savetxt(
workdir + 'RCCSD.txt',
np.array([energy, ]),
header='Energy'
)
elapsed = time.process_time() - tim
print('Done reference RCCSD, time: {}'.format(elapsed))
def run_cc_cpd(workdir):
from pyscf.lib import logger
print('Running CC-CPD')
# Restore RHF object
with open(workdir + 'rhf_results.p', 'rb') as fp:
rhf_results = pickle.load(fp)
e_tot, mo_coeff, mo_energy, atom = rhf_results
mol = gto.Mole()
mol.atom = atom
mol.basis = BASIS
mol.build()
# nbasis = mol.nao_nr()
rhf = scf.density_fit(scf.RHF(mol))
rhf.max_cycle = 1
rhf.scf()
nbasis_ri = rhf.with_df.get_naoaux()
# Get CCSD results to generate initial guess
with open(workdir + 'ccsd_results.p', 'rb') as fp:
energy_ref, amps_ref = pickle.load(fp)
# Run RCCSD_RI_CPD
from tcc.rccsd_cpd import RCCSD_nCPD_LS_T
from tcc.cc_solvers import classic_solver, update_diis_solver
from tcc.tensors import Tensors
from tcc.cpd import ncpd_initialize, als_dense
ranks_t = [int(el * nbasis_ri) for el in RANKS_T_FACTOR]
energies = []
deltas = []
for idxr, rank in enumerate(ranks_t):
tim = time.process_time()
if not isfile(
workdir +
'ccsd_results_rank_{}.p'.format(rank)):
cc = RCCSD_nCPD_LS_T(rhf,
mo_coeff=mo_coeff,
mo_energy=mo_energy)
# Initial guess
t2x = als_dense(
ncpd_initialize(amps_ref.t2.shape, rank),
amps_ref.t2, max_cycle=100, tensor_format='ncpd'
)
t2names = ['xlam', 'x1', 'x2', 'x3', 'x4']
amps_guess = Tensors(t1=amps_ref.t1,
t2=Tensors(zip(t2names, t2x)))
converged, energy, amps = update_diis_solver(
cc, conv_tol_energy=1e-6, conv_tol_res=1e-6,
max_cycle=500,
verbose=logger.INFO,
amps=amps_guess, ndiis=3)
if not converged:
energy = np.nan
ccsd_results = [energy, amps]
with open(workdir +
'ccsd_results_rank_{}.p'.format(rank), 'wb') as fp:
pickle.dump(ccsd_results, fp)
else:
with open(workdir +
'ccsd_results_rank_{}.p'.format(rank), 'rb') as fp:
ccsd_results = pickle.load(fp)
energy, _ = ccsd_results
energies.append(energy)
deltas.append(energy - energy_ref)
elapsed = time.process_time() - tim
print('Step {} out of {} done, rank = {}, time: {}'.format(
idxr + 1, len(ranks_t), rank, elapsed
))
np.savetxt(
workdir + 'RCCSD_CPD.txt',
np.column_stack((ranks_t, energies, deltas)),
header='Rank Energy Delta',
fmt=('%i', '%e', '%e')
)
print('Summary')
print('=========================================')
for idxr, rank in enumerate(ranks_t):
print('{} {}'.format(rank, deltas[idxr]))
print('=========================================')
def calculate_residuals(workdir):
print('Running CC-CPD residuals')
# Restore RHF object
with open(workdir + 'rhf_results.p', 'rb') as fp:
rhf_results = pickle.load(fp)
e_tot, mo_coeff, mo_energy, atom = rhf_results
mol = gto.Mole()
mol.atom = atom
mol.basis = BASIS
mol.build()
# nbasis = mol.nao_nr()
rhf = scf.density_fit(scf.RHF(mol))
rhf.max_cycle = 1
rhf.scf()
nbasis_ri = rhf.with_df.get_naoaux()
# Load RCCSD_RI_CPD results
from tcc.rccsd_cpd import RCCSD_nCPD_LS_T
from tcc.cc_solvers import classic_solver, update_diis_solver
from tcc.tensors import Tensors
from tcc.cpd import ncpd_rebuild
ranks_t = [int(el * nbasis_ri) for el in RANKS_T_FACTOR]
norms_t1 = []
norms_t2 = []
for idxr, rank in enumerate(ranks_t):
if isfile(
workdir +
'ccsd_results_rank_{}.p'.format(rank)):
with open(workdir +
'ccsd_results_rank_{}.p'.format(rank), 'rb') as fp:
ccsd_results = pickle.load(fp)
energy, amps = ccsd_results
# Create cc object
cc = RCCSD_nCPD_LS_T(rhf,
mo_coeff=mo_coeff,
mo_energy=mo_energy)
ham = cc.create_ham()
res = cc.calc_residuals(ham, amps)
# residuals
# res_full = Tensors(
# t1=res.t1,
# t2=ncpd_rebuild([res.t2.xlam, res.t2.x1, res.t2.x2,
# res.t2.x3, res.t2.x4])
# )
norms = res.map(np.linalg.norm)
else:
raise FileNotFoundError(
workdir +
'ccsd_results_rank_{}.p does not exist'.format(rank))
norms_t1.append(norms.t1)
norms_t2.append(norms.t2)
np.savetxt(
workdir + 'RCCSD_CPD_RES.txt',
np.column_stack((ranks_t, norms_t1, norms_t2)),
header='Rank |R1| |R2|',
fmt=('%i', '%e', '%e')
)
print('Summary')
print('=========================================')
for idxr, rank in enumerate(ranks_t):
print('{} {}'.format(rank, norms_t2[idxr]))
print('=========================================')
def collect_table():
"""
Build a table with results
"""
contents = os.listdir()
dirs = [elem for elem in sorted(contents) if isdir(elem)]
cwd = os.getcwd()
row_len = len(RANKS_T_FACTOR)
results = []
for subdir in dirs:
wd = cwd + '/' + subdir + '/'
if isfile(wd + 'RCCSD_CPD.txt'):
ranks, energies, deltas = np.loadtxt(
wd + 'RCCSD_CPD.txt', unpack=True)
else:
energies = [np.nan, ] * row_len
deltas = [np.nan, ] * row_len
if isfile(wd + 'RCCSD_CPD_RES.txt'):
ranks, res_t1, res_t2 = np.loadtxt(
wd + 'RCCSD_CPD_RES.txt', unpack=True)
else:
res_t1 = [np.nan, ] * row_len
res_t2 = [np.nan, ] * row_len
if isfile(wd + 'RCCSD.txt') and isfile(wd + 'RHF.txt'):
energy_ref = (
float(np.loadtxt(
wd + 'RCCSD.txt'))
+ float(np.loadtxt(
wd + 'RHF.txt'))
)
else:
energy_ref = np.nan
results.append((subdir, energy_ref, energies, deltas, res_t2))
with open('RESULTS.txt', 'w') as fp:
fp.write('System & Energy, H & '
+ ' & '.join('{:.1f}*N'.format(rr) for rr in RANKS_T_FACTOR)
+ ' & '
+ ' & '.join('{:.1f}*N'.format(rr) for rr in RANKS_T_FACTOR)
+ '\n')
for res in results:
fp.write(
'{} & '.format(res[0])
+ '{:.3f}'.format(res[1])
+ ' & '
+ ' & '.join('{:.3f}'.format(ee * 1000) for ee in res[3])
+ ' & '
+ ' & '.join('{:.3f}'.format(ee) for ee in res[4])
+ '\n')
def run_all():
"""
Run all systems until we fail!
"""
contents = os.listdir()
dirs = [elem for elem in sorted(contents) if isdir(elem)]
for dirname in dirs:
print('Working on: {}'.format(dirname))
run_dir(dirname + '/')
calculate_residuals(dirname + '/')
collect_table()
def run_dir(wd):
# Run RHF
build_rhf(wd)
# Run RCCSD
run_cc_ref(wd)
# Run RCCSD-CPD
run_cc_cpd(wd)
if __name__ == '__main__':
if (len(sys.argv) != 2 or not isdir(sys.argv[1])):
raise ValueError('usage: run_system.py folder')
wd = sys.argv[1]
wd = wd.rstrip('/') + '/' # Make sure we have the workdir
# with the trailing slash
# run_dir(wd)
# run_all()
collect_table()
| ddf27d08728239fcb39e188e5b05a23b7a6324c1 | [
"Python"
] | 11 | Python | qbit-/tcc-scratch | 909d3df320fc89a426496a612aab395296d1f62a | 81bdf00de97dcdb937b11de2bc33a72f69c75769 |
refs/heads/master | <file_sep>require 'net/http'
@cameraDelay = 1 # Needed for image sync.
@fetchNewImageEvery = '5s'
@camera1Host = "camera1host" ## CHANGE
@camera2Host = "camera2host" ## CHANGE
@camera3Host = "camera3host" ## CHANGE
@camera4Host = "camera4host" ## CHANGE
@camera5Host = "camera5host" ## CHANGE
@cameraPort = "cameraPort" ## CHANGE
@cameraUsername = 'cameraUsername' ## CHANGE
@cameraPassword = '<PASSWORD>' ## CHANGE
@cameraURL = "/img/snapshot.cgi?size=2"
@newFile1 = "assets/images/cameras/snapshot1_new.jpeg"
@oldFile1 = "assets/images/cameras/snapshot1_old.jpeg"
@newFile2 = "assets/images/cameras/snapshot2_new.jpeg"
@oldFile2 = "assets/images/cameras/snapshot2_old.jpeg"
@newFile3 = "assets/images/cameras/snapshot3_new.jpeg"
@oldFile3 = "assets/images/cameras/snapshot3_old.jpeg"
@newFile4 = "assets/images/cameras/snapshot4_new.jpeg"
@oldFile4 = "assets/images/cameras/snapshot4_old.jpeg"
@newFile5 = "assets/images/cameras/snapshot5_new.jpeg"
@oldFile5 = "assets/images/cameras/snapshot5_old.jpeg"
def fetch_image(host,old_file,new_file)
`rm #{old_file}`
`mv #{new_file} #{old_file}`
Net::HTTP.start(host,@cameraPort) do |http|
req = Net::HTTP::Get.new(@cameraURL)
req.basic_auth @cameraUsername, @cameraPassword
response = http.request(req)
open(new_file, "wb") do |file|
file.write(response.body)
end
end
new_file
end
def make_web_friendly(file)
"/" + File.basename(File.dirname(file)) + "/" + File.basename(file)
end
SCHEDULER.every @fetchNewImageEvery, first_in: 0 do
new_file1 = fetch_image(@camera1Host,@oldFile1,@newFile1)
new_file2 = fetch_image(@camera2Host,@oldFile2,@newFile2)
new_file3 = fetch_image(@camera3Host,@oldFile3,@newFile3)
new_file4 = fetch_image(@camera4Host,@oldFile4,@newFile4)
new_file5 = fetch_image(@camera5Host,@oldFile5,@newFile5)
if not File.exists?(@newFile1 && @newFile2 && @newFile3 && @newFile4 && @newFile5)
warn "Failed to Get Camera Image"
end
send_event('camera1', image: make_web_friendly(@oldFile1))
send_event('camera2', image: make_web_friendly(@oldFile2))
send_event('camera3', image: make_web_friendly(@oldFile3))
send_event('camera4', image: make_web_friendly(@oldFile4))
send_event('camera5', image: make_web_friendly(@oldFile5))
sleep(@cameraDelay)
send_event('camera1', image: make_web_friendly(new_file1))
send_event('camera2', image: make_web_friendly(new_file2))
send_event('camera3', image: make_web_friendly(new_file3))
send_event('camera4', image: make_web_friendly(new_file4))
send_event('camera5', image: make_web_friendly(new_file5))
end
| afdee8a5272a84a6f2d3f4ef5eccbae20d0153c4 | [
"Ruby"
] | 1 | Ruby | Beeposent5416/camera-widget | 529e95c590c0a2cd916b171203292e96a706d641 | c0792f47f6541c9fb669c160bb66db772041d7bd |
refs/heads/master | <repo_name>ParisXiao/MoreTextView<file_sep>/README.md
# MoreTextView
### 一个可以展开收起的textview 灵活容易扩展

### 欢迎感兴趣的猿下载使用,对使用疑惑的地方欢迎提出疑问
### android深度技术探讨与论证 420221427
<file_sep>/library/src/main/java/com/sunny/view/MoreTextView.java
/*
* Created by sunny on 18-2-8.
* <p>
*----------Dragon be here!----------/
* ┏┓ ┏┓
* ┏┛┻━━━━━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ ┳┛ ┗┳ ┃
* ┃ ┃
* ┃ ┻ ┃
* ┃ ┃
* ┗━━━┓ ┏━━━┛
* ┃ ┃神兽保佑
* ┃ ┃代码无BUG!
* ┃ ┗━━━━━━━━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━━━━━━━━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
* ━━━━━━神兽出没━━━━━━by:coder-sunny
*
*
* 展开收起的 MoreTextView
*
*/
package com.sunny.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import demo.sunny.com.mylibrary.R;
public class MoreTextView extends LinearLayout implements CompoundButton.OnCheckedChangeListener,ViewTreeObserver.OnPreDrawListener{
private int mMoreSwitchTextSize = 12;
private int mMoreTextSize = 12;
private int mMoreTextColor = Color.parseColor("#3c3c40");
private int mMoreSwitchTextColor = Color.parseColor("#fc9400");
private int mMaxHeight,mMinHeight,mMaxLine;
private int mMinLine = 3;
private int mLineHeight = -1;
private TextView mTextView;
private CheckBox mCheckBox;
private CharSequence [] mMoreSwitchHints = {"展开","收起"};
private Drawable mMoreSwitchDrawable = new ColorDrawable(Color.parseColor("#00000000"));
public MoreTextView(Context context) {
this(context,null);
}
public MoreTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public MoreTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.MoreTextView, defStyleAttr, 0);
mMoreSwitchTextColor = attributes.getColor(R.styleable.MoreTextView_moreSwitchTextColor, mMoreSwitchTextColor);
mMoreTextColor = attributes.getColor(R.styleable.MoreTextView_moreTextColor,mMoreTextColor);
mMinLine = attributes.getInt(R.styleable.MoreTextView_minLine, mMinLine);
mMoreTextSize = attributes.getDimensionPixelSize(R.styleable.MoreTextView_moreTextSize, mMoreTextSize);
mMoreSwitchTextSize = attributes.getDimensionPixelSize(R.styleable.MoreTextView_moreSwitchTextSize, mMoreSwitchTextSize);
mMoreSwitchDrawable = attributes.getDrawable(R.styleable.MoreTextView_moreSwitchDrawable);
attributes.recycle();
init();
}
private void init() {
setOrientation(VERTICAL);
View inflate = LayoutInflater.from(getContext()).inflate(R.layout.layout_more, this, true);
mTextView = inflate.findViewById(R.id.tv_more_content);
mCheckBox = inflate.findViewById(R.id.cb_more_checked);
mTextView.setMinLines(mMinLine);
mTextView.setTextColor(mMoreTextColor);
mTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,mMoreTextSize);
mCheckBox.setTextColor(mMoreSwitchTextColor);
mCheckBox.setTextSize(TypedValue.COMPLEX_UNIT_PX,mMoreSwitchTextSize);
setSwitchDrawable(mMoreSwitchDrawable);
mTextView.getViewTreeObserver().addOnPreDrawListener(this);
}
/**
*
* 设置文本
*
* @param sequence sequence
*/
public void setText(CharSequence sequence){
mTextView.setText(sequence);
mTextView.getViewTreeObserver().addOnPreDrawListener(this);
mCheckBox.setOnCheckedChangeListener(this);
}
/**
*
* 设置按钮的样式
*
*
*
* @param drawable drawable
*/
public void setSwitchStyle(Drawable drawable){
if (drawable == null) {
throw new NullPointerException("drawable is null !!!!!!!!");
}
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
mCheckBox.setCompoundDrawables(drawable,null,null,null);
}
/**
*
* 设置按钮的样式
*
*
*
* @param drawable drawable
*/
private void setSwitchDrawable(Drawable drawable){
if (drawable == null) {
return;
}
setSwitchStyle(drawable);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
mTextView.clearAnimation();
final int deltaValue;
final int startValue = mTextView.getHeight();
if (b) {
//展开
deltaValue = mMaxHeight - startValue;
} else {
//缩进
deltaValue = mMinHeight - startValue;
}
setMoreSwichHints();
Animation animation = new Animation() {
protected void applyTransformation(float interpolatedTime, Transformation t) {
mTextView.setHeight((int) (startValue + deltaValue * interpolatedTime));
if (interpolatedTime == 0) {
t.clear();
}
}
};
animation.setDuration(350);
mTextView.startAnimation(animation);
}
private void setMoreSwichHints() {
if (noDrawable()) {
if (mCheckBox.isChecked()) {
mCheckBox.setText(mMoreSwitchHints[1]);
}else {
mCheckBox.setText(mMoreSwitchHints[0]);
}
}
}
@Override
public boolean onPreDraw() {
mTextView.getViewTreeObserver().removeOnPreDrawListener(this);
mMaxLine = mTextView.getLineCount(); //获取当前最大的line
if (mMaxLine != 0) { // view初始化时 这个值肯定为0
//计算最大的高度
//得到行高
int tempLineHeight = mTextView.getHeight() / mMaxLine;
if (mLineHeight == -1 || tempLineHeight > mLineHeight) {
mLineHeight = tempLineHeight;
}
}
// 求出最大的高度
mMaxHeight = mLineHeight * mMaxLine;
//如果点击了展开 此时更新数据时 我们不想自动关闭它
if (mCheckBox.isChecked()) {
mTextView.setHeight(mMaxHeight);
return false;
}
if (mMaxLine > mMinLine) {
mTextView.setLines(mMinLine); //设置为最小的行数
//获取最小行的高度
mTextView.post(new Runnable() {
@Override
public void run() {
mMinHeight = mTextView.getHeight();
}
});
if (noDrawable()) {
mCheckBox.setText(mMoreSwitchHints[0]);
}
mCheckBox.setVisibility(VISIBLE);
return false;
}else {
if (noDrawable()) {
mCheckBox.setText(mMoreSwitchHints[1]);
}
mCheckBox.setVisibility(GONE);
}
return true;
}
private boolean noDrawable(){
return mMoreSwitchDrawable == null;
}
}
<file_sep>/app/src/main/java/demo/sunny/com/moretextview/MainActivity.kt
package demo.sunny.com.moretextview
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
more.setText("汉皇重色思倾国,御宇多年求不得。\n" +
"杨家有女初长成,养在深闺人未识。\n" +
"天生丽质难自弃,一朝选在君王侧。\n" +
"回眸一笑百媚生,六宫粉黛无颜色。\n" +
"春寒赐浴华清池,温泉水滑洗凝脂。\n" +
"侍儿扶起娇无力,始是新承恩泽时。\n" +
"云鬓花颜金步摇,芙蓉帐暖度春宵。\n" +
"春宵苦短日高起,从此君王不早朝。\n" +
"承欢侍宴无闲暇,春从春游夜专夜。")
}
}
| 434b7a37a6e2ffa9dcbbeb3d830e728974d186da | [
"Markdown",
"Java",
"Kotlin"
] | 3 | Markdown | ParisXiao/MoreTextView | 69899cfabda2e7dd58b0a9f99fa16a84bc50a703 | c854438a396edaa2fb59a5d5f1787960e7c47dce |
refs/heads/master | <repo_name>suki570/fastconsensus<file_sep>/community_ext/community_ext.py
# -*- coding: utf-8 -*-
"""
This package implements several community detection.
Originally based on community aka python-louvain library from <NAME>
(https://github.com/taynaud/python-louvain)
"""
from __future__ import print_function
import array
import random
from math import exp, log, sqrt
from collections import defaultdict
from collections import Counter
import networkx as nx
from .community_status import Status
__author__ = """<NAME> (<EMAIL>)"""
__author__ = """<NAME> (<EMAIL>)"""
# Copyright (C) 2018 by
# <NAME> (<EMAIL>>
# <NAME> (<EMAIL>)
# All rights reserved.
# BSD license.
__PASS_MAX = -1
__MIN = 0.0000001
def partition_at_level(dendrogram, level):
"""Return the partition of the nodes at the given level
A dendrogram is a tree and each level is a partition of the graph nodes.
Level 0 is the first partition, which contains the smallest communities,
and the best is len(dendrogram) - 1.
The higher the level is, the bigger are the communities
Parameters
----------
dendrogram : list of dict
a list of partitions, ie dictionnaries where keys of the i+1 are the
values of the i.
level : int
the level which belongs to [0..len(dendrogram)-1]
Returns
-------
partition : dictionnary
A dictionary where keys are the nodes and the values are the set it
belongs to
Raises
------
KeyError
If the dendrogram is not well formed or the level is too high
See Also
--------
best_partition which directly combines partition_at_level and
generate_dendrogram to obtain the partition of highest modularity
Examples
--------
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> dendrogram = generate_dendrogram(G)
>>> for level in range(len(dendrogram) - 1) :
>>> print("partition at level", level, "is", partition_at_level(dendrogram, level)) # NOQA
"""
partition = dendrogram[0].copy()
for index in range(1, level + 1):
for node, community in partition.items():
partition[node] = dendrogram[index][community]
return partition
def modularity(partition, graph, weight='weight',gamma = 1.):
"""Compute the modularity of a partition of a graph
Parameters
----------
partition : dict
the partition of the nodes, i.e a dictionary where keys are their nodes
and values the communities
graph : networkx.Graph
the networkx graph which is decomposed
weight : str, optional
the key in graph to use as weight. Default to 'weight'
gamma : float
a granularity parameter for the modularity
Returns
-------
modularity : float
The modularity
Raises
------
KeyError
If the partition is not a partition of all graph nodes
ValueError
If the graph has no link
TypeError
If graph is not a networkx.Graph
References
----------
.. 1. Newman, M.E.J. & <NAME>. Finding and evaluating community
structure in networks. Physical Review E 69, 26113(2004).
Examples
--------
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> part = best_partition(G, model = 'ppm')
>>> modularity(part, G)
"""
if graph.is_directed():
raise TypeError("Bad graph type, use only non directed graph")
inc = dict([])
deg = dict([])
links = graph.size(weight=weight)
if links == 0:
raise ValueError("A graph without link has an undefined modularity")
for node in graph:
com = partition[node]
deg[com] = deg.get(com, 0.) + graph.degree(node, weight=weight)
for neighbor, datas in graph[node].items():
edge_weight = datas.get(weight, 1)
if partition[neighbor] == com:
if neighbor == node:
inc[com] = inc.get(com, 0.) + float(edge_weight)
else:
inc[com] = inc.get(com, 0.) + float(edge_weight) / 2.
res = 0.
for com in set(partition.values()):
res += (inc.get(com, 0.) / links) - \
gamma * (deg.get(com, 0.) / (2. * links)) ** 2
return res
def best_partition(graph, model=None, partition=None,
weight='weight', resolution=1., randomize=False, pars = None):
assert model in ('dcppm','ppm','ilfr','ilfrs'), "Unknown model specified"
"""Compute the partition of the graph nodes which maximises the modularity
(or try..) using the Louvain heuristices
This is the partition of highest modularity, i.e. the highest partition
of the dendrogram generated by the Louvain algorithm.
Parameters
----------
graph : networkx.Graph
the networkx graph which is decomposed
model : string
should be 'ilfr', 'ilfrs', 'ppm' or 'dcppm'
partition : dict, optional
the algorithm will start using this partition of the nodes.
It's a dictionary where keys are their nodes and values the communities
weight : str, optional
the key in graph to use as weight. Default to 'weight'
resolution : double, optional
Will change the size of the communities, default to 1.
represents the time described in
"Laplacian Dynamics and Multiscale Modular Structure in Networks",
<NAME>, <NAME>, <NAME>
randomize : boolean, optional
Will randomize the node evaluation order and the community evaluation
order to get different partitions at each call
pars : dict, optional
the dict with 'mu' or 'gamma' key and a float value.
Use 'mu' within (0,1) for 'ilfr' and 'ilfrs' models and
'gamma' within (0,inf) for 'ppm' and 'dcppm' models.
Also, for 'ppm' model it's possible to use two optional parameters,
fixedPin and fixedPout, they could be used to modify the gamma calculation.
Returns
-------
partition : dictionary
The partition, with communities numbered from 0 to number of communities
Raises
------
NetworkXError
If the graph is not Eulerian.
See Also
--------
generate_dendrogram to obtain all the decompositions levels
Notes
-----
Uses Louvain algorithm
References
----------
.. 1. Blondel, V.D. et al. Fast unfolding of communities in
large networks. J. Stat. Mech 10008, 1-12(2008).
Examples
--------
>>> #Basic usage
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> part = best_partition(G, model='ppm')
>>> #other example to display a graph with its community :
>>> #better with karate_graph() as defined in networkx examples
>>> #erdos renyi don't have true community structure
>>> G = nx.erdos_renyi_graph(30, 0.05)
>>> #first compute the best partition
>>> partition = best_partition(G, model='ppm')
>>> #drawing
>>> size = float(len(set(partition.values())))
>>> pos = nx.spring_layout(G)
>>> count = 0.
>>> for com in set(partition.values()) :
>>> count += 1.
>>> list_nodes = [nodes for nodes in partition.keys()
>>> if partition[nodes] == com]
>>> nx.draw_networkx_nodes(G, pos, list_nodes, node_size = 20,
node_color = str(count / size))
>>> nx.draw_networkx_edges(G, pos, alpha=0.5)
>>> plt.show()
"""
dendo = generate_dendrogram(graph,
model,
partition,
weight,
resolution,
randomize,
pars=pars)
return partition_at_level(dendo, len(dendo) - 1)
def generate_dendrogram(graph,
model=None,
part_init=None,
weight='weight',
resolution=1.,
randomize=False,
pars = None):
"""Find communities in the graph and return the associated dendrogram
A dendrogram is a tree and each level is a partition of the graph nodes.
Level 0 is the first partition, which contains the smallest communities,
and the best is len(dendrogram) - 1. The higher the level is, the bigger
are the communities
Parameters
----------
graph : networkx.Graph
the networkx graph which will be decomposed
model : string
should be 'ilfr', 'ilfrs', 'ppm' or 'dcppm'
part_init : dict, optional
the algorithm will start using this partition of the nodes. It's a
dictionary where keys are their nodes and values the communities
weight : str, optional
the key in graph to use as weight. Default to 'weight'
resolution : double, optional
Will change the size of the communities, default to 1.
represents the time described in
"Laplacian Dynamics and Multiscale Modular Structure in Networks",
<NAME>, <NAME>, <NAME>
pars : dict, optional
the dict with 'mu' or 'gamma' key and a float value.
Use 'mu' within (0,1) for 'ilfr' and 'ilfrs' models and
'gamma' within (0,inf) for 'ppm' and 'dcppm' models.
Also, for 'ppm' model it's possible to use two optional parameters,
fixedPin and fixedPout, they could be used to modify the gamma calculation.
Returns
-------
dendrogram : list of dictionaries
a list of partitions, ie dictionnaries where keys of the i+1 are the
values of the i. and where keys of the first are the nodes of graph
Raises
------
TypeError
If the graph is not a networkx.Graph
See Also
--------
best_partition
Notes
-----
Uses Louvain algorithm
References
----------
.. 1. Blondel, V.D. et al. Fast unfolding of communities in large
networks. J. Stat. Mech 10008, 1-12(2008).
Examples
--------
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> dendo = generate_dendrogram(G, model='ppm')
>>> for level in range(len(dendo) - 1) :
>>> print("partition at level", level,
>>> "is", partition_at_level(dendo, level))
:param weight:
:type weight:
"""
if graph.is_directed():
raise TypeError("Bad graph type, use only non directed graph")
# special case, when there is no link
# the best partition is everyone in its community
if graph.number_of_edges() == 0:
part = dict([])
for node in graph.nodes():
part[node] = node
return [part]
current_graph = graph.copy()
status = Status()
status.init(current_graph, weight, part_init)
status_list = list()
__one_level(current_graph, status, weight, resolution, randomize, model=model, pars=pars)
new_mod = __modularity(status,model=model,pars=pars)
partition = __renumber(status.node2com)
status_list.append(partition)
mod = new_mod
current_graph = induced_graph(partition, current_graph, weight)
status.init(current_graph, weight, raw_partition = __transit(partition,status.rawnode2node), raw_graph=graph)
while True:
__one_level(current_graph, status, weight, resolution, randomize, model=model, pars=pars)
new_mod = __modularity(status,model=model,pars=pars)
if new_mod - mod < __MIN:
break
partition = __renumber(status.node2com)
status_list.append(partition)
mod = new_mod
current_graph = induced_graph(partition, current_graph, weight)
status.init(current_graph, weight, raw_partition = __transit(partition,status.rawnode2node), raw_graph=graph)
return status_list[:]
def induced_graph(partition, graph, weight="weight"):
"""Produce the graph where nodes are the communities
there is a link of weight w between communities if the sum of the weights
of the links between their elements is w
Parameters
----------
partition : dict
a dictionary where keys are graph nodes and values the part the node
belongs to
graph : networkx.Graph
the initial graph
weight : str, optional
the key in graph to use as weight. Default to 'weight'
Returns
-------
g : networkx.Graph
a networkx graph where nodes are the parts
Examples
--------
>>> n = 5
>>> g = nx.complete_graph(2*n)
>>> part = dict([])
>>> for node in g.nodes() :
>>> part[node] = node % 2
>>> ind = induced_graph(part, g)
>>> goal = nx.Graph()
>>> goal.add_weighted_edges_from([(0,1,n*n),(0,0,n*(n-1)/2), (1, 1, n*(n-1)/2)]) # NOQA
>>> nx.is_isomorphic(int, goal)
True
"""
ret = nx.Graph()
ret.add_nodes_from(partition.values())
for node1, node2, datas in graph.edges(data=True):
edge_weight = datas.get(weight, 1)
com1 = partition[node1]
com2 = partition[node2]
w_prec = ret.get_edge_data(com1, com2, {weight: 0}).get(weight, 1)
ret.add_edge(com1, com2, **{weight: w_prec + edge_weight})
return ret
def __renumber(dictionary):
"""Renumber the values of the dictionary from 0 to n
"""
count = 0
ret = dictionary.copy()
new_values = dict([])
for key in dictionary.keys():
value = dictionary[key]
new_value = new_values.get(value, -1)
if new_value == -1:
new_values[value] = count
new_value = count
count += 1
ret[key] = new_value
return ret
def __transit(partition,rawnodepart):
"""Map partition of partition to the partition of original nodes
"""
res = dict()
for n,mn in rawnodepart.items():
res[n] = partition[mn]
return res
def load_binary(data):
"""Load binary graph as used by the cpp implementation of this algorithm
"""
data = open(data, "rb")
reader = array.array("I")
reader.fromfile(data, 1)
num_nodes = reader.pop()
reader = array.array("I")
reader.fromfile(data, num_nodes)
cum_deg = reader.tolist()
num_links = reader.pop()
reader = array.array("I")
reader.fromfile(data, num_links)
links = reader.tolist()
graph = nx.Graph()
graph.add_nodes_from(range(num_nodes))
prec_deg = 0
for index in range(num_nodes):
last_deg = cum_deg[index]
neighbors = links[prec_deg:last_deg]
graph.add_edges_from([(index, int(neigh)) for neigh in neighbors])
prec_deg = last_deg
return graph
def __randomly(seq, randomize):
""" Convert sequence or iterable to an iterable in random order if
randomize """
if randomize:
shuffled = list(seq)
random.shuffle(shuffled)
return iter(shuffled)
return sorted(seq)
def __get_safe_par(model,pars=None):
""" Make sure "mu" par is in (0,1) and "gamma" par is in (0,inf)
"""
if not pars:
par = 1.-__MIN
else:
if model in ('ilfrs','ilfr'):
try:
par = pars.get('mu',1.)
except:
par = 1.
par = max(par,__MIN)
par = min(par,1.-__MIN)
elif model in ('dcppm','ppm'):
try:
par = pars.get('gamma',1.)
except:
par = 1.
par = max(par,__MIN)
return par
def __one_level(graph, status, weight_key, resolution, randomize, model='ppm', pars = None):
"""Compute one level of communities
"""
modified = True
nb_pass_done = 0
cur_mod = __modularity(status,model=model,pars=pars)
new_mod = cur_mod
par = __get_safe_par(model,pars)
__E = float(status.total_weight)
__2E = 2.*__E
mpar = 1.-par
__l2E = 0.
__l2Epar = 0.
__l2Epar2 = 0.
if __E>0:
__l2E = log(__2E)
if mpar>0.:
__l2Epar = log(__2E*mpar/par)
if mpar>0.:
__l2Epar2 = (log(par/mpar)-__l2E)
__lpar = log(par)
__l2Epar3 = (__lpar-__l2E)
__par2E = par/__2E
P2 = len(status.rawnode2node)
P2 = P2*(P2-1)/2.
while modified and nb_pass_done != __PASS_MAX:
cur_mod = new_mod
modified = False
nb_pass_done += 1
for node in __randomly(graph.nodes(), randomize):
com_node = status.node2com[node]
neigh_communities = __neighcom(node, graph, status, weight_key)
v_in_degree = neigh_communities.get(com_node,0)
if model=='dcppm':
com_degree = status.degrees.get(com_node, 0.)
v_degree = status.gdegrees.get(node, 0.)
pre_calc1 = par * v_degree / __2E
remove_cost = pre_calc1 * (com_degree - v_degree) - v_in_degree
elif model == 'ilfrs':
com_degree = status.degrees.get(com_node, 0.)
v_degree = status.gdegrees.get(node, 0.)
v_loops = graph.get_edge_data(node, node, default={weight_key: 0}).get(weight_key, 1)
com_in_degree = status.internals.get(com_node, 0.)
remove_cost = v_in_degree*__l2Epar2
if com_degree>0.:
remove_cost += com_in_degree * log(com_degree)
else:
remove_cost += com_in_degree / __MIN
if com_degree > v_degree: remove_cost -= (com_in_degree - v_loops - v_in_degree) * log(com_degree - v_degree)
elif model == 'ilfr':
com_degree = status.degrees.get(com_node, 0.)
v_degree = status.gdegrees.get(node, 0.)
v_loops = graph.get_edge_data(node, node, default={weight_key: 0}).get(weight_key, 1)
com_in_degree = status.internals.get(com_node, 0.)
remove_cost = v_in_degree*__l2Epar3
if com_degree >0: remove_cost -= com_in_degree*log((mpar/com_degree)+__par2E)
if com_degree-v_degree>0: remove_cost += (com_in_degree-v_in_degree-v_loops)*log((mpar/(com_degree-v_degree))+__par2E)
else:
volume_node = status.node2size[node]
volume_cluster = status.com2size[com_node] - volume_node
pre_calc1 = par*volume_node/P2
remove_cost = volume_cluster*pre_calc1 - v_in_degree/__E
__remove(node, com_node,
neigh_communities.get(com_node, 0.), status)
best_com = com_node
best_increase = 0.
for com, dnc in __randomly(neigh_communities.items(),
randomize):
if model=='dcppm':
com_degree = status.degrees.get(com, 0.)
add_cost = dnc - pre_calc1 * com_degree
elif model == 'ilfrs':
com_in_degree = status.internals.get(com, 0.)
com_degree = status.degrees.get(com, 0.)
add_cost = dnc*__l2Epar
add_cost += com_in_degree*log(com_degree)
add_cost -= (com_in_degree + v_loops + dnc) * log(com_degree + v_degree)
elif model == 'ilfr':
com_in_degree = status.internals.get(com, 0.)
com_degree = status.degrees.get(com, 0.)
add_cost = dnc*(__l2E-__lpar)
if com_degree >0: add_cost -= com_in_degree*log((mpar/com_degree)+__par2E)
if com_degree+v_degree>0: add_cost += (com_in_degree+dnc+v_loops)*log((mpar/(com_degree+v_degree))+__par2E)
else:
volume_cluster = status.com2size[com]
add_cost = dnc/__E - volume_cluster*pre_calc1
incr = add_cost + remove_cost
if incr > best_increase:
best_increase = incr
best_com = com
__insert(node, best_com,
neigh_communities.get(best_com, 0.), status)
if best_com != com_node:
modified = True
if modified:
new_mod = __modularity(status,model=model,pars=pars)
if new_mod - cur_mod < __MIN:
break
def __neighcom(node, graph, status, weight_key):
"""
Compute the communities in the neighborhood of node in the graph given
with the decomposition node2com
"""
weights = {}
for neighbor, datas in graph[node].items():
if neighbor != node:
edge_weight = datas.get(weight_key, 1)
neighborcom = status.node2com[neighbor]
weights[neighborcom] = weights.get(neighborcom, 0) + edge_weight
return weights
def __remove(node, com, weight, status):
""" Remove node from community com and modify status"""
status.degrees[com] = (status.degrees.get(com, 0.)
- status.gdegrees.get(node, 0.))
status.degrees[-1] = status.degrees.get(-1, 0.)+status.gdegrees.get(node, 0.)
status.internals[com] = float(status.internals.get(com, 0.) -
weight - status.loops.get(node, 0.))
status.node2com[node] = -1
status.internals[-1] = status.loops.get(node, 0.)
status.com2size[com] -= status.node2size[node]
def __insert(node, com, weight, status):
""" Insert node into community and modify status"""
status.node2com[node] = com
status.degrees[-1] = status.degrees.get(-1, 0.)-status.gdegrees.get(node, 0.)
status.degrees[com] = (status.degrees.get(com, 0.) +
status.gdegrees.get(node, 0.))
status.internals[com] = float(status.internals.get(com, 0.) +
weight + status.loops.get(node, 0.))
status.com2size[com] += status.node2size[node]
def __get_DLD(status):
""" Some intermediate optimization
"""
return sum(map(lambda x:x*log(x),filter(lambda x:x>0,status.rawnode2degree.values())))
def __get_es(status):
""" Some intermediate optimization
"""
E = float(status.total_weight)
Ein = 0
degrees_squared = 0.
for community in set(status.node2com.values()):
Ein += status.internals.get(community, 0.)
tmp = status.degrees.get(community, 0.)
degrees_squared += tmp*tmp #status.degrees.get(community, 0.)**2
Eout = max(0.,E - Ein)
return E,Ein,Eout,degrees_squared
def __get_SUMDC2_P2in(status):
""" Some intermediate optimization
"""
DC = defaultdict(int)
VC = defaultdict(int)
for n,mn in status.rawnode2node.items():
DC[status.node2com[mn]] += status.rawnode2degree.get(n,0)
VC[status.node2com[mn]] += 1
SUMDC2 = 0
P2in = 0
for c,d in DC.items():
SUMDC2 += d*d
P2in += VC[c]*(VC[c]-1)/2.
return SUMDC2,P2in
def __get_pin_pout(status):
""" Some intermediate optimization
"""
E,Ein,Eout,degrees_squared = __get_es(status)
SUMDC2,P2in = __get_SUMDC2_P2in(status)
Pin = 4.*Ein*E/SUMDC2
if Eout == 0:
Pout = __MIN
else:
Pout = 4.*Eout*E/(4.*E*E-SUMDC2)
return Pin,Pout,E,Ein,Eout,degrees_squared,SUMDC2,P2in
def __modularity(status,model='ppm',pars = None):
"""
Fast compute the log likelihood of the partition of the graph using
status precomputed
"""
par = __get_safe_par(model,pars)
if not pars: pars = {}
if model=='dcppm':
links = float(status.total_weight)
result = 0.
for community in set(status.node2com.values()):
in_degree = status.internals.get(community, 0.)
degree = status.degrees.get(community, 0.)
if links > 0:
result += in_degree / links - par * ((degree / (2. * links)) ** 2)
return result
elif model == 'ilfrs':
E,Ein,Eout,_ = __get_es(status)
result = 0.
par = max(par,__MIN)
par = min(par,1.-__MIN)
result += Eout * log( par )
result += Ein * log( 1 - par )
result += - Eout * log( 2*E )
for community in set(status.node2com.values()):
degree = status.degrees.get(community, 0.)
if degree>0:
result -= status.internals.get(community, 0.)*log(degree)
result -= E
result += __get_DLD(status)
return result
elif model == 'ilfr':
E,_,Eout,_ = __get_es(status)
DLD = __get_DLD(status)
par = max(par,__MIN)
logl = Eout*log(par)-Eout*log(2*E)+DLD-E
for community in set(status.node2com.values()):
degree = status.degrees.get(community, 0.)
if degree>0:
logl += status.internals.get(community, 0.)*log(((1.-par)/degree)+float(par)/(2.*E))
return logl
else:
E,Ein,Eout,_ = __get_es(status)
_,P2in = __get_SUMDC2_P2in(status)
P2 = len(status.rawnode2node)
P2 = P2*(P2-1)/2.
P2out = P2 - P2in
P2in = max(P2in,__MIN)
P2out = max(P2out,__MIN)
return (Ein - par*P2in*E/P2)/E
def model_log_likelihood(graph,part_init,model,weight='weight',pars=None):
""" Estimate log likelihood of the given partition of the graph considering the given model
and model's parameter value.
Parameters
----------
graph : networkx.Graph
the networkx graph which is decomposed
part_init : dict
the partition of the nodes, i.e a dictionary where keys are their nodes
and values the communities
model : string
should be 'ilfr', 'ilfrs', 'ppm' or 'dcppm'
pars : dict
the dict with 'mu' or 'gamma' key and a float value.
Use 'mu' within (0,1) for 'ilfr' and 'ilfrs' models and
'gamma' within (0,inf) for 'ppm' and 'dcppm' models.
Also, for 'ppm' model it's possible to use two optional parameters,
fixedPin and fixedPout, they could be used to modify the gamma calculation.
weight : str, optional
the key in graph to use as weight. Default to 'weight'
Returns
-------
r : float
log likelihood of the given partition considering the graph, the model and its parameter
Examples
--------
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> partition = best_partition(G, model='ppm', pars={'gamma':0.5})
>>> model_log_likelihood(G,partition,model='ppm',pars={'gamma':0.5})
"""
current_graph = graph.copy()
status = Status()
status.init(current_graph, weight, part_init)
assert model in ('dcppm','ppm','ilfr','ilfrs'), "Unknown model specified"
par = __get_safe_par(model,pars)
if not pars: pars = {}
if model == 'dcppm':
pin,pout,E,Ein,Eout,degrees_squared,_,_ = __get_pin_pout(status)
DLD = __get_DLD(status)
result = 0.
pin = max(pin,__MIN)
pout = max(pout,__MIN)
result += Ein*(log(pin)-log(pout))
result -= (pin-pout)*degrees_squared/(4.*E)
result += DLD
result += E*log(pout)
result -= E*pout
result -= E*log(2.*E)
return result
elif model in ('ilfr', 'ilfrs'):
if not pars.get('mu',None): # is None:
return __modularity(status,model=model,pars={'mu':estimate_mu(graph,part_init)})
else:
return __modularity(status,model=model,pars=pars)
elif model == 'ppm':
E,Ein,Eout,_ = __get_es(status)
_,P2in = __get_SUMDC2_P2in(status)
P2 = len(status.rawnode2node)
P2 = P2*(P2-1)/2.
P2out = P2 - P2in
P2in = max(P2in,__MIN)
P2out = max(P2out,__MIN)
Pin = Ein/P2in
Pout = Eout/P2out
ext_mod = -Eout - Ein
if 'fixedPin' in pars:
Pin = pars['fixedPin']
ext_mod += Ein - P2in*pars['fixedPin']
if 'fixedPout' in pars:
Pout = pars['fixedPout']
ext_mod += Eout - P2out*pars['fixedPout']
if Ein > 0.:
ext_mod += Ein*log(Pin)
if Eout > 0.:
ext_mod += Eout*log(Pout)
return ext_mod
def estimate_gamma(graph,part_init,weight='weight',model='ppm',pars=None):
""" Estimate the best gamma value given the model ("ppm" or "dcppm"),
the graph, its partition and some optional parameters.
Parameters
----------
graph : networkx.Graph
the networkx graph which is decomposed
part_init : dict
the partition of the nodes, i.e a dictionary where keys are their nodes
and values the communities
model : string
should be 'ppm' or 'dcppm'
weight : str, optional
the key in graph to use as weight. Default to 'weight'
pars : dict, optional
the dict with two optional parameters for 'ppm' model,
fixedPin and fixedPout, could be used to modify the gamma calculation.
Returns
-------
r : float
the estimation of the gamma value considering the graph and its partition
Examples
--------
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> partition = best_partition(G, model='ppm', pars={'gamma':0.5})
>>> estimate_gamma(G, partition, model='ppm')
"""
current_graph = graph.copy()
status = Status()
status.init(current_graph, weight, part_init)
if not pars: pars = {}
if model == 'dcppm':
Pin,Pout,_,_,_,_,_,_ = __get_pin_pout(status)
Pin = max(Pin,__MIN)
Pout = max(Pout,__MIN)
return (Pin-Pout)/(log(Pin)-log(Pout))
else:
E,Ein,Eout,_ = __get_es(status)
_,P2in = __get_SUMDC2_P2in(status)
P2 = len(status.rawnode2node)
P2 = P2*(P2-1)/2.
P2out = P2 - P2in
P2in = max(P2in,__MIN)
P2out = max(P2out,__MIN)
Pin = Ein/P2in
Pout = Eout/P2out
if 'fixedPin' in pars:
Pin = pars['fixedPin']
if 'fixedPout' in pars:
Pout = pars['fixedPout']
if Pin == 0.: Pin = __MIN
if Pout == 0.: Pout = __MIN
return P2 * (Pin - Pout) / (E * (log(Pin) - log(Pout)))
def estimate_mu(graph,partition):
""" Estimate the best mu value given the graph and its partition,
should be used for the "ilfrs" model
Parameters
----------
graph : networkx.Graph
the networkx graph which is decomposed
partition : dict
the partition of the nodes, i.e a dictionary where keys are their nodes
and values the communities
Returns
-------
r : float
the estimation of the mu value considering the graph and its partition
Examples
--------
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> partition = best_partition(G, model='ilfrs', pars={'mu':0.5})
>>> estimate_mu(G, partition)
"""
Eout = 0
Gsize = graph.size()
for n1,n2 in graph.edges(): #links:
if partition[n1] != partition[n2]:
Eout += 1
return float(Eout)/Gsize
def ilfr_mu_loglikelihood(graph,partition,current_mu=None,model=None,weight='weight'):
""" Compute log likelihood for the given mu value considering
the graph and the partition.
Parameters
----------
graph : networkx.Graph
the networkx graph which is decomposed
partition : dict
the partition of the nodes, i.e a dictionary where keys are their nodes
and values the communities
current_mu : float
the given value of the mu parameter
model : string
should always be 'ilfr', this parameter added for unification
weight : str, optional
the key in graph to use as weight. Default to 'weight'
Returns
-------
r : float
log likelihood of the given mu value considering the graph and its partition
Examples
--------
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> partition = best_partition(G, model='ilfr', pars={'mu':0.5})
>>> ilfr_mu_loglikelihood(G, partition, 0.5, model='ilfr')
"""
if model == 'ilfr':
current_graph = graph.copy()
status = Status()
status.init(current_graph, weight, partition)
E,_,Eout,_ = __get_es(status)
if current_mu is None: current_mu = Eout/float(E)
current_mu = max(current_mu,__MIN)
current_mu = min(current_mu,1.-__MIN)
res_mu = Eout*log(current_mu)
for community in set(status.node2com.values()):
degree = status.degrees.get(community, 0.)
in_degree = 2*status.internals.get(community, 0.)
if degree>0:
res_mu += in_degree*log(((1.-current_mu)/degree)+current_mu/(2.*E))/2.
return res_mu
return None
def _eta(data):
""" Compute eta for NMI calculation
"""
# if len(data) <= 1: return 0
ldata = len(list(data))
if ldata <= 1: return 0
_exp = exp(1)
counts = Counter()
for d in data:
counts[d] += 1
# probs = [float(c) / len(data) for c in counts.values()]
probs = [float(c) / ldata for c in counts.values()]
probs = [p for p in probs if p > 0.]
ent = 0
for p in probs:
if p > 0.:
ent -= p * log(p, _exp)
return ent
def _nmi(x, y):
""" Calculate NMI without including extra libraries
"""
# print(x,y)
# print(list(x))
sum_mi = 0.0
x_value_list = list(set(x))
y_value_list = list(set(y))
lx = len(list(x))
ly = len(list(y))
Px = []
for xval in x_value_list:
# Px.append( len(filter(lambda q:q==xval,x))/float(lx) )
Px.append( len(list(filter(lambda q:q==xval,x)))/float(lx) )
Py = []
for yval in y_value_list:
# Py.append( len(filter(lambda q:q==yval,y))/float(ly) )
Py.append( len(list(filter(lambda q:q==yval,y)))/float(ly) )
for i in range(len(x_value_list)):
if Px[i] ==0.:
continue
sy = []
for j,yj in enumerate(y):
if x[j] == x_value_list[i]:
sy.append( yj )
if len(sy)== 0:
continue
pxy = []
for yval in y_value_list:
# pxy.append( len(filter(lambda q:q==yval,sy))/float(ly) )
pxy.append( len(list(filter(lambda q:q==yval,sy)))/float(ly) )
t = []
for j,q in enumerate(Py):
if q>0:
t.append( pxy[j]/Py[j] / Px[i])
else:
t.append( -1 )
if t[-1]>0:
sum_mi += (pxy[j]*log( t[-1]) )
eta_xy = _eta(x)*_eta(y)
if eta_xy == 0.: return 0.,0.
return sum_mi/sqrt(_eta(x)*_eta(y)),2.*sum_mi/(_eta(x)+_eta(y))
def compare_partitions(p1,p2,safe=True):
"""Compute three metrics of two partitions similarity:
* Rand index
* Jaccard index
* NMI
Parameters
----------
p1 : dict
a first partition
p2 : dict
a second partition
Returns
-------
r : dict
with keys 'rand', 'jaccard', 'nmi'
Examples
--------
>>> G=nx.erdos_renyi_graph(100, 0.01)
>>> part1 = best_partition(G, model='ppm', pars={'gamma':0.5})
>>> part2 = best_partition(G, model='dcppm', pars={'gamma':0.5})
>>> compare_partitions(part1, part2)
"""
assert not set(p1.keys())^set(p2.keys()) or not safe, 'You tried to compare partitions with different numbers of nodes. Consider using safe=False flag for compare_partitions() call.'
p1_sets = defaultdict(set)
p2_sets = defaultdict(set)
[p1_sets[item[1]].add(item[0]) for item in p1.items()]
[p2_sets[item[1]].add(item[0]) for item in p2.items()]
p1_sets = p1_sets.values()
p2_sets = p2_sets.values()
cross_tab = [[0, 0], [0, 0]]
for a1, s1 in enumerate(p1_sets):
for a2, s2 in enumerate(p2_sets):
common = len(s1 & s2)
l1 = len(s1) - common
l2 = len(s2) - common
cross_tab[0][0] += common * (common-1)
cross_tab[1][0] += common * l2
cross_tab[0][1] += l1 * common
cross_tab[1][1] += l1 * l2
[[a00, a01], [a10, a11]] = cross_tab
# print(p1)
# print(p2)
p1_vec = list(map(lambda x:x[1],sorted(p1.items(),key=lambda x:x[0])))
p2_vec = list(map(lambda x:x[1],sorted(p2.items(),key=lambda x:x[0])))
# p1_vec = list(p1_vec)[:]
# print(list(p1_vec)[:])
nmis = _nmi(p1_vec,p2_vec)
res = {
'nmi': nmis[0],
'nmi_arithm': nmis[1],
}
if (a00 + a01 + a10 + a11) == 0:
res['rand'] = 1.
else:
res['rand'] = float(a00 + a11) / (a00 + a01 + a10 + a11)
if (a01 + a10 + a00) == 0:
res['jaccard'] = 1.
else:
res['jaccard'] = float(a00) / (a01 + a10 + a00)
return res
<file_sep>/fast_consensus.py
import networkx as nx
import numpy as np
import itertools
import sys
import os
import random
import igraph as ig
from networkx.algorithms import community
import networkx.algorithms.isolate
import community as cm
import math
import random
import argparse
import multiprocessing as mp
from community_ext import community_ext
def check_consensus_graph(G, n_p, delta):
'''
This function checks if the networkx graph has converged.
Input:
G: networkx graph
n_p: number of partitions while creating G
delta: if more than delta fraction of the edges have weight != n_p then returns False, else True
'''
count = 0
for wt in nx.get_edge_attributes(G, 'weight').values():
if wt != 0 and wt != n_p:
count += 1
if count > delta * G.number_of_edges():
return False
return True
def nx_to_igraph(Gnx):
'''
Function takes in a network Graph, Gnx and returns the equivalent
igraph graph g
'''
g = ig.Graph()
g.add_vertices(sorted(Gnx.nodes()))
g.add_edges(sorted(Gnx.edges()))
g.es["weight"] = 1.0
for edge in Gnx.edges():
g[edge[0], edge[1]] = Gnx[edge[0]][edge[1]]['weight']
return g
def group_to_partition(partition):
'''
Takes in a partition, dictionary in the format {node: community_membership}
Returns a nested list of communities [[comm1], [comm2], ...... [comm_n]]
'''
part_dict = {}
for index, value in partition.items():
if value in part_dict:
part_dict[value].append(index)
else:
part_dict[value] = [index]
return part_dict.values()
def check_arguments(args):
if (args.d > 0.2):
print('delta is too high. Allowed values are between 0.02 and 0.2')
return False
if (args.d < 0.02):
print('delta is too low. Allowed values are between 0.02 and 0.2')
return False
if (args.alg not in ('louvain', 'lpm', 'cnm', 'infomap')):
print('Incorrect algorithm entered. run with -h for help')
return False
if (args.t > 1 or args.t < 0):
print('Incorrect tau. run with -h for help')
return False
return True
def louvain_community_detection(networkx_graph):
"""
Do louvain community detection
:param networkx_graph:
:return:
"""
return cm.partition_at_level(cm.generate_dendrogram(networkx_graph, randomize=True, weight='weight'), 0)
def get_yielded_graph(graph, times):
"""
Creates an iterator containing the same graph object multiple times. Can be used for applying multiprocessing map
"""
for _ in range(times):
yield graph
def fast_consensus(G, algorithm='louvain', n_p=20, thresh=0.2, delta=0.02):
graph = G.copy()
L = G.number_of_edges()
N = G.number_of_nodes()
for u, v in graph.edges():
graph[u][v]['weight'] = 1.0
while (True):
if (algorithm == 'louvain'):
nextgraph = graph.copy()
L = G.number_of_edges()
for u, v in nextgraph.edges():
nextgraph[u][v]['weight'] = 0.0
with mp.Pool(processes=mp.cpu_count()) as pool:
communities_all = [
cm.partition_at_level(cm.generate_dendrogram(graph, randomize=True, weight='weight'), 0) for i in
range(n_p)]
for node, nbr in graph.edges():
if (node, nbr) in graph.edges() or (nbr, node) in graph.edges():
if graph[node][nbr]['weight'] not in (0, n_p):
for i in range(n_p):
communities = communities_all[i]
if communities[node] == communities[nbr]:
nextgraph[node][nbr]['weight'] += 1
remove_edges = []
for u, v in nextgraph.edges():
if nextgraph[u][v]['weight'] < thresh * n_p:
remove_edges.append((u, v))
nextgraph.remove_edges_from(remove_edges)
if check_consensus_graph(nextgraph, n_p=n_p, delta=delta):
break
for _ in range(L):
node = np.random.choice(nextgraph.nodes())
neighbors = [a[1] for a in nextgraph.edges(node)]
if (len(neighbors) >= 2):
a, b = random.sample(set(neighbors), 2)
if not nextgraph.has_edge(a, b):
nextgraph.add_edge(a, b, weight=0)
for i in range(n_p):
communities = communities_all[i]
if communities[a] == communities[b]:
nextgraph[a][b]['weight'] += 1
for node in nx.isolates(nextgraph):
nbr, weight = sorted(graph[node].items(), key=lambda edge: edge[1]['weight'])[0]
nextgraph.add_edge(node, nbr, weight=weight['weight'])
graph = nextgraph.copy()
if check_consensus_graph(nextgraph, n_p=n_p, delta=delta):
break
elif (algorithm in ('infomap', 'lpm')):
nextgraph = graph.copy()
for u, v in nextgraph.edges():
nextgraph[u][v]['weight'] = 0.0
if algorithm == 'infomap':
communities = [{frozenset(c) for c in nx_to_igraph(graph).community_infomap().as_cover()} for _ in
range(n_p)]
if algorithm == 'lpm':
communities = [{frozenset(c) for c in nx_to_igraph(graph).community_label_propagation().as_cover()} for
_ in range(n_p)]
for node, nbr in graph.edges():
for i in range(n_p):
for c in communities[i]:
if node in c and nbr in c:
if not nextgraph.has_edge(node, nbr):
nextgraph.add_edge(node, nbr, weight=0)
nextgraph[node][nbr]['weight'] += 1
remove_edges = []
for u, v in nextgraph.edges():
if nextgraph[u][v]['weight'] < thresh * n_p:
remove_edges.append((u, v))
nextgraph.remove_edges_from(remove_edges)
for _ in range(L):
node = np.random.choice(nextgraph.nodes())
neighbors = [a[1] for a in nextgraph.edges(node)]
if (len(neighbors) >= 2):
a, b = random.sample(set(neighbors), 2)
if not nextgraph.has_edge(a, b):
nextgraph.add_edge(a, b, weight=0)
for i in range(n_p):
if a in communities[i] and b in communities[i]:
nextgraph[a][b]['weight'] += 1
graph = nextgraph.copy()
if check_consensus_graph(nextgraph, n_p=n_p, delta=delta):
break
elif (algorithm == 'cnm'):
nextgraph = graph.copy()
for u, v in nextgraph.edges():
nextgraph[u][v]['weight'] = 0.0
communities = []
mapping = []
inv_map = []
for _ in range(n_p):
order = list(range(N))
random.shuffle(order)
maps = dict(zip(range(N), order))
mapping.append(maps)
inv_map.append({v: k for k, v in maps.items()})
G_c = nx.relabel_nodes(graph, mapping=maps, copy=True)
G_igraph = nx_to_igraph(G_c)
communities.append(G_igraph.community_fastgreedy(weights='weight').as_clustering())
for i in range(n_p):
edge_list = [(mapping[i][j], mapping[i][k]) for j, k in graph.edges()]
for node, nbr in edge_list:
a, b = inv_map[i][node], inv_map[i][nbr]
if graph[a][b] not in (0, n_p):
for c in communities[i]:
if node in c and nbr in c:
nextgraph[a][b]['weight'] += 1
remove_edges = []
for u, v in nextgraph.edges():
if nextgraph[u][v]['weight'] < thresh * n_p:
remove_edges.append((u, v))
nextgraph.remove_edges_from(remove_edges)
for _ in range(L):
node = np.random.choice(nextgraph.nodes())
neighbors = [a[1] for a in nextgraph.edges(node)]
if (len(neighbors) >= 2):
a, b = random.sample(set(neighbors), 2)
if not nextgraph.has_edge(a, b):
nextgraph.add_edge(a, b, weight=0)
for i in range(n_p):
for c in communities[i]:
if mapping[i][a] in c and mapping[i][b] in c:
nextgraph[a][b]['weight'] += 1
if check_consensus_graph(nextgraph, n_p, delta):
break
else:
break
if (algorithm == 'louvain'):
return [cm.partition_at_level(cm.generate_dendrogram(graph, randomize=True, weight='weight'), 0) for _ in
range(n_p)]
if algorithm == 'infomap':
return [{frozenset(c) for c in nx_to_igraph(graph).community_infomap().as_cover()} for _ in range(n_p)]
if algorithm == 'lpm':
return [{frozenset(c) for c in nx_to_igraph(graph).community_label_propagation().as_cover()} for _ in
range(n_p)]
if algorithm == 'cnm':
communities = []
mapping = []
inv_map = []
for _ in range(n_p):
order = list(range(N))
random.shuffle(order)
maps = dict(zip(range(N), order))
mapping.append(maps)
inv_map.append({v: k for k, v in maps.items()})
G_c = nx.relabel_nodes(graph, mapping=maps, copy=True)
G_igraph = nx_to_igraph(G_c)
communities.append(G_igraph.community_fastgreedy(weights='weight').as_clustering())
return communities
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-f', metavar='filename', type=str, nargs='?', help='file with edgelist')
parser.add_argument('-np', metavar='n_p', type=int, nargs='?', default=20,
help='number of input partitions for the algorithm (Default value: 20)')
parser.add_argument('-t', metavar='tau', type=float, nargs='?', help='used for filtering weak edges')
parser.add_argument('-d', metavar='del', type=float, nargs='?', default=0.02,
help='convergence parameter (default = 0.02). Converges when less than delta proportion of the edges are with wt = 1')
parser.add_argument('--alg', metavar='alg', type=str, nargs='?', default='louvain',
help='choose from \'louvain\' , \'cnm\' , \'lpm\' , \'infomap\' ')
args = parser.parse_args()
default_tau = {'louvain': 0.2, 'cnm': 0.7, 'infomap': 0.6, 'lpm': 0.8}
if (args.t == None):
args.t = default_tau.get(args.alg, 0.2)
if check_arguments(args) == False:
quit()
G = nx.read_edgelist(args.f, nodetype=int)
G = nx.convert_node_labels_to_integers(G, label_attribute='name')
output = fast_consensus(G, algorithm=args.alg, n_p=args.np, thresh=args.t, delta=args.d)
if not os.path.exists('out'):
os.makedirs('out')
if (args.alg == 'louvain'):
for i in range(len(output)):
output[i] = group_to_partition(output[i])
i = 0
for partition in output:
i += 1
with open('out/' + str(i), 'w') as f:
for community in partition:
for node in community:
print(G.nodes[node]['name'], end='\t', file=f)
print(file=f)
fn1 = "out_email/email-Eu-core-department-labels.txt"
fn2 = "out/1"
# load graph
G = nx.Graph()
for line in open(fn1):
from_node, to_node = map(int, line.rstrip().split(' '))
if from_node not in G or to_node not in G[from_node]:
G.add_edge(from_node, to_node)
# load the ground-truth partition
groundtruth_partition = dict()
i = 0
for line in open(fn2):
i = i + 1
for node in map(int, line.rstrip("\n").split()):
if node not in G.nodes(): continue
groundtruth_partition[node] = i
# print some general info
gt_mu = community_ext.estimate_mu(G, groundtruth_partition)
print("ground truth mu\t", gt_mu)
print("ground truth clusters\t", len(set(groundtruth_partition.values())))
print("ground truth modularity\t", community_ext.modularity(groundtruth_partition, G))
# now cycle thru the methods and optimize with each one
methods = ('ppm', 'dcppm', 'ilfrs')
for method in methods:
print('\nMethod', method)
# a starting parameter value depends on the method
if method in ('ilfrs',):
work_par = 0.5
else:
work_par = 1.
# now start the iterative process
prev_par, it = -1, 0
prev_pars = set()
while abs(work_par - prev_par) > 1e-5: # stop if the size of improvement too small
it += 1
if it > 100: break # stop after 100th iteration
# update the parameter value
prev_par = work_par
if prev_par in prev_pars: break # stop if we are in the cycle
prev_pars.add(prev_par)
# find the optimal partition with the current parameter value
if method in ('ilfrs',):
partition = community_ext.best_partition(G, model=method, pars={'mu': work_par})
else:
partition = community_ext.best_partition(G, model=method, pars={'gamma': work_par})
# calculate optimal parameter value for the current partition
if method in ('ilfrs',):
work_par = community_ext.estimate_mu(G, partition)
else:
work_par = community_ext.estimate_gamma(G, partition, model=method)
loglike = community_ext.model_log_likelihood(G, partition, model=method,
pars={'gamma': work_par, 'mu': work_par})
print('current par', work_par, 'loglike', loglike)
# calculate and print the scores of resulting partition
part_scores = community_ext.compare_partitions(groundtruth_partition, partition)
loglike = community_ext.model_log_likelihood(G, partition, model=method,
pars={'gamma': work_par, 'mu': work_par})
print('best par', work_par)
print("rand\t% 0f\tjaccard\t% 0f\tnmi\t% 0f\tnmi_arithm\t% 0f\tsize\t%d\tloglike\t% 0f" % \
(part_scores['rand'], part_scores['jaccard'], part_scores['nmi'], part_scores['nmi_arithm'],
len(set(partition.values())), loglike))
<file_sep>/community_ext/community_status.py
# coding=utf-8
# -*- coding: utf-8 -*-
"""
This package implements several community detection.
Originally based on community aka python-louvain library from Thomas Aynaud
(https://github.com/taynaud/python-louvain)
"""
__author__ = """<NAME> (<EMAIL>)"""
__author__ = """<NAME> (<EMAIL>)"""
# Copyright (C) 2018 by
# <NAME> (<EMAIL>>
# <NAME> (<EMAIL>)
# All rights reserved.
# BSD license.
class Status(object):
"""
To handle several data in one struct.
Could be replaced by named tuple, but don't want to depend on python 2.6
"""
node2com = {}
total_weight = 0
internals = {}
degrees = {}
gdegrees = {}
rawnode2node = {}
rawnode2degree = {}
com2size = {}
node2size = {}
def __init__(self):
self.node2com = dict([])
self.total_weight = 0
self.degrees = dict([])
self.gdegrees = dict([])
self.internals = dict([])
self.loops = dict([])
self.rawnode2node = dict([])
self.rawnode2degree = dict([])
self.com2size = dict([])
self.node2size = dict([])
def __str__(self):
return ("node2com : " + str(self.node2com) + " degrees : "
+ str(self.degrees) + " internals : " + str(self.internals)
+ " total_weight : " + str(self.total_weight)
+ " rawnode2node : " + str(self.rawnode2node)
+ " com2size : " + str(self.com2size)
+ " node2size : " + str(self.node2size)
)
def copy(self):
"""Perform a deep copy of status"""
new_status = Status()
new_status.node2com = self.node2com.copy()
new_status.rawnode2node = self.rawnode2node.copy()
new_status.com2size = self.com2size.copy()
new_status.internals = self.internals.copy()
new_status.degrees = self.degrees.copy()
new_status.gdegrees = self.gdegrees.copy()
new_status.total_weight = self.total_weight
new_status.rawnode2degree = self.rawnode2degree.copy()
def init(self, graph, weight, part=None, raw_partition=None, raw_graph=None):
"""Initialize the status of a graph with every node in one community"""
self.rawnode2node = dict([])
self.rawnode2degree = dict([])
self.com2size = dict([])
self.node2size = dict([])
self.node2com = dict([])
self.total_weight = 0
self.degrees = dict([])
self.gdegrees = dict([])
self.internals = dict([])
self.total_weight = graph.size(weight=weight)
count = 0
if part is None:
for node in sorted(graph.nodes()):
if raw_partition is None:
self.rawnode2node[node] = node
self.node2com[node] = count
deg = float(graph.degree(node, weight=weight))
if deg < 0:
error = "Bad graph type ({})".format(type(graph))
raise ValueError(error)
self.degrees[count] = deg
self.gdegrees[node] = deg
edge_data = graph.get_edge_data(node, node, default={weight: 0})
self.loops[node] = float(edge_data.get(weight, 1))
self.internals[count] = self.loops[node]
count += 1
else:
for node in graph.nodes():
if raw_partition is None:
self.rawnode2node[node] = node
com = part[node]
# self.rawnode2node[node] = com
self.node2com[node] = com
deg = float(graph.degree(node, weight=weight))
self.degrees[com] = self.degrees.get(com, 0) + deg
self.gdegrees[node] = deg
inc = 0.
for neighbor, datas in graph[node].items():
edge_weight = datas.get(weight, 1)
if edge_weight <= 0:
error = "Bad graph type ({})".format(type(graph))
raise ValueError(error)
if part[neighbor] == com:
if neighbor == node:
inc += float(edge_weight)
else:
inc += float(edge_weight) / 2.
self.internals[com] = self.internals.get(com, 0) + inc
if raw_partition:
for node,metanode in raw_partition.items():
self.rawnode2node[node] = metanode
for com in set(self.node2com.values()):
self.com2size[com] = 0
for rawnode,node in self.rawnode2node.items():
self.com2size[ self.node2com[node] ] += 1
if node not in self.node2size:
self.node2size[ node ] = 0
self.node2size[ node ] += 1
if raw_graph is None:
raw_graph = graph
for edge in raw_graph.edges():
self.rawnode2degree[edge[0]] = self.rawnode2degree.get(edge[0],0)+1
self.rawnode2degree[edge[1]] = self.rawnode2degree.get(edge[1],0)+1
| 7030009fbbd340b3e568ecb756bc61ab8db9b011 | [
"Python"
] | 3 | Python | suki570/fastconsensus | 1236248d8e552c0b0dd3d10f60f1e70583af44a5 | 7f9ae2f70999e182ed4f72346f5df430437033ff |
refs/heads/master | <file_sep># for-iStarDesign
markup
<file_sep>$(document).ready(function() {
// sliders
$('.slider_right').slick({
infinite: true,
dots: false,
autoplay: false,
speed: 500,
arrows: true,
vertical: true,
slidesToShow: 7,
slidesToScroll: 1,
nextArrow: '<i class="fa fa-angle-up" aria-hidden="true"></i>',
prevArrow: '<i class="fa fa-angle-down" aria-hidden="true"></i>',
focusOnSelect: true,
initialSlide: 7,
asNavFor: '.slider_left',
responsive: [
{
breakpoint: 720,
settings: {
slidesToShow: 7,
slidesToScroll: 1,
nextArrow: '<i class="fa fa-angle-right" aria-hidden="true"></i>',
prevArrow: '<i class="fa fa-angle-left" aria-hidden="true"></i>',
infinite: true,
vertical: false,
dots: false,
arrows: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 5,
slidesToScroll: 1,
nextArrow: '<i class="fa fa-angle-right" aria-hidden="true"></i>',
prevArrow: '<i class="fa fa-angle-left" aria-hidden="true"></i>',
infinite: true,
vertical: false,
dots: false,
arrows: true
}
},
{
breakpoint: 500,
settings: {
slidesToShow: 4,
slidesToScroll: 1,
nextArrow: '<i class="fa fa-angle-right" aria-hidden="true"></i>',
prevArrow: '<i class="fa fa-angle-left" aria-hidden="true"></i>',
infinite: true,
vertical: false,
dots: false,
arrows: true
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 4,
slidesToScroll: 1,
nextArrow: '<i class="fa fa-angle-right" aria-hidden="true"></i>',
prevArrow: '<i class="fa fa-angle-left" aria-hidden="true"></i>',
infinite: true,
vertical: false,
dots: false,
arrows: true
}
},
{
breakpoint: 360,
settings: {
slidesToShow: 4,
slidesToScroll: 1,
nextArrow: '<i class="fa fa-angle-right" aria-hidden="true"></i>',
prevArrow: '<i class="fa fa-angle-left" aria-hidden="true"></i>',
infinite: true,
vertical: false,
dots: false,
arrows: true
}
},
{
breakpoint: 320,
settings: {
slidesToShow: 4,
slidesToScroll: 1,
nextArrow: '<i class="fa fa-angle-right" aria-hidden="true"></i>',
prevArrow: '<i class="fa fa-angle-left" aria-hidden="true"></i>',
infinite: true,
vertical: false,
dots: false,
arrows: true
}
},
]
});
$('.slider_left').slick({
focusOnSelect: true,
dots: false,
arrows: false,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
asNavFor: '.slider_right',
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
dots: false,
arrows: false
}
},
{
breakpoint: 800,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
dots: false,
arrows: false,
asNavFor: '.sl3'
}
},
{
breakpoint: 768,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
dots: false
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
dots: false
}
},
{
breakpoint: 320,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
dots: false,
}
}
]
});
// bottom-slider
$('.products_similar__slider').slick({
focusOnSelect: true,
dots: false,
arrows: true,
infinite: true,
speed: 500,
nextArrow: '<span class="ti-angle-right"></span>',
prevArrow: '<span class="ti-angle-left"></span>',
slidesToShow: 4,
slidesToScroll: 1,
asNavFor: '.slider_right',
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
infinite: true,
dots: false,
arrows: true
}
},
{
breakpoint: 970,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
infinite: true,
dots: false,
arrows: true
}
},
{
breakpoint: 800,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
infinite: true,
dots: false,
arrows: true,
asNavFor: '.sl3'
}
},
{
breakpoint: 768,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
arrows: true,
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
arrows: true,
dots: false
}
},
{
breakpoint: 500,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
arrows: true,
dots: false
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
arrows: true,
dots: false
}
},
{
breakpoint: 320,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
arrows: true,
dots: false,
}
}
]
});
//active category
$(".category__item").click(function(){
$(".category__item").removeClass("active");
$(this).addClass("active");
});
// active menu
$("li.item_main").click(function(){
$("li.item_main").removeClass("active");
$(this).addClass("active");
});
// tabs
$(".tab_item").not(":first").hide();
$(".wrapper .tab").click(function() {
$(".wrapper .tab").removeClass("active").eq($(this).index()).addClass("active");
$(".tab_item").hide().eq($(this).index()).fadeIn()
}).eq(0).addClass("active");
// tabs_hidden
$(".tab_item").not(":first").hide();
$(".wrapper .tab_hidden").click(function() {
$(".wrapper .tab_hidden").removeClass("active").eq($(this).index()).addClass("active");
$(".tab_item").hide().eq($(this).index()).fadeIn()
}).eq(0).addClass("active");
// auto-height
function heightses(){
$(".descr__text p, .descr__price").height('auto').equalHeights();
}
$(window).resize(function() {
heightses();
});
setTimeout(function(){
heightses();
}, 500)
// toggle menu for small devices (767px)
$(".toggle_mnu").click(function() {
$(this).toggleClass("on");
$(".main-mnu").slideToggle();
$(".sandwich").toggleClass("active");
});
$('.main-mnu li').click(function(){
$(".main-mnu").slideToggle();
$(".sandwich").toggleClass("active");
});
$('.main-mnu li ul li').click(function(){
$(".main-mnu").slideToggle();
$(".sandwich").toggleClass("active");
});
// sidebar
$(".sidebar dd").hide().prev().click(function() {
$(this).parents(".sidebar").find("dd").not(this).slideUp().prev().removeClass("active");
$(this).next().not(":visible").slideDown().prev().addClass("active");
});
$(function() {
var $o, $n;
$(".title_block").on("click", function() {
$o = $(this).parents(".accordion_item"), $n = $o.find(".info"),
$o.hasClass("active_block") ? ($o.removeClass("active_block"),
$n.slideUp()) : ($o.addClass("active_block"), $n.stop(!0, !0).slideDown(),
$o.siblings(".active_block").removeClass("active_block").children(
".info").stop(!0, !0).slideUp())
});
});
$("form").submit(function() { //Change
var th = $(this);
$.ajax({
type: "POST",
url: "mail.php", //Change
data: th.serialize()
}).done(function() {
alert("Дякуємо за реєстрацію!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});
return false;
});
});
// loader
$(window).load(function() {
$(".loader_inner").fadeOut();
$(".loader").delay(400).fadeOut("slow");
});
| 185f61230f746d4bd484417d9cf377124d3b2b37 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Jazzyst/for-iStarDesign | ddc966b2fa6e6769e7f11c4fdba66314ca6466f3 | 419d6aa5796d3ebc3ce05a70e0ead2fc71668c78 |
refs/heads/master | <repo_name>Peetrs07/hello-world<file_sep>/README.md
# hello-world
Hi all!
I am new to programming and I have just started to play with Python.
<file_sep>/oko.py
from random import randrange
x = randrange(2,11)
while x <=21:
print("mas",x,)
odp = input("chces dalsi kartu?(y/n)")
if odp == "y":
k = randrange (2,11)
print("otocil jsi ", k)
x = x + k
elif odp == "n":
break
else:
print("nerozumim")
if x == 21:
print("gratuluji, vyhrals")
elif x > 21:
print("prohrals,chacha")
else:
print("chybelo ti jen ", 21 - x)
| 8cd99507503301759d5528b3ac5eaca3fef9db98 | [
"Markdown",
"Python"
] | 2 | Markdown | Peetrs07/hello-world | 5d300f10d07d227205246bb2bf3eecc088ce76d3 | 8a06968d1fbb5c11fa13667eb64180852ff56570 |
refs/heads/master | <repo_name>LinuxBozo/cf-dockerized-buildpack<file_sep>/sub-launcher.sh
#! /bin/bash
set -e
# For details on what these environment variables contain, see
# meta-launcher.sh.
cd $ORIGINAL_CWD
exec $ORIGINAL_ARGS
<file_sep>/README.md
This is an experiment to create a Docker container that approximates
the runtime environment of a cloud.gov/CloudFoundry droplet
using a Python buildpack on the [cflinuxfs2][] stack.
The Dockerfile is heavily inspired by [sclevine/cflocal][].
## Quick start
```
docker-compose build
docker-compose run app python
```
## Changing the Python version
To change the version of Python being used, you can change the
`PYTHON_VERSION` argument in `docker-compose.yml`. It needs
to be a valid Python version supported by
[CloudFoundry's Python buildpack][python-buildpack].
## Other references
* [buildpackapplifecycle][] - Source code for the Diego builder and
launcher used for CloudFoundry deployment.
* [CloudFoundry custom buildpack documentation][cfdocs]
[cflinuxfs2]: https://github.com/cloudfoundry/stacks/tree/master/cflinuxfs2
[sclevine/cflocal]: https://github.com/sclevine/cflocal
[buildpackapplifecycle]: https://github.com/cloudfoundry/buildpackapplifecycle
[python-buildpack]: https://github.com/cloudfoundry/python-buildpack
[cfdocs]: https://docs.cloudfoundry.org/buildpacks/custom.html
<file_sep>/meta-launcher.sh
#! /bin/bash
set -e
# This just wraps whatever the Docker host wants to run in the
# Diego buildpack lifecycle launcher, which sets up some environment
# variables and makes buildpack binaries accessible to us.
#
# The Diego launcher only seems to like running a single command in a
# specific home directory, though, so we're going to store our
# execution parameters in environment variables and restore them
# after the Diego launcher does its job.
export ORIGINAL_ARGS=$@
export ORIGINAL_CWD=$(pwd)
exec /tmp/lifecycle/launcher /tmp/app /home/vcap/sub-launcher.sh staging_info.yml
<file_sep>/Dockerfile
FROM cloudfoundry/cflinuxfs2
ENV BUILDPACKS \
http://github.com/cloudfoundry/python-buildpack
ENV \
GO_VERSION=1.7 \
DIEGO_VERSION=0.1482.0
RUN \
curl -L "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /usr/local -xz
RUN \
mkdir -p /tmp/compile && \
git -C /tmp/compile clone --single-branch https://github.com/cloudfoundry/diego-release && \
cd /tmp/compile/diego-release && \
git checkout "v${DIEGO_VERSION}" && \
git submodule update --init --recursive \
src/code.cloudfoundry.org/archiver \
src/code.cloudfoundry.org/buildpackapplifecycle \
src/code.cloudfoundry.org/bytefmt \
src/code.cloudfoundry.org/cacheddownloader \
src/github.com/cloudfoundry-incubator/candiedyaml \
src/github.com/cloudfoundry/systemcerts
RUN \
export PATH=/usr/local/go/bin:$PATH && \
export GOPATH=/tmp/compile/diego-release && \
go build -o /tmp/lifecycle/launcher code.cloudfoundry.org/buildpackapplifecycle/launcher && \
go build -o /tmp/lifecycle/builder code.cloudfoundry.org/buildpackapplifecycle/builder
ENV CF_STACK=cflinuxfs2
USER vcap
ARG PYTHON_VERSION=3.6.0
RUN \
mkdir -p /tmp/app && \
echo ${PYTHON_VERSION} > /tmp/app/runtime.txt && \
touch /tmp/app/requirements.txt && \
mkdir -p /home/vcap/tmp && \
cd /home/vcap && \
/tmp/lifecycle/builder -buildpackOrder "$(echo "$BUILDPACKS" | tr -s ' ' ,)"
COPY staging_info.yml meta-launcher.sh sub-launcher.sh /home/vcap/
ENTRYPOINT ["/home/vcap/meta-launcher.sh"]
| b15c4d94cefd6585861c4ba370a3b4cb40f949a4 | [
"Markdown",
"Dockerfile",
"Shell"
] | 4 | Shell | LinuxBozo/cf-dockerized-buildpack | e68f7113738c69c17cea49ab5d3d79cfafb7e411 | e9b68f52a098ca0f31db85cbd3b5d7979cec623e |
refs/heads/master | <repo_name>KaoutharAsma/Prayer-app<file_sep>/app/src/main/java/com/example/prayerapp/IApi.kt
package com.example.prayerapp
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import kotlinx.coroutines.Deferred
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
interface IApi {
@GET("timingsByCity")
fun getPrayer(
@Query("city") City:String,
@Query("country") Country:String
): Deferred<PrayerResponse>
companion object {
operator fun invoke():IApi{
val okHttpClient = OkHttpClient.Builder()
.build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://api.aladhan.com/v1/")
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(IApi::class.java)
}
}
}
<file_sep>/README.md
# PrayerApp
une application qui permet de notifier l’utilisateur des heures de prière
<file_sep>/app/src/main/java/com/example/prayerapp/MainActivity.kt
package com.example.prayerapp
import android.content.Intent
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.animation.AnimationUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var player = MediaPlayer()
val afd = assets.openFd("adhan.mp3")
println(afd.length)
player.setDataSource(afd.fileDescriptor)
player.reset()
player.setOnPreparedListener { player.start() }
player.prepareAsync()
player.start()
icon.startAnimation(AnimationUtils.loadAnimation(this , R.anim.splash_in))
Handler().postDelayed({
icon.startAnimation(AnimationUtils.loadAnimation(this, R.anim.solash_out))
Handler().postDelayed({
icon.visibility = View.GONE
startActivity(Intent(this , Dashboard::class.java ))
finish()
} , 500)
},1500)
}
}<file_sep>/app/src/main/java/com/example/prayerapp/PrayerService.kt
package com.example.prayerapp
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.IBinder
import android.view.View
import androidx.annotation.RequiresApi
import kotlinx.coroutines.*
import android.R
import android.app.*
import android.content.Context
import android.content.res.Resources
import android.net.Uri
import androidx.core.app.NotificationCompat
import android.media.MediaPlayer
import androidx.core.app.NotificationManagerCompat
class PrayerService : Service() {
lateinit var notificationManager: NotificationManager
lateinit var notificationChannel: NotificationChannel
lateinit var builder:Notification.Builder
private val channelId = "com.example.prayerapp"
private val description = "Test notification"
override fun onBind(intent: Intent): IBinder?{
return null
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate() {
super.onCreate()
var builder = NotificationCompat.Builder(applicationContext, channelId)
.setSmallIcon(R.drawable.ic_lock_idle_alarm)
.setContentTitle("Prayer time")
.setContentText("It's prayer time")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(Uri.parse("android.resource://$packageName/"))
// .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
val name = "chanel name"
val descriptionText = description
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(channelId, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
super.onCreate()
GlobalScope.launch(Dispatchers.Main) {
/*val apiService = IApi()
val response = apiService.getPrayer("Paris", "France").await()*/
val timerPrayer = TimerPrayer()
TimerPrayer.list.clear()
timerPrayer.addTolist("3:50")
timerPrayer.addTolist("5:42")
timerPrayer.addTolist("12:44")
timerPrayer.addTolist("14:33")
timerPrayer.addTolist("17:47")
timerPrayer.nextPrayer()
var last = false
var delay:Long
while(true){
last = false
delay = timerPrayer.getTimeRemaining().minus(2000)
while(timerPrayer.getTimeRemaining() > 0){
println("remaining time ... : "+ timerPrayer.getTimeRemaining())
if (!last){
Thread.sleep(delay)
last = true
}
}
with(NotificationManagerCompat.from(applicationContext)) {
notify(12345, builder.build())
}
timerPrayer.nextPrayer()
}
}
}
}
<file_sep>/app/src/main/java/com/example/prayerapp/Dashboard.kt
package com.example.prayerapp
import android.content.Intent
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.work.PeriodicWorkRequest
import kotlinx.android.synthetic.main.activity_dashboard.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class Dashboard : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
val apiService = IApi()
GlobalScope.launch(Dispatchers.Main) {
val response = apiService.getPrayer("Paris", "France").await()
Fajr.text = response.data.timings.fajr
Dhuhr.text = response.data.timings.dhuhr
Asr.text = response.data.timings.asr
Maghrib.text = response.data.timings.maghrib
Isha.text = response.data.timings.isha
val timerPrayer = TimerPrayer()
timerPrayer.addTolist(response.data.timings.fajr)
timerPrayer.addTolist(response.data.timings.dhuhr)
timerPrayer.addTolist(response.data.timings.asr)
timerPrayer.addTolist(response.data.timings.maghrib)
timerPrayer.addTolist(response.data.timings.isha)
timerPrayer.nextPrayer()
next.text = TimerPrayer.timeRemaining.toString()
}
val intent = Intent(this,PrayerService::class.java)
startService(intent)
}
}
| c4d2fc909d703fa4231e8b9f24247d75cd1ba937 | [
"Markdown",
"Kotlin"
] | 5 | Kotlin | KaoutharAsma/Prayer-app | 9475ce33bd44a917ad4b2ffeeeb4ecfe0d10e542 | 3e508eadbf968b271a67a3a85fd5bc8aca93eec8 |
refs/heads/master | <file_sep>
# Author: <NAME>
# Company: Softtek
# Date: Jan 30 2017
# Version 1.0
import xml.etree.ElementTree as ET
tree = ET.parse('LincesReportFindBugs.xml')
root = tree.getroot()
lines_seen = set()
filename = ('categories.txt')
variable = 1
for headTag in root.getchildren():
if headTag.tag == 'BugInstance' and headTag.attrib['category'] == 'SECURITY':
variable += 1
if headTag.attrib['type'] not in lines_seen:
lines_seen.add(headTag.attrib['type'])
linea = headTag.attrib['type']
print linea
with open(filename, 'a') as file_object:
file_object.write(linea + "\n")
<file_sep>
# Author: <NAME>
# Company: Softtek
# Date: Jan 30 2017
# Version 1.0
import xml.etree.ElementTree as ET
tree = ET.parse('LincesReportFindBugs.xml')
root = tree.getroot()
import ntpath
from pprint import pprint
fileread = ('categories.txt')
filewrite = ('findbugs-security.txt')
#sourcefile = root.findall(".//SourceLine/[@sourcefile]")
variable = 1
with open(fileread) as f:
for line in f:
line = line.rstrip()
print line
with open(filewrite, 'a') as file_object:
file_object.write(line + "\n")
for headTag in root.getchildren():
if headTag.tag == 'BugInstance' and headTag.attrib['type'] == line:
for bodyTag in headTag.getchildren():
if bodyTag.tag == 'SourceLine':
sourcepath=bodyTag.attrib['sourcepath'].title()
linea=bodyTag.attrib['start'].title()
ruta, archivo = ntpath.split(sourcepath)
lineafinal = (ruta + "," + archivo + "," + linea + "\n")
with open(filewrite, 'a') as file_object:
file_object.write(lineafinal)
<file_sep># findbugs-security-parser
Once you have the firebugs security results in a XML file, you will need this little script in order to get the number of lines per each finding
| d1201d2a3c11e79250a11392662a0c53404a3fbf | [
"Markdown",
"Python"
] | 3 | Python | Luisit0/findbugs-security-parser | afbbb0782eb1c3372885f58855b847f72e2375a7 | 3b143262cb6f4d77187fc21fabdd1632fad6bef5 |
refs/heads/master | <repo_name>dmytrohridin/Blog<file_sep>/Blog.DAL/Interfaces/IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Blog.DAL.Common;
namespace Blog.DAL.Interfaces
{
public interface IRepository<TType, in TKey> : IQueryable<TType>, IList<TType>
where TType : class, IKeyItem<TKey>, new()
{
int CommitChanges();
TType FindById(TKey id);
TType New();
new TType Add(TType entity);
TType Update(TType entity);
bool Remove(TKey id);
void Save(TType item);
}
}
<file_sep>/Blog.DAL/Repositories/EFRepository.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using Blog.DAL.Interfaces;
namespace Blog.DAL.Repositories
{
// ReSharper disable once InconsistentNaming
public class EFRepository<TType, TKey> : IRepository<TType, TKey>
where TType : class, IKeyItem<TKey>, new()
{
#region Fields
private readonly DbContext _dataProvider;
#endregion
#region Properties
protected IQueryable<TType> Items
{
get { return _dataProvider.Set<TType>(); }
}
#endregion
#region Constructors
public EFRepository(DbContext dataProvider)
{
_dataProvider = dataProvider;
}
#endregion
#region IEnumerable members
public IEnumerator<TType> GetEnumerator()
{
return Items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) Items).GetEnumerator();
}
#endregion
#region IQueryable members
public Expression Expression
{
get { return Items.Expression; }
}
public Type ElementType
{
get { return Items.ElementType; }
}
public IQueryProvider Provider
{
get { return Items.Provider; }
}
#endregion
#region ICollection members
void ICollection<TType>.Add(TType item)
{
Add(item);
}
public void Clear()
{
var keys = Items.Select(x => x.Id);
var iterator = keys.GetEnumerator();
iterator.Reset();
while (iterator.MoveNext())
Remove(iterator.Current);
}
public bool Contains(TType item)
{
return Items.Any(i => i.Id.Equals(item.Id));
}
public void CopyTo(TType[] array, int arrayIndex)
{
var count = Count - arrayIndex;
Array.Copy(Items.OrderBy(x => x.Id).Skip(arrayIndex).ToArray(), array, count < 0 ? 0 : count);
}
public bool Remove(TType item)
{
if (item != null)
{
if (_dataProvider.Entry(item).State == EntityState.Detached)
_dataProvider.Set<TType>().Attach(item);
_dataProvider.Set<TType>().Remove(item);
}
return _dataProvider.Entry(item).State == EntityState.Deleted;
}
public int Count
{
get { return Items.Count(); }
}
public bool IsReadOnly
{
get { return false; }
}
#endregion
#region IList members
public int IndexOf(TType item)
{
return Items.Select(x => x.Id).ToList().IndexOf(item.Id);
}
public void Insert(int index, TType item)
{
this[index] = item;
}
public void RemoveAt(int index)
{
Remove(Items.ElementAt(index));
}
public TType this[int index]
{
get { return Items.ElementAt(index); }
set
{
if (!value.Id.Equals(default(TKey)))
Update(value);
else
Add(value);
}
}
#endregion
#region IRepository members
public int CommitChanges()
{
var commitedItemsCount = -1;
try
{
commitedItemsCount = _dataProvider.SaveChanges();
}
catch (DbEntityValidationException exc)
{
foreach (var one in exc.EntityValidationErrors)
foreach (var error in one.ValidationErrors)
Debug.WriteLine(string.Format("{0} - {1}", error.PropertyName, error.ErrorMessage));
throw;
}
catch (DbUpdateException exc)
{
var printInnerInDebug = new Action<Exception>((e) => { });
var printInDebug = new Action<Exception>((e) =>
{
Debug.WriteLine(e.Message);
if (e.InnerException != null)
printInnerInDebug(e.InnerException);
});
printInnerInDebug = new Action<Exception>((e) =>
{
Debug.WriteLine(e.Message);
if (e.InnerException != null)
printInDebug(e.InnerException);
});
throw;
}
return commitedItemsCount;
}
public TType FindById(TKey id)
{
return _dataProvider.Set<TType>().Find(id);
}
public TType New()
{
return _dataProvider.Set<TType>().Create();
}
public TType Add(TType entity)
{
entity = _dataProvider.Set<TType>().Add(entity);
return entity;
}
public TType Update(TType entity)
{
if (entity != null)
{
var attached = _dataProvider.Entry(entity);
if (attached.State != EntityState.Modified)
{
TType itemInContext = _dataProvider.Set<TType>().Local.FirstOrDefault(x => x.Id.Equals(entity.Id));
if (itemInContext != null && !ReferenceEquals(entity, itemInContext))
_dataProvider.Entry(itemInContext).State = EntityState.Detached;
if (attached.State == EntityState.Detached)
_dataProvider.Set<TType>().Attach(entity);
attached.State = EntityState.Modified;
}
}
return entity;
}
public bool Remove(TKey id)
{
return Remove(new TType{ Id = id });
}
public void Save(TType item)
{
if (item.Id.Equals(default(TKey)))
Add(item);
else
Update(item);
}
#endregion
}
}
<file_sep>/Blog.DAL/Common/EventArgsHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blog.DAL.Common
{
public class CancellationEventArgs : EventArgs
{
public bool Cancel { get; set; }
}
public class CancellationCrudEventArgs<T> : CancellationEventArgs
{
public T Entity { get; set; }
}
public class ActionCompleteEventArgs<T> : EventArgs
{
public T Entity { get; set; }
}
}
<file_sep>/Blog.DAL/Interfaces/IKeyItem.cs
namespace Blog.DAL.Interfaces
{
public interface IKeyItem<T>
{
T Id { get; set; }
}
}
| 744711c181d2a86811aa48a3e36a9a17808d4c85 | [
"C#"
] | 4 | C# | dmytrohridin/Blog | 3941559d2869ccd787f1610fda359dafe590d104 | a9e0d4a47692b1eec5eaa69d86c67c5e2220a200 |
refs/heads/develop | <repo_name>AmbientLighter/nodeconductor-openstack<file_sep>/src/nodeconductor_openstack/openstack_tenant/models.py
from __future__ import unicode_literals
from urlparse import urlparse
from django.core.validators import RegexValidator
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from jsonfield import JSONField
from model_utils import FieldTracker
from model_utils.models import TimeStampedModel
from nodeconductor.core import models as core_models
from nodeconductor.logging.loggers import LoggableMixin
from nodeconductor.structure import models as structure_models, utils as structure_utils
from nodeconductor_openstack.openstack_base import models as openstack_base_models
class OpenStackTenantService(structure_models.Service):
projects = models.ManyToManyField(
structure_models.Project, related_name='openstack_tenant_services', through='OpenStackTenantServiceProjectLink')
class Meta:
unique_together = ('customer', 'settings')
verbose_name = 'OpenStackTenant service'
verbose_name_plural = 'OpenStackTenant services'
@classmethod
def get_url_name(cls):
return 'openstacktenant'
class OpenStackTenantServiceProjectLink(structure_models.ServiceProjectLink):
service = models.ForeignKey(OpenStackTenantService)
class Meta(structure_models.ServiceProjectLink.Meta):
verbose_name = 'OpenStackTenant service project link'
verbose_name_plural = 'OpenStackTenant service project links'
@classmethod
def get_url_name(cls):
return 'openstacktenant-spl'
class Flavor(LoggableMixin, structure_models.ServiceProperty):
cores = models.PositiveSmallIntegerField(help_text='Number of cores in a VM')
ram = models.PositiveIntegerField(help_text='Memory size in MiB')
disk = models.PositiveIntegerField(help_text='Root disk size in MiB')
@classmethod
def get_url_name(cls):
return 'openstacktenant-flavor'
class Image(structure_models.ServiceProperty):
min_disk = models.PositiveIntegerField(default=0, help_text='Minimum disk size in MiB')
min_ram = models.PositiveIntegerField(default=0, help_text='Minimum memory size in MiB')
@classmethod
def get_url_name(cls):
return 'openstacktenant-image'
class SecurityGroup(core_models.DescribableMixin, structure_models.ServiceProperty):
@classmethod
def get_url_name(cls):
return 'openstacktenant-sgp'
class SecurityGroupRule(openstack_base_models.BaseSecurityGroupRule):
security_group = models.ForeignKey(SecurityGroup, related_name='rules')
@python_2_unicode_compatible
class FloatingIP(structure_models.ServiceProperty):
address = models.GenericIPAddressField(protocol='IPv4', null=True)
runtime_state = models.CharField(max_length=30)
backend_network_id = models.CharField(max_length=255, editable=False)
is_booked = models.BooleanField(default=False, help_text='Marks if floating IP has been booked for provisioning.')
internal_ip = models.ForeignKey('InternalIP', related_name='floating_ips', null=True, on_delete=models.SET_NULL)
class Meta:
# It should be possible to create floating IP dynamically on instance creation
# so floating IP with empty backend id can exist.
unique_together = tuple()
def __str__(self):
return '%s:%s | %s' % (self.address, self.runtime_state, self.settings)
@classmethod
def get_url_name(cls):
return 'openstacktenant-fip'
def get_backend(self):
return self.settings.get_backend()
def increase_backend_quotas_usage(self, validate=True):
self.settings.add_quota_usage(self.settings.Quotas.floating_ip_count, 1, validate=validate)
class Volume(structure_models.Storage):
service_project_link = models.ForeignKey(
OpenStackTenantServiceProjectLink, related_name='volumes', on_delete=models.PROTECT)
instance = models.ForeignKey('Instance', related_name='volumes', blank=True, null=True)
device = models.CharField(
max_length=50, blank=True,
validators=[RegexValidator('^/dev/[a-zA-Z0-9]+$', message='Device should match pattern "/dev/alphanumeric+"')],
help_text='Name of volume as instance device e.g. /dev/vdb.')
bootable = models.BooleanField(default=False)
metadata = JSONField(blank=True)
image = models.ForeignKey(Image, null=True)
image_metadata = JSONField(blank=True)
type = models.CharField(max_length=100, blank=True)
source_snapshot = models.ForeignKey('Snapshot', related_name='volumes', null=True, on_delete=models.SET_NULL)
# TODO: Move this fields to resource model.
action = models.CharField(max_length=50, blank=True)
action_details = JSONField(default={})
tracker = FieldTracker()
def increase_backend_quotas_usage(self, validate=True):
settings = self.service_project_link.service.settings
settings.add_quota_usage(settings.Quotas.volumes, 1, validate=validate)
settings.add_quota_usage(settings.Quotas.storage, self.size, validate=validate)
def decrease_backend_quotas_usage(self):
settings = self.service_project_link.service.settings
settings.add_quota_usage(settings.Quotas.volumes, -1)
settings.add_quota_usage(settings.Quotas.storage, -self.size)
@classmethod
def get_url_name(cls):
return 'openstacktenant-volume'
class Snapshot(structure_models.Storage):
service_project_link = models.ForeignKey(
OpenStackTenantServiceProjectLink, related_name='snapshots', on_delete=models.PROTECT)
source_volume = models.ForeignKey(Volume, related_name='snapshots', null=True, on_delete=models.PROTECT)
metadata = JSONField(blank=True)
# TODO: Move this fields to resource model.
action = models.CharField(max_length=50, blank=True)
action_details = JSONField(default={})
snapshot_schedule = models.ForeignKey('SnapshotSchedule',
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name='snapshots')
tracker = FieldTracker()
kept_until = models.DateTimeField(
null=True,
blank=True,
help_text='Guaranteed time of snapshot retention. If null - keep forever.')
@classmethod
def get_url_name(cls):
return 'openstacktenant-snapshot'
def increase_backend_quotas_usage(self, validate=True):
settings = self.service_project_link.service.settings
settings.add_quota_usage(settings.Quotas.snapshots, 1, validate=validate)
settings.add_quota_usage(settings.Quotas.storage, self.size, validate=validate)
def decrease_backend_quotas_usage(self):
settings = self.service_project_link.service.settings
settings.add_quota_usage(settings.Quotas.snapshots, -1)
settings.add_quota_usage(settings.Quotas.storage, -self.size)
class SnapshotRestoration(core_models.UuidMixin, TimeStampedModel):
snapshot = models.ForeignKey(Snapshot, related_name='restorations')
volume = models.OneToOneField(Volume, related_name='restoration')
class Permissions(object):
customer_path = 'snapshot__service_project_link__project__customer'
project_path = 'snapshot__service_project_link__project'
class Instance(structure_models.VirtualMachineMixin, core_models.RuntimeStateMixin, structure_models.NewResource):
class RuntimeStates(object):
# All possible OpenStack Instance states on backend.
# See http://developer.openstack.org/api-ref-compute-v2.html
ACTIVE = 'ACTIVE'
BUILDING = 'BUILDING'
DELETED = 'DELETED'
SOFT_DELETED = 'SOFT_DELETED'
ERROR = 'ERROR'
UNKNOWN = 'UNKNOWN'
HARD_REBOOT = 'HARD_REBOOT'
REBOOT = 'REBOOT'
REBUILD = 'REBUILD'
PASSWORD = '<PASSWORD>'
PAUSED = 'PAUSED'
RESCUED = 'RESCUED'
RESIZED = 'RESIZED'
REVERT_RESIZE = 'REVERT_RESIZE'
SHUTOFF = 'SHUTOFF'
STOPPED = 'STOPPED'
SUSPENDED = 'SUSPENDED'
VERIFY_RESIZE = 'VERIFY_RESIZE'
service_project_link = models.ForeignKey(
OpenStackTenantServiceProjectLink, related_name='instances', on_delete=models.PROTECT)
flavor_name = models.CharField(max_length=255, blank=True)
flavor_disk = models.PositiveIntegerField(default=0, help_text='Flavor disk size in MiB')
security_groups = models.ManyToManyField(SecurityGroup, related_name='instances')
# TODO: Move this fields to resource model.
action = models.CharField(max_length=50, blank=True)
action_details = JSONField(default={})
subnets = models.ManyToManyField('SubNet', through='InternalIP')
tracker = FieldTracker()
@property
def external_ips(self):
return self.floating_ips.values_list('address', flat=True)
@property
def internal_ips(self):
return self.internal_ips_set.values_list('ip4_address', flat=True)
@property
def size(self):
return self.volumes.aggregate(models.Sum('size'))['size']
@classmethod
def get_url_name(cls):
return 'openstacktenant-instance'
def get_log_fields(self):
return ('uuid', 'name', 'type', 'service_project_link', 'ram', 'cores',)
def detect_coordinates(self):
settings = self.service_project_link.service.settings
options = settings.options or {}
if 'latitude' in options and 'longitude' in options:
return structure_utils.Coordinates(latitude=settings['latitude'], longitude=settings['longitude'])
else:
hostname = urlparse(settings.backend_url).hostname
if hostname:
return structure_utils.get_coordinates_by_ip(hostname)
def increase_backend_quotas_usage(self, validate=True):
settings = self.service_project_link.service.settings
settings.add_quota_usage(settings.Quotas.instances, 1, validate=validate)
settings.add_quota_usage(settings.Quotas.ram, self.ram, validate=validate)
settings.add_quota_usage(settings.Quotas.vcpu, self.cores, validate=validate)
def decrease_backend_quotas_usage(self):
settings = self.service_project_link.service.settings
settings.add_quota_usage(settings.Quotas.instances, -1)
settings.add_quota_usage(settings.Quotas.ram, -self.ram)
settings.add_quota_usage(settings.Quotas.vcpu, -self.cores)
@property
def floating_ips(self):
return FloatingIP.objects.filter(internal_ip__instance=self)
class Backup(structure_models.NewResource):
service_project_link = models.ForeignKey(
OpenStackTenantServiceProjectLink, related_name='backups', on_delete=models.PROTECT)
instance = models.ForeignKey(Instance, related_name='backups', on_delete=models.PROTECT)
backup_schedule = models.ForeignKey('BackupSchedule', blank=True, null=True,
on_delete=models.SET_NULL,
related_name='backups')
kept_until = models.DateTimeField(
null=True,
blank=True,
help_text='Guaranteed time of backup retention. If null - keep forever.')
metadata = JSONField(
blank=True,
help_text='Additional information about backup, can be used for backup restoration or deletion',
)
snapshots = models.ManyToManyField('Snapshot', related_name='backups')
@classmethod
def get_url_name(cls):
return 'openstacktenant-backup'
class BackupRestoration(core_models.UuidMixin, TimeStampedModel):
""" This model corresponds to instance restoration from backup. """
backup = models.ForeignKey(Backup, related_name='restorations')
instance = models.OneToOneField(Instance, related_name='+')
flavor = models.ForeignKey(Flavor, related_name='+', null=True, blank=True, on_delete=models.SET_NULL)
class Permissions(object):
customer_path = 'backup__service_project_link__project__customer'
project_path = 'backup__service_project_link__project'
class BaseSchedule(structure_models.NewResource, core_models.ScheduleMixin):
retention_time = models.PositiveIntegerField(
help_text='Retention time in days, if 0 - resource will be kept forever')
maximal_number_of_resources = models.PositiveSmallIntegerField()
call_count = models.PositiveSmallIntegerField(default=0, help_text="How many times a resource schedule was called.")
class Meta(object):
abstract = True
class BackupSchedule(BaseSchedule):
service_project_link = models.ForeignKey(
OpenStackTenantServiceProjectLink, related_name='backup_schedules', on_delete=models.PROTECT)
instance = models.ForeignKey(Instance, related_name='backup_schedules')
tracker = FieldTracker()
def __str__(self):
return 'BackupSchedule of %s. Active: %s' % (self.instance, self.is_active)
@classmethod
def get_url_name(cls):
return 'openstacktenant-backup-schedule'
class SnapshotSchedule(BaseSchedule):
service_project_link = models.ForeignKey(
OpenStackTenantServiceProjectLink, related_name='snapshot_schedules', on_delete=models.PROTECT)
source_volume = models.ForeignKey(Volume, related_name='snapshot_schedules')
tracker = FieldTracker()
def __str__(self):
return 'SnapshotSchedule of %s. Active: %s' % (self.source_volume, self.is_active)
@classmethod
def get_url_name(cls):
return 'openstacktenant-snapshot-schedule'
@python_2_unicode_compatible
class Network(core_models.DescribableMixin, structure_models.ServiceProperty):
is_external = models.BooleanField(default=False)
type = models.CharField(max_length=50, blank=True)
segmentation_id = models.IntegerField(null=True)
def __str__(self):
return self.name
@classmethod
def get_url_name(cls):
return 'openstacktenant-network'
@python_2_unicode_compatible
class SubNet(core_models.DescribableMixin, structure_models.ServiceProperty):
network = models.ForeignKey(Network, related_name='subnets')
cidr = models.CharField(max_length=32, blank=True)
gateway_ip = models.GenericIPAddressField(protocol='IPv4', null=True)
allocation_pools = JSONField(default={})
ip_version = models.SmallIntegerField(default=4)
enable_dhcp = models.BooleanField(default=True)
dns_nameservers = JSONField(default=[], help_text='List of DNS name servers associated with the subnet.')
def __str__(self):
return '%s (%s)' % (self.name, self.cidr)
@classmethod
def get_url_name(cls):
return 'openstacktenant-subnet'
class InternalIP(openstack_base_models.Port):
# Name "internal_ips" is reserved by virtual machine mixin and corresponds to list of internal IPs.
# So another related name should be used.
instance = models.ForeignKey(Instance, related_name='internal_ips_set')
subnet = models.ForeignKey(SubNet, related_name='internal_ips')
<file_sep>/src/nodeconductor_openstack/openstack/migrations/0030_subnet_dns_nameservers.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0029_tenant_quotas'),
]
operations = [
migrations.AddField(
model_name='subnet',
name='dns_nameservers',
field=jsonfield.fields.JSONField(default=[], help_text='List of DNS name servers associated with the subnet.'),
),
]
<file_sep>/src/nodeconductor_openstack/openstack_tenant/extension.py
from nodeconductor.core import NodeConductorExtension
class OpenStackTenantExtension(NodeConductorExtension):
class Settings:
NODECONDUCTOR_OPENSTACK_TENANT = {
'MAX_CONCURRENT_PROVISION': {
'OpenStack.Instance': 4,
'OpenStack.Volume': 4,
'OpenStack.Snapshot': 4,
},
}
@staticmethod
def django_app():
return 'nodeconductor_openstack.openstack_tenant'
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
@staticmethod
def celery_tasks():
from datetime import timedelta
return {
'openstacktenant-pull-resources': {
'task': 'openstack_tenant.PullResources',
'schedule': timedelta(minutes=30),
'args': (),
},
'openstacktenant-schedule-backups': {
'task': 'openstack_tenant.ScheduleBackups',
'schedule': timedelta(minutes=10),
'args': (),
},
'openstacktenant-delete-expired-backups': {
'task': 'openstack_tenant.DeleteExpiredBackups',
'schedule': timedelta(minutes=10),
'args': (),
},
'openstacktenant-schedule-snapshots': {
'task': 'openstack_tenant.ScheduleSnapshots',
'schedule': timedelta(minutes=10),
'args': (),
},
'openstacktenant-delete-expired-snapshots': {
'task': 'openstack_tenant.DeleteExpiredSnapshots',
'schedule': timedelta(minutes=10),
'args': (),
},
'openstacktenant-set-erred-stuck-resources': {
'task': 'openstack_tenant.SetErredStuckResources',
'schedule': timedelta(minutes=10),
'args': (),
},
}
<file_sep>/src/nodeconductor_openstack/openstack_tenant/tests/test_instance.py
from ddt import ddt, data
import mock
import urllib
import uuid
from cinderclient import exceptions as cinder_exceptions
from django.conf import settings
from django.test import override_settings
from novaclient import exceptions as nova_exceptions
from rest_framework import status, test
from nodeconductor.structure.tests import factories as structure_factories
from nodeconductor_openstack.openstack.tests.test_backend import BaseBackendTestCase
from .. import models, views
from . import factories, fixtures
@ddt
class InstanceCreateTest(test.APITransactionTestCase):
def setUp(self):
self.openstack_tenant_fixture = fixtures.OpenStackTenantFixture()
self.openstack_settings = self.openstack_tenant_fixture.openstack_tenant_service_settings
self.openstack_settings.options = {'external_network_id': uuid.uuid4().hex}
self.openstack_settings.save()
self.openstack_spl = self.openstack_tenant_fixture.spl
self.image = factories.ImageFactory(settings=self.openstack_settings, min_disk=10240, min_ram=1024)
self.flavor = factories.FlavorFactory(settings=self.openstack_settings)
self.client.force_authenticate(user=self.openstack_tenant_fixture.owner)
self.url = factories.InstanceFactory.get_list_url()
def get_valid_data(self, **extra):
default = {
'service_project_link': factories.OpenStackTenantServiceProjectLinkFactory.get_url(self.openstack_spl),
'flavor': factories.FlavorFactory.get_url(self.flavor),
'image': factories.ImageFactory.get_url(self.image),
'name': 'Valid name',
'system_volume_size': self.image.min_disk,
}
default.update(extra)
return default
def test_quotas_update(self):
response = self.client.post(self.url, self.get_valid_data())
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
instance = models.Instance.objects.get(uuid=response.data['uuid'])
Quotas = self.openstack_settings.Quotas
self.assertEqual(self.openstack_settings.quotas.get(name=Quotas.ram).usage, instance.ram)
self.assertEqual(self.openstack_settings.quotas.get(name=Quotas.storage).usage, instance.disk)
self.assertEqual(self.openstack_settings.quotas.get(name=Quotas.vcpu).usage, instance.cores)
self.assertEqual(self.openstack_settings.quotas.get(name=Quotas.instances).usage, 1)
@data('instances')
def test_quota_validation(self, quota_name):
self.openstack_settings.quotas.filter(name=quota_name).update(limit=0)
response = self.client.post(self.url, self.get_valid_data())
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_can_provision_instance(self):
response = self.client.post(self.url, self.get_valid_data())
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)
def test_user_can_define_instance_subnets(self):
subnet = self.openstack_tenant_fixture.subnet
data = self.get_valid_data(internal_ips_set=[{'subnet': factories.SubNetFactory.get_url(subnet)}])
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
instance = models.Instance.objects.get(uuid=response.data['uuid'])
self.assertTrue(models.InternalIP.objects.filter(subnet=subnet, instance=instance).exists())
def test_user_cannot_assign_subnet_from_other_settings_to_instance(self):
data = self.get_valid_data(internal_ips_set=[{'subnet': factories.SubNetFactory.get_url()}])
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_can_define_instance_floating_ips(self):
subnet = self.openstack_tenant_fixture.subnet
subnet_url = factories.SubNetFactory.get_url(subnet)
floating_ip = self.openstack_tenant_fixture.floating_ip
data = self.get_valid_data(
internal_ips_set=[{'subnet': subnet_url}],
floating_ips=[{'subnet': subnet_url, 'url': factories.FloatingIPFactory.get_url(floating_ip)}],
)
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)
instance = models.Instance.objects.get(uuid=response.data['uuid'])
self.assertIn(floating_ip, instance.floating_ips)
def test_user_cannot_assign_floating_ip_from_other_settings_to_instance(self):
subnet = self.openstack_tenant_fixture.subnet
subnet_url = factories.SubNetFactory.get_url(subnet)
floating_ip = factories.FloatingIPFactory()
data = self.get_valid_data(
internal_ips_set=[{'subnet': subnet_url}],
floating_ips=[{'subnet': subnet_url, 'url': factories.FloatingIPFactory.get_url(floating_ip)}],
)
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_cannot_assign_floating_ip_to_disconnected_subnet(self):
subnet = self.openstack_tenant_fixture.subnet
subnet_url = factories.SubNetFactory.get_url(subnet)
floating_ip = self.openstack_tenant_fixture.floating_ip
data = self.get_valid_data(
floating_ips=[{'subnet': subnet_url, 'url': factories.FloatingIPFactory.get_url(floating_ip)}],
)
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_cannot_assign_active_floating_ip(self):
subnet = self.openstack_tenant_fixture.subnet
subnet_url = factories.SubNetFactory.get_url(subnet)
floating_ip = factories.FloatingIPFactory(settings=self.openstack_settings, runtime_state='ACTIVE')
data = self.get_valid_data(
internal_ips_set=[{'subnet': subnet_url}],
floating_ips=[{'subnet': subnet_url, 'url': factories.FloatingIPFactory.get_url(floating_ip)}],
)
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_can_allocate_floating_ip(self):
subnet = self.openstack_tenant_fixture.subnet
subnet_url = factories.SubNetFactory.get_url(subnet)
self.openstack_tenant_fixture.floating_ip.status = 'ACTIVE'
self.openstack_tenant_fixture.floating_ip.save()
data = self.get_valid_data(
internal_ips_set=[{'subnet': subnet_url}],
floating_ips=[{'subnet': subnet_url}],
)
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
instance = models.Instance.objects.get(uuid=response.data['uuid'])
self.assertEqual(instance.floating_ips.count(), 1)
def test_user_cannot_allocate_floating_ip_if_quota_limit_is_reached(self):
self.openstack_settings.quotas.filter(name=self.openstack_settings.Quotas.floating_ip_count).update(limit=0)
subnet = self.openstack_tenant_fixture.subnet
subnet_url = factories.SubNetFactory.get_url(subnet)
self.openstack_tenant_fixture.floating_ip.status = 'ACTIVE'
self.openstack_tenant_fixture.floating_ip.save()
data = self.get_valid_data(
internal_ips_set=[{'subnet': subnet_url}],
floating_ips=[{'subnet': subnet_url}],
)
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
class InstanceDeleteTest(BaseBackendTestCase):
def setUp(self):
super(InstanceDeleteTest, self).setUp()
self.instance = factories.InstanceFactory(
state=models.Instance.States.OK,
runtime_state=models.Instance.RuntimeStates.SHUTOFF,
backend_id='VALID_ID'
)
self.instance.increase_backend_quotas_usage()
self.mocked_nova().servers.get.side_effect = nova_exceptions.NotFound(code=404)
views.InstanceViewSet.async_executor = False
def tearDown(self):
super(InstanceDeleteTest, self).tearDown()
views.InstanceViewSet.async_executor = True
def mock_volumes(self, delete_data_volume=True):
self.data_volume = self.instance.volumes.get(bootable=False)
self.data_volume.backend_id = 'DATA_VOLUME_ID'
self.data_volume.state = models.Volume.States.OK
self.data_volume.save()
self.data_volume.increase_backend_quotas_usage()
self.system_volume = self.instance.volumes.get(bootable=True)
self.system_volume.backend_id = 'SYSTEM_VOLUME_ID'
self.system_volume.state = models.Volume.States.OK
self.system_volume.save()
self.system_volume.increase_backend_quotas_usage()
def get_volume(backend_id):
if not delete_data_volume and backend_id == self.data_volume.backend_id:
mocked_volume = mock.Mock()
mocked_volume.status = 'available'
return mocked_volume
raise cinder_exceptions.NotFound(code=404)
self.mocked_cinder().volumes.get.side_effect = get_volume
def delete_instance(self, query_params=None):
staff = structure_factories.UserFactory(is_staff=True)
self.client.force_authenticate(user=staff)
url = factories.InstanceFactory.get_url(self.instance)
if query_params:
url += '?' + urllib.urlencode(query_params)
with override_settings(CELERY_ALWAYS_EAGER=True, CELERY_EAGER_PROPAGATES_EXCEPTIONS=True):
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.data)
def assert_quota_usage(self, quotas, name, value):
self.assertEqual(quotas.get(name=name).usage, value)
def test_nova_methods_are_called_if_instance_is_deleted_with_volumes(self):
self.mock_volumes(True)
self.delete_instance()
nova = self.mocked_nova()
nova.servers.delete.assert_called_once_with(self.instance.backend_id)
nova.servers.get.assert_called_once_with(self.instance.backend_id)
self.assertFalse(nova.volumes.delete_server_volume.called)
def test_database_models_deleted(self):
self.mock_volumes(True)
self.delete_instance()
self.assertFalse(models.Instance.objects.filter(id=self.instance.id).exists())
for volume in self.instance.volumes.all():
self.assertFalse(models.Volume.objects.filter(id=volume.id).exists())
def test_quotas_updated_if_instance_is_deleted_with_volumes(self):
self.mock_volumes(True)
self.delete_instance()
self.instance.service_project_link.service.settings.refresh_from_db()
quotas = self.instance.service_project_link.service.settings.quotas
self.assert_quota_usage(quotas, 'instances', 0)
self.assert_quota_usage(quotas, 'vcpu', 0)
self.assert_quota_usage(quotas, 'ram', 0)
self.assert_quota_usage(quotas, 'volumes', 0)
self.assert_quota_usage(quotas, 'storage', 0)
def test_backend_methods_are_called_if_instance_is_deleted_without_volumes(self):
self.mock_volumes(False)
self.delete_instance({
'delete_volumes': False
})
nova = self.mocked_nova()
nova.volumes.delete_server_volume.assert_called_once_with(
self.instance.backend_id, self.data_volume.backend_id)
nova.servers.delete.assert_called_once_with(self.instance.backend_id)
nova.servers.get.assert_called_once_with(self.instance.backend_id)
def test_system_volume_is_deleted_but_data_volume_exists(self):
self.mock_volumes(False)
self.delete_instance({
'delete_volumes': False
})
self.assertFalse(models.Instance.objects.filter(id=self.instance.id).exists())
self.assertTrue(models.Volume.objects.filter(id=self.data_volume.id).exists())
self.assertFalse(models.Volume.objects.filter(id=self.system_volume.id).exists())
def test_quotas_updated_if_instance_is_deleted_without_volumes(self):
self.mock_volumes(False)
self.delete_instance({
'delete_volumes': False
})
settings = self.instance.service_project_link.service.settings
settings.refresh_from_db()
self.assert_quota_usage(settings.quotas, 'instances', 0)
self.assert_quota_usage(settings.quotas, 'vcpu', 0)
self.assert_quota_usage(settings.quotas, 'ram', 0)
self.assert_quota_usage(settings.quotas, 'volumes', 1)
self.assert_quota_usage(settings.quotas, 'storage', self.data_volume.size)
def test_instance_cannot_be_deleted_if_it_has_backups(self):
self.instance = factories.InstanceFactory(
state=models.Instance.States.OK,
runtime_state=models.Instance.RuntimeStates.SHUTOFF,
backend_id='VALID_ID'
)
staff = structure_factories.UserFactory(is_staff=True)
self.client.force_authenticate(user=staff)
factories.BackupFactory(instance=self.instance, state=models.Backup.States.OK)
url = factories.InstanceFactory.get_url(self.instance)
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT, response.data)
class InstanceCreateBackupSchedule(test.APITransactionTestCase):
action_name = 'create_backup_schedule'
def setUp(self):
self.user = structure_factories.UserFactory.create(is_staff=True)
self.client.force_authenticate(user=self.user)
backupable = factories.InstanceFactory(state=models.Instance.States.OK)
self.create_url = factories.InstanceFactory.get_url(backupable, action=self.action_name)
self.backup_schedule_data = {
'name': 'test schedule',
'retention_time': 3,
'schedule': '0 * * * *',
'maximal_number_of_resources': 3,
}
def test_staff_can_create_backup_schedule(self):
response = self.client.post(self.create_url, self.backup_schedule_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['retention_time'], self.backup_schedule_data['retention_time'])
self.assertEqual(
response.data['maximal_number_of_resources'], self.backup_schedule_data['maximal_number_of_resources'])
self.assertEqual(response.data['schedule'], self.backup_schedule_data['schedule'])
def test_backup_schedule_default_state_is_OK(self):
response = self.client.post(self.create_url, self.backup_schedule_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
backup_schedule = models.BackupSchedule.objects.first()
self.assertIsNotNone(backup_schedule)
self.assertEqual(backup_schedule.state, backup_schedule.States.OK)
def test_backup_schedule_can_not_be_created_with_wrong_schedule(self):
# wrong schedule:
self.backup_schedule_data['schedule'] = 'wrong schedule'
response = self.client.post(self.create_url, self.backup_schedule_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('schedule', response.content)
def test_backup_schedule_creation_with_correct_timezone(self):
backupable = factories.InstanceFactory(state=models.Instance.States.OK)
create_url = factories.InstanceFactory.get_url(backupable, action=self.action_name)
backup_schedule_data = {
'name': '<NAME>',
'retention_time': 3,
'schedule': '0 * * * *',
'timezone': 'Europe/London',
'maximal_number_of_resources': 3,
}
response = self.client.post(create_url, backup_schedule_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['timezone'], 'Europe/London')
def test_backup_schedule_creation_with_incorrect_timezone(self):
backupable = factories.InstanceFactory(state=models.Instance.States.OK)
create_url = factories.InstanceFactory.get_url(backupable, action=self.action_name)
backup_schedule_data = {
'name': '<NAME>',
'retention_time': 3,
'schedule': '0 * * * *',
'timezone': 'incorrect',
'maximal_number_of_resources': 3,
}
response = self.client.post(create_url, backup_schedule_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('timezone', response.data)
def test_backup_schedule_creation_with_default_timezone(self):
backupable = factories.InstanceFactory(state=models.Instance.States.OK)
create_url = factories.InstanceFactory.get_url(backupable, action=self.action_name)
backup_schedule_data = {
'name': '<NAME>',
'retention_time': 3,
'schedule': '0 * * * *',
'maximal_number_of_resources': 3,
}
response = self.client.post(create_url, backup_schedule_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['timezone'], settings.TIME_ZONE)
class InstanceUpdateInternalIPsSetTest(test.APITransactionTestCase):
action_name = 'update_internal_ips_set'
def setUp(self):
self.fixture = fixtures.OpenStackTenantFixture()
self.client.force_authenticate(user=self.fixture.admin)
self.instance = self.fixture.instance
self.url = factories.InstanceFactory.get_url(self.instance, action=self.action_name)
def test_user_can_update_instance_internal_ips_set(self):
# instance had 2 internal IPs
ip_to_keep = factories.InternalIPFactory(instance=self.instance, subnet=self.fixture.subnet)
ip_to_delete = factories.InternalIPFactory(instance=self.instance)
# instance should be connected to new subnet
subnet_to_connect = factories.SubNetFactory(settings=self.fixture.openstack_tenant_service_settings)
response = self.client.post(self.url, data={
'internal_ips_set': [
{'subnet': factories.SubNetFactory.get_url(self.fixture.subnet)},
{'subnet': factories.SubNetFactory.get_url(subnet_to_connect)},
]
})
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
self.assertTrue(self.instance.internal_ips_set.filter(pk=ip_to_keep.pk).exists())
self.assertFalse(self.instance.internal_ips_set.filter(pk=ip_to_delete.pk).exists())
self.assertTrue(self.instance.internal_ips_set.filter(subnet=subnet_to_connect).exists())
def test_user_cannot_add_intenal_ip_from_different_settings(self):
subnet = factories.SubNetFactory()
response = self.client.post(self.url, data={
'internal_ips_set': [
{'subnet': factories.SubNetFactory.get_url(subnet)},
]
})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(self.instance.internal_ips_set.filter(subnet=subnet).exists())
def test_user_cannot_connect_instance_to_one_subnet_twice(self):
response = self.client.post(self.url, data={
'internal_ips_set': [
{'subnet': factories.SubNetFactory.get_url(self.fixture.subnet)},
{'subnet': factories.SubNetFactory.get_url(self.fixture.subnet)},
]
})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(self.instance.internal_ips_set.filter(subnet=self.fixture.subnet).exists())
class InstanceUpdateFloatingIPsTest(test.APITransactionTestCase):
action_name = 'update_floating_ips'
def setUp(self):
self.fixture = fixtures.OpenStackTenantFixture()
self.fixture.openstack_tenant_service_settings.options = {'external_network_id': uuid.uuid4().hex}
self.fixture.openstack_tenant_service_settings.save()
self.client.force_authenticate(user=self.fixture.admin)
self.instance = self.fixture.instance
factories.InternalIPFactory.create(instance=self.instance, subnet=self.fixture.subnet)
self.url = factories.InstanceFactory.get_url(self.instance, action=self.action_name)
self.subnet_url = factories.SubNetFactory.get_url(self.fixture.subnet)
def test_user_can_update_instance_floating_ips(self):
floating_ip_url = factories.FloatingIPFactory.get_url(self.fixture.floating_ip)
data = {
'floating_ips': [
{'subnet': self.subnet_url, 'url': floating_ip_url},
]
}
response = self.client.post(self.url, data=data)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
self.assertEqual(self.instance.floating_ips.count(), 1)
self.assertIn(self.fixture.floating_ip, self.instance.floating_ips)
def test_user_cannot_add_floating_ip_via_subnet_that_is_not_connected_to_instance(self):
subnet_url = factories.SubNetFactory.get_url()
data = {'floating_ips': [{'subnet': subnet_url}]}
response = self.client.post(self.url, data=data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_can_remove_floating_ip_from_instance(self):
self.fixture.floating_ip.internal_ip = self.instance.internal_ips_set.first()
self.fixture.floating_ip.save()
data = {'floating_ips': []}
response = self.client.post(self.url, data=data)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
self.assertEqual(self.instance.floating_ips.count(), 0)
def test_free_floating_ip_is_used_for_allocation(self):
external_network_id = self.fixture.openstack_tenant_service_settings.options['external_network_id']
self.fixture.floating_ip.backend_network_id = external_network_id
self.fixture.floating_ip.save()
data = {'floating_ips': [{'subnet': self.subnet_url}]}
response = self.client.post(self.url, data=data)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
self.assertIn(self.fixture.floating_ip, self.instance.floating_ips)
def test_user_cannot_use_same_subnet_twice(self):
data = {'floating_ips': [{'subnet': self.subnet_url}, {'subnet': self.subnet_url}]}
response = self.client.post(self.url, data=data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
<file_sep>/src/nodeconductor_openstack/openstack_tenant/tests/test_backups.py
from __future__ import unicode_literals
from mock import patch
from rest_framework import status
from rest_framework import test
from nodeconductor.core.tests import helpers
from nodeconductor.structure.tests import factories as structure_factories
from .. import models
from . import factories, fixtures
class BackupUsageTest(test.APITransactionTestCase):
def setUp(self):
self.user = structure_factories.UserFactory.create(is_staff=True, is_superuser=True)
self.client.force_authenticate(user=self.user)
def test_backup_manually_create(self):
backupable = factories.InstanceFactory(
state=models.Instance.States.OK,
runtime_state=models.Instance.RuntimeStates.SHUTOFF,
)
url = factories.InstanceFactory.get_url(backupable, action='backup')
response = self.client.post(url, data={'name': 'test backup'})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
models.Backup.objects.get(instance_id=backupable.id)
def test_user_cannot_backup_unstable_instance(self):
instance = factories.InstanceFactory(state=models.Instance.States.UPDATING)
url = factories.InstanceFactory.get_url(instance, action='backup')
response = self.client.post(url, data={'name': 'test backup'})
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
def test_backup_delete(self):
backup = factories.BackupFactory(state=models.Backup.States.OK)
url = factories.BackupFactory.get_url(backup)
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
class BackupListPermissionsTest(helpers.ListPermissionsTest):
def get_url(self):
return factories.BackupFactory.get_list_url()
def get_users_and_expected_results(self):
models.Backup.objects.all().delete()
instance = factories.InstanceFactory()
backup1 = factories.BackupFactory(instance=instance)
backup2 = factories.BackupFactory(instance=instance)
user_with_view_permission = structure_factories.UserFactory.create(is_staff=True, is_superuser=True)
user_without_view_permission = structure_factories.UserFactory.create()
return [
{
'user': user_with_view_permission,
'expected_results': [
{'url': factories.BackupFactory.get_url(backup1)},
{'url': factories.BackupFactory.get_url(backup2)}
]
},
{
'user': user_without_view_permission,
'expected_results': []
},
]
class BackupPermissionsTest(helpers.PermissionsTest):
def setUp(self):
super(BackupPermissionsTest, self).setUp()
self.fixture = fixtures.OpenStackTenantFixture()
self.instance = self.fixture.instance
self.backup = factories.BackupFactory(
service_project_link=self.fixture.spl,
state=models.Backup.States.OK,
instance=self.instance,
)
def get_users_with_permission(self, url, method):
if method == 'GET':
return [self.fixture.staff, self.fixture.admin, self.fixture.manager]
else:
return [self.fixture.staff, self.fixture.admin, self.fixture.manager, self.fixture.owner]
def get_users_without_permissions(self, url, method):
return [self.fixture.user]
def get_urls_configs(self):
yield {'url': factories.BackupFactory.get_url(self.backup), 'method': 'GET'}
yield {'url': factories.BackupFactory.get_url(self.backup), 'method': 'DELETE'}
def test_permissions(self):
with patch('nodeconductor_openstack.openstack_tenant.executors.BackupDeleteExecutor.execute'):
super(BackupPermissionsTest, self).test_permissions()
class BackupSourceFilterTest(test.APITransactionTestCase):
def test_filter_backup_by_scope(self):
user = structure_factories.UserFactory.create(is_staff=True)
instance1 = factories.InstanceFactory()
factories.BackupFactory(instance=instance1)
factories.BackupFactory(instance=instance1)
instance2 = factories.InstanceFactory()
factories.BackupFactory(instance=instance2)
self.client.force_authenticate(user=user)
response = self.client.get(factories.BackupFactory.get_list_url())
self.assertEqual(3, len(response.data))
response = self.client.get(factories.BackupFactory.get_list_url(), data={
'instance_uuid': instance1.uuid.hex})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(2, len(response.data))
self.assertEqual(factories.InstanceFactory.get_url(instance1), response.data[0]['instance'])
class BackupRestorationTest(test.APITransactionTestCase):
def setUp(self):
user = structure_factories.UserFactory(is_staff=True)
self.client.force_authenticate(user=user)
self.backup = factories.BackupFactory(state=models.Backup.States.OK)
self.url = factories.BackupFactory.get_url(self.backup, 'restore')
system_volume = self.backup.instance.volumes.get(bootable=True)
self.disk_size = system_volume.size
service_settings = self.backup.instance.service_project_link.service.settings
self.valid_flavor = factories.FlavorFactory(disk=self.disk_size + 10, settings=service_settings)
self.invalid_flavor = factories.FlavorFactory(disk=self.disk_size - 10, settings=service_settings)
def test_flavor_disk_size_should_match_system_volume_size(self):
response = self.client.post(self.url, {
'flavor': factories.FlavorFactory.get_url(self.valid_flavor)
})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_if_flavor_disk_size_lesser_then_system_volume_size_validation_fails(self):
response = self.client.post(self.url, {
'flavor': factories.FlavorFactory.get_url(self.invalid_flavor)
})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data)
self.assertEqual(response.data['flavor'], ['Flavor disk size should match system volume size.'])
<file_sep>/src/nodeconductor_openstack/openstack_tenant/admin.py
import pytz
from django import forms
from django.contrib import admin
from django.core.exceptions import ValidationError
from nodeconductor.core.admin import ExecutorAdminAction
from nodeconductor.structure import admin as structure_admin
from . import executors, models
class FlavorAdmin(admin.ModelAdmin):
list_filter = ('settings',)
list_display = ('name', 'settings', 'cores', 'ram', 'disk')
class ImageAdmin(admin.ModelAdmin):
list_filter = ('settings', )
list_display = ('name', 'settings', 'min_disk', 'min_ram')
class FloatingIPAdmin(admin.ModelAdmin):
list_filter = ('settings',)
list_display = ('address', 'settings', 'runtime_state', 'backend_network_id', 'is_booked')
class SecurityGroupRule(admin.TabularInline):
model = models.SecurityGroupRule
fields = ('protocol', 'from_port', 'to_port', 'cidr', 'backend_id')
readonly_fields = fields
extra = 0
can_delete = False
class SecurityGroupAdmin(admin.ModelAdmin):
inlines = [SecurityGroupRule]
list_filter = ('settings',)
list_display = ('name', 'settings')
class VolumeAdmin(structure_admin.ResourceAdmin):
class Pull(ExecutorAdminAction):
executor = executors.SnapshotPullExecutor
short_description = 'Pull'
def validate(self, instance):
if instance.state not in (models.Snapshot.States.OK, models.Snapshot.States.ERRED):
raise ValidationError('Snapshot has to be in OK or ERRED state.')
pull = Pull()
class SnapshotAdmin(structure_admin.ResourceAdmin):
class Pull(ExecutorAdminAction):
executor = executors.SnapshotPullExecutor
short_description = 'Pull'
def validate(self, instance):
if instance.state not in (models.Snapshot.States.OK, models.Snapshot.States.ERRED):
raise ValidationError('Snapshot has to be in OK or ERRED state.')
pull = Pull()
class InstanceAdmin(structure_admin.VirtualMachineAdmin):
actions = structure_admin.VirtualMachineAdmin.actions + ['pull']
class Pull(ExecutorAdminAction):
executor = executors.InstancePullExecutor
short_description = 'Pull'
def validate(self, instance):
if instance.state not in (models.Instance.States.OK, models.Instance.States.ERRED):
raise ValidationError('Instance has to be in OK or ERRED state.')
pull = Pull()
class BackupAdmin(admin.ModelAdmin):
readonly_fields = ('created', 'kept_until')
list_filter = ('uuid', 'state')
list_display = ('uuid', 'instance', 'state', 'project')
def project(self, obj):
return obj.instance.service_project_link.project
project.short_description = 'Project'
class BaseScheduleForm(forms.ModelForm):
def clean_timezone(self):
tz = self.cleaned_data['timezone']
if tz not in pytz.all_timezones:
raise ValidationError('Invalid timezone', code='invalid')
return self.cleaned_data['timezone']
class BaseScheduleAdmin(admin.ModelAdmin):
form = BaseScheduleForm
readonly_fields = ('next_trigger_at',)
list_filter = ('is_active',)
list_display = ('uuid', 'next_trigger_at', 'is_active', 'timezone')
class BackupScheduleAdmin(BaseScheduleAdmin):
list_display = BaseScheduleAdmin.list_display + ('instance',)
class SnapshotScheduleAdmin(BaseScheduleAdmin):
list_display = BaseScheduleAdmin.list_display + ('source_volume',)
admin.site.register(models.OpenStackTenantService, structure_admin.ServiceAdmin)
admin.site.register(models.OpenStackTenantServiceProjectLink, structure_admin.ServiceProjectLinkAdmin)
admin.site.register(models.Flavor, FlavorAdmin)
admin.site.register(models.Image, ImageAdmin)
admin.site.register(models.FloatingIP, FloatingIPAdmin)
admin.site.register(models.SecurityGroup, SecurityGroupAdmin)
admin.site.register(models.Volume, VolumeAdmin)
admin.site.register(models.Snapshot, SnapshotAdmin)
admin.site.register(models.Instance, InstanceAdmin)
admin.site.register(models.Backup, BackupAdmin)
admin.site.register(models.BackupSchedule, BackupScheduleAdmin)
admin.site.register(models.SnapshotSchedule, SnapshotScheduleAdmin)
<file_sep>/src/nodeconductor_openstack/openstack/tasks/__init__.py
from __future__ import absolute_import
# Global import of all tasks from submodules.
# Required for proper work of celery autodiscover
# and adding all tasks to the registry.
from .base import *
from .celerybeat import *
<file_sep>/src/nodeconductor_openstack/openstack/backend.py
import logging
import uuid
from django.db import transaction
from django.utils import six, timezone
from cinderclient import exceptions as cinder_exceptions
from glanceclient import exc as glance_exceptions
from keystoneclient import exceptions as keystone_exceptions
from neutronclient.client import exceptions as neutron_exceptions
from novaclient import exceptions as nova_exceptions
from nodeconductor.core.models import StateMixin
from nodeconductor.structure import log_backend_action, SupportedServices
from nodeconductor_openstack.openstack_base.backend import (
OpenStackBackendError, BaseOpenStackBackend, update_pulled_fields)
from . import models
logger = logging.getLogger(__name__)
class OpenStackBackend(BaseOpenStackBackend):
DEFAULTS = {
'tenant_name': 'admin',
'is_admin': True,
}
def check_admin_tenant(self):
try:
self.keystone_admin_client
except keystone_exceptions.AuthorizationFailure:
return False
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
else:
return True
def sync(self):
self._pull_flavors()
self._pull_images()
self._pull_service_settings_quotas()
def _get_domain(self):
""" Get current domain """
keystone = self.keystone_admin_client
return keystone.domains.find(name=self.settings.domain or 'Default')
def get_or_create_ssh_key_for_tenant(self, key_name, fingerprint, public_key):
nova = self.nova_client
try:
return nova.keypairs.find(fingerprint=fingerprint)
except nova_exceptions.NotFound:
# Fine, it's a new key, let's add it
try:
logger.info('Propagating ssh public key %s to backend', key_name)
return nova.keypairs.create(name=key_name, public_key=public_key)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
def remove_ssh_key_from_tenant(self, tenant, key_name, fingerprint):
nova = self.nova_client
# There could be leftovers of key duplicates: remove them all
keys = nova.keypairs.findall(fingerprint=fingerprint)
for key in keys:
# Remove only keys created with NC
if key.name == key_name:
nova.keypairs.delete(key)
logger.info('Deleted ssh public key %s from backend', key_name)
def _get_current_properties(self, model):
return {p.backend_id: p for p in model.objects.filter(settings=self.settings)}
def _are_rules_equal(self, backend_rule, nc_rule):
if backend_rule['from_port'] != nc_rule.from_port:
return False
if backend_rule['to_port'] != nc_rule.to_port:
return False
if backend_rule['ip_protocol'] != nc_rule.protocol:
return False
if backend_rule['ip_range'].get('cidr', '') != nc_rule.cidr:
return False
return True
def _are_security_groups_equal(self, backend_security_group, nc_security_group):
if backend_security_group.name != nc_security_group.name:
return False
if len(backend_security_group.rules) != nc_security_group.rules.count():
return False
for backend_rule, nc_rule in zip(backend_security_group.rules, nc_security_group.rules.all()):
if not self._are_rules_equal(backend_rule, nc_rule):
return False
return True
def _normalize_security_group_rule(self, rule):
if rule['ip_protocol'] is None:
rule['ip_protocol'] = ''
if 'cidr' not in rule['ip_range']:
rule['ip_range']['cidr'] = '0.0.0.0/0'
return rule
def _pull_flavors(self):
nova = self.nova_admin_client
try:
flavors = nova.flavors.findall(is_public=True)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
with transaction.atomic():
cur_flavors = self._get_current_properties(models.Flavor)
for backend_flavor in flavors:
cur_flavors.pop(backend_flavor.id, None)
models.Flavor.objects.update_or_create(
settings=self.settings,
backend_id=backend_flavor.id,
defaults={
'name': backend_flavor.name,
'cores': backend_flavor.vcpus,
'ram': backend_flavor.ram,
'disk': self.gb2mb(backend_flavor.disk),
})
models.Flavor.objects.filter(backend_id__in=cur_flavors.keys()).delete()
def _pull_images(self):
glance = self.glance_client
try:
images = glance.images.list()
except glance_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
with transaction.atomic():
cur_images = self._get_current_properties(models.Image)
for backend_image in images:
if backend_image.is_public and not backend_image.deleted:
cur_images.pop(backend_image.id, None)
models.Image.objects.update_or_create(
settings=self.settings,
backend_id=backend_image.id,
defaults={
'name': backend_image.name,
'min_ram': backend_image.min_ram,
'min_disk': self.gb2mb(backend_image.min_disk),
})
models.Image.objects.filter(backend_id__in=cur_images.keys()).delete()
@log_backend_action('push quotas for tenant')
def push_tenant_quotas(self, tenant, quotas):
cinder_quotas = {
'gigabytes': self.mb2gb(quotas.get('storage')) if 'storage' in quotas else None,
'volumes': quotas.get('volumes'),
'snapshots': quotas.get('snapshots'),
}
cinder_quotas = {k: v for k, v in cinder_quotas.items() if v is not None}
nova_quotas = {
'instances': quotas.get('instances'),
'cores': quotas.get('vcpu'),
'ram': quotas.get('ram'),
}
nova_quotas = {k: v for k, v in nova_quotas.items() if v is not None}
neutron_quotas = {
'security_group': quotas.get('security_group_count'),
'security_group_rule': quotas.get('security_group_rule_count'),
}
neutron_quotas = {k: v for k, v in neutron_quotas.items() if v is not None}
try:
if cinder_quotas:
self.cinder_client.quotas.update(tenant.backend_id, **cinder_quotas)
if nova_quotas:
self.nova_client.quotas.update(tenant.backend_id, **nova_quotas)
if neutron_quotas:
self.neutron_client.update_quota(tenant.backend_id, {'quota': neutron_quotas})
except Exception as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action('pull quotas for tenant')
def pull_tenant_quotas(self, tenant):
for quota_name, limit in self.get_tenant_quotas_limits(tenant.backend_id).items():
tenant.set_quota_limit(quota_name, limit)
for quota_name, usage in self.get_tenant_quotas_usage(tenant.backend_id).items():
tenant.set_quota_usage(quota_name, usage, fail_silently=True)
@log_backend_action('pull floating IPs for tenant')
def pull_floating_ips(self, tenant):
neutron = self.neutron_client
nc_floating_ips = {ip.backend_id: ip for ip in tenant.floating_ips.all()}
try:
backend_floating_ips = {
ip['id']: ip
for ip in neutron.list_floatingips(tenant_id=self.tenant_id)['floatingips']
if ip.get('floating_ip_address') and ip.get('status')
}
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
backend_ids = set(backend_floating_ips.keys())
nc_ids = set(nc_floating_ips.keys())
with transaction.atomic():
for ip_id in nc_ids - backend_ids:
ip = nc_floating_ips[ip_id]
ip.delete()
logger.info('Deleted stale floating IP port %s in database', ip.uuid)
for ip_id in backend_ids - nc_ids:
ip = backend_floating_ips[ip_id]
created_ip = tenant.floating_ips.create(
runtime_state=ip['status'],
backend_id=ip['id'],
address=ip['floating_ip_address'],
name=ip['floating_ip_address'],
backend_network_id=ip['floating_network_id'],
service_project_link=tenant.service_project_link
)
logger.info('Created new floating IP port %s in database', created_ip.uuid)
for ip_id in nc_ids & backend_ids:
nc_ip = nc_floating_ips[ip_id]
backend_ip = backend_floating_ips[ip_id]
if self._floating_ip_changed(nc_ip, backend_ip):
self._update_floating_ip(nc_ip, backend_ip)
def _floating_ip_changed(self, floating_ip, backend_floating_ip):
return (floating_ip.runtime_state != backend_floating_ip['status'] or
floating_ip.address != backend_floating_ip['floating_ip_address'] or
floating_ip.backend_network_id != backend_floating_ip['floating_network_id'] or
floating_ip.state != StateMixin.States.OK)
def _update_floating_ip(self, floating_ip, backend_floating_ip):
floating_ip.runtime_state = backend_floating_ip['status']
floating_ip.address = backend_floating_ip['floating_ip_address']
floating_ip.name = backend_floating_ip['floating_ip_address']
floating_ip.backend_network_id = backend_floating_ip['floating_network_id']
floating_ip.state = StateMixin.States.OK
floating_ip.save(update_fields=['runtime_state', 'address', 'name', 'backend_network_id', 'state'])
logger.info('Updated existing floating IP port %s in database', floating_ip.uuid)
@log_backend_action('pull security groups for tenant')
def pull_tenant_security_groups(self, tenant):
# security groups pull should be rewritten in WAL-323
nova = self.nova_client
try:
backend_security_groups = nova.security_groups.list()
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
states = models.SecurityGroup.States
# list of openstack security groups that do not exist in nc
nonexistent_groups = []
# list of openstack security groups that have wrong parameters in in nc
unsynchronized_groups = []
# list of nc security groups that do not exist in openstack
extra_groups = tenant.security_groups.exclude(backend_id__in=[g.id for g in backend_security_groups])
extra_groups = extra_groups.exclude(state__in=[states.CREATION_SCHEDULED, states.CREATING])
with transaction.atomic():
for backend_group in backend_security_groups:
try:
nc_group = tenant.security_groups.get(backend_id=backend_group.id)
if (not self._are_security_groups_equal(backend_group, nc_group) and
nc_group.state not in [states.UPDATING, states.UPDATE_SCHEDULED]):
unsynchronized_groups.append(backend_group)
except models.SecurityGroup.DoesNotExist:
nonexistent_groups.append(backend_group)
# deleting extra security groups
extra_groups.delete()
if extra_groups:
logger.debug('Deleted stale security group: %s.',
' ,'.join('%s (PK: %s)' % (sg.name, sg.pk) for sg in extra_groups))
# synchronizing unsynchronized security groups
for backend_group in unsynchronized_groups:
nc_security_group = tenant.security_groups.get(backend_id=backend_group.id)
if backend_group.name != nc_security_group.name:
nc_security_group.name = backend_group.name
nc_security_group.state = StateMixin.States.OK
nc_security_group.save()
self.pull_security_group_rules(nc_security_group)
logger.debug('Updated existing security group %s (PK: %s).',
nc_security_group.name, nc_security_group.pk)
# creating non-existed security groups
for backend_group in nonexistent_groups:
nc_security_group = tenant.security_groups.create(
backend_id=backend_group.id,
name=backend_group.name,
state=StateMixin.States.OK,
service_project_link=tenant.service_project_link,
)
self.pull_security_group_rules(nc_security_group)
logger.debug('Created new security group %s (PK: %s).',
nc_security_group.name, nc_security_group.pk)
def pull_security_group_rules(self, security_group):
nova = self.nova_client
try:
backend_security_group = nova.security_groups.get(group_id=security_group.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
backend_rules = [
self._normalize_security_group_rule(r)
for r in backend_security_group.rules
]
# list of openstack rules, that do not exist in nc
nonexistent_rules = []
# list of openstack rules, that have wrong parameters in in nc
unsynchronized_rules = []
# list of nc rules, that do not exist in openstack
extra_rules = security_group.rules.exclude(backend_id__in=[r['id'] for r in backend_rules])
with transaction.atomic():
for backend_rule in backend_rules:
try:
nc_rule = security_group.rules.get(backend_id=backend_rule['id'])
if not self._are_rules_equal(backend_rule, nc_rule):
unsynchronized_rules.append(backend_rule)
except security_group.rules.model.DoesNotExist:
nonexistent_rules.append(backend_rule)
# deleting extra rules
# XXX: In Django >= 1.9 delete method returns number of deleted objects, so this could be optimized
if extra_rules:
extra_rules.delete()
logger.info('Deleted stale security group rules in database')
# synchronizing unsynchronized rules
for backend_rule in unsynchronized_rules:
security_group.rules.filter(backend_id=backend_rule['id']).update(
from_port=backend_rule['from_port'],
to_port=backend_rule['to_port'],
protocol=backend_rule['ip_protocol'],
cidr=backend_rule['ip_range']['cidr'],
)
if unsynchronized_rules:
logger.debug('Updated existing security group rules in database')
# creating non-existed rules
for backend_rule in nonexistent_rules:
rule = security_group.rules.create(
from_port=backend_rule['from_port'],
to_port=backend_rule['to_port'],
protocol=backend_rule['ip_protocol'],
cidr=backend_rule['ip_range']['cidr'],
backend_id=backend_rule['id'],
)
logger.info('Created new security group rule %s in database', rule.id)
@log_backend_action()
def create_tenant(self, tenant):
keystone = self.keystone_admin_client
try:
backend_tenant = keystone.projects.create(
name=tenant.name, description=tenant.description, domain=self._get_domain())
tenant.backend_id = backend_tenant.id
tenant.save(update_fields=['backend_id'])
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
def import_tenant(self, tenant_backend_id, service_project_link=None, save=True):
keystone = self.keystone_admin_client
try:
backend_tenant = keystone.projects.get(tenant_backend_id)
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
tenant = models.Tenant()
tenant.name = backend_tenant.name
tenant.description = backend_tenant.description
tenant.backend_id = tenant_backend_id
if save and service_project_link:
tenant.service_project_link = service_project_link
tenant.state = models.Tenant.States.OK
tenant.save()
return tenant
@log_backend_action()
def pull_tenant(self, tenant):
import_time = timezone.now()
imported_tenant = self.import_tenant(tenant.backend_id, save=False)
tenant.refresh_from_db()
# if tenant was not modified in NC database after import.
if tenant.modified < import_time:
update_pulled_fields(tenant, imported_tenant, ('name', 'description'))
@log_backend_action()
def add_admin_user_to_tenant(self, tenant):
""" Add user from openstack settings to new tenant """
keystone = self.keystone_admin_client
try:
admin_user = keystone.users.find(name=self.settings.username)
admin_role = keystone.roles.find(name='admin')
try:
keystone.roles.grant(
user=admin_user.id,
role=admin_role.id,
project=tenant.backend_id)
except keystone_exceptions.Conflict:
pass
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action('add user to tenant')
def create_tenant_user(self, tenant):
keystone = self.keystone_client
try:
user = keystone.users.create(
name=tenant.user_username,
password=<PASSWORD>,
domain=self._get_domain(),
)
try:
role = keystone.roles.find(name='Member')
except keystone_exceptions.NotFound:
role = keystone.roles.find(name='_member_')
keystone.roles.grant(
user=user.id,
role=role.id,
project=tenant.backend_id,
)
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action('change password for tenant user')
def change_tenant_user_password(self, tenant):
keystone = self.keystone_client
try:
keystone_user = keystone.users.find(name=tenant.user_username)
keystone.users.update(user=keystone_user, password=tenant.user_password)
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
def get_resources_for_import(self, resource_type=None):
if self.settings.get_option('is_admin'):
return self.get_tenants_for_import()
else:
return []
def get_tenants_for_import(self):
cur_tenants = set(models.Tenant.objects.filter(
service_project_link__service__settings=self.settings
).values_list('backend_id', flat=True))
keystone = self.keystone_admin_client
try:
tenants = keystone.projects.list(domain=self._get_domain())
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
return [{
'id': tenant.id,
'name': tenant.name,
'description': tenant.description,
'type': SupportedServices.get_name_for_model(models.Tenant)
} for tenant in tenants if tenant.id not in cur_tenants]
def get_managed_resources(self):
return []
@log_backend_action()
def delete_tenant_floating_ips(self, tenant):
if not tenant.backend_id:
# This method will remove all floating IPs if tenant `backend_id` is not defined.
raise OpenStackBackendError('This method should not be called if tenant has no backend_id')
neutron = self.neutron_admin_client
try:
floatingips = neutron.list_floatingips(tenant_id=tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
for floating_ip in floatingips.get('floatingips', []):
self._delete_backend_floating_ip(floating_ip['id'], tenant.backend_id)
@log_backend_action()
def delete_tenant_ports(self, tenant):
if not tenant.backend_id:
# This method will remove all ports if tenant `backend_id` is not defined.
raise OpenStackBackendError('This method should not be called if tenant has no backend_id')
neutron = self.neutron_admin_client
try:
ports = neutron.list_ports(tenant_id=tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
for port in ports.get('ports', []):
logger.info("Deleting port %s interface_router from tenant %s", port['id'], tenant.backend_id)
try:
neutron.remove_interface_router(port['device_id'], {'port_id': port['id']})
except neutron_exceptions.NotFound:
logger.debug("Port %s interface_router is already gone from tenant %s", port['id'],
tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
logger.info("Deleting port %s from tenant %s", port['id'], tenant.backend_id)
try:
neutron.delete_port(port['id'])
except neutron_exceptions.NotFound:
logger.debug("Port %s is already gone from tenant %s", port['id'], tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def delete_tenant_routers(self, tenant):
if not tenant.backend_id:
# This method will remove all routers if tenant `backend_id` is not defined.
raise OpenStackBackendError('This method should not be called if tenant has no backend_id')
neutron = self.neutron_admin_client
try:
routers = neutron.list_routers(tenant_id=tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
for router in routers.get('routers', []):
logger.info("Deleting router %s from tenant %s", router['id'], tenant.backend_id)
try:
neutron.delete_router(router['id'])
except neutron_exceptions.NotFound:
logger.debug("Router %s is already gone from tenant %s", router['id'], tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def delete_tenant_networks(self, tenant):
if not tenant.backend_id:
# This method will remove all networks if tenant `backend_id` is not defined.
raise OpenStackBackendError('This method should not be called if tenant has no backend_id')
neutron = self.neutron_admin_client
try:
networks = neutron.list_networks(tenant_id=tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
for network in networks.get('networks', []):
if network['router:external']:
continue
for subnet in network['subnets']:
logger.info("Deleting subnetwork %s from tenant %s", subnet, tenant.backend_id)
try:
neutron.delete_subnet(subnet)
except neutron_exceptions.NotFound:
logger.info("Subnetwork %s is already gone from tenant %s", subnet, tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
logger.info("Deleting network %s from tenant %s", network['id'], tenant.backend_id)
try:
neutron.delete_network(network['id'])
except neutron_exceptions.NotFound:
logger.debug("Network %s is already gone from tenant %s", network['id'], tenant.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
tenant.set_quota_usage(tenant.Quotas.network_count, 0)
tenant.set_quota_usage(tenant.Quotas.subnet_count, 0)
@log_backend_action()
def delete_tenant_security_groups(self, tenant):
nova = self.nova_client
try:
sgroups = nova.security_groups.list()
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
for sgroup in sgroups:
logger.info("Deleting security group %s from tenant %s", sgroup.id, tenant.backend_id)
try:
sgroup.delete()
except nova_exceptions.NotFound:
logger.debug("Security group %s is already gone from tenant %s", sgroup.id, tenant.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def delete_tenant_instances(self, tenant):
nova = self.nova_client
try:
servers = nova.servers.list()
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
for server in servers:
logger.info("Deleting instance %s from tenant %s", server.id, tenant.backend_id)
try:
server.delete()
except nova_exceptions.NotFound:
logger.debug("Instance %s is already gone from tenant %s", server.id, tenant.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def are_all_tenant_instances_deleted(self, tenant):
nova = self.nova_client
try:
servers = nova.servers.list()
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
else:
return not servers
@log_backend_action()
def delete_tenant_snapshots(self, tenant):
cinder = self.cinder_client
try:
snapshots = cinder.volume_snapshots.list()
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
for snapshot in snapshots:
logger.info("Deleting snapshot %s from tenant %s", snapshot.id, tenant.backend_id)
try:
snapshot.delete()
except cinder_exceptions.NotFound:
logger.debug("Snapshot %s is already gone from tenant %s", snapshot.id, tenant.backend_id)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def are_all_tenant_snapshots_deleted(self, tenant):
cinder = self.cinder_client
try:
snapshots = cinder.volume_snapshots.list()
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
else:
return not snapshots
@log_backend_action()
def delete_tenant_volumes(self, tenant):
cinder = self.cinder_client
try:
volumes = cinder.volumes.list()
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
for volume in volumes:
logger.info("Deleting volume %s from tenant %s", volume.id, tenant.backend_id)
try:
volume.delete()
except cinder_exceptions.NotFound:
logger.debug("Volume %s is already gone from tenant %s", volume.id, tenant.backend_id)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def are_all_tenant_volumes_deleted(self, tenant):
cinder = self.cinder_client
try:
volumes = cinder.volumes.list()
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
else:
return not volumes
@log_backend_action()
def delete_tenant_user(self, tenant):
keystone = self.keystone_client
try:
user = keystone.users.find(name=tenant.user_username)
logger.info('Deleting user %s that was connected to tenant %s', user.name, tenant.backend_id)
user.delete()
except keystone_exceptions.NotFound:
logger.debug("User %s is already gone from tenant %s", tenant.user_username, tenant.backend_id)
except keystone_exceptions.ClientException as e:
logger.error('Cannot delete user %s from tenant %s. Error: %s', tenant.user_username, tenant.backend_id, e)
@log_backend_action()
def delete_tenant(self, tenant):
if not tenant.backend_id:
raise OpenStackBackendError('This method should not be called if tenant has no backend_id')
keystone = self.keystone_admin_client
logger.info("Deleting tenant %s", tenant.backend_id)
try:
keystone.projects.delete(tenant.backend_id)
except keystone_exceptions.NotFound:
logger.debug("Tenant %s is already gone", tenant.backend_id)
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def push_security_group_rules(self, security_group):
nova = self.nova_client
backend_security_group = nova.security_groups.get(group_id=security_group.backend_id)
backend_rules = {
rule['id']: self._normalize_security_group_rule(rule)
for rule in backend_security_group.rules
}
# list of nc rules, that do not exist in openstack
nonexistent_rules = []
# list of nc rules, that have wrong parameters in in openstack
unsynchronized_rules = []
# list of os rule ids, that exist in openstack and do not exist in nc
extra_rule_ids = backend_rules.keys()
for nc_rule in security_group.rules.all():
if nc_rule.backend_id not in backend_rules:
nonexistent_rules.append(nc_rule)
else:
backend_rule = backend_rules[nc_rule.backend_id]
if not self._are_rules_equal(backend_rule, nc_rule):
unsynchronized_rules.append(nc_rule)
extra_rule_ids.remove(nc_rule.backend_id)
# deleting extra rules
for backend_rule_id in extra_rule_ids:
logger.debug('About to delete security group rule with id %s in backend', backend_rule_id)
try:
nova.security_group_rules.delete(backend_rule_id)
except nova_exceptions.ClientException:
logger.exception('Failed to remove rule with id %s from security group %s in backend',
backend_rule_id, security_group)
else:
logger.info('Security group rule with id %s successfully deleted in backend', backend_rule_id)
# deleting unsynchronized rules
for nc_rule in unsynchronized_rules:
logger.debug('About to delete security group rule with id %s', nc_rule.backend_id)
try:
nova.security_group_rules.delete(nc_rule.backend_id)
except nova_exceptions.ClientException:
logger.exception('Failed to remove rule with id %s from security group %s in backend',
nc_rule.backend_id, security_group)
else:
logger.info('Security group rule with id %s successfully deleted in backend',
nc_rule.backend_id)
# creating nonexistent and unsynchronized rules
for nc_rule in unsynchronized_rules + nonexistent_rules:
logger.debug('About to create security group rule with id %s in backend', nc_rule.id)
try:
# The database has empty strings instead of nulls
if nc_rule.protocol == '':
nc_rule_protocol = None
else:
nc_rule_protocol = nc_rule.protocol
nova.security_group_rules.create(
parent_group_id=security_group.backend_id,
ip_protocol=nc_rule_protocol,
from_port=nc_rule.from_port,
to_port=nc_rule.to_port,
cidr=nc_rule.cidr,
)
except nova_exceptions.ClientException as e:
logger.exception('Failed to create rule %s for security group %s in backend',
nc_rule, security_group)
six.reraise(OpenStackBackendError, e)
else:
logger.info('Security group rule with id %s successfully created in backend', nc_rule.id)
@log_backend_action()
def create_security_group(self, security_group):
nova = self.nova_client
try:
backend_security_group = nova.security_groups.create(
name=security_group.name, description=security_group.description)
security_group.backend_id = backend_security_group.id
security_group.save()
self.push_security_group_rules(security_group)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def delete_security_group(self, security_group):
nova = self.nova_client
try:
nova.security_groups.delete(security_group.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
security_group.decrease_backend_quotas_usage()
@log_backend_action()
def update_security_group(self, security_group):
nova = self.nova_client
try:
backend_security_group = nova.security_groups.find(id=security_group.backend_id)
nova.security_groups.update(
backend_security_group, name=security_group.name, description=security_group.description)
self.push_security_group_rules(security_group)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action('create external network for tenant')
def create_external_network(self, tenant, neutron, network_ip, network_prefix,
vlan_id=None, vxlan_id=None, ips_count=None):
if tenant.external_network_id:
self.connect_tenant_to_external_network(tenant, tenant.external_network_id)
neutron = self.neutron_admin_client
# External network creation
network_name = 'nc-{0}-ext-net'.format(uuid.uuid4().hex)
network = {
'name': network_name,
'tenant_id': tenant.backend_id,
'router:external': True,
# XXX: provider:physical_network should be configurable.
'provider:physical_network': 'physnet1'
}
if vlan_id:
network['provider:network_type'] = 'vlan'
network['provider:segmentation_id'] = vlan_id
elif vxlan_id:
network['provider:network_type'] = 'vxlan'
network['provider:segmentation_id'] = vxlan_id
else:
raise OpenStackBackendError('VLAN or VXLAN ID should be provided.')
create_response = neutron.create_network({'networks': [network]})
network_id = create_response['networks'][0]['id']
logger.info('External network with name %s has been created.', network_name)
tenant.external_network_id = network_id
tenant.save(update_fields=['external_network_id'])
# Subnet creation
subnet_name = '{0}-sn01'.format(network_name)
cidr = '{0}/{1}'.format(network_ip, network_prefix)
subnet_data = {
'network_id': tenant.external_network_id,
'tenant_id': tenant.backend_id,
'cidr': cidr,
'name': subnet_name,
'ip_version': 4,
'enable_dhcp': False,
}
create_response = neutron.create_subnet({'subnets': [subnet_data]})
logger.info('Subnet with name %s has been created.', subnet_name)
# Router creation
self.get_or_create_router(network_name, create_response['subnets'][0]['id'])
# Floating IPs creation
floating_ip = {
'floating_network_id': tenant.external_network_id,
}
if vlan_id is not None and ips_count is not None:
for i in range(ips_count):
ip = neutron.create_floatingip({'floatingip': floating_ip})['floatingip']
logger.info('Floating ip %s for external network %s has been created.',
ip['floating_ip_address'], network_name)
return tenant.external_network_id
@log_backend_action()
def detect_external_network(self, tenant):
neutron = self.neutron_client
try:
routers = neutron.list_routers(tenant_id=tenant.backend_id)['routers']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
if bool(routers):
router = routers[0]
else:
logger.warning('Tenant %s (PK: %s) does not have connected routers.', tenant, tenant.pk)
return
ext_gw = router.get('external_gateway_info', {})
if ext_gw and 'network_id' in ext_gw:
tenant.external_network_id = ext_gw['network_id']
tenant.save()
logger.info('Found and set external network with id %s for tenant %s (PK: %s)',
ext_gw['network_id'], tenant, tenant.pk)
@log_backend_action('delete tenant external network')
def delete_external_network(self, tenant):
neutron = self.neutron_admin_client
try:
floating_ips = neutron.list_floatingips(
floating_network_id=tenant.external_network_id)['floatingips']
for ip in floating_ips:
neutron.delete_floatingip(ip['id'])
logger.info('Floating IP with id %s has been deleted.', ip['id'])
ports = neutron.list_ports(network_id=tenant.external_network_id)['ports']
for port in ports:
neutron.remove_interface_router(port['device_id'], {'port_id': port['id']})
logger.info('Port with id %s has been deleted.', port['id'])
subnets = neutron.list_subnets(network_id=tenant.external_network_id)['subnets']
for subnet in subnets:
neutron.delete_subnet(subnet['id'])
logger.info('Subnet with id %s has been deleted.', subnet['id'])
neutron.delete_network(tenant.external_network_id)
logger.info('External network with id %s has been deleted.', tenant.external_network_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
else:
tenant.external_network_id = ''
tenant.save()
@log_backend_action()
def create_network(self, network):
neutron = self.neutron_admin_client
data = {'name': network.name, 'tenant_id': network.tenant.backend_id}
try:
response = neutron.create_network({'networks': [data]})
except neutron_exceptions.NeutronException as e:
six.reraise(OpenStackBackendError, e)
else:
backend_network = response['networks'][0]
network.backend_id = backend_network['id']
network.runtime_state = backend_network['status']
if backend_network.get('provider:network_type'):
network.type = backend_network['provider:network_type']
if backend_network.get('provider:segmentation_id'):
network.segmentation_id = backend_network['provider:segmentation_id']
network.save()
# XXX: temporary fix - right now backend logic is based on statement "one tenant has one network"
# We need to fix this in the future.
network.tenant.internal_network_id = network.backend_id
network.tenant.save()
@log_backend_action()
def update_network(self, network):
neutron = self.neutron_admin_client
data = {'name': network.name}
try:
neutron.update_network(network.backend_id, {'network': data})
except neutron_exceptions.NeutronException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def delete_network(self, network):
for subnet in network.subnets.all():
self.delete_subnet(subnet)
neutron = self.neutron_admin_client
try:
neutron.delete_network(network.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
else:
network.decrease_backend_quotas_usage()
def import_network(self, network_backend_id):
neutron = self.neutron_admin_client
try:
backend_network = neutron.show_network(network_backend_id)['network']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
network = models.Network(
name=backend_network['name'],
type=backend_network.get('provider:network_type'),
segmentation_id=backend_network.get('provider:segmentation_id'),
runtime_state=backend_network['status'],
state=models.Network.States.OK,
)
return network
@log_backend_action()
def pull_network(self, network):
import_time = timezone.now()
imported_network = self.import_network(network.backend_id)
network.refresh_from_db()
if network.modified < import_time:
update_fields = ('name', 'type', 'segmentation_id', 'runtime_state')
update_pulled_fields(network, imported_network, update_fields)
@log_backend_action()
def create_subnet(self, subnet):
neutron = self.neutron_admin_client
data = {
'name': subnet.name,
'network_id': subnet.network.backend_id,
'tenant_id': subnet.network.tenant.backend_id,
'cidr': subnet.cidr,
'allocation_pools': subnet.allocation_pools,
'ip_version': subnet.ip_version,
'enable_dhcp': subnet.enable_dhcp,
}
if subnet.dns_nameservers:
data['dns_nameservers'] = subnet.dns_nameservers
try:
response = neutron.create_subnet({'subnets': [data]})
# Automatically create router for subnet
# TODO: Ideally: Create separate model for router and create it separately.
# Good enough: refactor `get_or_create_router` method: split it into several method.
self.get_or_create_router(subnet.network.name, response['subnets'][0]['id'],
tenant_id=subnet.network.tenant.backend_id)
except neutron_exceptions.NeutronException as e:
six.reraise(OpenStackBackendError, e)
else:
backend_subnet = response['subnets'][0]
subnet.backend_id = backend_subnet['id']
if backend_subnet.get('gateway_ip'):
subnet.gateway_ip = backend_subnet['gateway_ip']
subnet.save()
@log_backend_action()
def update_subnet(self, subnet):
neutron = self.neutron_admin_client
data = {'name': subnet.name}
try:
neutron.update_subnet(subnet.backend_id, {'subnet': data})
except neutron_exceptions.NeutronException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def delete_subnet(self, subnet):
neutron = self.neutron_admin_client
try:
neutron.delete_subnet(subnet.backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
else:
subnet.decrease_backend_quotas_usage()
def import_subnet(self, subnet_backend_id):
neutron = self.neutron_admin_client
try:
backend_subnet = neutron.show_subnet(subnet_backend_id)['subnet']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
subnet = models.SubNet(
name=backend_subnet['name'],
description=backend_subnet['description'],
allocation_pools=backend_subnet['allocation_pools'],
cidr=backend_subnet['cidr'],
ip_version=backend_subnet.get('ip_version'),
gateway_ip=backend_subnet.get('gateway_ip'),
enable_dhcp=backend_subnet.get('enable_dhcp', False),
state=models.Network.States.OK,
)
return subnet
@log_backend_action()
def pull_subnet(self, subnet):
import_time = timezone.now()
imported_subnet = self.import_subnet(subnet.backend_id)
subnet.refresh_from_db()
if subnet.modified < import_time:
update_fields = ('name', 'cidr', 'allocation_pools', 'ip_version', 'gateway_ip', 'enable_dhcp')
update_pulled_fields(subnet, imported_subnet, update_fields)
@log_backend_action('pull floating ip')
def pull_floating_ip(self, floating_ip):
neutron = self.neutron_client
try:
backend_floating_ip = neutron.show_floatingip(floating_ip.backend_id)['floatingip']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
else:
if self._floating_ip_changed(floating_ip, backend_floating_ip):
self._update_floating_ip(floating_ip, backend_floating_ip)
@log_backend_action('delete floating ip')
def delete_floating_ip(self, floating_ip):
self._delete_backend_floating_ip(floating_ip.backend_id, floating_ip.tenant.backend_id)
floating_ip.decrease_backend_quotas_usage()
def _delete_backend_floating_ip(self, backend_id, tenant_backend_id):
neutron = self.neutron_client
try:
logger.info("Deleting floating IP %s from tenant %s", backend_id, tenant_backend_id)
neutron.delete_floatingip(backend_id)
except neutron_exceptions.NotFound:
logger.debug("Floating IP %s is already gone from tenant %s", backend_id, tenant_backend_id)
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action('create floating ip')
def create_floating_ip(self, floating_ip):
neutron = self.neutron_client
try:
backend_floating_ip = neutron.create_floatingip({
'floatingip': {
'floating_network_id': floating_ip.tenant.external_network_id,
'tenant_id': floating_ip.tenant.backend_id,
}
})['floatingip']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
else:
floating_ip.runtime_state = backend_floating_ip['status']
floating_ip.address = backend_floating_ip['floating_ip_address']
floating_ip.name = backend_floating_ip['floating_ip_address']
floating_ip.backend_id = backend_floating_ip['id']
floating_ip.backend_network_id = backend_floating_ip['floating_network_id']
floating_ip.save()
@log_backend_action()
def connect_tenant_to_external_network(self, tenant, external_network_id):
neutron = self.neutron_admin_client
logger.debug('About to create external network for tenant "%s" (PK: %s)', tenant.name, tenant.pk)
try:
# check if the network actually exists
response = neutron.show_network(external_network_id)
except neutron_exceptions.NeutronClientException as e:
logger.exception('External network %s does not exist. Stale data in database?', external_network_id)
six.reraise(OpenStackBackendError, e)
network_name = response['network']['name']
subnet_id = response['network']['subnets'][0]
# XXX: refactor function call, split get_or_create_router into more fine grained
self.get_or_create_router(network_name, subnet_id,
external=True, network_id=response['network']['id'])
tenant.external_network_id = external_network_id
tenant.save()
logger.info('Router between external network %s and tenant %s was successfully created',
external_network_id, tenant.backend_id)
return external_network_id
def get_or_create_router(self, network_name, subnet_id, external=False, network_id=None, tenant_id=None):
neutron = self.neutron_admin_client
tenant_id = tenant_id or self.tenant_id
router_name = '{0}-router'.format(network_name)
try:
routers = neutron.list_routers(tenant_id=tenant_id)['routers']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
if routers:
logger.info('Router(s) in tenant with id %s already exist(s).', tenant_id)
router = routers[0]
else:
try:
router = neutron.create_router({'router': {'name': router_name, 'tenant_id': tenant_id}})['router']
logger.info('Router %s has been created.', router['name'])
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
try:
if not external:
ports = neutron.list_ports(device_id=router['id'], tenant_id=tenant_id)['ports']
if not ports:
# XXX: Ilja: revert to old behaviour as new check breaks setup of router legs
# if subnet_id in [port['fixed_ips'][0]['subnet_id'] for port in ports]:
neutron.add_interface_router(router['id'], {'subnet_id': subnet_id})
logger.info('Internal subnet %s was connected to the router %s.', subnet_id, router_name)
else:
logger.info('Internal subnet %s is already connected to the router %s.', subnet_id, router_name)
else:
if (not router.get('external_gateway_info') or
router['external_gateway_info'].get('network_id') != network_id):
neutron.add_gateway_router(router['id'], {'network_id': network_id})
logger.info('External network %s was connected to the router %s.', network_id, router_name)
else:
logger.info('External network %s is already connected to router %s.', network_id, router_name)
except neutron_exceptions.NeutronClientException as e:
logger.warning(e)
return router['id']
@log_backend_action()
def update_tenant(self, tenant):
keystone = self.keystone_admin_client
try:
keystone.projects.update(tenant.backend_id, name=tenant.name, description=tenant.description)
except keystone_exceptions.NotFound as e:
logger.error('Tenant with id %s does not exist', tenant.backend_id)
six.reraise(OpenStackBackendError, e)
def _pull_service_settings_quotas(self):
nova = self.nova_admin_client
try:
stats = nova.hypervisor_stats.statistics()
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
self.settings.set_quota_limit(self.settings.Quotas.openstack_vcpu, stats.vcpus)
self.settings.set_quota_usage(self.settings.Quotas.openstack_vcpu, stats.vcpus_used)
self.settings.set_quota_limit(self.settings.Quotas.openstack_ram, stats.memory_mb)
self.settings.set_quota_usage(self.settings.Quotas.openstack_ram, stats.memory_mb_used)
self.settings.set_quota_usage(self.settings.Quotas.openstack_storage, self.get_storage_usage())
def get_storage_usage(self):
cinder = self.cinder_admin_client
try:
volumes = cinder.volumes.list()
snapshots = cinder.volume_snapshots.list()
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
storage = sum(self.gb2mb(v.size) for v in volumes + snapshots)
return storage
def get_stats(self):
tenants = models.Tenant.objects.filter(service_project_link__service__settings=self.settings)
quota_names = ('vcpu', 'ram', 'storage')
quota_values = models.Tenant.get_sum_of_quotas_as_dict(
tenants, quota_names=quota_names, fields=['limit'])
quota_stats = {
'vcpu_quota': quota_values.get('vcpu', -1.0),
'ram_quota': quota_values.get('ram', -1.0),
'storage_quota': quota_values.get('storage', -1.0)
}
stats = {}
for quota in self.settings.quotas.all():
name = quota.name.replace('openstack_', '')
if name not in quota_names:
continue
stats[name] = quota.limit
stats[name + '_usage'] = quota.usage
stats.update(quota_stats)
return stats
<file_sep>/src/nodeconductor_openstack/openstack/migrations/0020_tenant_extra_configuration.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0019_remove_payable_mixin'),
]
operations = [
migrations.AddField(
model_name='tenant',
name='extra_configuration',
field=jsonfield.fields.JSONField(default={}, help_text='Configuration details that are not represented on backend.'),
),
]
<file_sep>/src/nodeconductor_openstack/openstack_base/models.py
from django.core.validators import MaxValueValidator
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from iptools.ipv4 import validate_cidr
@python_2_unicode_compatible
class BaseSecurityGroupRule(models.Model):
TCP = 'tcp'
UDP = 'udp'
ICMP = 'icmp'
CHOICES = (
(TCP, 'tcp'),
(UDP, 'udp'),
(ICMP, 'icmp'),
)
protocol = models.CharField(max_length=4, blank=True, choices=CHOICES)
from_port = models.IntegerField(validators=[MaxValueValidator(65535)], null=True)
to_port = models.IntegerField(validators=[MaxValueValidator(65535)], null=True)
cidr = models.CharField(max_length=32, blank=True)
backend_id = models.CharField(max_length=128, blank=True)
class Meta(object):
abstract = True
def validate_icmp(self):
if self.from_port is not None and not -1 <= self.from_port <= 255:
raise ValidationError('Wrong value for "from_port": '
'expected value in range [-1, 255], found %d' % self.from_port)
if self.to_port is not None and not -1 <= self.to_port <= 255:
raise ValidationError('Wrong value for "to_port": '
'expected value in range [-1, 255], found %d' % self.to_port)
def validate_port(self):
if self.from_port is not None and self.to_port is not None:
if self.from_port > self.to_port:
raise ValidationError('"from_port" should be less or equal to "to_port"')
if self.from_port is not None and self.from_port < 1:
raise ValidationError('Wrong value for "from_port": '
'expected value in range [1, 65535], found %d' % self.from_port)
if self.to_port is not None and self.to_port < 1:
raise ValidationError('Wrong value for "to_port": '
'expected value in range [1, 65535], found %d' % self.to_port)
def validate_cidr(self):
if not self.cidr:
return
if not validate_cidr(self.cidr):
raise ValidationError(
'Wrong cidr value. Expected cidr format: <0-255>.<0-255>.<0-255>.<0-255>/<0-32>')
def clean(self):
if self.to_port is None:
raise ValidationError('"to_port" cannot be empty')
if self.from_port is None:
raise ValidationError('"from_port" cannot be empty')
if self.protocol == 'icmp':
self.validate_icmp()
elif self.protocol in ('tcp', 'udp'):
self.validate_port()
else:
raise ValidationError('Wrong value for "protocol": '
'expected one of (tcp, udp, icmp), found %s' % self.protocol)
self.validate_cidr()
def __str__(self):
return '%s (%s): %s (%s -> %s)' % \
(self.security_group, self.protocol, self.cidr, self.from_port, self.to_port)
@python_2_unicode_compatible
class Port(models.Model):
# TODO: Use dedicated field: https://github.com/django-macaddress/django-macaddress
mac_address = models.CharField(max_length=32, blank=True)
ip4_address = models.GenericIPAddressField(null=True, blank=True, protocol='IPv4')
ip6_address = models.GenericIPAddressField(null=True, blank=True, protocol='IPv6')
backend_id = models.CharField(max_length=255, blank=True)
class Meta(object):
abstract = True
def __str__(self):
return self.ip4_address or self.ip6_address or 'Not initialized'
<file_sep>/src/nodeconductor_openstack/openstack/tests/test_tenant.py
from ddt import data, ddt
from django.contrib.auth import get_user_model
from mock import patch
from rest_framework import test, status
from nodeconductor.structure.tests import factories as structure_factories
from nodeconductor_openstack.openstack.models import Tenant, OpenStackService
from . import factories, fixtures
from .. import models
class BaseTenantActionsTest(test.APITransactionTestCase):
def setUp(self):
super(BaseTenantActionsTest, self).setUp()
self.fixture = fixtures.OpenStackFixture()
self.tenant = self.fixture.tenant
class TenantCreateTest(BaseTenantActionsTest):
def setUp(self):
super(TenantCreateTest, self).setUp()
self.valid_data = {
'name': 'Test tenant',
'service_project_link': factories.OpenStackServiceProjectLinkFactory.get_url(self.fixture.openstack_spl),
}
self.url = factories.TenantFactory.get_list_url()
def test_cannot_create_tenant_with_service_settings_username(self):
self.client.force_authenticate(self.fixture.staff)
self.fixture.openstack_service_settings.username = 'admin'
self.fixture.openstack_service_settings.save()
data = self.valid_data.copy()
data['user_username'] = self.fixture.openstack_service_settings.username
response = self.client.post(self.url, data=data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(models.Tenant.objects.filter(user_username=data['user_username']).exists())
def test_cannot_create_tenant_with_blacklisted_username(self):
self.client.force_authenticate(self.fixture.staff)
self.fixture.openstack_service_settings.options['blacklisted_usernames'] = ['admin']
data = self.valid_data.copy()
data['user_username'] = self.fixture.openstack_service_settings.options['blacklisted_usernames'][0]
response = self.client.post(self.url, data=data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(models.Tenant.objects.filter(user_username=data['user_username']).exists())
def test_cannot_create_tenant_with_duplicated_username(self):
self.client.force_authenticate(self.fixture.staff)
self.fixture.tenant.user_username = 'username'
self.fixture.tenant.save()
data = self.valid_data.copy()
data['user_username'] = self.fixture.tenant.user_username
response = self.client.post(self.url, data=data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(models.Tenant.objects.filter(user_username=data['user_username']).count(), 1)
@patch('nodeconductor_openstack.openstack.executors.TenantPushQuotasExecutor.execute')
class TenantQuotasTest(BaseTenantActionsTest):
def test_non_staff_user_cannot_set_tenant_quotas(self, mocked_task):
self.client.force_authenticate(user=structure_factories.UserFactory())
response = self.client.post(self.get_url())
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertFalse(mocked_task.called)
def test_staff_can_set_tenant_quotas(self, mocked_task):
self.client.force_authenticate(self.fixture.staff)
quotas_data = {'security_group_count': 100, 'security_group_rule_count': 100}
response = self.client.post(self.get_url(), data=quotas_data)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
mocked_task.assert_called_once_with(self.tenant, quotas=quotas_data)
def get_url(self):
return factories.TenantFactory.get_url(self.tenant, 'set_quotas')
@patch('nodeconductor_openstack.openstack.executors.TenantPullExecutor.execute')
class TenantPullTest(BaseTenantActionsTest):
def test_staff_can_pull_tenant(self, mocked_task):
self.client.force_authenticate(self.fixture.staff)
response = self.client.post(self.get_url())
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
mocked_task.assert_called_once_with(self.tenant)
def get_url(self):
return factories.TenantFactory.get_url(self.tenant, 'pull')
@patch('nodeconductor_openstack.openstack.executors.TenantDeleteExecutor.execute')
class TenantDeleteTest(BaseTenantActionsTest):
def test_staff_can_delete_tenant(self, mocked_task):
self.client.force_authenticate(self.fixture.staff)
response = self.client.delete(self.get_url())
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
mocked_task.assert_called_once_with(self.tenant, async=True, force=False)
def get_url(self):
return factories.TenantFactory.get_url(self.tenant)
@ddt
class TenantCreateServiceTest(BaseTenantActionsTest):
def setUp(self):
super(TenantCreateServiceTest, self).setUp()
self.settings = self.tenant.service_project_link.service.settings
self.url = factories.TenantFactory.get_url(self.tenant, 'create_service')
@data('owner', 'staff')
@patch('nodeconductor.structure.executors.ServiceSettingsCreateExecutor.execute')
def test_can_create_service(self, user, mocked_execute):
self.client.force_authenticate(getattr(self.fixture, user))
service_settings_name = 'Valid service settings name'
response = self.client.post(self.url, {'name': service_settings_name})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(mocked_execute.called)
self.assertTrue(OpenStackService.objects.filter(
customer=self.tenant.customer,
settings__name=service_settings_name,
settings__backend_url=self.settings.backend_url,
settings__username=self.tenant.user_username,
settings__password=<PASSWORD>
).exists())
@data('manager', 'admin')
def test_can_not_create_service(self, user):
self.client.force_authenticate(getattr(self.fixture, user))
response = self.client.post(self.url, {'name': 'Valid service'})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_can_not_create_service_from_erred_tenant(self):
self.tenant.state = Tenant.States.ERRED
self.tenant.save()
self.client.force_authenticate(self.fixture.owner)
response = self.client.post(self.url, {'name': 'Valid service'})
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
class TenantActionsMetadataTest(BaseTenantActionsTest):
def test_if_tenant_is_ok_actions_enabled(self):
self.client.force_authenticate(self.fixture.staff)
actions = self.get_actions()
for action in 'create_service', 'set_quotas':
self.assertTrue(actions[action]['enabled'])
def test_if_tenant_is_not_ok_actions_disabled(self):
self.tenant.state = Tenant.States.DELETING
self.tenant.save()
self.client.force_authenticate(self.fixture.owner)
actions = self.get_actions()
for action in 'create_service', 'set_quotas':
self.assertFalse(actions[action]['enabled'])
def get_actions(self):
url = factories.TenantFactory.get_url(self.tenant)
response = self.client.options(url)
return response.data['actions']
@patch('nodeconductor_openstack.openstack.executors.FloatingIPCreateExecutor.execute')
class TenantCreateFloatingIPTest(BaseTenantActionsTest):
def setUp(self):
super(TenantCreateFloatingIPTest, self).setUp()
self.client.force_authenticate(self.fixture.owner)
self.url = factories.TenantFactory.get_url(self.tenant, 'create_floating_ip')
def test_that_floating_ip_count_quota_increases_when_floating_ip_is_created(self, mocked_task):
response = self.client.post(self.url)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(self.tenant.floating_ips.count(), 1)
self.assertTrue(mocked_task.called)
def test_that_floating_ip_count_quota_exceeds_limit_if_too_many_ips_are_created(self, mocked_task):
self.tenant.set_quota_limit('floating_ip_count', 0)
response = self.client.post(self.url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(self.tenant.floating_ips.count(), 0)
self.assertFalse(mocked_task.called)
def test_user_cannot_create_floating_ip_if_external_network_is_not_defined_for_tenant(self, mocked_task):
self.tenant.external_network_id = ''
self.tenant.save()
response = self.client.post(self.url)
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
self.assertEqual(self.tenant.floating_ips.count(), 0)
self.assertFalse(mocked_task.called)
@patch('nodeconductor_openstack.openstack.executors.NetworkCreateExecutor.execute')
class TenantCreateNetworkTest(BaseTenantActionsTest):
quota_name = 'network_count'
def setUp(self):
super(TenantCreateNetworkTest, self).setUp()
self.client.force_authenticate(self.fixture.owner)
self.url = factories.TenantFactory.get_url(self.tenant, 'create_network')
self.request_data = {
'name': 'test_network_name'
}
def test_that_network_quota_is_increased_when_network_is_created(self, mocked_task):
response = self.client.post(self.url, self.request_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(self.tenant.networks.count(), 1)
self.assertEqual(self.tenant.quotas.get(name=self.quota_name).usage, 1)
self.assertTrue(mocked_task.called)
def test_that_network_is_not_created_when_quota_exceeds_set_limit(self, mocked_task):
self.tenant.set_quota_limit(self.quota_name, 0)
response = self.client.post(self.url, self.request_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(self.tenant.networks.count(), 0)
self.assertEqual(self.tenant.quotas.get(name=self.quota_name).usage, 0)
self.assertFalse(mocked_task.called)
@ddt
class TenantChangePasswordTest(BaseTenantActionsTest):
def setUp(self):
super(TenantChangePasswordTest, self).setUp()
self.tenant = self.fixture.tenant
self.url = factories.TenantFactory.get_url(self.tenant, action='change_password')
self.new_password = get_user_model().objects.make_random_password()[:50]
@data('owner', 'staff', 'admin', 'manager')
def test_user_can_change_tenant_user_password(self, user):
self.client.force_authenticate(getattr(self.fixture, user))
response = self.client.post(self.url, {'user_password': <PASSWORD>})
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
self.tenant.refresh_from_db()
self.assertEqual(self.tenant.user_password, <PASSWORD>)
@data('global_support', 'customer_support', 'project_support')
def test_user_cannot_change_tenant_user_password(self, user):
self.client.force_authenticate(getattr(self.fixture, user))
response = self.client.post(self.url, {'user_password': self.<PASSWORD>})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_user_cannot_set_password_if_it_consists_only_with_digits(self):
self.client.force_authenticate(self.fixture.owner)
response = self.client.post(self.url, {'user_password': <PASSWORD>})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_cannot_set_password_with_length_less_than_8_characters(self):
request_data = {
'user_password': get_user_model().objects.make_random_password()[:7]
}
self.client.force_authenticate(self.fixture.owner)
response = self.client.post(self.url, request_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_cannot_set_password_if_it_matches_to_the_old_one(self):
self.client.force_authenticate(self.fixture.owner)
response = self.client.post(self.url, {'user_password': self.fixture.tenant.user_password})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_cannot_change_password_if_tenant_is_not_in_OK_state(self):
self.tenant.state = self.tenant.States.ERRED
self.tenant.save()
self.client.force_authenticate(self.fixture.owner)
response = self.client.post(self.url, {'user_password': self.fixture.tenant.user_password})
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
def test_user_can_set_an_empty_password(self):
self.client.force_authenticate(self.fixture.owner)
response = self.client.post(self.url, {'user_password': ''})
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
@ddt
class SecurityGroupCreateTest(BaseTenantActionsTest):
def setUp(self):
super(SecurityGroupCreateTest, self).setUp()
self.valid_data = {
'name': 'test_security_group',
'description': 'test security_group description',
'rules': [
{
'protocol': 'tcp',
'from_port': 1,
'to_port': 10,
'cidr': '172.16.58.3/24',
}
]
}
self.url = factories.TenantFactory.get_url(self.fixture.tenant, action='create_security_group')
@data('owner', 'admin', 'manager')
def test_user_with_access_can_create_security_group(self, user):
self.client.force_authenticate(getattr(self.fixture, user))
response = self.client.post(self.url, self.valid_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(models.SecurityGroup.objects.filter(name=self.valid_data['name']).exists())
def test_security_group_can_not_be_created_if_quota_is_over_limit(self):
self.fixture.tenant.set_quota_limit('security_group_count', 0)
self.client.force_authenticate(self.fixture.admin)
response = self.client.post(self.url, self.valid_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(models.SecurityGroup.objects.filter(name=self.valid_data['name']).exists())
def test_security_group_quota_increses_on_security_group_creation(self):
self.client.force_authenticate(self.fixture.admin)
response = self.client.post(self.url, self.valid_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(self.fixture.tenant.quotas.get(name='security_group_count').usage, 1)
self.assertEqual(self.fixture.tenant.quotas.get(name='security_group_rule_count').usage, 1)
def test_security_group_can_not_be_created_if_rules_quota_is_over_limit(self):
self.fixture.tenant.set_quota_limit('security_group_rule_count', 0)
self.client.force_authenticate(self.fixture.admin)
response = self.client.post(self.url, self.valid_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(models.SecurityGroup.objects.filter(name=self.valid_data['name']).exists())
def test_security_group_creation_starts_sync_task(self):
self.client.force_authenticate(self.fixture.admin)
with patch('nodeconductor_openstack.openstack.executors.SecurityGroupCreateExecutor.execute') as mocked_execute:
response = self.client.post(self.url, data=self.valid_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)
security_group = models.SecurityGroup.objects.get(name=self.valid_data['name'])
mocked_execute.assert_called_once_with(security_group)
def test_security_group_raises_validation_error_if_rule_port_is_invalid(self):
self.valid_data['rules'][0]['to_port'] = 80000
self.client.force_authenticate(self.fixture.admin)
response = self.client.post(self.url, data=self.valid_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertFalse(models.SecurityGroup.objects.filter(name=self.valid_data['name']).exists())
<file_sep>/src/nodeconductor_openstack/openstack/views.py
import uuid
from django.utils import six
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, decorators, response, permissions, status, serializers as rf_serializers
from rest_framework.exceptions import ValidationError
from nodeconductor.core import validators as core_validators, exceptions as core_exceptions
from nodeconductor.structure import (
views as structure_views, SupportedServices, executors as structure_executors,
filters as structure_filters, permissions as structure_permissions)
from nodeconductor.structure.managers import filter_queryset_for_user
from . import models, filters, serializers, executors
class GenericImportMixin(object):
"""
This mixin selects serializer class by matching resource_type query parameter
against model name using import_serializers mapping.
"""
import_serializers = {}
def _can_import(self):
return self.import_serializers != {}
def get_serializer_class(self):
if self.request.method == 'POST' and self.action == 'link':
resource_type = self.request.data.get('resource_type') or self.request.query_params.get('resource_type')
items = self.import_serializers.items()
if len(items) == 1:
model_cls, serializer_cls = items[0]
return serializer_cls
for model_cls, serializer_cls in items:
if resource_type == SupportedServices.get_name_for_model(model_cls):
return serializer_cls
return super(GenericImportMixin, self).get_serializer_class()
class OpenStackServiceViewSet(GenericImportMixin, structure_views.BaseServiceViewSet):
queryset = models.OpenStackService.objects.all()
serializer_class = serializers.ServiceSerializer
import_serializer_class = serializers.TenantImportSerializer
import_serializers = {
models.Tenant: serializers.TenantImportSerializer,
}
def list(self, request, *args, **kwargs):
"""
To create a service, issue a **POST** to */api/openstack/* as a customer owner.
You can create service based on shared service settings. Example:
.. code-block:: http
POST /api/openstack/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token <PASSWORD>
Host: example.com
{
"name": "Common OpenStack",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"settings": "http://example.com/api/service-settings/93ba615d6111466ebe3f792669059cb4/"
}
Or provide your own credentials. Example:
.. code-block:: http
POST /api/openstack/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token <PASSWORD>
Host: example.com
{
"name": "My OpenStack",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"backend_url": "http://keystone.example.com:5000/v2.0",
"username": "admin",
"password": "<PASSWORD>"
}
"""
return super(OpenStackServiceViewSet, self).list(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
"""
To update OpenStack service issue **PUT** or **PATCH** against */api/openstack/<service_uuid>/*
as a customer owner. You can update service's `name` and `available_for_all` fields.
Example of a request:
.. code-block:: http
PUT /api/openstack/c6526bac12b343a9a65c4cd6710666ee/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token <PASSWORD>92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "My OpenStack2"
}
To remove OpenStack service, issue **DELETE** against */api/openstack/<service_uuid>/* as
staff user or customer owner.
"""
return super(OpenStackServiceViewSet, self).retrieve(request, *args, **kwargs)
def get_import_context(self):
context = {'resource_type': self.request.query_params.get('resource_type')}
tenant_uuid = self.request.query_params.get('tenant_uuid')
if tenant_uuid:
try:
uuid.UUID(tenant_uuid)
except ValueError:
raise ValidationError('Invalid tenant UUID')
queryset = filter_queryset_for_user(models.Tenant.objects.all(), self.request.user)
tenant = queryset.filter(service_project_link__service=self.get_object(),
uuid=tenant_uuid).first()
context['tenant'] = tenant
return context
class OpenStackServiceProjectLinkViewSet(structure_views.BaseServiceProjectLinkViewSet):
queryset = models.OpenStackServiceProjectLink.objects.all()
serializer_class = serializers.ServiceProjectLinkSerializer
filter_class = filters.OpenStackServiceProjectLinkFilter
def list(self, request, *args, **kwargs):
"""
In order to be able to provision OpenStack resources, it must first be linked to a project. To do that,
**POST** a connection between project and a service to */api/openstack-service-project-link/*
as stuff user or customer owner.
Example of a request:
.. code-block:: http
POST /api/openstack-service-project-link/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token <PASSWORD>
Host: example.com
{
"project": "http://example.com/api/projects/e5f973af2eb14d2d8c38d62bcbaccb33/",
"service": "http://example.com/api/openstack/b0e8a4cbd47c4f9ca01642b7ec033db4/"
}
To remove a link, issue DELETE to URL of the corresponding connection as stuff user or customer owner.
"""
return super(OpenStackServiceProjectLinkViewSet, self).list(request, *args, **kwargs)
class FlavorViewSet(structure_views.BaseServicePropertyViewSet):
"""
VM instance flavor is a pre-defined set of virtual hardware parameters that the instance will use:
CPU, memory, disk size etc. VM instance flavor is not to be confused with VM template -- flavor is a set of virtual
hardware parameters whereas template is a definition of a system to be installed on this instance.
"""
queryset = models.Flavor.objects.all().order_by('settings', 'cores', 'ram', 'disk')
serializer_class = serializers.FlavorSerializer
lookup_field = 'uuid'
filter_class = filters.FlavorFilter
class ImageViewSet(structure_views.BaseServicePropertyViewSet):
queryset = models.Image.objects.all()
serializer_class = serializers.ImageSerializer
lookup_field = 'uuid'
filter_class = filters.ImageFilter
class SecurityGroupViewSet(six.with_metaclass(structure_views.ResourceViewMetaclass, structure_views.ResourceViewSet)):
queryset = models.SecurityGroup.objects.all()
serializer_class = serializers.SecurityGroupSerializer
filter_class = filters.SecurityGroupFilter
disabled_actions = ['create', 'pull'] # pull operation should be implemented in WAL-323
update_executor = executors.SecurityGroupUpdateExecutor
delete_executor = executors.SecurityGroupDeleteExecutor
@decorators.detail_route(methods=['POST'])
def set_rules(self, request, uuid=None):
""" WARNING! Auto-generated HTML form is wrong for this endpoint. List should be defined as input.
Example:
[
{
"protocol": "tcp",
"from_port": 1,
"to_port": 10,
"cidr": "10.1.1.0/24"
}
]
"""
# XXX: DRF does not support forms generation for list serializers.
# Thats why we use different serializer in view.
serializer = serializers.SecurityGroupRuleListUpdateSerializer(
data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
serializer.save()
executors.PushSecurityGroupRulesExecutor().execute(self.get_object())
return response.Response(
{'status': 'Rules update was successfully scheduled.'}, status=status.HTTP_202_ACCEPTED)
set_rules_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
set_rules_serializer_class = serializers.SecurityGroupRuleUpdateSerializer
class IpMappingViewSet(viewsets.ModelViewSet):
queryset = models.IpMapping.objects.all()
serializer_class = serializers.IpMappingSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter, DjangoFilterBackend)
permission_classes = (permissions.IsAuthenticated, permissions.DjangoObjectPermissions)
filter_class = filters.IpMappingFilter
class FloatingIPViewSet(six.with_metaclass(structure_views.ResourceViewMetaclass,
structure_views.ResourceViewSet)):
queryset = models.FloatingIP.objects.all()
serializer_class = serializers.FloatingIPSerializer
filter_class = filters.FloatingIPFilter
disabled_actions = ['update', 'partial_update', 'create']
delete_executor = executors.FloatingIPDeleteExecutor
pull_executor = executors.FloatingIPPullExecutor
def list(self, request, *args, **kwargs):
"""
To get a list of all available floating IPs, issue **GET** against */api/floating-ips/*.
Floating IPs are read only. Each floating IP has fields: 'address', 'status'.
Status *DOWN* means that floating IP is not linked to a VM, status *ACTIVE* means that it is in use.
"""
return super(FloatingIPViewSet, self).list(request, *args, **kwargs)
class TenantViewSet(six.with_metaclass(structure_views.ResourceViewMetaclass, structure_views.ResourceViewSet)):
queryset = models.Tenant.objects.all()
serializer_class = serializers.TenantSerializer
filter_class = structure_filters.BaseResourceFilter
create_executor = executors.TenantCreateExecutor
update_executor = executors.TenantUpdateExecutor
delete_executor = executors.TenantDeleteExecutor
pull_executor = executors.TenantPullExecutor
@decorators.detail_route(methods=['post'])
def create_service(self, request, uuid=None):
"""Create non-admin service with credentials from the tenant"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
name = serializer.validated_data['name']
tenant = self.get_object()
service = tenant.create_service(name)
structure_executors.ServiceSettingsCreateExecutor.execute(service.settings, async=self.async_executor)
serializer = serializers.ServiceSerializer(service, context={'request': request})
return response.Response(serializer.data, status=status.HTTP_201_CREATED)
create_service_permissions = [structure_permissions.is_owner]
create_service_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
create_service_serializer_class = serializers.ServiceNameSerializer
@decorators.detail_route(methods=['post'])
def set_quotas(self, request, uuid=None):
"""
A quota can be set for a particular tenant. Only staff users can do that.
In order to set quota submit **POST** request to */api/openstack-tenants/<uuid>/set_quotas/*.
The quota values are propagated to the backend.
The following quotas are supported. All values are expected to be integers:
- instances - maximal number of created instances.
- ram - maximal size of ram for allocation. In MiB_.
- storage - maximal size of storage for allocation. In MiB_.
- vcpu - maximal number of virtual cores for allocation.
- security_group_count - maximal number of created security groups.
- security_group_rule_count - maximal number of created security groups rules.
- volumes - maximal number of created volumes.
- snapshots - maximal number of created snapshots.
It is possible to update quotas by one or by submitting all the fields in one request.
NodeConductor will attempt to update the provided quotas. Please note, that if provided quotas are
conflicting with the backend (e.g. requested number of instances is below of the already existing ones),
some quotas might not be applied.
.. _MiB: http://en.wikipedia.org/wiki/Mebibyte
.. _settings: http://nodeconductor.readthedocs.org/en/stable/guide/intro.html#id1
Example of a valid request (token is user specific):
.. code-block:: http
POST /api/openstack-tenants/c84d653b9ec92c6cbac41c706593e66f567a7fa4/set_quotas/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Host: example.com
{
"instances": 30,
"ram": 100000,
"storage": 1000000,
"vcpu": 30,
"security_group_count": 100,
"security_group_rule_count": 100,
"volumes": 10,
"snapshots": 20
}
Response code of a successful request is **202 ACCEPTED**.
In case tenant is in a non-stable status, the response would be **409 CONFLICT**.
In this case REST client is advised to repeat the request after some time.
On successful completion the task will synchronize quotas with the backend.
"""
tenant = self.get_object()
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
quotas = dict(serializer.validated_data)
for quota_name, limit in quotas.items():
tenant.set_quota_limit(quota_name, limit)
executors.TenantPushQuotasExecutor.execute(tenant, quotas=quotas)
return response.Response(
{'detail': 'Quota update has been scheduled'}, status=status.HTTP_202_ACCEPTED)
set_quotas_permissions = [structure_permissions.is_staff]
set_quotas_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
set_quotas_serializer_class = serializers.TenantQuotaSerializer
@decorators.detail_route(methods=['post'])
def create_network(self, request, uuid=None):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
network = serializer.save()
executors.NetworkCreateExecutor().execute(network)
return response.Response(serializer.data, status=status.HTTP_201_CREATED)
create_network_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
create_network_serializer_class = serializers.NetworkSerializer
def external_network_is_defined(tenant):
if not tenant.external_network_id:
raise core_exceptions.IncorrectStateException(
'Cannot create floating IP if tenant external network is not defined.')
@decorators.detail_route(methods=['post'])
def create_floating_ip(self, request, uuid=None):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
floating_ip = serializer.save()
executors.FloatingIPCreateExecutor.execute(floating_ip)
return response.Response(serializer.data, status=status.HTTP_201_CREATED)
create_floating_ip_validators = [core_validators.StateValidator(models.Tenant.States.OK),
external_network_is_defined]
create_floating_ip_serializer_class = serializers.FloatingIPSerializer
@decorators.detail_route(methods=['post'])
def pull_floating_ips(self, request, uuid=None):
tenant = self.get_object()
executors.TenantPullFloatingIPsExecutor.execute(tenant)
return response.Response(status=status.HTTP_202_ACCEPTED)
pull_floating_ips_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
pull_floating_ips_serializer_class = rf_serializers.Serializer
@decorators.detail_route(methods=['post'])
def create_security_group(self, request, uuid=None):
"""
Example of a request:
.. code-block:: http
{
"name": "Security group name",
"description": "description",
"rules": [
{
"protocol": "tcp",
"from_port": 1,
"to_port": 10,
"cidr": "10.1.1.0/24"
},
{
"protocol": "udp",
"from_port": 10,
"to_port": 8000,
"cidr": "10.1.1.0/24"
}
]
}
"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
security_group = serializer.save()
executors.SecurityGroupCreateExecutor().execute(security_group)
return response.Response(serializer.data, status=status.HTTP_201_CREATED)
create_security_group_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
create_security_group_serializer_class = serializers.SecurityGroupSerializer
@decorators.detail_route(methods=['post'])
def pull_security_groups(self, request, uuid=None):
executors.TenantPullSecurityGroupsExecutor.execute(self.get_object())
return response.Response(
{'status': 'Security groups pull has been scheduled.'}, status=status.HTTP_202_ACCEPTED)
pull_security_groups_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
@decorators.detail_route(methods=['post'])
def change_password(self, request, uuid=None):
serializer = self.get_serializer(instance=self.get_object(), data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
executors.TenantChangeUserPasswordExecutor.execute(self.get_object())
return response.Response({'status': 'Password update has been scheduled.'}, status=status.HTTP_202_ACCEPTED)
change_password_serializer_class = serializers.TenantChangePasswordSerializer
change_password_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
def pull_quotas(self, request, uuid=None):
executors.TenantPullQuotasExecutor.execute(self.get_object())
return response.Response({'status': 'Quotas pull has been scheduled.'}, status=status.HTTP_202_ACCEPTED)
pull_quotas_validators = [core_validators.StateValidator(models.Tenant.States.OK)]
class NetworkViewSet(six.with_metaclass(structure_views.ResourceViewMetaclass, structure_views.ResourceViewSet)):
queryset = models.Network.objects.all()
serializer_class = serializers.NetworkSerializer
filter_class = filters.NetworkFilter
disabled_actions = ['create']
update_executor = executors.NetworkUpdateExecutor
delete_executor = executors.NetworkDeleteExecutor
pull_executor = executors.NetworkPullExecutor
@decorators.detail_route(methods=['post'])
def create_subnet(self, request, uuid=None):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
subnet = serializer.save()
executors.SubNetCreateExecutor.execute(subnet)
return response.Response(serializer.data, status=status.HTTP_201_CREATED)
create_subnet_validators = [core_validators.StateValidator(models.Network.States.OK)]
create_subnet_serializer_class = serializers.SubNetSerializer
class SubNetViewSet(six.with_metaclass(structure_views.ResourceViewMetaclass, structure_views.ResourceViewSet)):
queryset = models.SubNet.objects.all()
serializer_class = serializers.SubNetSerializer
filter_class = filters.SubNetFilter
disabled_actions = ['create']
update_executor = executors.SubNetUpdateExecutor
delete_executor = executors.SubNetDeleteExecutor
pull_executor = executors.SubNetPullExecutor
<file_sep>/src/nodeconductor_openstack/openstack_tenant/tests/unittests/test_handlers.py
from __future__ import unicode_literals
from django.test import TestCase
from nodeconductor.core.models import StateMixin
from nodeconductor_openstack.openstack.tests import factories as openstack_factories
from nodeconductor.structure import models as structure_models
from nodeconductor.structure.tests import factories as structure_factories
from .. import factories
from ... import models
class SecurityGroupHandlerTest(TestCase):
def setUp(self):
self.tenant = openstack_factories.TenantFactory()
self.service_settings = structure_factories.ServiceSettingsFactory(scope=self.tenant)
def test_security_group_create(self):
openstack_security_group = openstack_factories.SecurityGroupFactory(
tenant=self.tenant,
state=StateMixin.States.CREATING
)
self.assertEqual(models.SecurityGroup.objects.count(), 0)
openstack_security_group.set_ok()
openstack_security_group.save()
self.assertEqual(models.SecurityGroup.objects.count(), 1)
def test_security_group_update(self):
openstack_security_group = openstack_factories.SecurityGroupFactory(
tenant=self.tenant,
name='New name',
description='New description',
state=StateMixin.States.UPDATING
)
security_group = factories.SecurityGroupFactory(
settings=self.service_settings,
backend_id=openstack_security_group.backend_id
)
openstack_security_group.set_ok()
openstack_security_group.save()
security_group.refresh_from_db()
self.assertIn(openstack_security_group.name, security_group.name)
self.assertIn(openstack_security_group.description, security_group.description)
def test_security_group_rules_are_updated_when_one_more_rule_is_added(self):
openstack_security_group = openstack_factories.SecurityGroupFactory(
tenant=self.tenant,
state=StateMixin.States.UPDATING
)
openstack_factories.SecurityGroupRuleFactory(security_group=openstack_security_group)
security_group = factories.SecurityGroupFactory(
settings=self.service_settings,
backend_id=openstack_security_group.backend_id
)
openstack_security_group.set_ok()
openstack_security_group.save()
self.assertEqual(security_group.rules.count(), 1, 'Security group rule has not been added')
self.assertEqual(security_group.rules.first().protocol, openstack_security_group.rules.first().protocol)
self.assertEqual(security_group.rules.first().from_port, openstack_security_group.rules.first().from_port)
self.assertEqual(security_group.rules.first().to_port, openstack_security_group.rules.first().to_port)
def test_security_group_is_deleted_when_openstack_security_group_is_deleted(self):
openstack_security_group = openstack_factories.SecurityGroupFactory(tenant=self.tenant)
factories.SecurityGroupFactory(settings=self.service_settings, backend_id=openstack_security_group.backend_id)
openstack_security_group.delete()
self.assertEqual(models.SecurityGroup.objects.count(), 0)
class FloatingIPHandlerTest(TestCase):
def setUp(self):
self.tenant = openstack_factories.TenantFactory()
self.service_settings = structure_factories.ServiceSettingsFactory(scope=self.tenant)
def test_floating_ip_create(self):
openstack_floating_ip = openstack_factories.FloatingIPFactory(
tenant=self.tenant,
state=StateMixin.States.CREATING
)
self.assertEqual(models.FloatingIP.objects.count(), 0)
openstack_floating_ip.set_ok()
openstack_floating_ip.save()
self.assertEqual(models.FloatingIP.objects.count(), 1)
def test_floating_ip_update(self):
openstack_floating_ip = openstack_factories.FloatingIPFactory(
tenant=self.tenant,
name='New name',
state=StateMixin.States.UPDATING
)
floating_ip = factories.FloatingIPFactory(
settings=self.service_settings,
backend_id=openstack_floating_ip.backend_id,
)
openstack_floating_ip.set_ok()
openstack_floating_ip.save()
floating_ip.refresh_from_db()
self.assertEqual(openstack_floating_ip.name, floating_ip.name)
self.assertEqual(openstack_floating_ip.address, floating_ip.address)
self.assertEqual(openstack_floating_ip.runtime_state, floating_ip.runtime_state)
self.assertEqual(openstack_floating_ip.backend_network_id, floating_ip.backend_network_id)
def test_floating_ip_delete(self):
openstack_floating_ip = openstack_factories.FloatingIPFactory(tenant=self.tenant)
factories.FloatingIPFactory(settings=self.service_settings, backend_id=openstack_floating_ip.backend_id)
openstack_floating_ip.delete()
self.assertEqual(models.FloatingIP.objects.count(), 0)
class TenantChangePasswordTest(TestCase):
def test_service_settings_password_updates_when_tenant_user_password_changes(self):
tenant = openstack_factories.TenantFactory()
service_settings = structure_models.ServiceSettings.objects.first()
service_settings.scope = tenant
service_settings.password = <PASSWORD>
service_settings.save()
new_password = '<PASSWORD>'
tenant.user_password = <PASSWORD>
tenant.save()
service_settings.refresh_from_db()
self.assertEqual(service_settings.password, <PASSWORD>)
class NetworkHandlerTest(TestCase):
def setUp(self):
self.tenant = openstack_factories.TenantFactory()
self.service_settings = structure_factories.ServiceSettingsFactory(scope=self.tenant)
def test_network_create(self):
openstack_network = openstack_factories.NetworkFactory(
tenant=self.tenant, state=StateMixin.States.CREATING)
self.assertEqual(models.Network.objects.count(), 0)
openstack_network.set_ok()
openstack_network.save()
self.assertTrue(models.Network.objects.filter(backend_id=openstack_network.backend_id).exists())
def test_network_update(self):
openstack_network = openstack_factories.NetworkFactory(
tenant=self.tenant,
name='New network name',
state=StateMixin.States.UPDATING
)
network = factories.NetworkFactory(
settings=self.service_settings,
backend_id=openstack_network.backend_id,
)
openstack_network.set_ok()
openstack_network.save()
network.refresh_from_db()
self.assertEqual(openstack_network.name, network.name)
self.assertEqual(openstack_network.is_external, network.is_external)
self.assertEqual(openstack_network.type, network.type)
self.assertEqual(openstack_network.segmentation_id, network.segmentation_id)
self.assertEqual(openstack_network.backend_id, network.backend_id)
def test_network_delete(self):
openstack_network = openstack_factories.NetworkFactory(tenant=self.tenant)
factories.NetworkFactory(settings=self.service_settings, backend_id=openstack_network.backend_id)
openstack_network.delete()
self.assertEqual(models.Network.objects.count(), 0)
class SubNetHandlerTest(TestCase):
def setUp(self):
self.tenant = openstack_factories.TenantFactory()
self.openstack_network = openstack_factories.NetworkFactory(tenant=self.tenant)
self.service_settings = structure_factories.ServiceSettingsFactory(scope=self.tenant)
self.network = factories.NetworkFactory(
settings=self.service_settings,
backend_id=self.openstack_network.backend_id
)
def test_subnet_create(self):
openstack_subnet = openstack_factories.SubNetFactory(
network=self.openstack_network,
state=StateMixin.States.CREATING
)
self.assertEqual(models.SubNet.objects.count(), 0)
openstack_subnet.set_ok()
openstack_subnet.save()
self.assertTrue(models.SubNet.objects.filter(backend_id=openstack_subnet.backend_id).exists())
def test_subnet_update(self):
openstack_subnet = openstack_factories.SubNetFactory(
network=self.openstack_network,
name='New subnet name',
state=StateMixin.States.UPDATING
)
subnet = factories.SubNetFactory(
network=self.network,
settings=self.service_settings,
backend_id=openstack_subnet.backend_id,
)
openstack_subnet.set_ok()
openstack_subnet.save()
subnet.refresh_from_db()
self.assertEqual(openstack_subnet.name, subnet.name)
self.assertEqual(openstack_subnet.cidr, subnet.cidr)
self.assertEqual(openstack_subnet.gateway_ip, subnet.gateway_ip)
self.assertEqual(openstack_subnet.allocation_pools, subnet.allocation_pools)
self.assertEqual(openstack_subnet.ip_version, subnet.ip_version)
self.assertEqual(openstack_subnet.enable_dhcp, subnet.enable_dhcp)
self.assertEqual(openstack_subnet.dns_nameservers, subnet.dns_nameservers)
def test_subnet_delete(self):
openstack_subnet = openstack_factories.SubNetFactory(network__tenant=self.tenant)
factories.SubNetFactory(settings=self.service_settings, backend_id=openstack_subnet.backend_id)
openstack_subnet.delete()
self.assertEqual(models.SubNet.objects.count(), 0)
<file_sep>/src/nodeconductor_openstack/openstack_tenant/tests/test_volume.py
from ddt import ddt, data
from django.conf import settings
from rest_framework import test, status
from nodeconductor.structure.models import ProjectRole
from nodeconductor.structure.tests import factories as structure_factories
from . import factories, fixtures
from .. import models
@ddt
class VolumeExtendTestCase(test.APITransactionTestCase):
def setUp(self):
self.admin = structure_factories.UserFactory()
self.manager = structure_factories.UserFactory()
self.staff = structure_factories.UserFactory(is_staff=True)
self.admined_volume = factories.VolumeFactory(state=models.Volume.States.OK)
admined_project = self.admined_volume.service_project_link.project
admined_project.add_user(self.admin, ProjectRole.ADMINISTRATOR)
admined_project.add_user(self.manager, ProjectRole.MANAGER)
@data('admin', 'manager')
def test_user_can_resize_size_of_volume_he_has_access_to(self, user):
self.client.force_authenticate(getattr(self, user))
new_size = self.admined_volume.size + 1024
url = factories.VolumeFactory.get_url(self.admined_volume, action='extend')
response = self.client.post(url, {'disk_size': new_size})
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.data)
self.admined_volume.refresh_from_db()
self.assertEqual(self.admined_volume.size, new_size)
def test_user_can_not_extend_volume_if_resulting_quota_usage_is_greater_then_limit(self):
self.client.force_authenticate(user=self.admin)
settings = self.admined_volume.service_project_link.service.settings
settings.set_quota_usage('storage', self.admined_volume.size)
settings.set_quota_limit('storage', self.admined_volume.size + 512)
new_size = self.admined_volume.size + 1024
url = factories.VolumeFactory.get_url(self.admined_volume, action='extend')
response = self.client.post(url, {'disk_size': new_size})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data)
def test_user_can_not_extend_volume_if_volume_operation_is_performed(self):
self.client.force_authenticate(user=self.admin)
self.admined_volume.state = models.Volume.States.UPDATING
self.admined_volume.save()
new_size = self.admined_volume.size + 1024
url = factories.VolumeFactory.get_url(self.admined_volume, action='extend')
response = self.client.post(url, {'disk_size': new_size})
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT, response.data)
def test_user_can_not_extend_volume_if_volume_is_in_erred_state(self):
self.client.force_authenticate(user=self.admin)
self.admined_volume.state = models.Instance.States.ERRED
self.admined_volume.save()
new_size = self.admined_volume.size + 1024
url = factories.VolumeFactory.get_url(self.admined_volume, action='extend')
response = self.client.post(url, {'disk_size': new_size})
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT, response.data)
class VolumeAttachTestCase(test.APITransactionTestCase):
def setUp(self):
self.fixture = fixtures.OpenStackTenantFixture()
self.volume = self.fixture.volume
self.instance = self.fixture.instance
self.url = factories.VolumeFactory.get_url(self.volume, action='attach')
def get_response(self):
self.client.force_authenticate(user=self.fixture.owner)
payload = {'instance': factories.InstanceFactory.get_url(self.instance)}
return self.client.post(self.url, payload)
def test_user_can_attach_volume_to_instance(self):
self.volume.state = models.Volume.States.OK
self.volume.runtime_state = 'available'
self.volume.save()
self.instance.state = models.Instance.States.OK
self.instance.runtime_state = models.Instance.RuntimeStates.SHUTOFF
self.instance.save()
response = self.get_response()
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.data)
def test_user_can_not_attach_erred_volume_to_instance(self):
self.volume.state = models.Volume.States.ERRED
self.volume.save()
response = self.get_response()
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
def test_user_can_not_attach_used_volume_to_instance(self):
self.volume.state = models.Volume.States.OK
self.volume.runtime_state = 'in-use'
self.volume.save()
response = self.get_response()
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
def test_user_can_not_attach_volume_to_instance_in_other_tenant(self):
self.volume.state = models.Volume.States.OK
self.volume.runtime_state = 'available'
self.volume.save()
self.instance = factories.InstanceFactory()
response = self.get_response()
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
class VolumeSnapshotTestCase(test.APITransactionTestCase):
def setUp(self):
self.fixture = fixtures.OpenStackTenantFixture()
self.volume = self.fixture.volume
self.url = factories.VolumeFactory.get_url(self.volume, action='snapshot')
self.volume.state = models.Volume.States.OK
self.volume.runtime_state = 'available'
self.volume.save()
self.client.force_authenticate(self.fixture.owner)
def test_user_can_create_volume_snapshot(self):
payload = {'name': '%s snapshot' % self.volume.name}
response = self.client.post(self.url, data=payload)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_snapshot_metadata_is_populated(self):
self.client.force_authenticate(self.fixture.owner)
payload = {'name': '%s snapshot' % self.volume.name}
response = self.client.post(self.url, data=payload)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
snapshot = models.Snapshot.objects.get(uuid=response.data['uuid'])
self.assertIn('source_volume_name', snapshot.metadata)
self.assertEqual(snapshot.metadata['source_volume_name'], self.volume.name)
self.assertEqual(snapshot.metadata['source_volume_description'], self.volume.description)
self.assertEqual(snapshot.metadata['source_volume_image_metadata'], self.volume.image_metadata)
@ddt
class VolumeCreateSnapshotScheduleTest(test.APITransactionTestCase):
action_name = 'create_snapshot_schedule'
def setUp(self):
self.fixture = fixtures.OpenStackTenantFixture()
self.url = factories.VolumeFactory.get_url(self.fixture.volume, self.action_name)
self.snapshot_schedule_data = {
'name': 'test schedule',
'retention_time': 3,
'schedule': '0 * * * *',
'maximal_number_of_resources': 3,
}
@data('owner', 'staff', 'admin', 'manager')
def test_user_can_create_snapshot_schedule(self, user):
self.client.force_authenticate(getattr(self.fixture, user))
response = self.client.post(self.url, self.snapshot_schedule_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['retention_time'], self.snapshot_schedule_data['retention_time'])
self.assertEqual(
response.data['maximal_number_of_resources'], self.snapshot_schedule_data['maximal_number_of_resources'])
self.assertEqual(response.data['schedule'], self.snapshot_schedule_data['schedule'])
def test_snapshot_schedule_cannot_be_created_if_schedule_is_less_than_1_hours(self):
self.client.force_authenticate(self.fixture.owner)
payload = self.snapshot_schedule_data
payload['schedule'] = '*/5 * * * *'
response = self.client.post(self.url, self.snapshot_schedule_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('schedule', response.data)
def test_snapshot_schedule_default_state_is_OK(self):
self.client.force_authenticate(self.fixture.owner)
response = self.client.post(self.url, self.snapshot_schedule_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
snapshot_schedule = models.SnapshotSchedule.objects.first()
self.assertIsNotNone(snapshot_schedule)
self.assertEqual(snapshot_schedule.state, snapshot_schedule.States.OK)
def test_snapshot_schedule_can_not_be_created_with_wrong_schedule(self):
self.client.force_authenticate(self.fixture.owner)
# wrong schedule:
self.snapshot_schedule_data['schedule'] = 'wrong schedule'
response = self.client.post(self.url, self.snapshot_schedule_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('schedule', response.content)
def test_snapshot_schedule_creation_with_correct_timezone(self):
self.client.force_authenticate(self.fixture.owner)
expected_timezone = 'Europe/London'
self.snapshot_schedule_data['timezone'] = expected_timezone
response = self.client.post(self.url, self.snapshot_schedule_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['timezone'], expected_timezone)
def test_snapshot_schedule_creation_with_incorrect_timezone(self):
self.client.force_authenticate(self.fixture.owner)
self.snapshot_schedule_data['timezone'] = 'incorrect'
response = self.client.post(self.url, self.snapshot_schedule_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('timezone', response.data)
def test_snapshot_schedule_creation_with_default_timezone(self):
self.client.force_authenticate(self.fixture.owner)
response = self.client.post(self.url, self.snapshot_schedule_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['timezone'], settings.TIME_ZONE)
<file_sep>/src/nodeconductor_openstack/openstack/tests/test_backend.py
import mock
from rest_framework import test
class MockedSession(mock.MagicMock):
auth_ref = 'AUTH_REF'
class BaseBackendTestCase(test.APITransactionTestCase):
def setUp(self):
self.session_patcher = mock.patch('keystoneauth1.session.Session', MockedSession)
self.session_patcher.start()
self.session_recover_patcher = mock.patch('nodeconductor_openstack.openstack_base.backend.OpenStackSession.recover')
self.session_recover_patcher.start()
self.keystone_patcher = mock.patch('keystoneclient.v2_0.client.Client')
self.mocked_keystone = self.keystone_patcher.start()
self.nova_patcher = mock.patch('novaclient.v2.client.Client')
self.mocked_nova = self.nova_patcher.start()
self.cinder_patcher = mock.patch('cinderclient.v2.client.Client')
self.mocked_cinder = self.cinder_patcher.start()
def tearDown(self):
super(BaseBackendTestCase, self).tearDown()
self.session_patcher.stop()
self.session_recover_patcher.stop()
self.keystone_patcher.stop()
self.nova_patcher.stop()
self.cinder_patcher.stop()
<file_sep>/src/nodeconductor_openstack/openstack/serializers.py
from __future__ import unicode_literals
import logging
import re
import urlparse
from django.conf import settings
from django.core import validators
from django.contrib.auth import password_validation
from django.db import transaction
from django.template.defaultfilters import slugify
from netaddr import IPNetwork
from rest_framework import serializers
from nodeconductor.core import utils as core_utils, serializers as core_serializers
from nodeconductor.core.fields import JsonField
from nodeconductor.quotas import serializers as quotas_serializers
from nodeconductor.structure import serializers as structure_serializers
from nodeconductor.structure.managers import filter_queryset_for_user
from . import models
from .backend import OpenStackBackendError
logger = logging.getLogger(__name__)
class ServiceSerializer(core_serializers.ExtraFieldOptionsMixin,
core_serializers.RequiredFieldsMixin,
structure_serializers.BaseServiceSerializer):
SERVICE_ACCOUNT_FIELDS = {
'backend_url': 'Keystone auth URL (e.g. http://keystone.example.com:5000/v2.0)',
'username': 'Administrative user',
'domain': 'Domain name. If not defined default domain will be used.',
'password': '',
}
SERVICE_ACCOUNT_EXTRA_FIELDS = {
'tenant_name': '',
'is_admin': 'Configure service with admin privileges',
'availability_zone': 'Default availability zone for provisioned instances',
'external_network_id': 'ID of OpenStack external network that will be connected to tenants',
'latitude': 'Latitude of the datacenter (e.g. 40.712784)',
'longitude': 'Longitude of the datacenter (e.g. -74.005941)',
'access_url': 'Publicly accessible OpenStack dashboard URL',
'dns_nameservers': 'Default value for new subnets DNS name servers. Should be defined as list.',
}
class Meta(structure_serializers.BaseServiceSerializer.Meta):
model = models.OpenStackService
required_fields = 'backend_url', 'username', 'password', 'tenant_name'
fields = structure_serializers.BaseServiceSerializer.Meta.fields + ('is_admin_tenant',)
extra_field_options = {
'backend_url': {
'label': 'API URL',
'default_value': 'http://keystone.example.com:5000/v2.0',
},
'is_admin': {
'default_value': 'True',
},
'username': {
'default_value': 'admin',
},
'tenant_name': {
'label': 'Tenant name',
'default_value': 'admin',
},
'external_network_id': {
'label': 'Public/gateway network UUID',
},
'availability_zone': {
'placeholder': 'default',
},
'access_url': {
'label': 'Access URL',
},
}
def _validate_settings(self, settings):
if settings.get_option('is_admin'):
backend = settings.get_backend()
try:
if not backend.check_admin_tenant():
raise serializers.ValidationError({
'non_field_errors': 'Provided credentials are not for admin tenant.'
})
except OpenStackBackendError:
raise serializers.ValidationError({
'non_field_errors': 'Unable to validate credentials.'
})
elif settings.get_option('tenant_name') == 'admin':
raise serializers.ValidationError({
'tenant_name': 'Invalid tenant name for non-admin service.'
})
class ServiceNameSerializer(serializers.Serializer):
name = serializers.CharField(required=True)
class FlavorSerializer(structure_serializers.BasePropertySerializer):
class Meta(object):
model = models.Flavor
fields = ('url', 'uuid', 'name', 'cores', 'ram', 'disk', 'display_name')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
}
display_name = serializers.SerializerMethodField()
def get_display_name(self, flavor):
return "{} ({} CPU, {} MB RAM, {} MB HDD)".format(
flavor.name, flavor.cores, flavor.ram, flavor.disk)
class ImageSerializer(structure_serializers.BasePropertySerializer):
class Meta(object):
model = models.Image
fields = ('url', 'uuid', 'name', 'min_disk', 'min_ram')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
}
class ServiceProjectLinkSerializer(structure_serializers.BaseServiceProjectLinkSerializer):
class Meta(structure_serializers.BaseServiceProjectLinkSerializer.Meta):
model = models.OpenStackServiceProjectLink
extra_kwargs = {
'service': {'lookup_field': 'uuid', 'view_name': 'openstack-detail'},
}
class TenantQuotaSerializer(serializers.Serializer):
instances = serializers.IntegerField(min_value=1, required=False)
volumes = serializers.IntegerField(min_value=1, required=False)
snapshots = serializers.IntegerField(min_value=1, required=False)
ram = serializers.IntegerField(min_value=1, required=False)
vcpu = serializers.IntegerField(min_value=1, required=False)
storage = serializers.IntegerField(min_value=1, required=False)
security_group_count = serializers.IntegerField(min_value=1, required=False)
security_group_rule_count = serializers.IntegerField(min_value=1, required=False)
class NestedServiceProjectLinkSerializer(structure_serializers.PermissionFieldFilteringMixin,
core_serializers.AugmentedSerializerMixin,
core_serializers.HyperlinkedRelatedModelSerializer):
service_name = serializers.ReadOnlyField(source='service.settings.name')
class Meta(object):
model = models.OpenStackServiceProjectLink
fields = (
'url',
'project', 'project_name', 'project_uuid',
'service', 'service_name', 'service_uuid',
)
related_paths = 'project', 'service'
extra_kwargs = {
'service': {'lookup_field': 'uuid', 'view_name': 'openstack-detail'},
'project': {'lookup_field': 'uuid'},
}
def run_validators(self, value):
# No need to validate any fields except 'url' that is validated in to_internal_value method
pass
def get_filtered_field_names(self):
return 'project', 'service'
class ExternalNetworkSerializer(serializers.Serializer):
vlan_id = serializers.CharField(required=False)
vxlan_id = serializers.CharField(required=False)
network_ip = serializers.IPAddressField(protocol='ipv4')
network_prefix = serializers.IntegerField(min_value=0, max_value=32)
ips_count = serializers.IntegerField(min_value=1, required=False)
def validate(self, attrs):
vlan_id = attrs.get('vlan_id')
vxlan_id = attrs.get('vxlan_id')
if vlan_id is None and vxlan_id is None:
raise serializers.ValidationError("VLAN or VXLAN ID should be provided.")
elif vlan_id and vxlan_id:
raise serializers.ValidationError("VLAN and VXLAN networks cannot be created simultaneously.")
ips_count = attrs.get('ips_count')
if ips_count is None:
return attrs
network_ip = attrs.get('network_ip')
network_prefix = attrs.get('network_prefix')
cidr = IPNetwork(network_ip)
cidr.prefixlen = network_prefix
# subtract router and broadcast IPs
if cidr.size < ips_count - 2:
raise serializers.ValidationError("Not enough Floating IP Addresses available.")
return attrs
class IpMappingSerializer(core_serializers.AugmentedSerializerMixin,
serializers.HyperlinkedModelSerializer):
class Meta:
model = models.IpMapping
fields = ('url', 'uuid', 'public_ip', 'private_ip', 'project')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'project': {'lookup_field': 'uuid', 'view_name': 'project-detail'}
}
class FloatingIPSerializer(structure_serializers.BaseResourceSerializer):
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstack-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstack-spl-detail',
read_only=True)
class Meta(structure_serializers.BaseResourceSerializer.Meta):
model = models.FloatingIP
fields = structure_serializers.BaseResourceSerializer.Meta.fields + (
'runtime_state', 'address', 'backend_network_id',
'tenant', 'tenant_name', 'tenant_uuid')
related_paths = ('tenant',)
read_only_fields = structure_serializers.BaseResourceSerializer.Meta.read_only_fields + (
'runtime_state', 'address', 'description', 'name', 'tenant', 'backend_network_id')
extra_kwargs = dict(
tenant={'lookup_field': 'uuid', 'view_name': 'openstack-tenant-detail'},
**structure_serializers.BaseResourceSerializer.Meta.extra_kwargs
)
def create(self, validated_data):
validated_data['tenant'] = tenant = self.context['view'].get_object()
validated_data['service_project_link'] = tenant.service_project_link
return super(FloatingIPSerializer, self).create(validated_data)
class SecurityGroupRuleSerializer(serializers.ModelSerializer):
class Meta:
model = models.SecurityGroupRule
fields = ('id', 'protocol', 'from_port', 'to_port', 'cidr')
class SecurityGroupRuleCreateSerializer(SecurityGroupRuleSerializer):
""" Create rules on security group creation """
def to_internal_value(self, data):
if 'id' in data:
raise serializers.ValidationError('Cannot add existed rule with id %s to new security group' % data['id'])
internal_data = super(SecurityGroupRuleSerializer, self).to_internal_value(data)
return models.SecurityGroupRule(**internal_data)
class SecurityGroupRuleUpdateSerializer(SecurityGroupRuleSerializer):
def to_internal_value(self, data):
""" Create new rule if id is not specified, update exist rule if id is specified """
security_group = self.context['view'].get_object()
internal_data = super(SecurityGroupRuleSerializer, self).to_internal_value(data)
if 'id' not in data:
return models.SecurityGroupRule(security_group=security_group, **internal_data)
rule_id = data.pop('id')
try:
rule = security_group.rules.get(id=rule_id)
except models.SecurityGroupRule.DoesNotExist:
raise serializers.ValidationError({'id': 'Security group does not have rule with id %s.' % rule_id})
for key, value in internal_data.items():
setattr(rule, key, value)
return rule
class SecurityGroupRuleListUpdateSerializer(serializers.ListSerializer):
child = SecurityGroupRuleUpdateSerializer()
@transaction.atomic()
def save(self, **kwargs):
security_group = self.context['view'].get_object()
old_rules_count = security_group.rules.count()
rules = self.validated_data
security_group.rules.exclude(id__in=[r.id for r in rules if r.id]).delete()
for rule in rules:
rule.save()
security_group.change_backend_quotas_usage_on_rules_update(old_rules_count)
return rules
class SecurityGroupSerializer(structure_serializers.BaseResourceSerializer):
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstack-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstack-spl-detail',
read_only=True)
rules = SecurityGroupRuleCreateSerializer(many=True)
class Meta(structure_serializers.BaseResourceSerializer.Meta):
model = models.SecurityGroup
fields = structure_serializers.BaseResourceSerializer.Meta.fields + (
'tenant', 'tenant_name', 'tenant_uuid', 'rules',
)
related_paths = ('tenant',)
protected_fields = structure_serializers.BaseResourceSerializer.Meta.protected_fields + ('rules',)
extra_kwargs = {
'url': {'lookup_field': 'uuid', 'view_name': 'openstack-sgp-detail'},
'tenant': {'lookup_field': 'uuid', 'view_name': 'openstack-tenant-detail', 'read_only': True},
}
def validate_rules(self, value):
for rule in value:
if rule.id is not None:
raise serializers.ValidationError('Cannot add existed rule with id %s to new security group' % rule.id)
rule.full_clean(exclude=['security_group'])
return value
def create(self, validated_data):
rules = validated_data.pop('rules', [])
validated_data['tenant'] = tenant = self.context['view'].get_object()
validated_data['service_project_link'] = tenant.service_project_link
with transaction.atomic():
# quota usage has to be increased only after rules creation,
# so we cannot execute BaseResourceSerializer create method.
security_group = super(structure_serializers.BaseResourceSerializer, self).create(validated_data)
for rule in rules:
security_group.rules.add(rule, bulk=False)
security_group.increase_backend_quotas_usage()
return security_group
class TenantImportSerializer(structure_serializers.BaseResourceImportSerializer):
class Meta(structure_serializers.BaseResourceImportSerializer.Meta):
model = models.Tenant
def create(self, validated_data):
service_project_link = validated_data['service_project_link']
if not service_project_link.service.is_admin_tenant():
raise serializers.ValidationError({
'non_field_errors': 'Tenant import is only possible for admin service.'
})
backend = self.context['service'].get_backend()
backend_id = validated_data['backend_id']
try:
tenant = backend.import_tenant(backend_id, service_project_link)
except OpenStackBackendError as e:
raise serializers.ValidationError({
'backend_id': "Can't import tenant with ID %s. Reason: %s" % (backend_id, e)
})
return tenant
class BaseTenantImportSerializer(structure_serializers.BaseResourceImportSerializer):
class Meta(structure_serializers.BaseResourceImportSerializer.Meta):
fields = structure_serializers.BaseResourceImportSerializer.Meta.fields + ('tenant',)
tenant = serializers.HyperlinkedRelatedField(
queryset=models.Tenant.objects.all(),
view_name='openstack-tenant-detail',
lookup_field='uuid',
write_only=True)
def get_fields(self):
fields = super(BaseTenantImportSerializer, self).get_fields()
if 'request' in self.context:
request = self.context['request']
fields['tenant'].queryset = filter_queryset_for_user(
models.Tenant.objects.all(), request.user
)
return fields
def validate(self, attrs):
attrs = super(BaseTenantImportSerializer, self).validate(attrs)
tenant = attrs['tenant']
project = attrs['project']
if tenant.service_project_link.project != project:
raise serializers.ValidationError({
'project': 'Tenant should belong to the same project.'
})
return attrs
def create(self, validated_data):
tenant = validated_data['tenant']
backend_id = validated_data['backend_id']
backend = tenant.get_backend()
try:
return self.import_resource(backend, backend_id)
except OpenStackBackendError as e:
raise serializers.ValidationError({
'backend_id': "Can't import resource with ID %s. Reason: %s" % (backend_id, e)
})
def import_resource(self, backend, backend_id):
raise NotImplementedError()
subnet_cidr_validator = validators.RegexValidator(
re.compile(settings.NODECONDUCTOR_OPENSTACK['SUBNET']['CIDR_REGEX']),
settings.NODECONDUCTOR_OPENSTACK['SUBNET']['CIDR_REGEX_EXPLANATION'],
)
class TenantSerializer(structure_serializers.PrivateCloudSerializer):
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstack-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstack-spl-detail',
queryset=models.OpenStackServiceProjectLink.objects.all(),
write_only=True)
quotas = quotas_serializers.QuotaSerializer(many=True, read_only=True)
subnet_cidr = serializers.CharField(
validators=[subnet_cidr_validator], default='192.168.42.0/24', initial='192.168.42.0/24', write_only=True)
class Meta(structure_serializers.PrivateCloudSerializer.Meta):
model = models.Tenant
fields = structure_serializers.PrivateCloudSerializer.Meta.fields + (
'availability_zone', 'internal_network_id', 'external_network_id',
'user_username', 'user_password', 'quotas', 'subnet_cidr',
)
read_only_fields = structure_serializers.PrivateCloudSerializer.Meta.read_only_fields + (
'internal_network_id', 'external_network_id', 'user_password',
)
protected_fields = structure_serializers.PrivateCloudSerializer.Meta.protected_fields + (
'user_username', 'subnet_cidr',
)
def get_access_url(self, tenant):
settings = tenant.service_project_link.service.settings
access_url = settings.get_option('access_url')
if access_url:
return access_url
if settings.backend_url:
parsed = urlparse.urlparse(settings.backend_url)
return '%s://%s/dashboard' % (parsed.scheme, parsed.hostname)
def validate(self, attrs):
if self.instance is not None:
return attrs
if not attrs.get('user_username'):
attrs['user_username'] = slugify(attrs['name'])[:30] + '-user'
service_settings = attrs['service_project_link'].service.settings
neighbour_tenants = models.Tenant.objects.filter(service_project_link__service__settings=service_settings)
existing_usernames = [service_settings.username] + list(neighbour_tenants.values_list('user_username', flat=True))
user_username = attrs['user_username']
if user_username in existing_usernames:
raise serializers.ValidationError(
'Name "%s" is already registered. Please choose another one.' % user_username)
blacklisted_usernames = service_settings.options.get(
'blacklisted_usernames', settings.NODECONDUCTOR_OPENSTACK['DEFAULT_BLACKLISTED_USERNAMES'])
if user_username in blacklisted_usernames:
raise serializers.ValidationError('Name "%s" cannot be used as tenant user username.' % user_username)
return attrs
def create(self, validated_data):
spl = validated_data['service_project_link']
if not spl.service.is_admin_tenant():
raise serializers.ValidationError({
'non_field_errors': 'Tenant provisioning is only possible for admin service.'
})
# get availability zone from service settings if it is not defined
if not validated_data.get('availability_zone'):
validated_data['availability_zone'] = spl.service.settings.get_option('availability_zone') or ''
# init tenant user username(if not defined) and password
slugified_name = slugify(validated_data['name'])[:30]
if not validated_data.get('user_username'):
validated_data['user_username'] = slugified_name + '-user'
validated_data['user_password'] = core_utils.pwgen()
subnet_cidr = validated_data.pop('subnet_cidr')
with transaction.atomic():
tenant = super(TenantSerializer, self).create(validated_data)
network = models.Network.objects.create(
name=slugified_name + '-int-net',
description='Internal network for tenant %s' % tenant.name,
tenant=tenant,
service_project_link=tenant.service_project_link,
)
models.SubNet.objects.create(
name=slugified_name + '-sub-net',
description='SubNet for tenant %s internal network' % tenant.name,
network=network,
service_project_link=tenant.service_project_link,
cidr=subnet_cidr,
allocation_pools=_generate_subnet_allocation_pool(subnet_cidr),
dns_nameservers=spl.service.settings.options.get('dns_nameservers', [])
)
return tenant
class _NestedSubNetSerializer(serializers.ModelSerializer):
class Meta(object):
model = models.SubNet
fields = ('name', 'description', 'cidr', 'gateway_ip', 'allocation_pools', 'ip_version', 'enable_dhcp')
class NetworkSerializer(structure_serializers.BaseResourceSerializer):
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstack-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstack-spl-detail',
read_only=True)
subnets = _NestedSubNetSerializer(many=True, read_only=True)
tenant_name = serializers.CharField(source='tenant.name', read_only=True)
class Meta(structure_serializers.BaseResourceSerializer.Meta):
model = models.Network
fields = structure_serializers.BaseResourceSerializer.Meta.fields + (
'tenant', 'tenant_name', 'is_external', 'type', 'segmentation_id', 'subnets')
read_only_fields = structure_serializers.BaseResourceSerializer.Meta.read_only_fields + (
'tenant', 'is_external', 'type', 'segmentation_id')
extra_kwargs = dict(
tenant={'lookup_field': 'uuid', 'view_name': 'openstack-tenant-detail'},
**structure_serializers.BaseResourceSerializer.Meta.extra_kwargs
)
@transaction.atomic
def create(self, validated_data):
validated_data['tenant'] = tenant = self.context['view'].get_object()
validated_data['service_project_link'] = tenant.service_project_link
return super(NetworkSerializer, self).create(validated_data)
class SubNetSerializer(structure_serializers.BaseResourceSerializer):
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstack-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstack-spl-detail',
read_only=True)
cidr = serializers.CharField(
validators=[subnet_cidr_validator], default='192.168.42.0/24', initial='192.168.42.0/24')
allocation_pools = JsonField(read_only=True)
network_name = serializers.CharField(source='network.name', read_only=True)
tenant = serializers.HyperlinkedRelatedField(
source='network.tenant',
view_name='openstack-tenant-detail',
read_only=True,
lookup_field='uuid')
tenant_name = serializers.CharField(source='network.tenant.name', read_only=True)
dns_nameservers = JsonField(read_only=True)
class Meta(structure_serializers.BaseResourceSerializer.Meta):
model = models.SubNet
fields = structure_serializers.BaseResourceSerializer.Meta.fields + (
'tenant', 'tenant_name', 'network', 'network_name', 'cidr',
'gateway_ip', 'allocation_pools', 'ip_version', 'enable_dhcp', 'dns_nameservers')
protected_fields = structure_serializers.BaseResourceSerializer.Meta.protected_fields + ('cidr',)
read_only_fields = structure_serializers.BaseResourceSerializer.Meta.read_only_fields + (
'tenant', 'network', 'gateway_ip', 'ip_version', 'enable_dhcp')
extra_kwargs = dict(
network={'lookup_field': 'uuid', 'view_name': 'openstack-network-detail'},
**structure_serializers.BaseResourceSerializer.Meta.extra_kwargs
)
def validate(self, attrs):
if self.instance is None:
attrs['network'] = network = self.context['view'].get_object()
if network.subnets.count() >= 1:
raise serializers.ValidationError('Internal network cannot have more than one subnet.')
cidr = attrs['cidr']
if models.SubNet.objects.filter(cidr=cidr, network__tenant=network.tenant).exists():
raise serializers.ValidationError('Subnet with cidr "%s" is already registered' % cidr)
return attrs
def create(self, validated_data):
network = validated_data['network']
validated_data['service_project_link'] = network.service_project_link
spl = network.service_project_link
validated_data['allocation_pools'] = _generate_subnet_allocation_pool(validated_data['cidr'])
validated_data['dns_nameservers'] = spl.service.settings.options.get('dns_nameservers', [])
return super(SubNetSerializer, self).create(validated_data)
def _generate_subnet_allocation_pool(cidr):
first_octet, second_octet, third_octet, _ = cidr.split('.', 3)
subnet_settings = settings.NODECONDUCTOR_OPENSTACK['SUBNET']
format_data = {'first_octet': first_octet, 'second_octet': second_octet, 'third_octet': third_octet}
return [{
'start': subnet_settings['ALLOCATION_POOL_START'].format(**format_data),
'end': subnet_settings['ALLOCATION_POOL_END'].format(**format_data),
}]
class TenantChangePasswordSerializer(serializers.Serializer):
user_password = serializers.CharField(max_length=50,
allow_blank=True,
validators=[password_validation.validate_password],
help_text='New tenant user password.')
def validate_user_password(self, user_password):
if self.instance.user_password == user_password:
raise serializers.ValidationError('New password cannot match the old password.')
return user_password
def update(self, tenant, validated_data):
tenant.user_password = validated_data['<PASSWORD>_password']
tenant.save(update_fields=['user_password'])
return tenant
<file_sep>/src/nodeconductor_openstack/openstack/admin.py
from django.contrib import admin
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from nodeconductor.core.admin import ExecutorAdminAction
from nodeconductor.quotas.admin import QuotaInline
from nodeconductor.structure import admin as structure_admin
from . import executors, models
def _get_obj_admin_url(obj):
return reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name), args=[obj.id])
def _get_list_admin_url(model):
return reverse('admin:%s_%s_changelist' % (model._meta.app_label, model._meta.model_name))
class ServiceProjectLinkAdmin(structure_admin.ServiceProjectLinkAdmin):
readonly_fields = ('get_service_settings_username', 'get_service_settings_password') + \
structure_admin.ServiceProjectLinkAdmin.readonly_fields
def get_service_settings_username(self, obj):
return obj.service.settings.username
get_service_settings_username.short_description = 'Username'
def get_service_settings_password(self, obj):
return obj.service.settings.password
get_service_settings_password.short_description = 'Password'
class TenantAdmin(structure_admin.ResourceAdmin):
actions = ('pull', 'detect_external_networks', 'allocate_floating_ip', 'pull_security_groups',
'pull_floating_ips', 'pull_quotas')
inlines = [QuotaInline]
class OKTenantAction(ExecutorAdminAction):
""" Execute action with tenant that is in state OK """
def validate(self, tenant):
if tenant.state != models.Tenant.States.OK:
raise ValidationError('Tenant has to be in state OK to pull security groups.')
class PullSecurityGroups(OKTenantAction):
executor = executors.TenantPullSecurityGroupsExecutor
short_description = 'Pull security groups'
pull_security_groups = PullSecurityGroups()
class AllocateFloatingIP(OKTenantAction):
executor = executors.TenantAllocateFloatingIPExecutor
short_description = 'Allocate floating IPs'
def validate(self, tenant):
super(TenantAdmin.AllocateFloatingIP, self).validate(tenant)
if not tenant.external_network_id:
raise ValidationError('Tenant has to have external network to allocate floating IP.')
allocate_floating_ip = AllocateFloatingIP()
class DetectExternalNetworks(OKTenantAction):
executor = executors.TenantDetectExternalNetworkExecutor
short_description = 'Attempt to lookup and set external network id of the connected router'
detect_external_networks = DetectExternalNetworks()
class PullFloatingIPs(OKTenantAction):
executor = executors.TenantPullFloatingIPsExecutor
short_description = 'Pull floating IPs'
pull_floating_ips = PullFloatingIPs()
class PullQuotas(OKTenantAction):
executor = executors.TenantPullQuotasExecutor
short_description = 'Pull quotas'
pull_quotas = PullQuotas()
class Pull(ExecutorAdminAction):
executor = executors.TenantPullExecutor
short_description = 'Pull'
def validate(self, tenant):
if tenant.state not in (models.Tenant.States.OK, models.Tenant.States.ERRED):
raise ValidationError('Tenant has to be OK or erred.')
if not tenant.service_project_link.service.is_admin_tenant():
raise ValidationError('Tenant pull is only possible for admin service.')
pull = Pull()
class FlavorAdmin(admin.ModelAdmin):
list_filter = ('settings',)
list_display = ('name', 'settings', 'cores', 'ram', 'disk')
class ImageAdmin(admin.ModelAdmin):
list_filter = ('settings', )
list_display = ('name', 'min_disk', 'min_ram')
class TenantResourceAdmin(structure_admin.ResourceAdmin):
""" Admin model for resources that are connected to tenant.
Expects that resource has attribute `tenant`.
"""
list_display = structure_admin.ResourceAdmin.list_display + ('get_tenant', )
list_filter = structure_admin.ResourceAdmin.list_filter + ('tenant', )
def get_tenant(self, obj):
tenant = obj.tenant
return '<a href="%s">%s</a>' % (_get_obj_admin_url(tenant), tenant.name)
get_tenant.short_description = 'Tenant'
get_tenant.allow_tags = True
admin.site.register(models.Tenant, TenantAdmin)
admin.site.register(models.Flavor, FlavorAdmin)
admin.site.register(models.Image, ImageAdmin)
admin.site.register(models.OpenStackService, structure_admin.ServiceAdmin)
admin.site.register(models.OpenStackServiceProjectLink, ServiceProjectLinkAdmin)
admin.site.register(models.FloatingIP)
<file_sep>/src/nodeconductor_openstack/openstack_tenant/backend.py
import json
import logging
import time
from django.db import transaction
from django.utils import six, timezone, dateparse
from ceilometerclient import exc as ceilometer_exceptions
from cinderclient import exceptions as cinder_exceptions
from glanceclient import exc as glance_exceptions
from keystoneclient import exceptions as keystone_exceptions
from neutronclient.client import exceptions as neutron_exceptions
from novaclient import exceptions as nova_exceptions
from nodeconductor.structure import log_backend_action
from nodeconductor_openstack.openstack_base.backend import (
BaseOpenStackBackend, OpenStackBackendError, update_pulled_fields)
from . import models
logger = logging.getLogger(__name__)
class OpenStackTenantBackend(BaseOpenStackBackend):
VOLUME_UPDATE_FIELDS = ('name', 'description', 'size', 'metadata', 'type', 'bootable', 'runtime_state', 'device')
SNAPSHOT_UPDATE_FIELDS = ('name', 'description', 'size', 'metadata', 'source_volume', 'runtime_state')
INSTANCE_UPDATE_FIELDS = ('name', 'flavor_name', 'flavor_disk', 'ram', 'cores', 'disk',
'runtime_state', 'error_message')
def __init__(self, settings):
super(OpenStackTenantBackend, self).__init__(settings, settings.options['tenant_id'])
@property
def external_network_id(self):
return self.settings.options['external_network_id']
def sync(self):
self._pull_flavors()
self._pull_images()
self.pull_floating_ips()
self._pull_security_groups()
self._pull_quotas()
self._pull_networks()
self._pull_subnets()
def _pull_flavors(self):
nova = self.nova_client
try:
flavors = nova.flavors.findall(is_public=True)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
with transaction.atomic():
cur_flavors = self._get_current_properties(models.Flavor)
for backend_flavor in flavors:
cur_flavors.pop(backend_flavor.id, None)
models.Flavor.objects.update_or_create(
settings=self.settings,
backend_id=backend_flavor.id,
defaults={
'name': backend_flavor.name,
'cores': backend_flavor.vcpus,
'ram': backend_flavor.ram,
'disk': self.gb2mb(backend_flavor.disk),
})
models.Flavor.objects.filter(backend_id__in=cur_flavors.keys()).delete()
def _pull_images(self):
glance = self.glance_client
try:
images = [image for image in glance.images.list() if image.is_public and not image.deleted]
except glance_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
with transaction.atomic():
cur_images = self._get_current_properties(models.Image)
for backend_image in images:
cur_images.pop(backend_image.id, None)
models.Image.objects.update_or_create(
settings=self.settings,
backend_id=backend_image.id,
defaults={
'name': backend_image.name,
'min_ram': backend_image.min_ram,
'min_disk': self.gb2mb(backend_image.min_disk),
})
models.Image.objects.filter(backend_id__in=cur_images.keys()).delete()
def pull_floating_ips(self):
neutron = self.neutron_client
try:
ips = [ip for ip in neutron.list_floatingips(tenant_id=self.tenant_id)['floatingips']
if ip.get('floating_ip_address') and ip.get('status')]
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
with transaction.atomic():
cur_ips = self._get_current_properties(models.FloatingIP)
for backend_ip in ips:
cur_ips.pop(backend_ip['id'], None)
models.FloatingIP.objects.update_or_create(
settings=self.settings,
backend_id=backend_ip['id'],
defaults={
'runtime_state': backend_ip['status'],
'address': backend_ip['floating_ip_address'],
'backend_network_id': backend_ip['floating_network_id'],
})
models.FloatingIP.objects.filter(backend_id__in=cur_ips.keys()).exclude(is_booked=True).delete()
def _pull_security_groups(self):
nova = self.nova_client
try:
security_groups = nova.security_groups.list()
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
with transaction.atomic():
cur_security_groups = self._get_current_properties(models.SecurityGroup)
for backend_security_group in security_groups:
cur_security_groups.pop(backend_security_group.id, None)
security_group, _ = models.SecurityGroup.objects.update_or_create(
settings=self.settings,
backend_id=backend_security_group.id,
defaults={
'name': backend_security_group.name,
'description': backend_security_group.description,
})
self._pull_security_group_rules(security_group, backend_security_group)
models.SecurityGroup.objects.filter(backend_id__in=cur_security_groups.keys()).delete()
def _pull_security_group_rules(self, security_group, backend_security_group):
backend_rules = [self._normalize_security_group_rule(r) for r in backend_security_group.rules]
cur_rules = {rule.backend_id: rule for rule in security_group.rules.all()}
for backend_rule in backend_rules:
cur_rules.pop(backend_rule['id'], None)
security_group.rules.update_or_create(
backend_id=backend_rule['id'],
defaults={
'from_port': backend_rule['from_port'],
'to_port': backend_rule['to_port'],
'protocol': backend_rule['ip_protocol'],
'cidr': backend_rule['ip_range']['cidr'],
})
security_group.rules.filter(backend_id__in=cur_rules.keys()).delete()
def _normalize_security_group_rule(self, rule):
if rule['ip_protocol'] is None:
rule['ip_protocol'] = ''
if 'cidr' not in rule['ip_range']:
rule['ip_range']['cidr'] = '0.0.0.0/0'
return rule
def _pull_quotas(self):
for quota_name, limit in self.get_tenant_quotas_limits(self.tenant_id).items():
self.settings.set_quota_limit(quota_name, limit)
for quota_name, usage in self.get_tenant_quotas_usage(self.tenant_id).items():
self.settings.set_quota_usage(quota_name, usage, fail_silently=True)
def _pull_networks(self):
neutron = self.neutron_client
try:
networks = neutron.list_networks(tenant_id=self.tenant_id)['networks']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
with transaction.atomic():
cur_networks = self._get_current_properties(models.Network)
for backend_network in networks:
cur_networks.pop(backend_network['id'], None)
defaults = {
'name': backend_network['name'],
'description': backend_network['description'],
}
if backend_network.get('provider:network_type'):
defaults['type'] = backend_network['provider:network_type']
if backend_network.get('provider:segmentation_id'):
defaults['segmentation_id'] = backend_network['provider:segmentation_id']
models.Network.objects.update_or_create(
settings=self.settings,
backend_id=backend_network['id'],
defaults=defaults)
models.Network.objects.filter(backend_id__in=cur_networks.keys()).delete()
def _pull_subnets(self):
neutron = self.neutron_client
try:
subnets = neutron.list_subnets(tenant_id=self.tenant_id)['subnets']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
with transaction.atomic():
cur_subnets = self._get_current_properties(models.SubNet)
for backend_subnet in subnets:
cur_subnets.pop(backend_subnet['id'], None)
try:
network = models.Network.objects.get(
settings=self.settings, backend_id=backend_subnet['network_id'])
except models.Network.DoesNotExist:
raise OpenStackBackendError(
'Cannot pull subnet for network with id "%s". Network is not pulled yet.')
defaults = {
'name': backend_subnet['name'],
'description': backend_subnet['description'],
'allocation_pools': backend_subnet['allocation_pools'],
'cidr': backend_subnet['cidr'],
'ip_version': backend_subnet.get('ip_version'),
'gateway_ip': backend_subnet.get('gateway_ip'),
'enable_dhcp': backend_subnet.get('enable_dhcp', False),
'network': network,
}
models.SubNet.objects.update_or_create(
settings=self.settings,
backend_id=backend_subnet['id'],
defaults=defaults)
models.SubNet.objects.filter(backend_id__in=cur_subnets.keys()).delete()
def _get_current_properties(self, model):
return {p.backend_id: p for p in model.objects.filter(settings=self.settings)}
@log_backend_action()
def create_volume(self, volume):
kwargs = {
'size': self.mb2gb(volume.size),
'name': volume.name,
'description': volume.description,
}
if volume.source_snapshot:
kwargs['snapshot_id'] = volume.source_snapshot.backend_id
if volume.type:
kwargs['volume_type'] = volume.type
if volume.image:
kwargs['imageRef'] = volume.image.backend_id
cinder = self.cinder_client
try:
backend_volume = cinder.volumes.create(**kwargs)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
volume.backend_id = backend_volume.id
if hasattr(backend_volume, 'volume_image_metadata'):
volume.image_metadata = backend_volume.volume_image_metadata
volume.bootable = backend_volume.bootable == 'true'
volume.runtime_state = backend_volume.status
volume.save()
return volume
@log_backend_action()
def update_volume(self, volume):
cinder = self.cinder_client
try:
cinder.volumes.update(volume.backend_id, name=volume.name, description=volume.description)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def delete_volume(self, volume):
cinder = self.cinder_client
try:
cinder.volumes.delete(volume.backend_id)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
volume.decrease_backend_quotas_usage()
@log_backend_action()
def attach_volume(self, volume, instance_uuid, device=None):
instance = models.Instance.objects.get(uuid=instance_uuid)
nova = self.nova_client
try:
nova.volumes.create_server_volume(instance.backend_id, volume.backend_id,
device=None if device == '' else device)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
else:
volume.instance = instance
volume.device = device
volume.save(update_fields=['instance', 'device'])
@log_backend_action()
def detach_volume(self, volume):
nova = self.nova_client
try:
nova.volumes.delete_server_volume(volume.instance.backend_id, volume.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
else:
volume.instance = None
volume.device = ''
volume.save(update_fields=['instance', 'device'])
@log_backend_action()
def extend_volume(self, volume):
cinder = self.cinder_client
try:
cinder.volumes.extend(volume.backend_id, self.mb2gb(volume.size))
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
def import_volume(self, backend_volume_id, save=True, service_project_link=None):
""" Restore NC Volume instance based on backend data. """
cinder = self.cinder_client
try:
backend_volume = cinder.volumes.get(backend_volume_id)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
volume = self._backend_volume_to_volume(backend_volume)
if service_project_link is not None:
volume.service_project_link = service_project_link
if save:
volume.save()
return volume
def _backend_volume_to_volume(self, backend_volume):
volume = models.Volume(
name=backend_volume.name,
description=backend_volume.description or '',
size=self.gb2mb(backend_volume.size),
metadata=backend_volume.metadata,
backend_id=backend_volume.id,
type=backend_volume.volume_type or '',
bootable=backend_volume.bootable == 'true',
runtime_state=backend_volume.status,
state=models.Volume.States.OK,
)
if getattr(backend_volume, 'volume_image_metadata', False):
volume.image_metadata = backend_volume.volume_image_metadata
try:
volume.image = models.Image.objects.get(
settings=self.settings, backend_id=volume.image_metadata['image_id'])
except models.Image.DoesNotExist:
pass
# In our setup volume could be attached only to one instance.
if getattr(backend_volume, 'attachments', False):
if 'device' in backend_volume.attachments[0]:
volume.device = backend_volume.attachments[0]['device']
return volume
def get_volumes(self):
cinder = self.cinder_client
try:
backend_volumes = cinder.volumes.list()
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
return [self._backend_volume_to_volume(backend_volume) for backend_volume in backend_volumes]
@log_backend_action()
def pull_volume(self, volume, update_fields=None):
import_time = timezone.now()
imported_volume = self.import_volume(volume.backend_id, save=False)
volume.refresh_from_db()
if volume.modified < import_time:
if not update_fields:
update_fields = self.VOLUME_UPDATE_FIELDS
update_pulled_fields(volume, imported_volume, update_fields)
@log_backend_action()
def pull_volume_runtime_state(self, volume):
cinder = self.cinder_client
try:
backend_volume = cinder.volumes.get(volume.backend_id)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
if backend_volume.status != volume.runtime_state:
volume.runtime_state = backend_volume.status
volume.save(update_fields=['runtime_state'])
@log_backend_action('check is volume deleted')
def is_volume_deleted(self, volume):
cinder = self.cinder_client
try:
cinder.volumes.get(volume.backend_id)
return False
except cinder_exceptions.NotFound:
return True
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def create_snapshot(self, snapshot, force=True):
kwargs = {
'name': snapshot.name,
'description': snapshot.description,
'force': force,
'metadata': snapshot.metadata,
}
cinder = self.cinder_client
try:
backend_snapshot = cinder.volume_snapshots.create(snapshot.source_volume.backend_id, **kwargs)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
snapshot.backend_id = backend_snapshot.id
snapshot.runtime_state = backend_snapshot.status
snapshot.size = self.gb2mb(backend_snapshot.size)
snapshot.save()
return snapshot
def import_snapshot(self, backend_snapshot_id, save=True, service_project_link=None):
""" Restore NC Snapshot instance based on backend data. """
cinder = self.cinder_client
try:
backend_snapshot = cinder.volume_snapshots.get(backend_snapshot_id)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
snapshot = self._backend_snapshot_to_snapshot(backend_snapshot)
if service_project_link is not None:
snapshot.service_project_link = service_project_link
if save:
snapshot.save()
return snapshot
def _backend_snapshot_to_snapshot(self, backend_snapshot):
snapshot = models.Snapshot(
name=backend_snapshot.name,
description=backend_snapshot.description or '',
size=self.gb2mb(backend_snapshot.size),
metadata=backend_snapshot.metadata,
backend_id=backend_snapshot.id,
runtime_state=backend_snapshot.status,
state=models.Snapshot.States.OK,
)
if hasattr(backend_snapshot, 'volume_id'):
snapshot.source_volume = models.Volume.objects.filter(
service_project_link__service__settings=self.settings, backend_id=backend_snapshot.volume_id).first()
return snapshot
def get_snapshots(self):
cinder = self.cinder_client
try:
backend_snapshots = cinder.volume_snapshots.list()
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
return [self._backend_snapshot_to_snapshot(backend_snapshot) for backend_snapshot in backend_snapshots]
@log_backend_action()
def pull_snapshot(self, snapshot, update_fields=None):
import_time = timezone.now()
imported_snapshot = self.import_snapshot(snapshot.backend_id, save=False)
snapshot.refresh_from_db()
if snapshot.modified < import_time:
if update_fields is None:
update_fields = self.SNAPSHOT_UPDATE_FIELDS
update_pulled_fields(snapshot, imported_snapshot, update_fields)
@log_backend_action()
def pull_snapshot_runtime_state(self, snapshot):
cinder = self.cinder_client
try:
backend_snapshot = cinder.volume_snapshots.get(snapshot.backend_id)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
if backend_snapshot.status != snapshot.runtime_state:
snapshot.runtime_state = backend_snapshot.status
snapshot.save(update_fields=['runtime_state'])
return snapshot
@log_backend_action()
def delete_snapshot(self, snapshot):
cinder = self.cinder_client
try:
cinder.volume_snapshots.delete(snapshot.backend_id)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
snapshot.decrease_backend_quotas_usage()
@log_backend_action()
def update_snapshot(self, snapshot):
cinder = self.cinder_client
try:
cinder.volume_snapshots.update(
snapshot.backend_id, name=snapshot.name, description=snapshot.description)
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action('check is snapshot deleted')
def is_snapshot_deleted(self, snapshot):
cinder = self.cinder_client
try:
cinder.volume_snapshots.get(snapshot.backend_id)
return False
except cinder_exceptions.NotFound:
return True
except cinder_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def create_instance(self, instance, backend_flavor_id=None, public_key=None):
nova = self.nova_client
neutron = self.neutron_client
try:
backend_flavor = nova.flavors.get(backend_flavor_id)
# instance key name and fingerprint are optional
if instance.key_name:
backend_public_key = self._get_or_create_ssh_key(
instance.key_name, instance.key_fingerprint, public_key)
else:
backend_public_key = None
if instance.volumes.count() != 2:
raise OpenStackBackendError('Current installation can create instance with 2 volumes only.')
try:
system_volume = instance.volumes.get(bootable=True)
data_volume = instance.volumes.get(bootable=False)
except models.Volume.DoesNotExist:
raise OpenStackBackendError(
'Current installation can create only instance with 1 system volume and 1 data volume.')
security_group_ids = instance.security_groups.values_list('backend_id', flat=True)
internal_ips = instance.internal_ips_set.all()
network_ids = [{'net-id': internal_ip.subnet.network.backend_id} for internal_ip in internal_ips]
server_create_parameters = dict(
name=instance.name,
image=None, # Boot from volume, see boot_index below
flavor=backend_flavor,
block_device_mapping_v2=[
{
'boot_index': 0,
'destination_type': 'volume',
'device_type': 'disk',
'source_type': 'volume',
'uuid': system_volume.backend_id,
'delete_on_termination': True,
},
{
'destination_type': 'volume',
'device_type': 'disk',
'source_type': 'volume',
'uuid': data_volume.backend_id,
'delete_on_termination': True,
},
],
nics=network_ids,
key_name=backend_public_key.name if backend_public_key is not None else None,
security_groups=security_group_ids,
)
availability_zone = self.settings.options['availability_zone']
if availability_zone:
server_create_parameters['availability_zone'] = availability_zone
if instance.user_data:
server_create_parameters['userdata'] = instance.user_data
server = nova.servers.create(**server_create_parameters)
instance.backend_id = server.id
instance.save()
if not self._wait_for_instance_status(instance, nova, 'ACTIVE', 'ERROR'):
logger.error(
"Failed to provision instance %s: timed out waiting "
"for instance to become online",
instance.uuid)
raise OpenStackBackendError("Timed out waiting for instance %s to provision" % instance.uuid)
# nova does not return enough information about internal IPs on creation,
# we need to pull it additionally from neutron
for internal_ip in instance.internal_ips_set.all():
backend_internal_ip = neutron.list_ports(
device_id=instance.backend_id, network_id=internal_ip.subnet.network.backend_id)['ports'][0]
internal_ip.backend_id = backend_internal_ip['id']
internal_ip.ip4_address = backend_internal_ip['fixed_ips'][0]['ip_address']
internal_ip.mac_address = backend_internal_ip['mac_address']
internal_ip.save()
backend_security_groups = server.list_security_group()
for bsg in backend_security_groups:
if instance.security_groups.filter(name=bsg.name).exists():
continue
try:
security_group = models.SecurityGroup.objects.get(name=bsg.name, settings=self.settings)
except models.SecurityGroup.DoesNotExist:
logger.error(
'Security group "%s" does not exist, but instance %s (PK: %s) has it.' %
(bsg.name, instance, instance.pk)
)
else:
instance.security_groups.add(security_group)
except (nova_exceptions.ClientException, neutron_exceptions.NeutronClientException) as e:
logger.exception("Failed to provision instance %s", instance.uuid)
six.reraise(OpenStackBackendError, e)
else:
logger.info("Successfully provisioned instance %s", instance.uuid)
def _import_instance_internal_ips(self, instance_backend_id):
neutron = self.neutron_client
internal_ips = []
logger.debug('About to infer internal ip addresses of instance backend_id: %s', instance_backend_id)
try:
ports = neutron.list_ports(device_id=instance_backend_id)['ports']
except (nova_exceptions.ClientException, KeyError, IndexError):
logger.exception(
'Failed to infer internal ip addresses of instance backend_id %s', instance_backend_id)
else:
for port in ports:
fixed_ip = port['fixed_ips'][0]
subnet_backend_id = fixed_ip['subnet_id']
try:
subnet = models.SubNet.objects.get(settings=self.settings, backend_id=subnet_backend_id)
except models.SubNet.DoesNotExist:
# subnet was not pulled yet. Floating IP will be pulled with subnet later.
continue
internal_ip = models.InternalIP(
subnet=subnet,
mac_address=port['mac_address'],
ip4_address=fixed_ip['ip_address'],
backend_id=port['id'],
)
internal_ips.append(internal_ip)
logger.info(
'Successfully inferred internal ip addresses of instance backend_id %s', instance_backend_id)
return internal_ips
# XXX: This method partly duplicates "pull_floating_ips". It would be better to merge them in one.
def pull_instance_floating_ips(self, instance):
# method assumes that instance internal IPs is up to date.
neutron = self.neutron_client
instance_internal_ips = {ip.backend_id: ip for ip in instance.internal_ips_set.all()}
try:
backend_floating_ips = neutron.list_floatingips(port_id=instance_internal_ips.keys())['floatingips']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
# delete stale:
for floating_ip in instance.floating_ips.exclude(backend_id__in=[ip['id'] for ip in backend_floating_ips]):
floating_ip.internal_ip = None
floating_ip.save()
# create or update exist:
for backend_floating_ip in backend_floating_ips:
internal_ip = instance_internal_ips[backend_floating_ip['port_id']]
models.FloatingIP.objects.update_or_create(
backend_id=backend_floating_ip['id'],
settings=self.settings,
defaults={
'runtime_state': backend_floating_ip['status'],
'address': backend_floating_ip['floating_ip_address'],
'backend_network_id': backend_floating_ip['floating_network_id'],
'internal_ip': internal_ip,
}
)
@log_backend_action()
def push_instance_floating_ips(self, instance):
neutron = self.neutron_client
instance_floating_ips = instance.floating_ips
try:
backend_floating_ips = neutron.list_floatingips(
port_id=instance.internal_ips_set.values_list('backend_id', flat=True))['floatingips']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
# disconnect stale
instance_floating_ips_ids = [fip.backend_id for fip in instance_floating_ips]
for backend_floating_ip in backend_floating_ips:
if backend_floating_ip['id'] not in instance_floating_ips_ids:
neutron.update_floatingip(backend_floating_ip['id'], body={'floatingip': {'port_id': None}})
# connect new ones
backend_floating_ip_ids = {fip['id']: fip for fip in backend_floating_ips}
for floating_ip in instance_floating_ips:
backend_floating_ip = backend_floating_ip_ids.get(floating_ip.backend_id)
if not backend_floating_ip or backend_floating_ip['port_id'] != floating_ip.internal_ip.backend_id:
neutron.update_floatingip(
floating_ip.backend_id, body={'floatingip': {'port_id': floating_ip.internal_ip.backend_id}})
def create_floating_ip(self, floating_ip):
neutron = self.neutron_client
try:
backend_floating_ip = neutron.create_floatingip({
'floatingip': {
'floating_network_id': floating_ip.backend_network_id,
'tenant_id': self.tenant_id,
}
})['floatingip']
except neutron_exceptions.NeutronClientException as e:
floating_ip.runtime_state = 'ERRED'
floating_ip.save()
six.reraise(OpenStackBackendError, e)
else:
floating_ip.address = backend_floating_ip['floating_ip_address']
floating_ip.backend_id = backend_floating_ip['id']
floating_ip.save()
@log_backend_action()
def pull_floating_ip_runtime_state(self, floating_ip):
neutron = self.neutron_client
try:
backend_floating_ip = neutron.show_floatingip(floating_ip.backend_id)['floatingip']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
else:
floating_ip.runtime_state = backend_floating_ip['status']
floating_ip.save()
def _get_or_create_ssh_key(self, key_name, fingerprint, public_key):
nova = self.nova_client
try:
return nova.keypairs.find(fingerprint=fingerprint)
except nova_exceptions.NotFound:
# Fine, it's a new key, let's add it
try:
logger.info('Propagating ssh public key %s to backend', key_name)
return nova.keypairs.create(name=key_name, public_key=public_key)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
def _wait_for_instance_status(self, instance, nova, complete_status,
error_status=None, retries=300, poll_interval=3):
complete_state_predicate = lambda o: o.status == complete_status
if error_status is not None:
error_state_predicate = lambda o: o.status == error_status
else:
error_state_predicate = lambda _: False
for _ in range(retries):
obj = nova.servers.get(instance.backend_id)
logger.debug('Instance %s status: "%s"' % (obj, obj.status))
if instance.runtime_state != obj.status:
instance.runtime_state = obj.status
instance.save(update_fields=['runtime_state'])
if complete_state_predicate(obj):
return True
if error_state_predicate(obj):
return False
time.sleep(poll_interval)
else:
return False
@log_backend_action()
def update_instance(self, instance):
nova = self.nova_client
try:
nova.servers.update(instance.backend_id, name=instance.name)
except keystone_exceptions.NotFound as e:
six.reraise(OpenStackBackendError, e)
def import_instance(self, backend_instance_id, save=True, service_project_link=None):
# NB! This method does not import instance sub-objects like security groups or internal IPs.
# They have to be pulled separately.
nova = self.nova_client
try:
backend_instance = nova.servers.get(backend_instance_id)
flavor = nova.flavors.get(backend_instance.flavor['id'])
attached_volume_ids = [v.volumeId for v in nova.volumes.get_server_volumes(backend_instance_id)]
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
instance = self._backend_instance_to_instance(backend_instance, flavor)
with transaction.atomic():
# import instance volumes, or use existed if they already exist in NodeConductor.
volumes = []
for backend_volume_id in attached_volume_ids:
try:
volumes.append(models.Volume.objects.get(
service_project_link__service__settings=self.settings, backend_id=backend_volume_id))
except models.Volume.DoesNotExist:
volumes.append(self.import_volume(backend_volume_id, save=save))
if service_project_link:
instance.service_project_link = service_project_link
if hasattr(backend_instance, 'fault'):
instance.error_message = backend_instance.fault['message']
if save:
instance.save()
instance.volumes.add(*volumes)
return instance
def _backend_instance_to_instance(self, backend_instance, backend_flavor):
# parse launch time
try:
d = dateparse.parse_datetime(backend_instance.to_dict()['OS-SRV-USG:launched_at'])
except (KeyError, ValueError, TypeError):
launch_time = None
else:
# At the moment OpenStack does not provide any timezone info,
# but in future it might do.
if timezone.is_naive(d):
launch_time = timezone.make_aware(d, timezone.utc)
return models.Instance(
name=backend_instance.name or backend_instance.id,
key_name=backend_instance.key_name or '',
start_time=launch_time,
state=models.Instance.States.OK,
runtime_state=backend_instance.status,
created=dateparse.parse_datetime(backend_instance.created),
flavor_name=backend_flavor.name,
flavor_disk=backend_flavor.disk,
cores=backend_flavor.vcpus,
ram=backend_flavor.ram,
backend_id=backend_instance.id,
)
def get_instances(self):
nova = self.nova_client
try:
backend_instances = nova.servers.list()
backend_flavors = nova.flavors.list()
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
backend_flavors_map = {flavor.id: flavor for flavor in backend_flavors}
instances = []
for backend_instance in backend_instances:
instance_flavor = backend_flavors_map[backend_instance.flavor['id']]
instances.append(self._backend_instance_to_instance(backend_instance, instance_flavor))
return instances
@log_backend_action()
def pull_instance(self, instance, update_fields=None):
import_time = timezone.now()
imported_instance = self.import_instance(instance.backend_id, save=False)
instance.refresh_from_db()
if instance.modified < import_time:
if update_fields is None:
update_fields = self.INSTANCE_UPDATE_FIELDS
update_pulled_fields(instance, imported_instance, update_fields)
@log_backend_action()
def pull_instance_internal_ips(self, instance):
# we assume that instance can be connected to subnet only once.
neutron = self.neutron_client
try:
backend_internal_ips = neutron.list_ports(device_id=instance.backend_id)['ports']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
# remove stale internal IPs
instance.internal_ips_set.exclude(backend_id__in=[ip['id'] for ip in backend_internal_ips]).delete()
# add or update exist internal IPs
for backend_internal_ip in backend_internal_ips:
backend_subnet_id = backend_internal_ip['fixed_ips'][0]['subnet_id']
try:
subnet = models.SubNet.objects.get(settings=self.settings, backend_id=backend_subnet_id)
except models.SubNet.DoesNotExist:
# subnet was not pulled yet. Internal IP will be pulled with subnet later.
continue
instance.internal_ips_set.update_or_create(
backend_id=backend_internal_ip['id'],
defaults={
'subnet': subnet,
'mac_address': backend_internal_ip['mac_address'],
'ip4_address': backend_internal_ip['fixed_ips'][0]['ip_address'],
}
)
@log_backend_action()
def push_instance_internal_ips(self, instance):
# we assume that instance can be connected to subnet only once
# we assume that internal IP subnet cannot be changed
neutron = self.neutron_client
try:
backend_internal_ips = neutron.list_ports(device_id=instance.backend_id)['ports']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
# delete stale internal IPs
exist_ids = instance.internal_ips_set.values_list('backend_id', flat=True)
for backend_internal_ip in backend_internal_ips:
if backend_internal_ip['id'] not in exist_ids:
neutron.delete_port(backend_internal_ip['id'])
# create new internal IPs
new_internal_ips = instance.internal_ips_set.exclude(backend_id__in=[ip['id'] for ip in backend_internal_ips])
for new_internal_ip in new_internal_ips:
try:
backend_internal_ip = neutron.create_port({'port': {
'network_id': new_internal_ip.subnet.network.backend_id,
'device_id': instance.backend_id}
})['port']
except neutron_exceptions.NeutronClientException as e:
six.reraise(OpenStackBackendError, e)
new_internal_ip.mac_address = backend_internal_ip['mac_address']
new_internal_ip.ip4_address = backend_internal_ip['fixed_ips'][0]['ip_address']
new_internal_ip.backend_id = backend_internal_ip['id']
new_internal_ip.save()
@log_backend_action()
def pull_instance_security_groups(self, instance):
nova = self.nova_client
server_id = instance.backend_id
try:
backend_groups = nova.servers.list_security_group(server_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
backend_ids = set(g.id for g in backend_groups)
nc_ids = set(
models.SecurityGroup.objects
.filter(instances=instance)
.exclude(backend_id='')
.values_list('backend_id', flat=True)
)
# remove stale groups
stale_groups = models.SecurityGroup.objects.filter(backend_id__in=(nc_ids - backend_ids))
instance.security_groups.remove(*stale_groups)
# add missing groups
for group_id in backend_ids - nc_ids:
try:
security_group = models.SecurityGroup.objects.get(settings=self.settings, backend_id=group_id)
except models.SecurityGroup.DoesNotExist:
logger.exception(
'Security group with id %s does not exist at NC. Tenant : %s' % (group_id, instance.tenant))
else:
instance.security_groups.add(security_group)
@log_backend_action()
def push_instance_security_groups(self, instance):
nova = self.nova_client
server_id = instance.backend_id
try:
backend_ids = set(g.id for g in nova.servers.list_security_group(server_id))
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
nc_ids = set(
models.SecurityGroup.objects
.filter(instances=instance)
.exclude(backend_id='')
.values_list('backend_id', flat=True)
)
# remove stale groups
for group_id in backend_ids - nc_ids:
try:
nova.servers.remove_security_group(server_id, group_id)
except nova_exceptions.ClientException:
logger.exception('Failed to remove security group %s from instance %s', group_id, server_id)
else:
logger.info('Removed security group %s from instance %s', group_id, server_id)
# add missing groups
for group_id in nc_ids - backend_ids:
try:
nova.servers.add_security_group(server_id, group_id)
except nova_exceptions.ClientException:
logger.exception('Failed to add security group %s to instance %s', group_id, server_id)
else:
logger.info('Added security group %s to instance %s', group_id, server_id)
@log_backend_action()
def delete_instance(self, instance):
nova = self.nova_client
try:
nova.servers.delete(instance.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
instance.decrease_backend_quotas_usage()
@log_backend_action('check is instance deleted')
def is_instance_deleted(self, instance):
nova = self.nova_client
try:
nova.servers.get(instance.backend_id)
return False
except nova_exceptions.NotFound:
return True
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def pull_instance_volumes(self, instance):
for volume in instance.volumes.all():
if self.is_volume_deleted(volume):
with transaction.atomic():
volume.decrease_backend_quotas_usage()
volume.delete()
@log_backend_action()
def start_instance(self, instance):
nova = self.nova_client
try:
nova.servers.start(instance.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def stop_instance(self, instance):
nova = self.nova_client
try:
nova.servers.stop(instance.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
else:
instance.start_time = None
instance.save(update_fields=['start_time'])
@log_backend_action()
def restart_instance(self, instance):
nova = self.nova_client
try:
nova.servers.reboot(instance.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def resize_instance(self, instance, flavor_id):
nova = self.nova_client
try:
nova.servers.resize(instance.backend_id, flavor_id, 'MANUAL')
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def pull_instance_runtime_state(self, instance):
nova = self.nova_client
try:
backend_instance = nova.servers.get(instance.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
if backend_instance.status != instance.runtime_state:
instance.runtime_state = backend_instance.status
instance.save(update_fields=['runtime_state'])
@log_backend_action()
def confirm_instance_resize(self, instance):
nova = self.nova_client
try:
nova.servers.confirm_resize(instance.backend_id)
except nova_exceptions.ClientException as e:
six.reraise(OpenStackBackendError, e)
@log_backend_action()
def list_meters(self, resource):
try:
file_name = self._get_meters_file_name(resource.__class__)
with open(file_name) as meters_file:
meters = json.load(meters_file)
except (KeyError, IOError):
raise OpenStackBackendError("Cannot find meters for the '%s' resources" % resource.__class__.__name__)
return meters
@log_backend_action()
def get_meter_samples(self, resource, meter_name, start=None, end=None):
query = [dict(field='resource_id', op='eq', value=resource.backend_id)]
if start is not None:
query.append(dict(field='timestamp', op='ge', value=start.strftime('%Y-%m-%dT%H:%M:%S')))
if end is not None:
query.append(dict(field='timestamp', op='le', value=end.strftime('%Y-%m-%dT%H:%M:%S')))
ceilometer = self.ceilometer_client
try:
samples = ceilometer.samples.list(meter_name=meter_name, q=query)
except ceilometer_exceptions.BaseException as e:
six.reraise(OpenStackBackendError, e)
return samples
<file_sep>/src/nodeconductor_openstack/openstack/tests/unittests/test_handlers.py
from django.test import TestCase
from mock import patch
from permission.utils.autodiscover import autodiscover
from nodeconductor.core import utils as core_utils
from nodeconductor.structure import models as structure_models
from nodeconductor.structure.tests import factories as structure_factories
from .. import factories
@patch('nodeconductor.core.tasks.BackendMethodTask.delay')
class SshKeysHandlersTest(TestCase):
def setUp(self):
autodiscover() # permissions could be not discovered in unittests
self.user = structure_factories.UserFactory()
self.ssh_key = structure_factories.SshPublicKeyFactory(user=self.user)
self.tenant = factories.TenantFactory()
def test_ssh_key_will_be_removed_if_user_lost_connection_to_tenant(self, mocked_task_call):
project = self.tenant.service_project_link.project
project.add_user(self.user, structure_models.ProjectRole.ADMINISTRATOR)
project.remove_user(self.user)
serialized_tenant = core_utils.serialize_instance(self.tenant)
mocked_task_call.assert_called_once_with(
serialized_tenant, 'remove_ssh_key_from_tenant', self.ssh_key.name, self.ssh_key.fingerprint)
def test_ssh_key_will_not_be_removed_if_user_still_has_connection_to_tenant(self, mocked_task_call):
project = self.tenant.service_project_link.project
project.add_user(self.user, structure_models.ProjectRole.ADMINISTRATOR)
project.customer.add_user(self.user, structure_models.CustomerRole.OWNER)
project.remove_user(self.user)
self.assertEqual(mocked_task_call.call_count, 0)
def test_ssh_key_will_be_deleted_from_tenant_on_user_deletion(self, mocked_task_call):
project = self.tenant.service_project_link.project
project.add_user(self.user, structure_models.ProjectRole.ADMINISTRATOR)
self.user.delete()
serialized_tenant = core_utils.serialize_instance(self.tenant)
mocked_task_call.assert_called_once_with(
serialized_tenant, 'remove_ssh_key_from_tenant', self.ssh_key.name, self.ssh_key.fingerprint)
def test_ssh_key_will_be_deleted_from_tenant_on_ssh_key_deletion(self, mocked_task_call):
project = self.tenant.service_project_link.project
project.add_user(self.user, structure_models.ProjectRole.ADMINISTRATOR)
self.ssh_key.delete()
serialized_tenant = core_utils.serialize_instance(self.tenant)
mocked_task_call.assert_called_once_with(
serialized_tenant, 'remove_ssh_key_from_tenant', self.ssh_key.name, self.ssh_key.fingerprint)
<file_sep>/src/nodeconductor_openstack/openstack/perms.py
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure import models as structure_models, perms as structure_perms
def openstack_permission_logic(prefix):
return FilteredCollaboratorsPermissionLogic(
collaborators_query=[
'%s__service_project_link__project__customer__permissions__user' % prefix,
'%s__service_project_link__project__permissions__user' % prefix,
'%s__service_project_link__project__permissions__user' % prefix,
],
collaborators_filter=[
{'%s__service_project_link__project__customer__permissions__role' % prefix:
structure_models.CustomerRole.OWNER,
'%s__service_project_link__project__customer__permissions__is_active' % prefix: True},
{'%s__service_project_link__project__permissions__role' % prefix:
structure_models.ProjectRole.ADMINISTRATOR,
'%s__service_project_link__project__permissions__is_active' % prefix: True},
{'%s__service_project_link__project__permissions__role' % prefix:
structure_models.ProjectRole.MANAGER,
'%s__service_project_link__project__permissions__is_active' % prefix: True},
],
any_permission=True,
)
PERMISSION_LOGICS = (
('openstack.OpenStackService', structure_perms.service_permission_logic),
('openstack.OpenStackServiceProjectLink', structure_perms.service_project_link_permission_logic),
('openstack.SecurityGroup', FilteredCollaboratorsPermissionLogic(
collaborators_query=[
'service_project_link__service__customer__permissions__user',
'service_project_link__project__permissions__user',
'service_project_link__project__permissions__user',
],
collaborators_filter=[
{'service_project_link__service__customer__permissions__role': structure_models.CustomerRole.OWNER,
'service_project_link__service__customer__permissions__is_active': True},
{'service_project_link__project__permissions__role': structure_models.ProjectRole.ADMINISTRATOR,
'service_project_link__project__permissions__is_active': True},
{'service_project_link__project__permissions__role': structure_models.ProjectRole.MANAGER,
'service_project_link__project__permissions__is_active': True},
],
any_permission=True,
)),
('openstack.SecurityGroupRule', openstack_permission_logic('security_group')),
('openstack.Tenant', structure_perms.resource_permission_logic),
('openstack.Flavor', StaffPermissionLogic(any_permission=True)),
('openstack.Image', StaffPermissionLogic(any_permission=True)),
('openstack.IpMapping', StaffPermissionLogic(any_permission=True)),
('openstack.FloatingIP', StaffPermissionLogic(any_permission=True)),
)
<file_sep>/src/nodeconductor_openstack/openstack_tenant/serializers.py
from __future__ import unicode_literals
import collections
import logging
import pytz
import re
from django.db import transaction
from django.utils import timezone
from rest_framework import serializers
from nodeconductor.core import serializers as core_serializers, fields as core_fields, utils as core_utils
from nodeconductor.structure import serializers as structure_serializers
from . import models, fields
logger = logging.getLogger(__name__)
class ServiceSerializer(core_serializers.ExtraFieldOptionsMixin,
core_serializers.RequiredFieldsMixin,
structure_serializers.BaseServiceSerializer):
SERVICE_ACCOUNT_FIELDS = {
'backend_url': 'Keystone auth URL (e.g. http://keystone.example.com:5000/v2.0)',
'username': 'Tenant user username',
'password': '<PASSWORD>',
}
SERVICE_ACCOUNT_EXTRA_FIELDS = {
'tenant_id': 'Tenant ID in OpenStack',
'availability_zone': 'Default availability zone for provisioned instances',
}
class Meta(structure_serializers.BaseServiceSerializer.Meta):
model = models.OpenStackTenantService
required_fields = ('backend_url', 'username', 'password', 'tenant_id')
extra_field_options = {
'backend_url': {
'label': 'API URL',
'default_value': 'http://keystone.example.com:5000/v2.0',
},
'tenant_id': {
'label': 'Tenant ID',
},
'availability_zone': {
'placeholder': 'default',
},
}
class ServiceProjectLinkSerializer(structure_serializers.BaseServiceProjectLinkSerializer):
class Meta(structure_serializers.BaseServiceProjectLinkSerializer.Meta):
model = models.OpenStackTenantServiceProjectLink
extra_kwargs = {
'service': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-detail'},
}
class ImageSerializer(structure_serializers.BasePropertySerializer):
class Meta(structure_serializers.BasePropertySerializer.Meta):
model = models.Image
fields = ('url', 'uuid', 'name', 'settings', 'min_disk', 'min_ram',)
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'settings': {'lookup_field': 'uuid'},
}
class FlavorSerializer(structure_serializers.BasePropertySerializer):
class Meta(structure_serializers.BasePropertySerializer.Meta):
model = models.Flavor
fields = ('url', 'uuid', 'name', 'settings', 'cores', 'ram', 'disk',)
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'settings': {'lookup_field': 'uuid'},
}
class NetworkSerializer(structure_serializers.BasePropertySerializer):
class Meta(structure_serializers.BasePropertySerializer.Meta):
model = models.Network
fields = ('url', 'uuid', 'name',
'type', 'is_external', 'segmentation_id', 'subnets')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'settings': {'lookup_field': 'uuid'},
'subnets': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-subnet-detail'}
}
class SubNetSerializer(structure_serializers.BasePropertySerializer):
dns_nameservers = core_fields.JsonField(read_only=True)
allocation_pools = core_fields.JsonField(read_only=True)
class Meta(structure_serializers.BasePropertySerializer.Meta):
model = models.SubNet
fields = ('url', 'uuid', 'name',
'cidr', 'gateway_ip', 'allocation_pools', 'ip_version', 'enable_dhcp', 'dns_nameservers', 'network')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'settings': {'lookup_field': 'uuid'},
'network': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-network-detail'},
}
class FloatingIPSerializer(structure_serializers.BasePropertySerializer):
class Meta(structure_serializers.BasePropertySerializer.Meta):
model = models.FloatingIP
fields = ('url', 'uuid', 'settings', 'address', 'runtime_state', 'is_booked',)
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'settings': {'lookup_field': 'uuid'},
}
class SecurityGroupSerializer(structure_serializers.BasePropertySerializer):
rules = serializers.SerializerMethodField()
class Meta(structure_serializers.BasePropertySerializer.Meta):
model = models.SecurityGroup
fields = ('url', 'uuid', 'name', 'settings', 'description', 'rules')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'settings': {'lookup_field': 'uuid'},
}
def get_rules(self, security_group):
rules = []
for rule in security_group.rules.all():
rules.append({
'protocol': rule.protocol,
'from_port': rule.from_port,
'to_port': rule.to_port,
'cidr': rule.cidr,
})
return rules
class VolumeSerializer(structure_serializers.BaseResourceSerializer):
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstacktenant-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstacktenant-spl-detail',
queryset=models.OpenStackTenantServiceProjectLink.objects.all(),
)
action_details = core_serializers.JSONField(read_only=True)
instance_name = serializers.SerializerMethodField()
class Meta(structure_serializers.BaseResourceSerializer.Meta):
model = models.Volume
fields = structure_serializers.BaseResourceSerializer.Meta.fields + (
'source_snapshot', 'size', 'bootable', 'metadata',
'image', 'image_metadata', 'type', 'runtime_state',
'device', 'action', 'action_details', 'instance', 'instance_name',
)
read_only_fields = structure_serializers.BaseResourceSerializer.Meta.read_only_fields + (
'image_metadata', 'bootable', 'source_snapshot', 'runtime_state', 'device', 'metadata',
'action', 'instance', 'type',
)
protected_fields = structure_serializers.BaseResourceSerializer.Meta.protected_fields + (
'size', 'image',
)
extra_kwargs = dict(
instance={'lookup_field': 'uuid', 'view_name': 'openstacktenant-instance-detail'},
image={'lookup_field': 'uuid', 'view_name': 'openstacktenant-image-detail'},
source_snapshot={'lookup_field': 'uuid', 'view_name': 'openstacktenant-snapshot-detail'},
size={'required': False, 'allow_null': True},
**structure_serializers.BaseResourceSerializer.Meta.extra_kwargs
)
def get_instance_name(self, volume):
if volume.instance:
return volume.instance.name
def validate(self, attrs):
if self.instance is None:
# image validation
image = attrs.get('image')
spl = attrs['service_project_link']
if image and image.settings != spl.service.settings:
raise serializers.ValidationError({'image': 'Image must belong to the same service settings'})
# snapshot & size validation
size = attrs.get('size')
snapshot = attrs.get('snapshot')
if not size and not snapshot:
raise serializers.ValidationError('Snapshot or size should be defined')
if size and snapshot:
raise serializers.ValidationError('It is impossible to define both snapshot and size')
# image & size validation
size = size or snapshot.size
if image and image.min_disk > size:
raise serializers.ValidationError({
'size': 'Volume size should be equal or greater than %s for selected image' % image.min_disk
})
return attrs
def create(self, validated_data):
if not validated_data.get('size'):
validated_data['size'] = validated_data['snapshot'].size
return super(VolumeSerializer, self).create(validated_data)
class VolumeExtendSerializer(serializers.Serializer):
disk_size = serializers.IntegerField(min_value=1, label='Disk size')
def validate_disk_size(self, disk_size):
if disk_size < self.instance.size + 1024:
raise serializers.ValidationError(
'Disk size should be greater or equal to %s' % (self.instance.size + 1024))
return disk_size
@transaction.atomic
def update(self, instance, validated_data):
new_size = validated_data.get('disk_size')
instance.service_project_link.service.settings.add_quota_usage(
'storage', new_size - instance.size, validate=True)
instance.size = new_size
instance.save(update_fields=['size'])
return instance
class VolumeAttachSerializer(structure_serializers.PermissionFieldFilteringMixin,
serializers.HyperlinkedModelSerializer):
class Meta(object):
model = models.Volume
fields = ('instance', 'device')
extra_kwargs = dict(
instance={
'required': True,
'allow_null': False,
'view_name': 'openstacktenant-instance-detail',
'lookup_field': 'uuid',
}
)
def get_fields(self):
fields = super(VolumeAttachSerializer, self).get_fields()
volume = self.instance
if volume:
fields['instance'].display_name_field = 'name'
fields['instance'].query_params = {
'project_uuid': volume.service_project_link.project.uuid.hex,
'service_uuid': volume.service_project_link.service.uuid.hex,
}
return fields
def get_filtered_field_names(self):
return ('instance',)
def validate_instance(self, instance):
States, RuntimeStates = models.Instance.States, models.Instance.RuntimeStates
if instance.state != States.OK or instance.runtime_state != RuntimeStates.SHUTOFF:
raise serializers.ValidationError(
'Volume can be attached only to instance that is shutoff and in state OK.')
volume = self.instance
if instance.service_project_link != volume.service_project_link:
raise serializers.ValidationError('Volume and instance should belong to the same service and project.')
return instance
def validate(self, attrs):
instance = attrs['instance']
device = attrs.get('device')
if device and instance.volumes.filter(device=device).exists():
raise serializers.ValidationError({'device': 'The supplied device path (%s) is in use.' % device})
return attrs
class SnapshotRestorationSerializer(core_serializers.AugmentedSerializerMixin, serializers.HyperlinkedModelSerializer):
name = serializers.CharField(write_only=True, help_text='New volume name.')
description = serializers.CharField(required=False, help_text='New volume description.')
class Meta(object):
model = models.SnapshotRestoration
fields = ('uuid', 'created', 'name', 'description',
'volume', 'volume_name', 'volume_state', 'volume_runtime_state', 'volume_size', 'volume_device')
read_only_fields = ('uuid', 'created', 'volume')
related_paths = {
'volume': ('name', 'state', 'runtime_state', 'size', 'device')
}
extra_kwargs = dict(
volume={'lookup_field': 'uuid', 'view_name': 'openstacktenant-volume-detail'},
volume_state={'source': 'volume.human_readable_state'}
)
@transaction.atomic
def create(self, validated_data):
snapshot = self.context['view'].get_object()
validated_data['snapshot'] = snapshot
description = validated_data.pop('description', None) or 'Restored from snapshot %s' % snapshot.name
volume = models.Volume(
source_snapshot=snapshot,
service_project_link=snapshot.service_project_link,
name=validated_data.pop('name'),
description=description,
size=snapshot.size,
)
if 'source_volume_image_metadata' in snapshot.metadata:
volume.image_metadata = snapshot.metadata['source_volume_image_metadata']
volume.save()
volume.increase_backend_quotas_usage()
validated_data['volume'] = volume
return super(SnapshotRestorationSerializer, self).create(validated_data)
class SnapshotSerializer(structure_serializers.BaseResourceSerializer):
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstacktenant-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstacktenant-spl-detail',
read_only=True)
source_volume_name = serializers.ReadOnlyField(source='source_volume.name')
action_details = core_serializers.JSONField(read_only=True)
metadata = core_serializers.JSONField(required=False)
restorations = SnapshotRestorationSerializer(many=True, read_only=True)
snapshot_schedule_uuid = serializers.ReadOnlyField(source='snapshot_schedule.uuid')
class Meta(structure_serializers.BaseResourceSerializer.Meta):
model = models.Snapshot
fields = structure_serializers.BaseResourceSerializer.Meta.fields + (
'source_volume', 'size', 'metadata', 'runtime_state', 'source_volume_name', 'action', 'action_details',
'restorations', 'kept_until', 'snapshot_schedule', 'snapshot_schedule_uuid'
)
read_only_fields = structure_serializers.BaseResourceSerializer.Meta.read_only_fields + (
'size', 'source_volume', 'metadata', 'runtime_state', 'action', 'snapshot_schedule',
)
extra_kwargs = dict(
source_volume={'lookup_field': 'uuid', 'view_name': 'openstacktenant-volume-detail'},
snapshot_schedule={'lookup_field': 'uuid', 'view_name': 'openstacktenant-snapshot-schedule-detail'},
**structure_serializers.BaseResourceSerializer.Meta.extra_kwargs
)
def create(self, validated_data):
validated_data['source_volume'] = source_volume = self.context['view'].get_object()
validated_data['service_project_link'] = source_volume.service_project_link
validated_data['size'] = source_volume.size
validated_data['metadata'] = self.get_snapshot_metadata(source_volume)
return super(SnapshotSerializer, self).create(validated_data)
@staticmethod
def get_snapshot_metadata(volume):
return {
'source_volume_name': volume.name,
'source_volume_description': volume.description,
'source_volume_image_metadata': volume.image_metadata,
}
class NestedVolumeSerializer(core_serializers.AugmentedSerializerMixin,
serializers.HyperlinkedModelSerializer,
structure_serializers.BasicResourceSerializer):
state = serializers.ReadOnlyField(source='get_state_display')
class Meta:
model = models.Volume
fields = 'url', 'uuid', 'name', 'state', 'bootable', 'size', 'resource_type'
extra_kwargs = {
'url': {'lookup_field': 'uuid'}
}
class NestedSecurityGroupRuleSerializer(serializers.ModelSerializer):
class Meta:
model = models.SecurityGroupRule
fields = ('id', 'protocol', 'from_port', 'to_port', 'cidr')
def to_internal_value(self, data):
# Return exist security group as internal value if id is provided
if 'id' in data:
try:
return models.SecurityGroupRule.objects.get(id=data['id'])
except models.SecurityGroup:
raise serializers.ValidationError('Security group with id %s does not exist' % data['id'])
else:
internal_data = super(NestedSecurityGroupRuleSerializer, self).to_internal_value(data)
return models.SecurityGroupRule(**internal_data)
class NestedSecurityGroupSerializer(core_serializers.AugmentedSerializerMixin,
core_serializers.HyperlinkedRelatedModelSerializer):
rules = NestedSecurityGroupRuleSerializer(
many=True,
read_only=True,
)
state = serializers.ReadOnlyField(source='human_readable_state')
class Meta(object):
model = models.SecurityGroup
fields = ('url', 'name', 'rules', 'description', 'state')
read_only_fields = ('name', 'rules', 'description', 'state')
extra_kwargs = {
'url': {'lookup_field': 'uuid'}
}
class NestedInternalIPSerializer(core_serializers.AugmentedSerializerMixin, serializers.HyperlinkedModelSerializer):
class Meta(object):
model = models.InternalIP
fields = (
'ip4_address', 'mac_address', 'subnet', 'subnet_uuid', 'subnet_name', 'subnet_description', 'subnet_cidr')
read_only_fields = (
'ip4_address', 'mac_address', 'subnet_uuid', 'subnet_name', 'subnet_description', 'subnet_cidr')
related_paths = {
'subnet': ('uuid', 'name', 'description', 'cidr'),
}
extra_kwargs = {
'subnet': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-subnet-detail'},
}
def to_internal_value(self, data):
internal_value = super(NestedInternalIPSerializer, self).to_internal_value(data)
return models.InternalIP(subnet=internal_value['subnet'])
class NestedFloatingIPSerializer(core_serializers.AugmentedSerializerMixin,
core_serializers.HyperlinkedRelatedModelSerializer):
subnet = serializers.HyperlinkedRelatedField(
queryset=models.SubNet.objects.all(),
source='internal_ip.subnet',
view_name='openstacktenant-subnet-detail',
lookup_field='uuid')
subnet_uuid = serializers.ReadOnlyField(source='internal_ip.subnet.uuid')
subnet_name = serializers.ReadOnlyField(source='internal_ip.subnet.name')
subnet_description = serializers.ReadOnlyField(source='internal_ip.subnet.description')
subnet_cidr = serializers.ReadOnlyField(source='internal_ip.subnet.cidr')
class Meta(object):
model = models.FloatingIP
fields = ('url', 'uuid', 'address', 'internal_ip_ip4_address', 'internal_ip_mac_address',
'subnet', 'subnet_uuid', 'subnet_name', 'subnet_description', 'subnet_cidr')
read_only_fields = ('address', 'internal_ip_ip4_address', 'internal_ip_mac_address')
related_paths = {
'internal_ip': ('ip4_address', 'mac_address')
}
extra_kwargs = {
'url': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-fip-detail'},
}
def to_internal_value(self, data):
"""
Return pair (floating_ip, subnet) as internal value.
On floating IP creation user should specify what subnet should be used
for connection and may specify what exactly floating IP should be used.
If floating IP is not specified it will be represented as None.
"""
floating_ip = None
if 'url' in data:
# use HyperlinkedRelatedModelSerializer (parent of NestedFloatingIPSerializer)
# method to convert "url" to FloatingIP object
floating_ip = super(NestedFloatingIPSerializer, self).to_internal_value(data)
# use HyperlinkedModelSerializer (parent of HyperlinkedRelatedModelSerializer)
# to convert "subnet" to SubNet object
internal_value = super(core_serializers.HyperlinkedRelatedModelSerializer, self).to_internal_value(data)
subnet = internal_value['internal_ip']['subnet']
return floating_ip, subnet
def _validate_instance_internal_ips(internal_ips, settings):
""" - make sure that internal_ips belong to specified setting
- make sure that internal_ips does not connect to the same subnet twice
"""
subnets = [internal_ip.subnet for internal_ip in internal_ips]
for subnet in subnets:
if subnet.settings != settings:
raise serializers.ValidationError(
'Subnet %s does not belong to the same service settings as service project link.' % subnet)
duplicates = [subnet for subnet, count in collections.Counter(subnets).items() if count > 1]
if duplicates:
raise serializers.ValidationError('It is impossible to connect to subnet %s twice.' % duplicates[0])
def _validate_instance_floating_ips(floating_ips_with_subnets, settings, instance_subnets):
if floating_ips_with_subnets and 'external_network_id' not in settings.options:
raise serializers.ValidationError('Please specify tenant external network to perform floating IP operations.')
for floating_ip, subnet in floating_ips_with_subnets:
if subnet not in instance_subnets:
message = 'SubNet %s is not connected to instance.' % subnet
raise serializers.ValidationError({'floating_ips': message})
if not floating_ip:
continue
if floating_ip.is_booked:
raise serializers.ValidationError(
'Floating IP %s is already booked for another instance creation' % floating_ip)
if not floating_ip.internal_ip and floating_ip.runtime_state != 'DOWN':
raise serializers.ValidationError('Floating IP %s runtime state should be DOWN.' % floating_ip)
if floating_ip.settings != settings:
message = (
'Floating IP %s does not belong to the same service settings as service project link.' % floating_ip)
raise serializers.ValidationError({'floating_ips': message})
subnets = [subnet for _, subnet in floating_ips_with_subnets]
duplicates = [subnet for subnet, count in collections.Counter(subnets).items() if count > 1]
if duplicates:
raise serializers.ValidationError('It is impossible to use subnet %s twice.' % duplicates[0])
def _connect_floating_ip_to_instance(floating_ip, subnet, instance):
""" Connect floating IP to instance via specified subnet.
If floating IP is not defined - take exist free one or create a new one.
"""
settings = instance.service_project_link.service.settings
if not floating_ip:
kwargs = {
'runtime_state': 'DOWN',
'settings': settings,
'is_booked': False,
'backend_network_id': settings.options['external_network_id'],
}
floating_ip = models.FloatingIP.objects.filter(**kwargs).first()
if not floating_ip:
floating_ip = models.FloatingIP(**kwargs)
floating_ip.increase_backend_quotas_usage()
floating_ip.is_booked = True
floating_ip.internal_ip = models.InternalIP.objects.get(instance=instance, subnet=subnet)
floating_ip.save()
return floating_ip
class InstanceSerializer(structure_serializers.VirtualMachineSerializer):
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstacktenant-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstacktenant-spl-detail',
queryset=models.OpenStackTenantServiceProjectLink.objects.all())
flavor = serializers.HyperlinkedRelatedField(
view_name='openstacktenant-flavor-detail',
lookup_field='uuid',
queryset=models.Flavor.objects.all().select_related('settings'),
write_only=True)
image = serializers.HyperlinkedRelatedField(
view_name='openstacktenant-image-detail',
lookup_field='uuid',
queryset=models.Image.objects.all().select_related('settings'),
write_only=True)
security_groups = NestedSecurityGroupSerializer(
queryset=models.SecurityGroup.objects.all(), many=True, required=False)
internal_ips_set = NestedInternalIPSerializer(many=True, required=False)
floating_ips = NestedFloatingIPSerializer(queryset=models.FloatingIP.objects.all(), many=True, required=False)
system_volume_size = serializers.IntegerField(min_value=1024, write_only=True)
data_volume_size = serializers.IntegerField(initial=20 * 1024, default=20 * 1024, min_value=1024, write_only=True)
volumes = NestedVolumeSerializer(many=True, required=False, read_only=True)
action_details = core_serializers.JSONField(read_only=True)
class Meta(structure_serializers.VirtualMachineSerializer.Meta):
model = models.Instance
fields = structure_serializers.VirtualMachineSerializer.Meta.fields + (
'flavor', 'image', 'system_volume_size', 'data_volume_size',
'security_groups', 'internal_ips', 'flavor_disk', 'flavor_name',
'floating_ips', 'volumes', 'runtime_state', 'action', 'action_details', 'internal_ips_set',
)
protected_fields = structure_serializers.VirtualMachineSerializer.Meta.protected_fields + (
'flavor', 'image', 'system_volume_size', 'data_volume_size',
'floating_ips', 'security_groups', 'internal_ips_set',
)
read_only_fields = structure_serializers.VirtualMachineSerializer.Meta.read_only_fields + (
'flavor_disk', 'runtime_state', 'flavor_name', 'action',
)
def get_fields(self):
fields = super(InstanceSerializer, self).get_fields()
floating_ip_field = fields.get('floating_ip')
if floating_ip_field:
floating_ip_field.query_params = {'runtime_state': 'DOWN'}
floating_ip_field.value_field = 'url'
floating_ip_field.display_name_field = 'address'
return fields
@staticmethod
def eager_load(queryset):
queryset = structure_serializers.VirtualMachineSerializer.eager_load(queryset)
return queryset.prefetch_related(
'security_groups',
'security_groups__rules',
'volumes',
)
def validate(self, attrs):
# skip validation on object update
if self.instance is not None:
return attrs
service_project_link = attrs['service_project_link']
settings = service_project_link.service.settings
flavor = attrs['flavor']
image = attrs['image']
if any([flavor.settings != settings, image.settings != settings]):
raise serializers.ValidationError(
'Flavor and image must belong to the same service settings as service project link.')
if image.min_ram > flavor.ram:
raise serializers.ValidationError(
{'flavor': 'RAM of flavor is not enough for selected image %s' % image.min_ram})
if image.min_disk > flavor.disk:
raise serializers.ValidationError({
'flavor': "Flavor's disk is too small for the selected image."
})
if image.min_disk > attrs['system_volume_size']:
raise serializers.ValidationError(
{'system_volume_size': 'System volume size has to be greater than %s' % image.min_disk})
for security_group in attrs.get('security_groups', []):
if security_group.settings != settings:
raise serializers.ValidationError(
'Security group {} does not belong to the same service settings as service project link.'.format(
security_group.name))
internal_ips = attrs.get('internal_ips_set', [])
_validate_instance_internal_ips(internal_ips, settings)
subnets = [internal_ip.subnet for internal_ip in internal_ips]
_validate_instance_floating_ips(attrs.get('floating_ips', []), settings, subnets)
return attrs
@transaction.atomic
def create(self, validated_data):
""" Store flavor, ssh_key and image details into instance model.
Create volumes and security groups for instance.
"""
security_groups = validated_data.pop('security_groups', [])
internal_ips = validated_data.pop('internal_ips_set', [])
floating_ips_with_subnets = validated_data.pop('floating_ips', [])
spl = validated_data['service_project_link']
ssh_key = validated_data.get('ssh_public_key')
if ssh_key:
# We want names to be human readable in backend.
# OpenStack only allows latin letters, digits, dashes, underscores and spaces
# as key names, thus we mangle the original name.
safe_name = re.sub(r'[^-a-zA-Z0-9 _]+', '_', ssh_key.name)[:17]
validated_data['key_name'] = '{0}-{1}'.format(ssh_key.uuid.hex, safe_name)
validated_data['key_fingerprint'] = ssh_key.fingerprint
flavor = validated_data['flavor']
validated_data['flavor_name'] = flavor.name
validated_data['cores'] = flavor.cores
validated_data['ram'] = flavor.ram
validated_data['flavor_disk'] = flavor.disk
image = validated_data['image']
validated_data['image_name'] = image.name
validated_data['min_disk'] = image.min_disk
validated_data['min_ram'] = image.min_ram
system_volume_size = validated_data['system_volume_size']
data_volume_size = validated_data['data_volume_size']
validated_data['disk'] = data_volume_size + system_volume_size
instance = super(InstanceSerializer, self).create(validated_data)
# security groups
instance.security_groups.add(*security_groups)
# internal IPs
for internal_ip in internal_ips:
internal_ip.instance = instance
internal_ip.save()
# floating IPs
for floating_ip, subnet in floating_ips_with_subnets:
_connect_floating_ip_to_instance(floating_ip, subnet, instance)
# volumes
system_volume = models.Volume.objects.create(
name='{0}-system'.format(instance.name[:143]), # volume name cannot be longer than 150 symbols
service_project_link=spl,
size=system_volume_size,
image=image,
bootable=True,
)
system_volume.increase_backend_quotas_usage()
data_volume = models.Volume.objects.create(
name='{0}-data'.format(instance.name[:145]), # volume name cannot be longer than 150 symbols
service_project_link=spl,
size=data_volume_size,
)
data_volume.increase_backend_quotas_usage()
instance.volumes.add(system_volume, data_volume)
return instance
def update(self, instance, validated_data):
# DRF adds data_volume_size to validated_data, because it has default value.
# This field is protected, so it should not be used for update.
if 'data_volume_size' in validated_data:
del validated_data['data_volume_size']
return super(InstanceSerializer, self).update(instance, validated_data)
class AssignFloatingIpSerializer(serializers.Serializer):
floating_ip = serializers.HyperlinkedRelatedField(
label='Floating IP',
required=False,
allow_null=True,
view_name='openstacktenant-fip-detail',
lookup_field='uuid',
queryset=models.FloatingIP.objects.all()
)
def get_fields(self):
fields = super(AssignFloatingIpSerializer, self).get_fields()
if self.instance:
query_params = {
'runtime_state': 'DOWN',
'settings_uuid': self.instance.service_project_link.service.settings.uuid.hex,
}
field = fields['floating_ip']
field.query_params = query_params
field.value_field = 'url'
field.display_name_field = 'address'
return fields
def validate_floating_ip(self, floating_ip):
if floating_ip is not None:
if floating_ip.runtime_state != 'DOWN':
raise serializers.ValidationError('Floating IP runtime_state must be DOWN.')
elif floating_ip.settings != self.instance.service_project_link.service.settings:
raise serializers.ValidationError('Floating IP must belong to same settings as instance.')
return floating_ip
def save(self):
# Increase service settings quota on floating IP quota if new one will be created.
if not self.validated_data.get('floating_ip'):
settings = self.instance.service_project_link.service.settings
settings.add_quota_usage(settings.Quotas.floating_ip_count, 1, validate=True)
return self.validated_data.get('floating_ip')
class InstanceFlavorChangeSerializer(structure_serializers.PermissionFieldFilteringMixin, serializers.Serializer):
flavor = serializers.HyperlinkedRelatedField(
view_name='openstacktenant-flavor-detail',
lookup_field='uuid',
queryset=models.Flavor.objects.all(),
)
def get_fields(self):
fields = super(InstanceFlavorChangeSerializer, self).get_fields()
if self.instance:
fields['flavor'].query_params = {
'settings_uuid': self.instance.service_project_link.service.settings.uuid
}
return fields
def get_filtered_field_names(self):
return ('flavor',)
def validate_flavor(self, value):
if value is not None:
spl = self.instance.service_project_link
if value.name == self.instance.flavor_name:
raise serializers.ValidationError(
'New flavor is the same as current.')
if value.settings != spl.service.settings:
raise serializers.ValidationError(
'New flavor is not within the same service settings')
if value.disk < self.instance.flavor_disk:
raise serializers.ValidationError(
'New flavor disk should be greater than the previous value')
return value
@transaction.atomic
def update(self, instance, validated_data):
flavor = validated_data.get('flavor')
settings = instance.service_project_link.service.settings
settings.add_quota_usage(settings.Quotas.ram, flavor.ram - instance.ram, validate=True)
settings.add_quota_usage(settings.Quotas.vcpu, flavor.cores - instance.cores, validate=True)
instance.ram = flavor.ram
instance.cores = flavor.cores
instance.flavor_disk = flavor.disk
instance.flavor_name = flavor.name
instance.save(update_fields=['ram', 'cores', 'flavor_name', 'flavor_disk'])
return instance
class InstanceDeleteSerializer(serializers.Serializer):
delete_volumes = serializers.BooleanField(default=True)
def validate(self, attrs):
if attrs['delete_volumes'] and models.Snapshot.objects.filter(source_volume__instance=self.instance).exists():
raise serializers.ValidationError('Cannot delete instance. One of its volumes has attached snapshot.')
return attrs
class InstanceSecurityGroupsUpdateSerializer(serializers.Serializer):
security_groups = NestedSecurityGroupSerializer(
queryset=models.SecurityGroup.objects.all(),
many=True,
)
def get_fields(self):
fields = super(InstanceSecurityGroupsUpdateSerializer, self).get_fields()
instance = self.instance
if instance:
fields['security_groups'].display_name_field = 'name'
fields['security_groups'].view_name = 'openstacktenant-sgp-detail'
fields['security_groups'].query_params = {
'settings_uuid': instance.service_project_link.service.settings.uuid
}
return fields
def validate_security_groups(self, security_groups):
spl = self.instance.service_project_link
for security_group in security_groups:
if security_group.settings != spl.service.settings:
raise serializers.ValidationError(
'Security group %s is not within the same service settings' % security_group.name)
return security_groups
@transaction.atomic
def update(self, instance, validated_data):
security_groups = validated_data.pop('security_groups', None)
if security_groups is not None:
instance.security_groups.clear()
instance.security_groups.add(*security_groups)
return instance
class InstanceInternalIPsSetUpdateSerializer(serializers.Serializer):
internal_ips_set = NestedInternalIPSerializer(many=True)
def get_fields(self):
fields = super(InstanceInternalIPsSetUpdateSerializer, self).get_fields()
instance = self.instance
if instance:
fields['internal_ips_set'].view_name = 'openstacktenant-subnet-detail'
fields['internal_ips_set'].query_params = {
'settings_uuid': instance.service_project_link.service.settings.uuid
}
return fields
def validate_internal_ips_set(self, internal_ips_set):
spl = self.instance.service_project_link
_validate_instance_internal_ips(internal_ips_set, spl.service.settings)
return internal_ips_set
@transaction.atomic
def update(self, instance, validated_data):
internal_ips_set = validated_data['internal_ips_set']
new_subnets = [ip.subnet for ip in internal_ips_set]
# delete stale IPs
models.InternalIP.objects.filter(instance=instance).exclude(subnet__in=new_subnets).delete()
# create new IPs
for internal_ip in internal_ips_set:
models.InternalIP.objects.get_or_create(instance=instance, subnet=internal_ip.subnet)
return instance
class InstanceFloatingIPsUpdateSerializer(serializers.Serializer):
floating_ips = NestedFloatingIPSerializer(queryset=models.FloatingIP.objects.all(), many=True, required=False)
def get_fields(self):
fields = super(InstanceFloatingIPsUpdateSerializer, self).get_fields()
instance = self.instance
if instance:
fields['floating_ips'].view_name = 'openstacktenant-fip-detail'
fields['floating_ips'].query_params = {
'settings_uuid': instance.service_project_link.service.settings.uuid.hex,
'runtime_state': 'DOWN',
'is_booked': False,
}
return fields
def validate_floating_ips(self, floating_ips):
spl = self.instance.service_project_link
subnets = self.instance.subnets.all()
_validate_instance_floating_ips(floating_ips, spl.service.settings, subnets)
return floating_ips
def update(self, instance, validated_data):
floating_ips_with_subnets = validated_data['floating_ips']
floating_ips_to_disconnect = list(self.instance.floating_ips)
for floating_ip, subnet in floating_ips_with_subnets:
if floating_ip in floating_ips_to_disconnect:
floating_ips_to_disconnect.remove(floating_ip)
continue
_connect_floating_ip_to_instance(floating_ip, subnet, instance)
for floating_ip in floating_ips_to_disconnect:
floating_ip.internal_ip = None
floating_ip.save()
return instance
class BackupRestorationSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField(
required=False, help_text='New instance name. Leave blank to use source instance name.')
class Meta(object):
model = models.BackupRestoration
fields = ('uuid', 'instance', 'created', 'flavor', 'name')
read_only_fields = ('url', 'uuid', 'instance', 'created', 'backup')
extra_kwargs = dict(
instance={'lookup_field': 'uuid', 'view_name': 'openstacktenant-instance-detail'},
flavor={'lookup_field': 'uuid', 'view_name': 'openstacktenant-flavor-detail', 'allow_null': False,
'required': True},
)
def get_fields(self):
fields = super(BackupRestorationSerializer, self).get_fields()
view = self.context.get('view') # On docs generation context does not contain "view".
if view and view.action == 'restore':
fields['flavor'].display_name_field = 'name'
fields['flavor'].view_name = 'openstacktenant-flavor-detail'
# View doesn't have object during schema generation
if hasattr(view, 'lookup_field') and view.lookup_field in view.kwargs:
backup = view.get_object()
# It is assumed that valid OpenStack Instance has exactly one bootable volume
system_volume = backup.instance.volumes.get(bootable=True)
fields['flavor'].query_params = {
'settings_uuid': backup.service_project_link.service.settings.uuid,
'disk__gte': system_volume.size,
}
return fields
def validate(self, attrs):
flavor = attrs['flavor']
backup = self.context['view'].get_object()
system_volume = backup.instance.volumes.get(bootable=True)
if flavor.settings != backup.instance.service_project_link.service.settings:
raise serializers.ValidationError({'flavor': "Flavor is not within services' settings."})
if flavor.disk < system_volume.size:
raise serializers.ValidationError({'flavor': 'Flavor disk size should match system volume size.'})
return attrs
@transaction.atomic
def create(self, validated_data):
flavor = validated_data['flavor']
validated_data['backup'] = backup = self.context['view'].get_object()
source_instance = backup.instance
# instance that will be restored
metadata = backup.metadata or {}
instance = models.Instance.objects.create(
name=validated_data.pop('name', None) or metadata.get('name', source_instance.name),
description=metadata.get('description', ''),
service_project_link=backup.service_project_link,
flavor_disk=flavor.disk,
flavor_name=flavor.name,
cores=flavor.cores,
ram=flavor.ram,
min_ram=metadata.get('min_ram', 0),
min_disk=metadata.get('min_disk', 0),
image_name=metadata.get('image_name', ''),
user_data=metadata.get('user_data', ''),
disk=sum([snapshot.size for snapshot in backup.snapshots.all()]),
)
instance.increase_backend_quotas_usage()
validated_data['instance'] = instance
backup_restoration = super(BackupRestorationSerializer, self).create(validated_data)
# restoration for each instance volume from snapshot.
for snapshot in backup.snapshots.all():
volume = models.Volume(
source_snapshot=snapshot,
service_project_link=snapshot.service_project_link,
name='{0}-volume'.format(instance.name[:143]),
description='Restored from backup %s' % backup.uuid.hex,
size=snapshot.size,
)
if 'source_volume_image_metadata' in snapshot.metadata:
volume.image_metadata = snapshot.metadata['source_volume_image_metadata']
volume.save()
volume.increase_backend_quotas_usage()
instance.volumes.add(volume)
return backup_restoration
class BackupSerializer(structure_serializers.BaseResourceSerializer):
# Serializer requires OpenStack Instance in context on creation
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstacktenant-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstacktenant-spl-detail',
read_only=True,
)
metadata = core_fields.JsonField(read_only=True)
instance_name = serializers.ReadOnlyField(source='instance.name')
restorations = BackupRestorationSerializer(many=True, read_only=True)
backup_schedule_uuid = serializers.ReadOnlyField(source='backup_schedule.uuid')
class Meta(structure_serializers.BaseResourceSerializer.Meta):
model = models.Backup
fields = structure_serializers.BaseResourceSerializer.Meta.fields + (
'kept_until', 'metadata', 'instance', 'instance_name', 'restorations',
'backup_schedule', 'backup_schedule_uuid')
read_only_fields = structure_serializers.BaseResourceSerializer.Meta.read_only_fields + (
'instance', 'service_project_link', 'backup_schedule')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'instance': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-instance-detail'},
'backup_schedule': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-backup-schedule-detail'},
}
@transaction.atomic
def create(self, validated_data):
validated_data['instance'] = instance = self.context['view'].get_object()
validated_data['service_project_link'] = instance.service_project_link
validated_data['metadata'] = self.get_backup_metadata(instance)
backup = super(BackupSerializer, self).create(validated_data)
self.create_backup_snapshots(backup)
return backup
@staticmethod
def get_backup_metadata(instance):
return {
'name': instance.name,
'description': instance.description,
'min_ram': instance.min_ram,
'min_disk': instance.min_disk,
'key_name': instance.key_name,
'key_fingerprint': instance.key_fingerprint,
'user_data': instance.user_data,
'flavor_name': instance.flavor_name,
'image_name': instance.image_name,
}
@staticmethod
def create_backup_snapshots(backup):
for volume in backup.instance.volumes.all():
snapshot = models.Snapshot.objects.create(
name='Part of backup: %s (volume: %s)' % (backup.name[:60], volume.name[:60]),
service_project_link=backup.service_project_link,
size=volume.size,
source_volume=volume,
description='Part of backup %s (UUID: %s)' % (backup.name, backup.uuid.hex),
metadata=SnapshotSerializer.get_snapshot_metadata(volume),
)
snapshot.increase_backend_quotas_usage()
backup.snapshots.add(snapshot)
class BaseScheduleSerializer(structure_serializers.BaseResourceSerializer):
timezone = serializers.ChoiceField(choices=[(t, t) for t in pytz.all_timezones],
initial=timezone.get_current_timezone_name(),
default=timezone.get_current_timezone_name())
service = serializers.HyperlinkedRelatedField(
source='service_project_link.service',
view_name='openstacktenant-detail',
read_only=True,
lookup_field='uuid')
service_project_link = serializers.HyperlinkedRelatedField(
view_name='openstacktenant-spl-detail',
read_only=True,
)
class Meta(structure_serializers.BaseResourceSerializer.Meta):
fields = structure_serializers.BaseResourceSerializer.Meta.fields + (
'retention_time', 'timezone', 'maximal_number_of_resources', 'schedule',
'is_active', 'next_trigger_at')
read_only_fields = structure_serializers.BaseResourceSerializer.Meta.read_only_fields + (
'is_active', 'next_trigger_at', 'service_project_link')
class BackupScheduleSerializer(BaseScheduleSerializer):
class Meta(BaseScheduleSerializer.Meta):
model = models.BackupSchedule
fields = BaseScheduleSerializer.Meta.fields + (
'instance', 'instance_name')
read_only_fields = BaseScheduleSerializer.Meta.read_only_fields + (
'backups', 'instance')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'instance': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-instance-detail'},
}
related_paths = {
'instance': ('name',),
}
def create(self, validated_data):
instance = self.context['view'].get_object()
validated_data['instance'] = instance
validated_data['service_project_link'] = instance.service_project_link
validated_data['state'] = instance.States.OK
return super(BackupScheduleSerializer, self).create(validated_data)
class SnapshotScheduleSerializer(BaseScheduleSerializer):
class Meta(BaseScheduleSerializer.Meta):
model = models.SnapshotSchedule
fields = BaseScheduleSerializer.Meta.fields + (
'source_volume', 'source_volume_name')
read_only_fields = BaseScheduleSerializer.Meta.read_only_fields + (
'snapshots', 'source_volume')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
'source_volume': {'lookup_field': 'uuid', 'view_name': 'openstacktenant-volume-detail'},
}
related_paths = {
'source_volume': ('name',),
}
def create(self, validated_data):
volume = self.context['view'].get_object()
validated_data['source_volume'] = volume
validated_data['service_project_link'] = volume.service_project_link
validated_data['state'] = volume.States.OK
return super(SnapshotScheduleSerializer, self).create(validated_data)
class MeterSampleSerializer(serializers.Serializer):
name = serializers.CharField(source='counter_name')
value = serializers.FloatField(source='counter_volume')
type = serializers.CharField(source='counter_type')
unit = serializers.CharField(source='counter_unit')
timestamp = fields.StringTimestampField(formats=('%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S'))
recorded_at = fields.StringTimestampField(formats=('%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S'))
class MeterTimestampIntervalSerializer(core_serializers.TimestampIntervalSerializer):
def get_fields(self):
fields = super(MeterTimestampIntervalSerializer, self).get_fields()
fields['start'].default = core_utils.timeshift(hours=-1)
fields['end'].default = core_utils.timeshift()
return fields
<file_sep>/src/nodeconductor_openstack/openstack/tests/test_import.py
import mock
import unittest
from rest_framework import status
from nodeconductor.structure.tests import factories as structure_factories
from .test_backend import BaseBackendTestCase
from . import factories
from .. import models
class BaseImportTestCase(BaseBackendTestCase):
def setUp(self):
super(BaseImportTestCase, self).setUp()
self.staff = structure_factories.UserFactory(is_staff=True)
self.client.force_authenticate(user=self.staff)
self.link = factories.OpenStackServiceProjectLinkFactory()
self.service = self.link.service
self.project = self.link.project
self.url = factories.OpenStackServiceFactory.get_url(self.service, 'link')
@unittest.skip('Import operation is not supported yet.')
class TenantImportTestCase(BaseImportTestCase):
def setUp(self):
super(TenantImportTestCase, self).setUp()
self.mocked_tenant = mock.Mock()
self.mocked_tenant.id = '1'
self.mocked_tenant.name = 'PRD'
self.mocked_tenant.description = 'Production tenant'
self.mocked_keystone().tenants.list.return_value = [self.mocked_tenant]
self.mocked_keystone().tenants.get.return_value = self.mocked_tenant
def test_user_can_not_list_importable_tenants_from_non_admin_service(self):
self.service.settings.options['is_admin'] = False
self.service.settings.save()
response = self.client.get(self.url)
self.assertEqual(response.data, [])
def test_user_can_not_import_tenants_from_non_admin_service(self):
self.service.settings.options['is_admin'] = False
self.service.settings.save()
response = self.client.post(self.url, self.get_valid_data())
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_user_can_list_importable_tenants(self):
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
self.assertEqual(response.data, [{
'id': self.mocked_tenant.id,
'name': self.mocked_tenant.name,
'description': self.mocked_tenant.description,
'type': 'OpenStack.Tenant'
}])
def test_user_can_import_tenant(self):
response = self.client.post(self.url, self.get_valid_data())
self.assertEqual(response.status_code, status.HTTP_200_OK)
tenant = models.Tenant.objects.get(uuid=response.data['uuid'])
self.assertEqual(tenant.service_project_link, self.link)
self.assertEqual(tenant.name, self.mocked_tenant.name)
self.assertEqual(tenant.backend_id, self.mocked_tenant.id)
self.assertEqual(tenant.state, models.Tenant.States.OK)
def get_valid_data(self):
return {
'backend_id': self.mocked_tenant.id,
'resource_type': 'OpenStack.Tenant',
'project': structure_factories.ProjectFactory.get_url(self.project)
}
<file_sep>/src/nodeconductor_openstack/openstack/tasks/celerybeat.py
import logging
from django.utils import six
from nodeconductor.structure import ServiceBackendError, tasks as structure_tasks
from nodeconductor_openstack.openstack import models
logger = logging.getLogger(__name__)
# XXX: This task should be rewritten in WAL-323.
# We should pull all security groups, floating IPs and tenants at once.
class TenantBackgroundPullTask(structure_tasks.BackgroundPullTask):
def pull(self, tenant):
backend = tenant.get_backend()
backend.pull_tenant(tenant)
def on_pull_success(self, tenant):
super(TenantBackgroundPullTask, self).on_pull_success(tenant)
try:
backend = tenant.get_backend()
backend.pull_tenant_security_groups(tenant)
backend.pull_floating_ips(tenant)
backend.pull_tenant_quotas(tenant)
except ServiceBackendError as e:
error_message = six.text_type(e)
logger.warning('Failed to pull properties of tenant: %s (PK: %s). Error: %s' % (
tenant, tenant.pk, error_message))
class TenantListPullTask(structure_tasks.BackgroundListPullTask):
name = 'openstack.TenantListPullTask'
model = models.Tenant
pull_task = TenantBackgroundPullTask
<file_sep>/src/nodeconductor_openstack/openstack/__init__.py
from nodeconductor import _get_version
__version__ = _get_version('nodeconductor_openstack')
default_app_config = 'nodeconductor_openstack.openstack.apps.OpenStackConfig'
<file_sep>/setup.py
#!/usr/bin/env python
from setuptools import setup, find_packages
tests_requires = [
'ddt>=1.0.0'
]
dev_requires = [
'Sphinx==1.2.2',
]
install_requires = [
'iptools>=0.6.1',
'nodeconductor>0.124.0',
'python-ceilometerclient>=2.3.0',
'python-cinderclient>=1.6.0,<2.0.0',
'python-glanceclient>=2.0.0',
'python-keystoneclient>=2.3.1',
'python-neutronclient>=4.1.1',
'python-novaclient>=3.3.0,<3.4.0',
]
setup(
name='nodeconductor-openstack',
version='0.20.0',
author='<NAME>',
author_email='<EMAIL>',
url='http://nodeconductor.com',
description='NodeConductor plugin for managing OpenStack resources.',
long_description=open('README.rst').read(),
package_dir={'': 'src'},
packages=find_packages('src', exclude=['*.tests', '*.tests.*', 'tests.*', 'tests']),
install_requires=install_requires,
zip_safe=False,
extras_require={
'dev': dev_requires,
'tests': tests_requires,
},
test_suite='nodeconductor.server.test_runner.run_tests',
entry_points={
'nodeconductor_extensions': (
'openstack = nodeconductor_openstack.openstack.extension:OpenStackExtension',
'openstack_tenant = nodeconductor_openstack.openstack_tenant.extension:OpenStackTenantExtension',
),
},
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
],
)
<file_sep>/src/nodeconductor_openstack/openstack/tests/test_subnet.py
import mock
from rest_framework import status, test
from . import factories, fixtures
class BaseSubNetTest(test.APITransactionTestCase):
def setUp(self):
self.fixture = fixtures.OpenStackFixture()
class SubNetCreateActionTest(BaseSubNetTest):
def setUp(self):
super(SubNetCreateActionTest, self).setUp()
self.client.force_authenticate(user=self.fixture.user)
def test_subnet_create_action_is_not_allowed(self):
url = factories.SubNetFactory.get_list_url()
response = self.client.post(url)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
@mock.patch('nodeconductor_openstack.openstack.executors.SubNetDeleteExecutor.execute')
class SubNetDeleteActionTest(BaseSubNetTest):
def setUp(self):
super(SubNetDeleteActionTest, self).setUp()
self.client.force_authenticate(user=self.fixture.admin)
self.url = factories.SubNetFactory.get_url(self.fixture.subnet)
def test_subnet_delete_action_triggers_create_executor(self, executor_action_mock):
response = self.client.delete(self.url)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
executor_action_mock.assert_called_once()
def test_subnet_delete_action_decreases_set_quota_limit(self, executor_action_mock):
self.fixture.subnet.increase_backend_quotas_usage()
self.assertEqual(self.fixture.subnet.network.tenant.quotas.get(name='subnet_count').usage, 1)
response = self.client.delete(self.url)
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
self.assertEqual(self.fixture.tenant.quotas.get(name='subnet_count').usage, 0)
executor_action_mock.assert_called_once()
class SubNetUpdateActionTest(BaseSubNetTest):
def setUp(self):
super(SubNetUpdateActionTest, self).setUp()
self.client.force_authenticate(user=self.fixture.admin)
self.url = factories.SubNetFactory.get_url(self.fixture.subnet)
self.request_data = {
'name': 'test_name'
}
@mock.patch('nodeconductor_openstack.openstack.executors.SubNetUpdateExecutor.execute')
def test_subnet_update_action_triggers_update_executor(self, executor_action_mock):
response = self.client.put(self.url, self.request_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
executor_action_mock.assert_called_once()
<file_sep>/src/nodeconductor_openstack/openstack_tenant/handlers.py
from __future__ import unicode_literals
from django.core import exceptions as django_exceptions
from nodeconductor.core.models import StateMixin
from nodeconductor.structure import models as structure_models
from ..openstack import models as openstack_models
from . import log, models
def _log_scheduled_action(resource, action, action_details):
class_name = resource.__class__.__name__.lower()
message = _get_action_message(action, action_details)
log.event_logger.openstack_resource_action.info(
'Operation "%s" has been scheduled for %s "%s"' % (message, class_name, resource.name),
event_type=_get_action_event_type(action, 'scheduled'),
event_context={'resource': resource, 'action_details': action_details},
)
def _log_succeeded_action(resource, action, action_details):
class_name = resource.__class__.__name__.lower()
message = _get_action_message(action, action_details)
log.event_logger.openstack_resource_action.info(
'Successfully executed "%s" operation for %s "%s"' % (message, class_name, resource.name),
event_type=_get_action_event_type(action, 'succeeded'),
event_context={'resource': resource, 'action_details': action_details},
)
def _log_failed_action(resource, action, action_details):
class_name = resource.__class__.__name__.lower()
message = _get_action_message(action, action_details)
log.event_logger.openstack_resource_action.warning(
'Failed to execute "%s" operation for %s "%s"' % (message, class_name, resource.name),
event_type=_get_action_event_type(action, 'failed'),
event_context={'resource': resource, 'action_details': action_details},
)
def _get_action_message(action, action_details):
return action_details.pop('message', action)
def _get_action_event_type(action, event_state):
return 'resource_%s_%s' % (action.replace(' ', '_').lower(), event_state)
def log_action(sender, instance, created=False, **kwargs):
""" Log any resource action.
Example of logged volume extend action:
{
'event_type': 'volume_extend_succeeded',
'message': 'Successfully executed "Extend volume from 1024 MB to 2048 MB" operation for volume "pavel-test"',
'action_details': {'old_size': 1024, 'new_size': 2048}
}
"""
resource = instance
if created or not resource.tracker.has_changed('action'):
return
if resource.state == StateMixin.States.UPDATE_SCHEDULED:
_log_scheduled_action(resource, resource.action, resource.action_details)
if resource.state == StateMixin.States.OK:
_log_succeeded_action(
resource, resource.tracker.previous('action'), resource.tracker.previous('action_details'))
elif resource.state == StateMixin.States.ERRED:
_log_failed_action(
resource, resource.tracker.previous('action'), resource.tracker.previous('action_details'))
def log_snapshot_schedule_creation(sender, instance, created=False, **kwargs):
if not created:
return
snapshot_schedule = instance
log.event_logger.openstack_snapshot_schedule.info(
'Snapshot schedule "%s" has been created' % snapshot_schedule.name,
event_type='resource_snapshot_schedule_created',
event_context={'resource': snapshot_schedule.source_volume, 'snapshot_schedule': snapshot_schedule},
)
def log_snapshot_schedule_action(sender, instance, created=False, **kwargs):
snapshot_schedule = instance
if created or not snapshot_schedule.tracker.has_changed('is_active'):
return
context = {'resource': snapshot_schedule.source_volume, 'snapshot_schedule': snapshot_schedule}
if snapshot_schedule.is_active:
log.event_logger.openstack_snapshot_schedule.info(
'Snapshot schedule "%s" has been activated' % snapshot_schedule.name,
event_type='resource_snapshot_schedule_activated',
event_context=context,
)
else:
if snapshot_schedule.error_message:
message = 'Snapshot schedule "%s" has been deactivated because of error' % snapshot_schedule.name
else:
message = 'Snapshot schedule "%s" has been deactivated' % snapshot_schedule.name
log.event_logger.openstack_snapshot_schedule.info(
message,
event_type='resource_snapshot_schedule_deactivated',
event_context=context,
)
def log_snapshot_schedule_deletion(sender, instance, **kwargs):
snapshot_schedule = instance
log.event_logger.openstack_snapshot_schedule.info(
'Snapshot schedule "%s" has been deleted' % snapshot_schedule.name,
event_type='resource_snapshot_schedule_deleted',
event_context={'resource': snapshot_schedule.source_volume, 'snapshot_schedule': snapshot_schedule},
)
def log_backup_schedule_creation(sender, instance, created=False, **kwargs):
if not created:
return
backup_schedule = instance
log.event_logger.openstack_backup_schedule.info(
'Backup schedule "%s" has been created' % backup_schedule.name,
event_type='resource_backup_schedule_created',
event_context={'resource': backup_schedule.instance, 'backup_schedule': backup_schedule},
)
def log_backup_schedule_action(sender, instance, created=False, **kwargs):
backup_schedule = instance
if created or not backup_schedule.tracker.has_changed('is_active'):
return
context = {'resource': backup_schedule.instance, 'backup_schedule': backup_schedule}
if backup_schedule.is_active:
log.event_logger.openstack_backup_schedule.info(
'Backup schedule "%s" has been activated' % backup_schedule.name,
event_type='resource_backup_schedule_activated',
event_context=context,
)
else:
if backup_schedule.error_message:
message = 'Backup schedule "%s" has been deactivated because of error' % backup_schedule.name
else:
message = 'Backup schedule "%s" has been deactivated' % backup_schedule.name
log.event_logger.openstack_backup_schedule.info(
message,
event_type='resource_backup_schedule_deactivated',
event_context=context,
)
def log_backup_schedule_deletion(sender, instance, **kwargs):
backup_schedule = instance
log.event_logger.openstack_backup_schedule.info(
'Backup schedule "%s" has been deleted' % backup_schedule.name,
event_type='resource_backup_schedule_deleted',
event_context={'resource': backup_schedule.instance, 'backup_schedule': backup_schedule},
)
def update_service_settings_password(sender, instance, created=False, **kwargs):
"""
Updates service settings password on tenant user_password change.
It is possible to change a user password in tenant,
as service settings copies tenant user password on creation it has to be update on change.
"""
if created:
return
tenant = instance
if tenant.tracker.has_changed('user_password'):
service_settings = structure_models.ServiceSettings.objects.filter(scope=tenant).first()
if service_settings:
service_settings.password = <PASSWORD>
service_settings.save()
class BaseSynchronizationHandler(object):
"""
This class provides signal handlers for synchronization of OpenStack properties
when parent OpenStack resource are created, updated or deleted.
Security groups, floating IPs, networks and subnets are implemented as
resources in openstack application. However they are implemented as service properties
in the openstack_tenant application.
"""
property_model = None
resource_model = None
fields = []
def get_tenant(self, resource):
return resource.tenant
def get_service_settings(self, resource):
try:
return structure_models.ServiceSettings.objects.get(scope=self.get_tenant(resource))
except (django_exceptions.ObjectDoesNotExist, django_exceptions.MultipleObjectsReturned):
return
def get_service_property(self, resource, settings):
try:
return self.property_model.objects.get(settings=settings, backend_id=resource.backend_id)
except (django_exceptions.ObjectDoesNotExist, django_exceptions.MultipleObjectsReturned):
return
def map_resource_to_dict(self, resource):
return {field: getattr(resource, field) for field in self.fields}
def create_service_property(self, resource, settings):
params = self.map_resource_to_dict(resource)
return self.property_model.objects.create(
settings=settings,
backend_id=resource.backend_id,
name=resource.name,
**params
)
def update_service_property(self, resource, settings):
service_property = self.get_service_property(resource, settings)
if not service_property:
return
params = self.map_resource_to_dict(resource)
for key, value in params.items():
setattr(service_property, key, value)
service_property.name = resource.name
service_property.save()
return service_property
def create_handler(self, sender, instance, name, source, target, **kwargs):
"""
Creates service property on resource transition from 'CREATING' state to 'OK'.
"""
if source == StateMixin.States.CREATING and target == StateMixin.States.OK:
settings = self.get_service_settings(instance)
if settings:
self.create_service_property(instance, settings)
def update_handler(self, sender, instance, name, source, target, **kwargs):
"""
Updates service property on resource transition from 'UPDATING' state to 'OK'.
"""
if source == StateMixin.States.UPDATING and target == StateMixin.States.OK:
settings = self.get_service_settings(instance)
if settings:
self.update_service_property(instance, settings)
def delete_handler(self, sender, instance, **kwargs):
"""
Deletes service property on resource deletion
"""
settings = self.get_service_settings(instance)
if not settings:
return
service_property = self.get_service_property(instance, settings)
if not service_property:
return
service_property.delete()
class FloatingIPHandler(BaseSynchronizationHandler):
property_model = models.FloatingIP
resource_model = openstack_models.FloatingIP
fields = ('address', 'backend_network_id', 'runtime_state')
class SecurityGroupHandler(BaseSynchronizationHandler):
property_model = models.SecurityGroup
resource_model = openstack_models.SecurityGroup
fields = ('description',)
def map_rules(self, security_group, openstack_security_group):
return [models.SecurityGroupRule(
protocol=rule.protocol,
from_port=rule.from_port,
to_port=rule.to_port,
cidr=rule.cidr,
backend_id=rule.backend_id,
security_group=security_group,
) for rule in openstack_security_group.rules.iterator()]
def create_service_property(self, resource, settings):
service_property = super(SecurityGroupHandler, self).create_service_property(resource, settings)
if resource.rules.count() > 0:
group_rules = self.map_rules(service_property, resource)
service_property.rules.bulk_create(group_rules)
return service_property
def update_service_property(self, resource, settings):
service_property = super(SecurityGroupHandler, self).update_service_property(resource, settings)
service_property.rules.all().delete()
group_rules = self.map_rules(service_property, resource)
service_property.rules.bulk_create(group_rules)
return service_property
class NetworkHandler(BaseSynchronizationHandler):
property_model = models.Network
resource_model = openstack_models.Network
fields = ('is_external', 'segmentation_id', 'type')
class SubNetHandler(BaseSynchronizationHandler):
property_model = models.SubNet
resource_model = openstack_models.SubNet
fields = ('allocation_pools', 'cidr', 'dns_nameservers', 'enable_dhcp', 'ip_version')
def get_tenant(self, resource):
return resource.network.tenant
def map_resource_to_dict(self, resource):
params = super(SubNetHandler, self).map_resource_to_dict(resource)
params['network'] = models.Network.objects.get(backend_id=resource.network.backend_id)
return params
resource_handlers = (
FloatingIPHandler(),
SecurityGroupHandler(),
NetworkHandler(),
SubNetHandler(),
)
<file_sep>/README.rst
NodeConductor OpenStack
=======================
NodeConductor plugin for managing OpenStack resources.
<file_sep>/src/nodeconductor_openstack/openstack/apps.py
from django.apps import AppConfig
from django.db.models import signals
class OpenStackConfig(AppConfig):
""" OpenStack is a toolkit for building private and public clouds.
This application adds support for managing OpenStack deployments -
tenants, instances, security groups and networks.
"""
name = 'nodeconductor_openstack.openstack'
label = 'openstack'
verbose_name = 'OpenStack'
service_name = 'OpenStack'
def ready(self):
from nodeconductor.core import models as core_models
from nodeconductor.structure import SupportedServices, signals as structure_signals, models as structure_models
from . import handlers
Tenant = self.get_model('Tenant')
# structure
from .backend import OpenStackBackend
SupportedServices.register_backend(OpenStackBackend)
from nodeconductor.structure.models import ServiceSettings
from nodeconductor.quotas.fields import QuotaField
for resource in ('vcpu', 'ram', 'storage'):
ServiceSettings.add_quota_field(
name='openstack_%s' % resource,
quota_field=QuotaField(
creation_condition=lambda service_settings:
service_settings.type == OpenStackConfig.service_name
)
)
signals.post_save.connect(
handlers.create_initial_security_groups,
sender=Tenant,
dispatch_uid='openstack.handlers.create_initial_security_groups',
)
for model in (structure_models.Project, structure_models.Customer):
structure_signals.structure_role_revoked.connect(
handlers.remove_ssh_key_from_tenants,
sender=model,
dispatch_uid='openstack.handlers.remove_ssh_key_from_tenants__%s' % model.__name__,
)
signals.pre_delete.connect(
handlers.remove_ssh_key_from_all_tenants_on_it_deletion,
sender=core_models.SshPublicKey,
dispatch_uid='openstack.handlers.remove_ssh_key_from_all_tenants_on_it_deletion',
)
from nodeconductor.quotas.models import Quota
signals.post_save.connect(
handlers.log_tenant_quota_update,
sender=Quota,
dispatch_uid='openstack.handlers.log_tenant_quota_update',
)
<file_sep>/src/nodeconductor_openstack/openstack_base/backend.py
import datetime
import hashlib
import pickle
import six
import logging
from django.core.cache import cache
from django.utils import six, timezone
from requests import ConnectionError
from keystoneauth1.identity import v3
from keystoneauth1 import session as keystone_session
from ceilometerclient import client as ceilometer_client
from cinderclient.v2 import client as cinder_client
from glanceclient.v1 import client as glance_client
from keystoneclient.v3 import client as keystone_client
from neutronclient.v2_0 import client as neutron_client
from novaclient.v2 import client as nova_client
from ceilometerclient import exc as ceilometer_exceptions
from cinderclient import exceptions as cinder_exceptions
from glanceclient import exc as glance_exceptions
from keystoneclient import exceptions as keystone_exceptions
from neutronclient.client import exceptions as neutron_exceptions
from novaclient import exceptions as nova_exceptions
from nodeconductor.structure import ServiceBackend, ServiceBackendError
from nodeconductor_openstack.openstack.models import Tenant
logger = logging.getLogger(__name__)
class OpenStackBackendError(ServiceBackendError):
def __init__(self, *args, **kwargs):
if not args:
super(OpenStackBackendError, self).__init__(*args, **kwargs)
# OpenStack client exceptions, such as cinder_exceptions.ClientException
# are not serializable by Celery, because they use custom arguments *args
# and define __init__ method, but don't call Exception.__init__ method
# http://docs.celeryproject.org/en/latest/userguide/tasks.html#creating-pickleable-exceptions
# That's why when Celery worker tries to deserialize OpenStack client exception,
# it uses empty invalid *args. It leads to unrecoverable error and worker dies.
# When all workers are dead, all tasks are stuck in pending state forever.
# In order to fix this issue we serialize exception to text type explicitly.
args = list(args)
for i, arg in enumerate(args):
try:
pickle.loads(pickle.dumps(arg))
except (pickle.PickleError, TypeError):
args[i] = six.text_type(arg)
super(OpenStackBackendError, self).__init__(*args, **kwargs)
class OpenStackSessionExpired(OpenStackBackendError):
pass
class OpenStackAuthorizationFailed(OpenStackBackendError):
pass
def update_pulled_fields(instance, imported_instance, fields):
""" Update instance fields based on imported from backend data.
Save changes to DB only one or more fields were changed.
"""
modified = False
for field in fields:
pulled_value = getattr(imported_instance, field)
current_value = getattr(instance, field)
if current_value != pulled_value:
setattr(instance, field, pulled_value)
logger.info("%s's with uuid %s %s field updated from value '%s' to value '%s'",
instance.__class__.__name__, instance.uuid.hex, field, current_value, pulled_value)
modified = True
if modified:
instance.save()
class OpenStackSession(dict):
""" Serializable session """
def __init__(self, ks_session=None, verify_ssl=False, **credentials):
self.keystone_session = ks_session
if not self.keystone_session:
auth_plugin = v3.Password(**credentials)
self.keystone_session = keystone_session.Session(auth=auth_plugin, verify=verify_ssl)
try:
# This will eagerly sign in throwing AuthorizationFailure on bad credentials
self.keystone_session.get_auth_headers()
except keystone_exceptions.ClientException as e:
six.reraise(OpenStackAuthorizationFailed, e)
for opt in ('auth_ref', 'auth_url', 'project_id', 'project_name', 'project_domain_name'):
self[opt] = getattr(self.auth, opt)
def __getattr__(self, name):
return getattr(self.keystone_session, name)
@classmethod
def recover(cls, session, verify_ssl=False):
if not isinstance(session, dict) or not session.get('auth_ref'):
raise OpenStackBackendError('Invalid OpenStack session')
args = {
'auth_url': session['auth_url'],
'token': session['auth_ref'].auth_token,
}
if session.get('project_id'):
args['project_id'] = session['project_id']
elif session.get('project_name') and session.get('project_domain_name'):
args['project_name'] = session['project_name']
args['project_domain_name'] = session['project_domain_name']
ks_session = keystone_session.Session(auth=v3.Token(**args), verify=verify_ssl)
return cls(ks_session=ks_session)
def validate(self):
if self.auth.auth_ref.expires > timezone.now() + datetime.timedelta(minutes=10):
return True
raise OpenStackSessionExpired('OpenStack session is expired')
def __str__(self):
return str({k: v if k != 'password' else '***' for k, v in self.items()})
class OpenStackClient(object):
""" Generic OpenStack client. """
def __init__(self, session=None, verify_ssl=False, **credentials):
self.verify_ssl = verify_ssl
if session:
if isinstance(session, dict):
logger.debug('Trying to recover OpenStack session.')
self.session = OpenStackSession.recover(session, verify_ssl=verify_ssl)
self.session.validate()
else:
self.session = session
else:
try:
self.session = OpenStackSession(verify_ssl=verify_ssl, **credentials)
except AttributeError as e:
logger.error('Failed to create OpenStack session.')
six.reraise(OpenStackBackendError, e)
@property
def keystone(self):
return keystone_client.Client(session=self.session.keystone_session)
@property
def nova(self):
try:
return nova_client.Client(session=self.session.keystone_session)
except nova_exceptions.ClientException as e:
logger.exception('Failed to create nova client: %s', e)
six.reraise(OpenStackBackendError, e)
@property
def neutron(self):
try:
return neutron_client.Client(session=self.session.keystone_session)
except neutron_exceptions.NeutronClientException as e:
logger.exception('Failed to create neutron client: %s', e)
six.reraise(OpenStackBackendError, e)
@property
def cinder(self):
try:
return cinder_client.Client(session=self.session.keystone_session)
except cinder_exceptions.ClientException as e:
logger.exception('Failed to create cinder client: %s', e)
six.reraise(OpenStackBackendError, e)
@property
def glance(self):
try:
return glance_client.Client(session=self.session.keystone_session)
except glance_exceptions.ClientException as e:
logger.exception('Failed to create glance client: %s', e)
six.reraise(OpenStackBackendError, e)
@property
def ceilometer(self):
try:
return ceilometer_client.Client('2', session=self.session.keystone_session)
except ceilometer_exceptions.BaseException as e:
logger.exception('Failed to create ceilometer client: %s', e)
six.reraise(OpenStackBackendError, e)
class BaseOpenStackBackend(ServiceBackend):
def __init__(self, settings, tenant_id=None):
self.settings = settings
self.tenant_id = tenant_id
def _get_cached_session_key(self, admin):
key = 'OPENSTACK_ADMIN_SESSION' if admin else 'OPENSTACK_SESSION_%s' % self.tenant_id
settings_key = str(self.settings.backend_url) + str(self.settings.password) + str(self.settings.username)
hashed_settings_key = hashlib.sha256(settings_key).hexdigest()
return '%s_%s_%s' % (self.settings.uuid.hex, hashed_settings_key, key)
def get_client(self, name=None, admin=False):
domain_name = self.settings.domain or 'Default'
credentials = {
'auth_url': self.settings.backend_url,
'username': self.settings.username,
'password': self.<PASSWORD>,
'user_domain_name': domain_name,
}
if self.tenant_id:
credentials['project_id'] = self.tenant_id
else:
credentials['project_domain_name'] = domain_name
credentials['project_name'] = self.settings.get_option('tenant_name')
# Skip cache if service settings do no exist
if not self.settings.uuid:
return OpenStackClient(**credentials)
client = None
attr_name = 'admin_session' if admin else 'session'
key = self._get_cached_session_key(admin)
if hasattr(self, attr_name): # try to get client from object
client = getattr(self, attr_name)
elif key in cache: # try to get session from cache
session = cache.get(key)
try:
client = OpenStackClient(session=session)
except (OpenStackSessionExpired, OpenStackAuthorizationFailed):
pass
if client is None: # create new token if session is not cached or expired
client = OpenStackClient(**credentials)
setattr(self, attr_name, client) # Cache client in the object
cache.set(key, dict(client.session), 24 * 60 * 60) # Add session to cache
if name:
return getattr(client, name)
else:
return client
def __getattr__(self, name):
clients = 'keystone', 'nova', 'neutron', 'cinder', 'glance', 'ceilometer'
for client in clients:
if name == '{}_client'.format(client):
return self.get_client(client, admin=False)
if name == '{}_admin_client'.format(client):
return self.get_client(client, admin=True)
raise AttributeError(
"'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
def ping(self, raise_exception=False):
try:
self.keystone_client
except keystone_exceptions.ClientException as e:
if raise_exception:
six.reraise(OpenStackBackendError, e)
return False
else:
return True
def ping_resource(self, instance):
try:
self.nova_client.servers.get(instance.backend_id)
except (ConnectionError, nova_exceptions.ClientException):
return False
else:
return True
def get_tenant_quotas_limits(self, tenant_backend_id):
nova = self.nova_client
neutron = self.neutron_client
cinder = self.cinder_client
try:
nova_quotas = nova.quotas.get(tenant_id=tenant_backend_id)
cinder_quotas = cinder.quotas.get(tenant_id=tenant_backend_id)
neutron_quotas = neutron.show_quota(tenant_id=tenant_backend_id)['quota']
except (nova_exceptions.ClientException,
cinder_exceptions.ClientException,
neutron_exceptions.NeutronClientException) as e:
six.reraise(OpenStackBackendError, e)
return {
Tenant.Quotas.ram: nova_quotas.ram,
Tenant.Quotas.vcpu: nova_quotas.cores,
Tenant.Quotas.storage: self.gb2mb(cinder_quotas.gigabytes),
Tenant.Quotas.snapshots: cinder_quotas.snapshots,
Tenant.Quotas.volumes: cinder_quotas.volumes,
Tenant.Quotas.instances: nova_quotas.instances,
Tenant.Quotas.security_group_count: neutron_quotas['security_group'],
Tenant.Quotas.security_group_rule_count: neutron_quotas['security_group_rule'],
Tenant.Quotas.floating_ip_count: neutron_quotas['floatingip'],
Tenant.Quotas.network_count: neutron_quotas['network'],
Tenant.Quotas.subnet_count: neutron_quotas['subnet'],
}
def get_tenant_quotas_usage(self, tenant_backend_id):
nova = self.nova_client
neutron = self.neutron_client
cinder = self.cinder_client
try:
volumes = cinder.volumes.list()
snapshots = cinder.volume_snapshots.list()
instances = nova.servers.list()
security_groups = nova.security_groups.list()
floating_ips = neutron.list_floatingips(tenant_id=tenant_backend_id)['floatingips']
networks = neutron.list_networks(tenant_id=tenant_backend_id)['networks']
subnets = neutron.list_subnets(tenant_id=tenant_backend_id)['subnets']
flavors = {flavor.id: flavor for flavor in nova.flavors.list()}
ram, vcpu = 0, 0
for flavor_id in (instance.flavor['id'] for instance in instances):
try:
flavor = flavors.get(flavor_id, nova.flavors.get(flavor_id))
except nova_exceptions.NotFound:
logger.warning('Cannot find flavor with id %s', flavor_id)
continue
ram += getattr(flavor, 'ram', 0)
vcpu += getattr(flavor, 'vcpus', 0)
except (nova_exceptions.ClientException,
cinder_exceptions.ClientException,
neutron_exceptions.NeutronClientException) as e:
six.reraise(OpenStackBackendError, e)
return {
Tenant.Quotas.ram: ram,
Tenant.Quotas.vcpu: vcpu,
Tenant.Quotas.storage: sum(self.gb2mb(v.size) for v in volumes + snapshots),
Tenant.Quotas.volumes: len(volumes),
Tenant.Quotas.snapshots: len(snapshots),
Tenant.Quotas.instances: len(instances),
Tenant.Quotas.security_group_count: len(security_groups),
Tenant.Quotas.security_group_rule_count: len(sum([sg.rules for sg in security_groups], [])),
Tenant.Quotas.floating_ip_count: len(floating_ips),
Tenant.Quotas.network_count: len(networks),
Tenant.Quotas.subnet_count: len(subnets),
}
<file_sep>/src/nodeconductor_openstack/openstack/handlers.py
from __future__ import unicode_literals
import logging
from django.conf import settings
from django.core.exceptions import ValidationError
from nodeconductor.core import models as core_models, tasks as core_tasks, utils as core_utils
from nodeconductor.structure import filters as structure_filters, models as structure_models
from .log import event_logger
from .models import SecurityGroup, SecurityGroupRule, Tenant
logger = logging.getLogger(__name__)
class SecurityGroupCreateException(Exception):
pass
def create_initial_security_groups(sender, instance=None, created=False, **kwargs):
if not created:
return
nc_settings = getattr(settings, 'NODECONDUCTOR_OPENSTACK', {})
config_groups = nc_settings.get('DEFAULT_SECURITY_GROUPS', [])
for group in config_groups:
try:
create_security_group(instance, group)
except SecurityGroupCreateException as e:
logger.error(e)
def create_security_group(tenant, group):
sg_name = group.get('name')
if sg_name in (None, ''):
raise SecurityGroupCreateException(
'Skipping misconfigured security group: parameter "name" not found or is empty.')
rules = group.get('rules')
if type(rules) not in (list, tuple):
raise SecurityGroupCreateException(
'Skipping misconfigured security group: parameter "rules" should be list or tuple.')
sg_description = group.get('description', None)
sg = SecurityGroup.objects.get_or_create(
service_project_link=tenant.service_project_link,
tenant=tenant,
description=sg_description,
name=sg_name)[0]
for rule in rules:
if 'icmp_type' in rule:
rule['from_port'] = rule.pop('icmp_type')
if 'icmp_code' in rule:
rule['to_port'] = rule.pop('icmp_code')
try:
rule = SecurityGroupRule(security_group=sg, **rule)
rule.full_clean()
except ValidationError as e:
logger.error('Failed to create rule for security group %s: %s.' % (sg_name, e))
else:
rule.save()
return sg
def remove_ssh_key_from_tenants(sender, structure, user, role, **kwargs):
""" Delete user ssh keys from tenants that he does not have access now. """
tenants = Tenant.objects.filter(**{sender.__name__.lower(): structure})
ssh_keys = core_models.SshPublicKey.objects.filter(user=user)
for tenant in tenants:
if user.has_perm('openstack.change_tenant', tenant):
continue # no need to delete ssh keys if user still have permissions for tenant.
serialized_tenant = core_utils.serialize_instance(tenant)
for key in ssh_keys:
core_tasks.BackendMethodTask().delay(
serialized_tenant, 'remove_ssh_key_from_tenant', key.name, key.fingerprint)
def remove_ssh_key_from_all_tenants_on_it_deletion(sender, instance, **kwargs):
""" Delete key from all tenants that are accessible for user on key deletion. """
ssh_key = instance
user = ssh_key.user
tenants = structure_filters.filter_queryset_for_user(Tenant.objects.all(), user)
for tenant in tenants:
if not user.has_perm('openstack.change_tenant', tenant):
continue
serialized_tenant = core_utils.serialize_instance(tenant)
core_tasks.BackendMethodTask().delay(
serialized_tenant, 'remove_ssh_key_from_tenant', ssh_key.name, ssh_key.fingerprint)
def log_tenant_quota_update(sender, instance, created=False, **kwargs):
quota = instance
if created or not isinstance(quota.scope, Tenant):
return
if not quota.tracker.has_changed('limit'):
return
tenant = quota.scope
event_logger.openstack_tenant_quota.info(
'{quota_name} quota limit has been updated for tenant {tenant_name}.',
event_type='openstack_tenant_quota_limit_updated',
event_context={
'quota': quota,
'tenant': tenant,
'limit': float(quota.limit), # Prevent passing integer
})
<file_sep>/src/nodeconductor_openstack/openstack/tasks/base.py
from nodeconductor.core import tasks as core_tasks
from .. import models
class TenantCreateErrorTask(core_tasks.ErrorStateTransitionTask):
def execute(self, tenant):
super(TenantCreateErrorTask, self).execute(tenant)
# Delete network and subnet if they were not created on backend,
# mark as erred if they were created
network = tenant.networks.first()
subnet = network.subnets.first()
if subnet.state == models.SubNet.States.CREATION_SCHEDULED:
subnet.delete()
else:
super(TenantCreateErrorTask, self).execute(subnet)
if network.state == models.Network.States.CREATION_SCHEDULED:
network.delete()
else:
super(TenantCreateErrorTask, self).execute(network)
class TenantCreateSuccessTask(core_tasks.StateTransitionTask):
def execute(self, tenant):
network = tenant.networks.first()
subnet = network.subnets.first()
self.state_transition(network, 'set_ok')
self.state_transition(subnet, 'set_ok')
self.state_transition(tenant, 'set_ok')
return super(TenantCreateSuccessTask, self).execute(tenant)
class PollBackendCheckTask(core_tasks.Task):
max_retries = 60
default_retry_delay = 5
@classmethod
def get_description(cls, instance, backend_check_method, *args, **kwargs):
return 'Check instance "%s" with method "%s"' % (instance, backend_check_method)
def get_backend(self, instance):
return instance.get_backend()
def execute(self, instance, backend_check_method):
# backend_check_method should return True if object does not exist at backend
backend = self.get_backend(instance)
if not getattr(backend, backend_check_method)(instance):
self.retry()
return instance
<file_sep>/src/nodeconductor_openstack/openstack_tenant/perms.py
from nodeconductor.core.permissions import StaffPermissionLogic, FilteredCollaboratorsPermissionLogic
from nodeconductor.structure import perms as structure_perms, models as structure_models
def prefixed_permission_logic(prefix):
return FilteredCollaboratorsPermissionLogic(
collaborators_query=[
'%s__service_project_link__project__customer__permissions__user' % prefix,
'%s__service_project_link__project__permissions__user' % prefix,
'%s__service_project_link__project__permissions__user' % prefix,
],
collaborators_filter=[
{'%s__service_project_link__project__customer__permissions__role' % prefix:
structure_models.CustomerRole.OWNER,
'%s__service_project_link__project__customer__permissions__is_active' % prefix: True},
{'%s__service_project_link__project__permissions__role' % prefix:
structure_models.ProjectRole.ADMINISTRATOR,
'%s__service_project_link__project__permissions__is_active' % prefix: True},
{'%s__service_project_link__project__permissions__role' % prefix:
structure_models.ProjectRole.MANAGER,
'%s__service_project_link__project__permissions__is_active' % prefix: True},
],
any_permission=True,
)
PERMISSION_LOGICS = (
('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic),
('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic),
('openstack_tenant.Flavor', StaffPermissionLogic(any_permission=True)),
('openstack_tenant.Image', StaffPermissionLogic(any_permission=True)),
('openstack_tenant.FloatingIP', StaffPermissionLogic(any_permission=True)),
('openstack_tenant.SecurityGroup', StaffPermissionLogic(any_permission=True)),
('openstack_tenant.SecurityGroupRule', StaffPermissionLogic(any_permission=True)),
('openstack_tenant.Volume', structure_perms.resource_permission_logic),
('openstack_tenant.Snapshot', structure_perms.resource_permission_logic),
('openstack_tenant.Instance', structure_perms.resource_permission_logic),
('openstack_tenant.Backup', structure_perms.resource_permission_logic),
('openstack_tenant.BackupSchedule', structure_perms.resource_permission_logic),
('openstack_tenant.SnapshotSchedule', structure_perms.resource_permission_logic),
)
<file_sep>/src/nodeconductor_openstack/openstack_tenant/apps.py
from django.apps import AppConfig
from django.db.models import signals
from django_fsm import signals as fsm_signals
class OpenStackTenantConfig(AppConfig):
""" OpenStack is a toolkit for building private and public clouds.
This application adds support for managing OpenStack tenant resources -
instances, volumes and snapshots.
"""
name = 'nodeconductor_openstack.openstack_tenant'
label = 'openstack_tenant'
verbose_name = 'OpenStackTenant'
service_name = 'OpenStackTenant'
def ready(self):
from nodeconductor.structure import SupportedServices
from .backend import OpenStackTenantBackend
SupportedServices.register_backend(OpenStackTenantBackend)
# Initialize service settings quotas based on tenant.
from nodeconductor.structure.models import ServiceSettings
from nodeconductor.quotas.fields import QuotaField
from nodeconductor_openstack.openstack.models import Tenant
for quota in Tenant.get_quotas_fields():
ServiceSettings.add_quota_field(
name=quota.name,
quota_field=QuotaField(
is_backend=True,
default_limit=quota.default_limit,
creation_condition=lambda service_settings:
service_settings.type == OpenStackTenantConfig.service_name
)
)
from . import handlers, models
for Resource in (models.Instance, models.Volume, models.Snapshot):
name = Resource.__name__.lower()
signals.post_save.connect(
handlers.log_action,
sender=Resource,
dispatch_uid='openstack_tenant.handlers.log_%s_action' % name,
)
for handler in handlers.resource_handlers:
model = handler.resource_model
name = model.__name__.lower()
fsm_signals.post_transition.connect(
handler.create_handler,
sender=model,
dispatch_uid='openstack_tenant.handlers.create_%s' % name,
)
fsm_signals.post_transition.connect(
handler.update_handler,
sender=model,
dispatch_uid='openstack_tenant.handlers.update_%s' % name,
)
signals.post_delete.connect(
handler.delete_handler,
sender=model,
dispatch_uid='openstack_tenant.handlers.delete_%s' % name,
)
signals.post_save.connect(
handlers.log_backup_schedule_creation,
sender=models.BackupSchedule,
dispatch_uid='openstack_tenant.handlers.log_backup_schedule_creation',
)
signals.post_save.connect(
handlers.log_backup_schedule_action,
sender=models.BackupSchedule,
dispatch_uid='openstack_tenant.handlers.log_backup_schedule_action',
)
signals.pre_delete.connect(
handlers.log_backup_schedule_deletion,
sender=models.BackupSchedule,
dispatch_uid='openstack_tenant.handlers.log_backup_schedule_deletion',
)
signals.post_save.connect(
handlers.log_snapshot_schedule_creation,
sender=models.SnapshotSchedule,
dispatch_uid='openstack_tenant.handlers.log_snapshot_schedule_creation',
)
signals.post_save.connect(
handlers.log_snapshot_schedule_action,
sender=models.SnapshotSchedule,
dispatch_uid='openstack_tenant.handlers.log_snapshot_schedule_action',
)
signals.pre_delete.connect(
handlers.log_snapshot_schedule_deletion,
sender=models.SnapshotSchedule,
dispatch_uid='openstack_tenant.handlers.log_snapshot_schedule_deletion',
)
signals.post_save.connect(
handlers.update_service_settings_password,
sender=Tenant,
dispatch_uid='openstack.handlers.update_service_settings_password',
)
<file_sep>/src/nodeconductor_openstack/openstack_tenant/cost_tracking.py
from nodeconductor.cost_tracking import CostTrackingStrategy, ConsumableItem
from . import models, ApplicationTypes, OsTypes, SupportTypes, PriceItemTypes
class InstanceStrategy(CostTrackingStrategy):
resource_class = models.Instance
class Types(object):
FLAVOR = PriceItemTypes.FLAVOR
LICENSE_APPLICATION = PriceItemTypes.LICENSE_APPLICATION
LICENSE_OS = PriceItemTypes.LICENSE_OS
SUPPORT = PriceItemTypes.SUPPORT
@classmethod
def get_consumable_items(cls):
for os, name in OsTypes.CHOICES:
yield ConsumableItem(item_type=cls.Types.LICENSE_OS, key=os, name='OS: %s' % os)
for key, name in ApplicationTypes.CHOICES:
yield ConsumableItem(
item_type=cls.Types.LICENSE_APPLICATION, key=key, name='Application: %s' % name)
for key, name in SupportTypes.CHOICES:
yield ConsumableItem(item_type=cls.Types.SUPPORT, key=key, name='Support: %s' % name)
for flavor_name in set(models.Flavor.objects.all().values_list('name', flat=True)):
yield ConsumableItem(item_type=cls.Types.FLAVOR, key=flavor_name, name='Flavor: %s' % flavor_name)
@classmethod
def get_configuration(cls, instance):
States = models.Instance.States
RuntimeStates = models.Instance.RuntimeStates
tags = [t.name for t in instance.tags.all()]
consumables = {}
for type in (cls.Types.LICENSE_APPLICATION, cls.Types.LICENSE_OS, cls.Types.SUPPORT):
try:
key = [t.split(':')[1] for t in tags if t.startswith('%s:' % type)][0]
except IndexError:
continue
consumables[ConsumableItem(item_type=type, key=key)] = 1
if instance.state == States.OK and instance.runtime_state == RuntimeStates.ACTIVE:
consumables[ConsumableItem(item_type=cls.Types.FLAVOR, key=instance.flavor_name)] = 1
return consumables
class VolumeStrategy(CostTrackingStrategy):
resource_class = models.Volume
class Types(object):
STORAGE = PriceItemTypes.STORAGE
class Keys(object):
STORAGE = '1 GB'
@classmethod
def get_consumable_items(cls):
return [ConsumableItem(item_type=cls.Types.STORAGE, key=cls.Keys.STORAGE, name='1 GB of storage', units='GB')]
@classmethod
def get_configuration(cls, volume):
return {ConsumableItem(item_type=cls.Types.STORAGE, key=cls.Keys.STORAGE): float(volume.size) / 1024}
class SnapshotStrategy(CostTrackingStrategy):
resource_class = models.Snapshot
class Types(object):
STORAGE = PriceItemTypes.STORAGE
class Keys(object):
STORAGE = '1 GB'
@classmethod
def get_consumable_items(cls):
return [ConsumableItem(item_type=cls.Types.STORAGE, key=cls.Keys.STORAGE, name='1 GB of storage', units='GB')]
@classmethod
def get_configuration(cls, snapshot):
return {ConsumableItem(item_type=cls.Types.STORAGE, key=cls.Keys.STORAGE): float(snapshot.size) / 1024}
<file_sep>/src/nodeconductor_openstack/openstack_tenant/migrations/0006_resource_action_details.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0005_resources_actions'),
]
operations = [
migrations.AlterField(
model_name='instance',
name='action_details',
field=jsonfield.fields.JSONField(default={}),
),
migrations.AlterField(
model_name='snapshot',
name='action_details',
field=jsonfield.fields.JSONField(default={}),
),
migrations.AlterField(
model_name='volume',
name='action_details',
field=jsonfield.fields.JSONField(default={}),
),
]
<file_sep>/src/nodeconductor_openstack/openstack_tenant/tasks.py
from __future__ import unicode_literals
import logging
from datetime import timedelta
from django.conf import settings
from django.db import transaction
from django.utils import timezone
from nodeconductor.core import tasks as core_tasks, models as core_models, utils as core_utils
from nodeconductor.quotas import exceptions as quotas_exceptions
from nodeconductor.structure import (models as structure_models, ServiceBackendError, tasks as structure_tasks,
SupportedServices)
from nodeconductor_openstack.openstack_base.backend import update_pulled_fields
from . import models, apps, serializers
logger = logging.getLogger(__name__)
class RuntimeStateException(Exception):
pass
class PollRuntimeStateTask(core_tasks.Task):
max_retries = 300
default_retry_delay = 5
@classmethod
def get_description(cls, instance, backend_pull_method, *args, **kwargs):
return 'Poll instance "%s" with method "%s"' % (instance, backend_pull_method)
def get_backend(self, instance):
return instance.get_backend()
def execute(self, instance, backend_pull_method, success_state, erred_state):
backend = self.get_backend(instance)
getattr(backend, backend_pull_method)(instance)
instance.refresh_from_db()
if instance.runtime_state not in (success_state, erred_state):
self.retry()
elif instance.runtime_state == erred_state:
raise RuntimeStateException(
'%s %s (PK: %s) runtime state become erred: %s' % (
instance.__class__.__name__, instance, instance.pk, erred_state))
return instance
class SetInstanceOKTask(core_tasks.StateTransitionTask):
""" Additionally mark or related floating IPs as free """
def pre_execute(self, instance):
self.kwargs['state_transition'] = 'set_ok'
self.kwargs['action'] = ''
self.kwargs['action_details'] = {}
super(SetInstanceOKTask, self).pre_execute(instance)
def execute(self, instance, *args, **kwargs):
super(SetInstanceOKTask, self).execute(instance)
instance.floating_ips.update(is_booked=False)
class SetInstanceErredTask(core_tasks.ErrorStateTransitionTask):
""" Mark instance as erred and delete resources that were not created. """
def execute(self, instance):
super(SetInstanceErredTask, self).execute(instance)
# delete volumes if they were not created on backend,
# mark as erred if creation was started, but not ended,
# leave as is, if they are OK.
for volume in instance.volumes.all():
if volume.state == models.Volume.States.CREATION_SCHEDULED:
volume.delete()
elif volume.state == models.Volume.States.OK:
pass
else:
volume.set_erred()
volume.save(update_fields=['state'])
# set instance floating IPs as free, delete not created ones.
instance.floating_ips.filter(backend_id='').delete()
instance.floating_ips.update(is_booked=False)
class SetBackupErredTask(core_tasks.ErrorStateTransitionTask):
""" Mark DR backup and all related resources that are not in state OK as Erred """
def execute(self, backup):
super(SetBackupErredTask, self).execute(backup)
for snapshot in backup.snapshots.all():
# If snapshot creation was not started - delete it from NC DB.
if snapshot.state == models.Snapshot.States.CREATION_SCHEDULED:
snapshot.decrease_backend_quotas_usage()
snapshot.delete()
else:
snapshot.set_erred()
snapshot.save(update_fields=['state'])
# Deactivate schedule if its backup become erred.
schedule = backup.backup_schedule
if schedule:
schedule.error_message = 'Failed to execute backup schedule for %s. Error: %s' % (
backup.instance, backup.error_message)
schedule.is_active = False
schedule.save()
class ForceDeleteBackupTask(core_tasks.DeletionTask):
def execute(self, backup):
backup.snapshots.all().delete()
super(ForceDeleteBackupTask, self).execute(backup)
class SetBackupRestorationErredTask(core_tasks.ErrorStateTransitionTask):
""" Mark backup restoration instance as erred and
delete volume records that have not been created on backend.
"""
def execute(self, backup_restoration):
instance = backup_restoration.instance
super(SetBackupRestorationErredTask, self).execute(instance)
# delete volumes if they were not created on backend,
# mark as erred if creation was started, but not ended,
# leave as is, if they are OK.
for volume in instance.volumes.all():
if volume.state == models.Volume.States.CREATION_SCHEDULED:
volume.delete()
elif volume.state == models.Volume.States.OK:
pass
else:
volume.set_erred()
volume.save(update_fields=['state'])
class VolumeExtendErredTask(core_tasks.ErrorStateTransitionTask):
""" Mark volume and its instance as erred on fail """
def execute(self, volume):
super(VolumeExtendErredTask, self).execute(volume)
if volume.instance is not None:
super(VolumeExtendErredTask, self).execute(volume.instance)
# CELERYBEAT
class PullResources(core_tasks.BackgroundTask):
name = 'openstack_tenant.PullResources'
def is_equal(self, other_task):
return self.name == other_task.get('name')
def run(self):
type = apps.OpenStackTenantConfig.service_name
ok_state = structure_models.ServiceSettings.States.OK
for service_settings in structure_models.ServiceSettings.objects.filter(type=type, state=ok_state):
serialized_service_settings = core_utils.serialize_instance(service_settings)
PullServiceSettingsResources().delay(serialized_service_settings)
class PullServiceSettingsResources(core_tasks.BackgroundTask):
name = 'openstack_tenant.PullServiceSettingsResources'
stable_states = (core_models.StateMixin.States.OK, core_models.StateMixin.States.ERRED)
def is_equal(self, other_task, serialized_service_settings):
return self.name == other_task.get('name') and serialized_service_settings in other_task.get('args', [])
def run(self, serialized_service_settings):
service_settings = core_utils.deserialize_instance(serialized_service_settings)
backend = service_settings.get_backend()
try:
self.pull_volumes(service_settings, backend)
self.pull_snapshots(service_settings, backend)
self.pull_instances(service_settings, backend)
except ServiceBackendError as e:
logger.error('Failed to pull resources for service settings: %s. Error: %s' % (service_settings, e))
service_settings.set_erred()
service_settings.error_message = str(e)
service_settings.save()
def pull_volumes(self, service_settings, backend):
backend_volumes = backend.get_volumes()
volumes = models.Volume.objects.filter(
service_project_link__service__settings=service_settings, state__in=self.stable_states)
backend_volumes_map = {backend_volume.backend_id: backend_volume for backend_volume in backend_volumes}
for volume in volumes:
try:
backend_volume = backend_volumes_map[volume.backend_id]
except KeyError:
self._set_erred(volume)
else:
self._update(volume, backend_volume, backend.VOLUME_UPDATE_FIELDS)
def pull_snapshots(self, service_settings, backend):
backend_snapshots = backend.get_snapshots()
snapshots = models.Snapshot.objects.filter(
service_project_link__service__settings=service_settings, state__in=self.stable_states)
backend_snapshots_map = {backend_snapshot.backend_id: backend_snapshot
for backend_snapshot in backend_snapshots}
for snapshot in snapshots:
try:
backend_snapshot = backend_snapshots_map[snapshot.backend_id]
except KeyError:
self._set_erred(snapshot)
else:
self._update(snapshot, backend_snapshot, backend.SNAPSHOT_UPDATE_FIELDS)
def pull_instances(self, service_settings, backend):
backend_instances = backend.get_instances()
instances = models.Instance.objects.filter(
service_project_link__service__settings=service_settings, state__in=self.stable_states)
backend_instances_map = {backend_instance.backend_id: backend_instance
for backend_instance in backend_instances}
for instance in instances:
try:
backend_instance = backend_instances_map[instance.backend_id]
except KeyError:
self._set_erred(instance)
else:
self._update(instance, backend_instance, backend.INSTANCE_UPDATE_FIELDS)
backend.pull_instance_security_groups(instance)
backend.pull_instance_internal_ips(instance)
backend.pull_instance_floating_ips(instance)
def _set_erred(self, resource):
resource.set_erred()
resource.runtime_state = ''
message = 'Does not exist at backend.'
if message not in resource.error_message:
if not resource.error_message:
resource.error_message = message
else:
resource.error_message = resource.error_message + ' (%s)' % message
resource.save()
logger.warning('%s %s (PK: %s) does not exist at backend.' % (
resource.__class__.__name__, resource, resource.pk))
def _update(self, resource, backend_resource, fields):
update_pulled_fields(resource, backend_resource, fields)
if resource.state == core_models.StateMixin.States.ERRED:
resource.recover()
resource.error_message = ''
resource.save(update_fields=['state', 'error_message'])
logger.info('%s %s (PK: %s) successfully pulled from backend.' % (
resource.__class__.__name__, resource, resource.pk))
class BaseScheduleTask(core_tasks.BackgroundTask):
model = NotImplemented
def is_equal(self, other_task):
return self.name == other_task.get('name')
def run(self):
schedules = self.model.objects.filter(is_active=True, next_trigger_at__lt=timezone.now())
for schedule in schedules:
kept_until = None
if schedule.retention_time:
kept_until = timezone.now() + timezone.timedelta(days=schedule.retention_time)
try:
with transaction.atomic():
schedule.call_count += 1
schedule.save()
resource = self._create_resource(schedule, kept_until=kept_until)
except quotas_exceptions.QuotaValidationError as e:
message = 'Failed to schedule "%s" creation. Error: %s' % (self.model.__name__, e)
logger.exception(
'Resource schedule (PK: %s), (Name: %s) execution failed. %s' % (schedule.pk,
schedule.name,
message))
schedule.is_active = False
schedule.error_message = message
schedule.save()
else:
executor = self._get_create_executor()
executor.execute(resource)
def _create_resource(self, schedule, kept_until):
raise NotImplementedError()
def _get_create_executor(self):
raise NotImplementedError()
class ScheduleBackups(BaseScheduleTask):
name = 'openstack_tenant.ScheduleBackups'
model = models.BackupSchedule
def _create_resource(self, schedule, kept_until):
backup = models.Backup.objects.create(
name='Backup#%s of %s' % (schedule.call_count, schedule.instance.name),
description='Scheduled backup of instance "%s"' % schedule.instance,
service_project_link=schedule.instance.service_project_link,
instance=schedule.instance,
backup_schedule=schedule,
metadata=serializers.BackupSerializer.get_backup_metadata(schedule.instance),
kept_until=kept_until,
)
serializers.BackupSerializer.create_backup_snapshots(backup)
return backup
def _get_create_executor(self):
from . import executors
return executors.BackupCreateExecutor
class DeleteExpiredBackups(core_tasks.BackgroundTask):
name = 'openstack_tenant.DeleteExpiredBackups'
def is_equal(self, other_task):
return self.name == other_task.get('name')
def run(self):
from . import executors
for backup in models.Backup.objects.filter(kept_until__lt=timezone.now(), state=models.Backup.States.OK):
executors.BackupDeleteExecutor.execute(backup)
class ScheduleSnapshots(BaseScheduleTask):
name = 'openstack_tenant.ScheduleSnapshots'
model = models.SnapshotSchedule
def _create_resource(self, schedule, kept_until):
snapshot = models.Snapshot.objects.create(
name='Snapshot#%s of %s' % (schedule.call_count, schedule.source_volume.name),
description='Scheduled snapshot of volume "%s"' % schedule.source_volume,
service_project_link=schedule.source_volume.service_project_link,
source_volume=schedule.source_volume,
snapshot_schedule=schedule,
size=schedule.source_volume.size,
metadata=serializers.SnapshotSerializer.get_snapshot_metadata(schedule.source_volume),
kept_until=kept_until,
)
snapshot.increase_backend_quotas_usage()
return snapshot
def _get_create_executor(self):
from . import executors
return executors.SnapshotCreateExecutor
class DeleteExpiredSnapshots(core_tasks.BackgroundTask):
name = 'openstack_tenant.DeleteExpiredSnapshots'
def is_equal(self, other_task):
return self.name == other_task.get('name')
def run(self):
from . import executors
for snapshot in models.Snapshot.objects.filter(kept_until__lt=timezone.now(), state=models.Snapshot.States.OK):
executors.SnapshotDeleteExecutor.execute(snapshot)
class SetErredStuckResources(core_tasks.BackgroundTask):
name = 'openstack_tenant.SetErredStuckResources'
def is_equal(self, other_task):
return self.name == other_task.get('name')
def run(self):
for model in (models.Instance, models.Volume, models.Snapshot):
cutoff = timezone.now() - timedelta(minutes=30)
for resource in model.objects.filter(modified__lt=cutoff,
state=structure_models.NewResource.States.CREATING):
resource.set_erred()
resource.error_message = 'Provisioning is timed out.'
resource.save(update_fields=['state', 'error_message'])
logger.warning('Switching resource %s to erred state, '
'because provisioning is timed out.',
core_utils.serialize_instance(resource))
class LimitedPerTypeThrottleMixin(object):
def get_limit(self, resource):
nc_settings = getattr(settings, 'NODECONDUCTOR_OPENSTACK', {})
limit_per_type = nc_settings.get('MAX_CONCURRENT_PROVISION', {})
model_name = SupportedServices.get_name_for_model(resource)
return limit_per_type.get(model_name, super(LimitedPerTypeThrottleMixin, self).get_limit(resource))
class ThrottleProvisionTask(LimitedPerTypeThrottleMixin, structure_tasks.ThrottleProvisionTask):
pass
class ThrottleProvisionStateTask(LimitedPerTypeThrottleMixin, structure_tasks.ThrottleProvisionStateTask):
pass
| c0fb580b32f31512ad721d220857ea694bcc26d3 | [
"Python",
"reStructuredText"
] | 37 | Python | AmbientLighter/nodeconductor-openstack | bb9ecaed61a74448f05d137ea6bbb32c218f56ac | ec13eeabfdaaaa625d5cb8799b58185055064146 |
refs/heads/master | <file_sep>artifactId=core
groupId=com.aimbra.finance
version=1.0-SNAPSHOT
<file_sep>CREATE DATABASE ABRFIN;
insert into abrfin.abrprod.products
<file_sep>package com.aimbra.finance.product.endpoints.controllers;
import com.aimbra.finance.core.entities.Product;
import com.aimbra.finance.product.endpoints.services.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "v1/products")
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ProductController {
private final ProductService productService;
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Iterable<Product>> findAll(Pageable pageable) {
return new ResponseEntity<>(productService.findAll(pageable), HttpStatus.OK);
}
}
<file_sep>package com.aimbra.finance.product.endpoints.services;
import com.aimbra.finance.core.entities.Product;
import com.aimbra.finance.core.repositories.ProductRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ProductService {
private final ProductRepository productRepository;
public Iterable<Product> findAll(Pageable pageable) {
log.info("Listing all products");
return productRepository.findAll(pageable);
}
}
| e5ac87109ff0d0fc56c8715e86ce6a6352220bfa | [
"Java",
"SQL",
"INI"
] | 4 | INI | thiagosantoscunha/aimbra-finance | 7960f4de5048ddc054a32be4ba36f8cf2b2039fd | 1b6f1f3a9b2b1c21fefb652b5ee25d6d9d18a714 |
refs/heads/master | <repo_name>nelglez/MonthCal<file_sep>/Sources/MonthCal/ViewModel/DayCellView.swift
//
// CellView.swift
// CalSwiftUI
//
// Created by <NAME> on 11/13/19.
// Copyright © 2019 KesDev. All rights reserved.
//
import SwiftUI
@available(OSX 10.15, *)
@available(iOS 13.0, *)
struct DayCellView: View {
@ObservedObject var day: Day
var body: some View {
Text(day.dayName).frame(width: 32, height: 32)
.foregroundColor(day.textColor)
.background(day.backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: 10))
.clipped()
.onTapGesture {
if self.day.disabled == false && self.day.selectableDays {
self.day.isSelected.toggle()
}
}
}
}
@available(OSX 10.15, *)
@available(iOS 13.0, *)
struct CellView_Previews: PreviewProvider {
static var previews: some View {
DayCellView(day: Day(date: Date()))
}
}
<file_sep>/Sources/MonthCal/Model/Day.swift
//
// Day.swift
// CalSwiftUI
//
// Created by <NAME> on 11/12/19.
// Copyright © 2019 KesDev. All rights reserved.
//
import Foundation
import SwiftUI
@available(OSX 10.15, *)
@available(iOS 13.0, *)
class Day: ObservableObject {
@Published var isSelected = false
var selectableDays: Bool
var dayDate: Date
var dayName: String {
dayDate.dateToString(format: "d")
}
var isToday = false
var disabled = false
let colors = Colors()
var textColor: Color {
if isSelected {
return colors.selectedColor
} else if isToday {
return colors.todayColor
} else if disabled {
return colors.disabledColor
}
return colors.textColor
}
var backgroundColor: Color {
if isSelected {
return colors.selectedBackgroundColor
} else {
return colors.backgroundColor
}
}
init(date: Date, today: Bool = false, disable: Bool = false, selectable: Bool = true) {
dayDate = date
isToday = today
disabled = disable
selectableDays = selectable
}
}
<file_sep>/README.md
# MonthCal
**A SwiftUI Calendar Generator for IOS**
## Features:
- Supply starting date
- Select months to display
- Disabled, Enabled, Selected, Today day states
- Color control
- Dark Mode Support
## Photos


## Installation
- Requires IOS 13.0+ / Xcode 11+ / Swift 5.1+
### Option 1
- Copy `Sources/MonthCal` files into your xcode project
### Option 2
- Add via Swift Package Manager
### Configure
- To customize the colors used, edit colors listed in the `Colors.swift` file
### Usage
- Show calendar with a start date and amount of months to display
```
Import MonthCal
CalendarView(start: Date(), monthsToShow: 6)
```
- Disable ability for dates to be selected
```
Import MonthCal
CalendarView(start: Date(), monthsToShow: 6, daysSelectable: false)
```
## License
- MonthCal is available under the MIT license. See the `LICENSE` file for more info.
## Shoutouts
- <NAME> - [@twostraws](https://twitter.com/twostraws) - https://www.hackingwithswift.com/100/swiftui
- RaffiKian - https://github.com/RaffiKian/RKCalendar - Inspiration
<file_sep>/Tests/LinuxMain.swift
import XCTest
import MonthCalTests
var tests = [XCTestCaseEntry]()
tests += MonthCalTests.allTests()
XCTMain(tests)
| 4818c33d7504d84a9c556ef2ddbc4026ae872879 | [
"Swift",
"Markdown"
] | 4 | Swift | nelglez/MonthCal | f93ad08d62f4333ee6894a52218b98269bc2070c | d5202c67ef16ab6f6ecd08967bc36e136574fbd7 |
refs/heads/master | <repo_name>rhaag71/bathclock<file_sep>/lib/BH1750FVI/examples/BH1750FVI_Simple/BH1750FVI_Simple.ino
/*
This is a simple example to test the BH1750 Light sensor
Connect the sensor to a NodeMCU ESP8266:
VCC <-> 3V3 [grey]
GND <-> Gnd [purple]
SDA <-> D2 [green]
SCL <-> D1 [blue]
ADDR <-> RX [yellow]
*/
#include <Wire.h>
#include <BH1750FVI.h>
// Settings
uint8_t ADDRESSPIN = 13;
BH1750FVI::eDeviceAddress_t DEVICEADDRESS = BH1750FVI::k_DevAddress_H;
BH1750FVI::eDeviceMode_t DEVICEMODE = BH1750FVI::k_DevModeContHighRes;
// Create the Lightsensor instance
BH1750FVI LightSensor(ADDRESSPIN, DEVICEADDRESS, DEVICEMODE);
void setup()
{
Serial.begin(115200);
LightSensor.begin();
Serial.println("Running...");
}
void loop()
{
uint16_t lux = LightSensor.GetLightIntensity();
Serial.print("Light: ");
Serial.println(lux);
delay(250);
}
<file_sep>/src/main.cpp
#include <Arduino.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
/**
* GLOBAL PIN CONFIGURATION
*/
const int TFT_CS = 15;
const int TFT_DC = 4;
const int TFT_MOSI = 23;
const int TFT_SLK = 18;
const int TFT_RST = 2;
const int TFT_LED = 19;
const int BUZZER = 5;
const int NIGHTLIGHT = 17;
const int LUX_SDA = 21;
const int LUX_SCL = 22;
const int DHT_OUT = 27;
/**
* EEPROM libraries and resources
*/
#include "EEPROM.h"
#define EEPROM_SIZE 64
/**
* ILI9341 TFT libraries and resources
*/
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include "Fonts/FreeSans9pt7b.h"
#include "Fonts/FreeSans12pt7b.h"
#include "Fonts/FreeSans18pt7b.h"
#include "Fonts/FreeSans24pt7b.h"
// cs dc mosi slk rst
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_SLK, TFT_RST);
#define ILI9341_LCYAN 0x0418
#define ILI9341_LORANGE 0xFC08
#define ILI9341_LGREEN 0x87F0
#define ILI9341_LGRAY 0x8410
#define ILI9341_BLACK 0x0000 ///< 0, 0, 0
#define ILI9341_NAVY 0x000F ///< 0, 0, 123
#define ILI9341_DARKGREEN 0x03E0 ///< 0, 125, 0
#define ILI9341_DARKCYAN 0x03EF ///< 0, 125, 123
#define ILI9341_MAROON 0x7800 ///< 123, 0, 0
#define ILI9341_PURPLE 0x780F ///< 123, 0, 123
#define ILI9341_OLIVE 0x7BE0 ///< 123, 125, 0
#define ILI9341_LIGHTGREY 0xC618 ///< 198, 195, 198
#define ILI9341_DARKGREY 0x7BEF ///< 123, 125, 123
#define ILI9341_BLUE 0x001F ///< 0, 0, 255
#define ILI9341_GREEN 0x07E0 ///< 0, 255, 0
#define ILI9341_CYAN 0x07FF ///< 0, 255, 255
#define ILI9341_RED 0xF800 ///< 255, 0, 0
#define ILI9341_MAGENTA 0xF81F ///< 255, 0, 255
#define ILI9341_YELLOW 0xFFE0 ///< 255, 255, 0
#define ILI9341_WHITE 0xFFFF ///< 255, 255, 255
#define ILI9341_ORANGE 0xFD20 ///< 255, 165, 0
#define ILI9341_GREENYELLOW 0xAFE5 ///< 173, 255, 41
#define ILI9341_PINK 0xFC18 ///< 255, 130, 198
/**
* BH1750 Lux meter libraries and resources
*/
#include <BH1750FVI.h>
// Create the Lightsensor instance
BH1750FVI LightSensor(BH1750FVI::k_DevModeContHighRes);
/**
* DHT-11 Temp and humidity sensor libraries and resources
*/
#include "DHT.h"
#define DHTTYPE DHT11
DHT dht(DHT_OUT, DHTTYPE);
/**
* WIFI Libraries and resources
*/
#include <WiFi.h>
//Absolute path to file containing WiFi credentials
const char* host = "bathclock";
const char* ssid = "Gamma-Ray";
const char* password = "<PASSWORD>";
const int connTimeout = 10; //Seconds
WebServer server(80);
/*
* Login page
*/
const char* loginIndex =
"<form name='loginForm'>"
"<table width='20%' bgcolor='A09F9F' align='center'>"
"<tr>"
"<td colspan=2>"
"<center><font size=4><b>ESP32 Login Page</b></font></center>"
"<br>"
"</td>"
"<br>"
"<br>"
"</tr>"
"<td>Username:</td>"
"<td><input type='text' size=25 name='userid'><br></td>"
"</tr>"
"<br>"
"<br>"
"<tr>"
"<td>Password:</td>"
"<td><input type='Password' size=25 name='pwd'><br></td>"
"<br>"
"<br>"
"</tr>"
"<tr>"
"<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
"</tr>"
"</table>"
"</form>"
"<script>"
"function check(form)"
"{"
"if(form.userid.value=='admin' && form.pwd.value=='<PASSWORD>')"
"{"
"window.open('/serverIndex')"
"}"
"else"
"{"
" alert('Error Password or Username')/*displays error message*/"
"}"
"}"
"</script>";
/*
* Server Index Page
*/
const char* serverIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
"<input type='file' name='update'>"
"<input type='submit' value='Update'>"
"</form>"
"<div id='prg'>progress: 0%</div>"
"<script>"
"$('form').submit(function(e){"
"e.preventDefault();"
"var form = $('#upload_form')[0];"
"var data = new FormData(form);"
" $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data,"
"contentType: false,"
"processData:false,"
"xhr: function() {"
"var xhr = new window.XMLHttpRequest();"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');"
"}"
"}, false);"
"return xhr;"
"},"
"success:function(d, s) {"
"console.log('success!')"
"},"
"error: function (a, b, c) {"
"}"
"});"
"});"
"</script>";
/**
* TIME libraries and resources
*/
#include "time.h"
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = -18000;
const int daylightOffset_sec = 3600;
/**
* For rounding values
*/
#include "math.h"
/**
* PWM Constants
*/
const int freq = 5000;
const int tftledChannel = 0;
const int resolution = 8;
/**
* TFT Display Constants
*/
const int xTime = 10;
const int yTime = 75;
const int tftBG = ILI9341_BLACK;
const int tftTimeFG = ILI9341_RED;
/**
* GLOBALS
*/
String prevTime = "";
String currTime = "";
String prevDate = "";
String currDate = "";
uint16_t prevLux = 0;
uint16_t currLux = 0;
float prevTemp = 0;
float currTemp = 0;
float prevHumi = 0;
float currHumi = 0;
bool onWifi = false;
String weekDays[] = {"", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"};
String months[] = {"", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
const unsigned long bathroomTimeInterval = 240000; // 4 minutes
unsigned long previousMillis;
unsigned long currentMillis;
//Configurable values
int bootWait; //Seconds
byte maxLux;
byte minLux;
byte minBrightness;
// forward declarations
void loadConfiguration();
void setBGLuminosity(int level);
void nightLight(int mode);
bool wifiConnect();
bool getNtpTime();
void displayTime();
void displayDate();
void displayTemp();
void displayHumi();
// void displayLux();
uint16_t getCurrentLux();
float getCurrentTemp();
float getCurrentHumi();
int returnCurrHour();
void refreshTime();
String hourMinuteToTime(int hour, int minute);
void timeChanged(String prevTime, String currTime);
void dateChanged(String prevDate, String currDate);
void luxChanged(uint16_t prevLux, uint16_t currLux);
void tempChanged(float prevTemp, float currTemp);
void humiChanged(float prevHumi, float currHumi);
byte getBootWait();
void setBootWait(byte value);
byte getMaxLux();
byte getMinLux();
byte getMinBrightness();
void setMaxLux(byte value);
void setMinLux(byte value);
void setMinBrightness(byte value);
void calculateAndSetBGLuminosity(uint16_t currLux);
void setup() {
/**
* Serial port
*/
Serial.begin(115200);
/**
* EEPROM
*/
EEPROM.begin(EEPROM_SIZE);
/**
* Loads EEPROM configuration
*/
loadConfiguration();
/**
* TFT DISPLAY
*/
//Background light PWM
ledcSetup(tftledChannel, freq, resolution);
ledcAttachPin(TFT_LED, tftledChannel);
//Start with high intensity
setBGLuminosity(255);
tft.begin();
tft.setRotation(3);
yield();
//Boot screen
tft.fillScreen(ILI9341_BLACK);
yield();
tft.setTextSize(2);
tft.setTextColor(ILI9341_YELLOW);
tft.println("You no sleep on toilet!");
tft.setTextSize(1);
tft.setTextColor(ILI9341_WHITE);
tft.println("");
tft.println("Booting...");
tft.println("Setting up devices...");
/**
* BUZZER
*/
pinMode(BUZZER, OUTPUT);
/**
* NIGHTLIGHT
*/
pinMode(NIGHTLIGHT, OUTPUT);
/**
* Light sensor
*/
LightSensor.begin();
/**
* Temperature and humidity sensor
*/
dht.begin();
/**
* Wifi connect
*/
tft.print("Connecting to WiFi AP ");
tft.println(ssid);
wifiConnect();
if(onWifi == true){
tft.print(" Connection succeed, obtained IP ");
tft.println(WiFi.localIP());
}else{
tft.println("*** Connection failed. Unexpected operation results.");
}
tft.println("Obtaining NTP time from remote server...");
/**
* NTP Time
*/
getNtpTime();
delay(100); //We need a delay to allow info propagation
/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
Serial.println("\n ");
/*return index page which is stored in serverIndex */
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", loginIndex);
});
server.on("/serverIndex", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
/*handling uploading firmware file */
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
server.begin();
tft.println("Ready...");
/**
* Blink night light for "ready..."
*/
digitalWrite(NIGHTLIGHT, HIGH);
delay(350);
digitalWrite(NIGHTLIGHT, LOW);
delay(350);
digitalWrite(NIGHTLIGHT, HIGH);
delay(350);
digitalWrite(NIGHTLIGHT, LOW);
//Prepare screen for normal operation
setBGLuminosity(0);
tft.fillScreen(ILI9341_BLACK);
yield();
//Paint elements
displayTime();
displayDate();
displayTemp();
displayHumi();
// displayLux(); // for debug if needed
setBGLuminosity(255);
/**
* TESTING
*/
}
void loop() {
getCurrentLux();
getCurrentTemp();
getCurrentHumi();
refreshTime();
server.handleClient();
delay(100);
}
/**
* Connects to WIFI
*/
bool wifiConnect(){
onWifi = false;
int retries = 0;
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
retries++;
if(retries == (connTimeout * 2)){
Serial.println(" TIMEOUT");
break;
}
}
if(WiFi.status() == WL_CONNECTED){
onWifi = true;
Serial.println(" CONNECTED");
}
return onWifi;
}
/**
* Obtains time from NTP server
*/
bool getNtpTime(){
bool result = false;
if(onWifi == true){
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
result = true;
}else{
Serial.println("getNtpTime: Not connected to wifi!");
}
return result;
}
/**
* Returns a string formatted HH:MM based on hours and minutes
*/
String hourMinuteToTime(int hour, int minute){
String sTime;
char cTime[12]=" ";
if(hour==0){
hour=12;
sprintf(cTime, "%02d:%02d AM", hour, minute);
}
else if(hour==12){
hour=12;
sprintf(cTime, "%02d:%02d PM", hour, minute);
}
else if(hour<12&&hour!=0){
if(hour>9) {
sprintf(cTime, "%02d:%02d AM", hour, minute);
} else {
sprintf(cTime, " %01d:%02d AM", hour, minute);
}
}
else if(hour>12&&hour!=0)
{
hour=hour-12;
if(hour>9) {
sprintf(cTime, "%02d:%02d PM", hour, minute);
} else {
sprintf(cTime, " %01d:%02d PM", hour, minute);
}
}
sTime = (char*)cTime;
return sTime;
}
/*
* Returns current time in HH:MM format
*/
void refreshTime(){
//Time
time_t now;
struct tm * timeinfo;
time(&now);
timeinfo = localtime(&now);
prevTime = currTime;
currTime = hourMinuteToTime(timeinfo->tm_hour, timeinfo->tm_min);
if(prevTime != currTime){
timeChanged(prevTime, currTime);
//If time has changed, lets check if date has changed too
//Date
int wDay;
wDay = timeinfo->tm_wday;
if(wDay == 0){
wDay = 7;
}
String calDate = "";
calDate = calDate + weekDays[wDay];
calDate = calDate + " ";
calDate = calDate + months[(timeinfo->tm_mon + 1)];
calDate = calDate + " ";
calDate = calDate + timeinfo->tm_mday;
calDate = calDate + ", ";
calDate = calDate + (timeinfo->tm_year + 1900);
if(calDate.length() == 21){
calDate = " " + calDate;
}
prevDate = currDate;
currDate = calDate;
if(prevDate != currDate){
dateChanged(prevDate, currDate);
}
}
}
/**
* Return the current hour
*/
int returnCurrHour() {
time_t now;
struct tm * timeinfo;
time(&now);
timeinfo = localtime(&now);
// Serial.println(timeinfo->tm_hour); // debug
return timeinfo->tm_hour;
}
/**
* Displays time string erasing the previous one
*/
void displayTime(){
tft.setFont(&FreeSans18pt7b);
tft.setTextSize(2);
tft.setCursor(xTime, yTime);
tft.setTextColor(tftBG);
yield();
tft.println(prevTime);
yield();
tft.setCursor(xTime, yTime);
tft.setTextColor(tftTimeFG);
yield();
tft.println(currTime);
yield();
tft.setFont();
yield();
}
/**
* Displays date string
*/
void displayDate(){
tft.fillRect(14, 94, 192, 30, ILI9341_BLACK);
tft.setFont(&FreeSans9pt7b);
tft.setTextSize(1.5);
tft.setCursor(40, 115);
tft.setTextColor(ILI9341_LIGHTGREY);
yield();
tft.println(currDate);
yield();
tft.setFont();
yield();
}
/**
* Displays temperature
*/
void displayTemp(){
int bgColor = 0;
int rndTemp = 0;
bgColor = ILI9341_BLACK;
tft.setTextColor(ILI9341_WHITE);
yield();
tft.fillRect(25, 124, 100, 100, bgColor);
tft.drawRect(25, 124, 100, 100, ILI9341_BLACK);
yield();
tft.setFont(&FreeSans18pt7b);
tft.setTextSize(1.5);
tft.setCursor(40, 175);
rndTemp = round(currTemp);
tft.print(rndTemp);
tft.print(" F");
tft.setFont();
tft.setCursor(82, 145);
tft.setTextSize(2);
tft.print(char(247));
tft.setTextColor(ILI9341_BLACK);
}
/**
* Displays relative humidity
*/
void displayHumi(){
int bgColor = 0;
int rndHumi = 0;
bgColor = ILI9341_BLACK;
tft.setTextColor(ILI9341_WHITE);
yield();
tft.fillRect(130, 124, 140, 100, bgColor);
tft.drawRect(130, 124, 140, 100, ILI9341_BLACK);
yield();
tft.setFont(&FreeSans18pt7b);
tft.setTextSize(1.5);
tft.setCursor(160, 175);
rndHumi = round(currHumi);
tft.print(rndHumi);
tft.print("%");
tft.setFont();
}
/**
* Displays lux (debug if needed)
* if used uncomment forward declaration at top of code
*/
// void displayLux(){
// int bgColor = 0;
// bgColor = ILI9341_BLACK;
// tft.setTextColor(ILI9341_WHITE);
// yield();
// tft.fillRect(212, 170, 92, 60, bgColor);
// tft.drawRect(212, 170, 92, 60, ILI9341_BLACK);
// yield();
// tft.setFont(&FreeSans9pt7b);
// tft.setTextSize(1.5);
// tft.setCursor(214, 200);
// char cLux[5]=" ";
// sprintf(cLux, "%05d", currLux);
// tft.print(cLux);
// tft.setFont();
// }
/**
* Sets TFT background luminosity (0-255)
*/
void setBGLuminosity(int level){
ledcWrite(tftledChannel, level);
}
/**
* Play alarm noise
*/
void playAlarm() {
Serial.println("playing alarm..");
for(int i=0; i< 200; i++) {
digitalWrite(BUZZER, HIGH);
delay(1);
digitalWrite(BUZZER, LOW);
delay(1);
}
}
/**
* Turn on nightlight if lights out, off if lights on
*/
void nightLight(int mode) {
// Ambient lights are off
if(mode==1) {
digitalWrite(NIGHTLIGHT, HIGH);
// delete countdown indicator circle
tft.fillCircle(300, 220, 3,ILI9341_BLACK);
tft.drawCircle(300, 220, 3,ILI9341_BLACK);
previousMillis = millis();
}
// Ambient lights are on
if(mode==0) {
digitalWrite(NIGHTLIGHT, LOW);
int thisHour = returnCurrHour();
currentMillis = millis();
if (thisHour<=6) {
// display countdown indicator circle, showing that there is an alarm countdown happening
tft.fillCircle(300, 220, 3,ILI9341_YELLOW);
tft.drawCircle(300, 220, 3,ILI9341_WHITE);
if (currentMillis - previousMillis >= bathroomTimeInterval) {
playAlarm();
}
}
}
}
/**
* Returns ambient light luxes
*/
uint16_t getCurrentLux(){
prevLux = currLux;
currLux = LightSensor.GetLightIntensity();
if(prevLux != currLux){
Serial.println(currLux);
luxChanged(prevLux , currLux);
}
return currLux;
}
/**
* Calculates and sets screen backlight brightness
*/
void calculateAndSetBGLuminosity(uint16_t currLux){
int finalLux = currLux;
if(finalLux > maxLux){
finalLux = maxLux;
}
if(finalLux < minLux){
finalLux = minLux;
}
double levelsWidth = maxLux - minLux;
double level = finalLux - minLux;
double ratio = level / levelsWidth;
double brightnessWidth = 255 - minBrightness;
int brightnessValue = (brightnessWidth * ratio) + minBrightness;
setBGLuminosity(brightnessValue);
}
/**
* Returns temperature
*/
float getCurrentTemp(){
prevTemp = currTemp;
currTemp = (dht.readTemperature()*1.8)+32;
if(prevTemp != currTemp){
tempChanged(prevTemp , currTemp);
}
return currTemp;
}
/**
* Returns humidity
*/
float getCurrentHumi(){
prevHumi = currHumi;
currHumi = dht.readHumidity();
if(prevHumi != currHumi){
humiChanged(prevHumi , currHumi);
}
return currHumi;
}
/**
* EVENTS
*/
/**
* Event for change of time HH:MM
*/
void timeChanged(String prevTime, String currTime){
//Serial.println("timeChanged event fired!");
displayTime();
}
/**
* Event for change of date weekDay, day de Month de Year
*/
void dateChanged(String prevDate, String currDate){
//Serial.print("dateChanged event fired! ");
//Serial.println(currDate);
displayDate();
}
/**
* Event for change of ambient light
*/
void luxChanged(uint16_t prevLux, uint16_t currLux){
//Serial.print("luxChanged event fired! ");
//Serial.println(currLux);
if(currLux<80) {
int mode = 1;
nightLight(mode);
}
if(currLux>180) {
int mode = 0;
nightLight(mode);
}
calculateAndSetBGLuminosity(currLux);
}
/**
* Event for change of temperature
*/
void tempChanged(float prevTemp, float currTemp){
//Serial.print("tempChanged event fired! ");
//Serial.println(currTemp);
displayTemp();
}
/**
* Event for change of humidity
*/
void humiChanged(float prevHumi, float currHumi){
//Serial.println("humiChanged event fired!");
// Serial.println(currHumi);
displayHumi();
}
/**
* Load Configuration from EEPROM
*/
void loadConfiguration(){
bootWait = getBootWait();
maxLux = getMaxLux();
minLux = getMinLux();
minBrightness = getMinBrightness();
}
/**
* Boot Wait
* Address 0
*/
byte getBootWait(){
byte value = byte(EEPROM.read(0));
if(value == 255){
value = 20;
}
return value;
}
void setBootWait(byte value){
EEPROM.write(0, value);
EEPROM.commit();
bootWait = value;
}
/* maxLux
* Address 8
*/
byte getMaxLux(){
byte value = byte(EEPROM.read(8));
if(value == 255){
value = 20;
}
return value;
}
void setMaxLux(byte value){
EEPROM.write(8, value);
EEPROM.commit();
maxLux = value;
calculateAndSetBGLuminosity(currLux);
}
/* minLux
* Address 9
*/
byte getMinLux(){
byte value = byte(EEPROM.read(9));
if(value == 255){
value = 0;
}
return value;
}
void setMinLux(byte value){
EEPROM.write(9, value);
EEPROM.commit();
minLux = value;
calculateAndSetBGLuminosity(currLux);
}
/* minBrightness
* Address 10
*/
byte getMinBrightness(){
byte value = byte(EEPROM.read(10));
if(value == 255){
value = 10;
}
return value;
}
void setMinBrightness(byte value){
EEPROM.write(10, value);
EEPROM.commit();
minBrightness = value;
calculateAndSetBGLuminosity(currLux);
}
<file_sep>/lib/BH1750FVI/src/README.txt
** BH1750FVI driver **
This library aims to provide an easy use of the BH1750FVI Lightsensor.
License: MIT License
Copyright (c) 2017 PeterEmbedded
| a15953ba3c2436869855c65be0fa9c563062e703 | [
"Text",
"C++"
] | 3 | C++ | rhaag71/bathclock | 08cfb6d8511db196bf3dbc3561dd99cca7190c2d | 50308c49fc8740cf8ded647d638b6434b5fe25a6 |
refs/heads/master | <repo_name>consolacion/Greenhouse<file_sep>/greenhouse26.ino
/****************************************************************
03-04-2016 added lcd.clear on pushbutton change
03-04-2016 added mintemp store slaat dagelijks laagst gemeten temp op
27-03-2016 correctie Winter_zomer routine
27-03-2016 waarde 255 van warmtetotaalopbrengst uitgesloten
17-03-2016 printlogWarmth toegevoegd
16-03-2016 slaat 1 jaar stooktijd in EEPROM op
15-03-2016 upper limit naar 21 graden
11-03-2016 added toggle voor tomaat
09-03-2016 addedcheck for heat on around midnight
08-03-2016 Alarm voor losse sensor toegevoegd
08-03=2016 Added running warmtime and count
07-03-2016 Correctie: lsb en dst waren beide 25
06-03-2016 Lichtschema toegevoegd
06-03-2016 start up optie voor tomaat
06-03-2016 hernoemd: versie 26
05-03-2016 warmcount toegevoegd, telt aantal keren dat de verwarming aangaat
04-03-2016 corrected totalling, corrected print of seconds in lower right corner
01-03-2016 added totalling time heating on
29-02-2016 added setting for tomatoes: 22-20 in day time and 20-18 at night
15-02-2016 Schakelt nu verwarming aan op 19 en uit op 22
13-02-2016 Added dst
29-11-2015 Added Winsen MH-Z19 CO2 sensor
28-11-2015 lcd.clear was removed for less flickering in LCD. Necessary area's overwritten by Spaces
21-11-2015 added hydroponics setting
19-11-2015 changed into once every 4 minutes for measurement
23-11-2015 log functie toegevoegd
measure soil moisture
if less than required value switch pump on
measure temperature
if less than required value switch on heating
measure humidity
if higher than desired value Switch on fan
Consider leaving fan on at night
http://www.quickgrow.com/gardening_articles/fans_air_movement.html
CO2 700-1400ppm atmosfeer is ca 395ppm
http://co2now.org/
http://www.omafra.gov.on.ca/english/crops/facts/00-077.htm
MG811 http://sandboxelectronics.com/?p=147
http://sandboxelectronics.com/?product=mh-z16-ndir-co2-sensor-with-i2cuart-5v3-3v-interface-for-arduinoraspeberry-pi
LCD commands:
lcd.setBacklight(LED_OFF);
lcd.noBacklight();
lcd.setBacklight(HIGH);
lcd.setBacklight(LOW);
lcd.clear();
lcd.home();
lcd.setCursor(positie, regel);
convert floats to strings:
float myFloat;
char buffer[5];
String s = dtostrf(myFloat, 1, 4, buffer);
But Serial.print() sends floats as strings too
uno has 1k EEPROM
========================================================= */
//sudo ln /dev/ttyS0 /dev/ttyACM9
/**********************************************************************
* Import needed libraries *
* LiquidCrystal_I2C is from <NAME> *
* dht library http://arduino.cc/playground/Main/DHTLib <NAME> *
* RTClib from Adafruit *
* If the library is in the sketch folder change #include <name> to *
* #include "name" *
* this tells the compiler to look in the sketch directory first. *
***********************************************************************/
//---------------------------------------
#include <Wire.h>
#include <LiquidCrystal_I2C.h> // Malpartida
#include "dht.h" // <NAME>
#include "myRTClib.h" // Modified Adafruit 56 bytes NVRAM
#include <EEPROM.h>
/*************************************************************
* Declare objects *
* RTC *
* DHT *
* LCD *
**************************************************************/
//RTC_DS1307 rtc;
RTC_DS1307 RTC; //declare object RTC
dht DHT; //declare object DHT11
/**************************************************************
* declare LCD data *
* set the LCD address to 0x27 for a 20 chars 2 line display *
* Set the pins on the I2C chip used for LCD connections: *
* addr, en,rw,rs,d4,d5,d6,d7,bl,blpol *
***************************************************************/
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address
// Mega: D20=A4 D21=SCL
/**************************************************************
* Declare pins ) *
***************************************************************/
//analogue pins
byte moisturePin = A0; // read soil moisture
byte levelPin = A1; // set level for irrigation
byte NTCPin = A2; // voor NTC if used
byte LDRPin = A3; // analog pin for LDR
//digital pins
byte humidPin = 2; // Humidity sensor
byte SwitchButton = 3; // Make Switch
byte PushButton = 4; // PushButton
byte lightPin = 5; // Switches on light
byte fanPin = 6; // Switches fan
byte pumpPin = 7; // Switches pump
byte hotPin = 8; // Switches heater
byte buzPin = 9; // Switches buzzer
byte emptyPin = 10; // digital Pin10 guards waterlevel
byte CO2Pin = 11; // Winsen MH-Z19 PWM pin 9 pin 7 =gnd
byte spikePin = 12; // Digital Pin12 ->for intermittent switching of sensor spike
byte signalPin = 13; // used for signal functions LED
/**************************************************************
* Variables *
***************************************************************/
volatile byte seconds;
byte push = 0; // contains the state of the pushbutton
byte sButton = 0; // contains the state of the throw switch
byte light; // contains the value for LDR reading
byte pump = 0; // contains the pump state
unsigned int moist = 0; // contains the soil moisture level
unsigned int irrigate = 0; // contains the set level for irrigation in case no potmeter
byte level = 0; // contains level of the waterlevel (HIGH or LOW)
int c; // contains the temperature reading
byte setLow = 19; // lage temperastuurgrens 'boven 19' >=
byte setHigh = 22; // hoge temperatuurgrens <=
int CO2ppmRead = 0; // contains CO2 reading
boolean ready_to_read = 1; // is set every 4 minutes, it begins set in order to start with a measurement imemdiately
boolean hydro = 0; // no more moisture readings but just a 6 times a day irrigation
boolean hydroPump_flag = 0; // checks if pump was set according to a hydroponics scheme or because of measurement
boolean t_flag = 0; // makes sure temp is written only once
boolean CO2Read_flag = 0; // CO2 is read (1), not read(0)
boolean tomaat = 0; // indicates tomato protocol
// de warmte tellers
unsigned long starttime = 0;
int length = 0; // running time
int lengthtotaal = 0; // total time
boolean lengthstat = false;
boolean countflag = 0; // zorgt ervoor dat er maar 1x gestart of gestopt wordt met tellen
byte warmcount = 0; // telt aantal keren dat verwarming aangaat running number
byte warmcounttotal; // total number of heat cycles
int mintemp = 100; // slaat de laagst gemeten temperatuur op
boolean lastpush = 0;
byte m = 0; // contains the minutes, refreshed each loop
byte h = 0; // contains the hours, refreshed each loop
byte s = 0; // contains the seconds, refreshed each loop
byte mo = 0; // contains the month, refreshes each loop
byte j = 0; // contains the year, refreshed each loop
byte d = 0; // contains the day (1-31)
byte dag = 0; // contains day of week (0-6)
int doy = 0; // contains day of year (1-366)
// Constants
// these constants won't change:
const int sensorMin = 40; // LDR minimum, discovered through experiment
const int sensorMax = 1012; // LDR maximum, discovered through experiment
/**
* Memory use 0-23 uren
24 bLSB van lengthtotaal
25 bMSB van lengthtotaal
26=warmcounttotal bevat het aantal keren dat de verwarming aanging in de afgelopen dag
27=warmcount telt het aantal keren dat de verwarming aanging running number
28=dst
29=LSB van running length
30=MSB van running length
25 bytes over
*/
const byte dst = 28;// moet dan maar 28 worden
byte wintertimeday = 25; // basevalue for day of wintertime start
byte summertimeday = 25; // basevalue for day of summertime start
/* Definitions */
#define DHT11_PIN humidPin // in fact a bit double
#define DS1307_I2C_ADDRESS 0x68 // each I2C object has a unique bus address, the DS1307 is 0x68
byte incomingByte = 0;
byte meten = 243; //lcd char te printen bij meten
int CO2ppmLimit = 340; // set lower CO2 value
/**************************************************************
* Macro's/Defines *
* ***********************************************************/
#define eersteRegel lcd.setCursor(0, 0)
#define tweedeRegel lcd.setCursor(0, 1)
#define pompAAN digitalWrite(pumpPin,HIGH)
#define pompUIT digitalWrite(pumpPin,LOW)
#define BAUD_RATE 115200
/*************************************************************
* ---------------- Define Special Characters-----------------*
* Create a set of new characters *
* 0=fan *
* 1=degree sign *
* 2=termometer *
* 3=waterdruppel / voor humidity *
* 4=spikes / voor soil moisture *
* 5=pump *
* 6=up arrow / reservoir vol *
* 7=down arrow / reservoir leeg *
//************************************************************/
const uint8_t charBitmap[][8] =
{
{
// fan wellicht char(248) gebruiken
B00000, // -----
B10001, // X---X
B01010, // -X-X-
B00100, // --X--
B01010, // -X-X-
B10001, // X---X
B00000, // -----
B00000 // -----
}
,
{
// degree wellicht char(223) gebruiken
B00110, // --XX-
B01001, // -X--X
B01001, // -X--X
B00110, // --XX-
B00000, // -----
B00000, // -----
B00000, // -----
B00000 // -----
// 0x6, 0x9, 0x9, 0x6, 0, 0, 0, 0
}
,
{
// termometer
B00100, // --X--
B01010, // -X-X-
B01010, // -X-X-
B01110, // -XXX-
B01110, // -XXX-
B11111, // XXXXX
B11111, // XXXXX
B01110 // -XXX-
}
,
{
// druppel
B00100, // --X--
B00100, // --X--
B01010, // -X-X-
B01010, // -X-X-
B10001, // X---X
B10001, // X---X
B10001, // X---X
B01110 // -XXX-
}
,
{
// moisture sensor
0b00100, // --X--
0b01110, // -XXX-
0b01010, // -X-X-
0b01010, // -X-X-
0b01010, // -X-X-
0b01010, // -X-X-
0b01010, // -X-X-
0b00000 // -----
}
,
{
//pomp
B01010, // -X-X-
B00100, // --X--
B00100, // --X--
B00100, // --X--
B11111, // XXXXX
B11011, // XX-XX
B11111 // XXXXX
}
,
{
// up arrow - reservoir full
0x0, 0x4, 0xE, 0x15, 0x4, 0x4, 0x4, 0x0
// -----
// --X--
// -X-X-
// X-X-X
// --X--
// --X--
// --X--
// -----
}
,
{
// down arrow - reservoir empty
0x4, 0x4, 0x4, 0x4, 0x15, 0xE, 0x4, 0x0
// -----
// --X--
// --X--
// --X--
// X-X-X
// -X-X-
// --X--
// -----
}
};
//-------- end creation--------------
void setup()
{
/************************************************************
* The timer is being set up in order to have a 4 minute *
* event in the ISR(TIMER1_COMPA_vect) routine for reading *
* of a sensor... should one wish that *
* ofcourse it is also possible to do a check on the *
* minutes dividable by 4 ( min % 4==0) *
************************************************************/
// initialize Timer1
cli(); // disable global interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
// set compare match register to desired timer count:
OCR1A = 15624;
// turn on CTC mode:
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS10);
TCCR1B |= (1 << CS12);
// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
// enable global interrupts:
sei();
//---------------end timer initialisation *
//***********************************************************
Serial.begin(BAUD_RATE);
/************************************************************
* Set up the RTC *
*************************************************************/
/*********************************************************
* Set up the in and output pins *
**********************************************************/
pinMode(levelPin, INPUT); // set level
pinMode(humidPin, INPUT); // measures humidity
pinMode(emptyPin, INPUT); // measures reservoir
pinMode(SwitchButton, INPUT); // make Switch
pinMode(PushButton, INPUT); // PushButton
pinMode(spikePin, OUTPUT); // for alternative supply to spikes
pinMode(pumpPin, OUTPUT); // Output for Relay
pinMode(fanPin, OUTPUT); // Output for fan
pinMode(hotPin, OUTPUT); // Output for heater
pinMode(lightPin, OUTPUT); // Output for light
pinMode(buzPin, OUTPUT); // Output for buzzer
digitalWrite(pumpPin, LOW); // Pump off
digitalWrite(spikePin, LOW); // moisture sensor off
digitalWrite(fanPin, LOW); // fan Off
digitalWrite(hotPin, LOW); // heater off
digitalWrite(lightPin, LOW); // light Off
digitalWrite(buzPin, LOW);
// buzzer off
/* Now LCD */
/*********************************************************
* Set up LCD *
* initialize the lcd for 16 chars 2 lines *
* load the character definitions *
* print some messages and blink the backlight *
*********************************************************/
lcd.begin(20, 4);
//upload defined characters to LCD
int charBitmapSize = (sizeof(charBitmap ) / sizeof (charBitmap[0]));
for ( int i = 0; i < charBitmapSize; i++ )
{
lcd.createChar ( i, (uint8_t *)charBitmap[i] );// zijn al geladen
}
//---------------end upload----------------
lcd.backlight();
// Print a message to the LCD.
lcd.setCursor(0, 0);// topleft
lcd.print("Greenhouse");
Serial.println("Greenhouse");
lcd.setCursor(0, 1);
//************************************************************
// Check buttons at startup *
//************************************************************
}
/*----------------------------(end setup )---------------------*/
/***************************************************************
* Main loop *
* get and print Date/time *
* Check if the reservoir is full *
* Read soil humidity *
* Switch pump *
* Read Air Humidity and temperature *
* Read light *
* Display data *
* Switch heating on or off *
* Switch fan on or off *
***************************************************************/
void loop()
{
/****************************************************
* DST *
* **************************************************/
// hbyte running warmtime
/******************************************************
* Lichtschema *
* ****************************************************/
/*******************************************************/
//-------------------------------------------end DST
if (Serial.available() > 0)
{
incomingByte = Serial.read();
switch (incomingByte)
{
case 63://?
// printLogTemp();
break;
case 108: //l
// logTemp(c);
break;
case 109: //m
Serial.print(mintemp);
break;
case 84: //T
break;
case 116: //t
break;
case 87: //W klok1 uur achteruit wintertijd
break;
case 119: // w Klok 1 uur vooruit zomertijd
break;
case 120://x
break;
default:
break;
}
}
/********************************************************************************
* Klok gelijkzet routine *
* 1- vat leeg digitalRead(emptyPin)=0; //pin10
* 2- grond vochtig >200 sample(moisturePin) A0
* 3- hydroponics mode (digitalRead(SwitchButton) == 0) //pin d3
* 4- pushbutton=+10 min digitalRead(PushButton);//d4
* *****************************************************************************/
/*********************************************************************************
*-------------3. test the DHT11 humidity/temp sensor----------------- *
**********************************************************************************/
// Serial.print("DHT11, \t");
int chk = DHT.read11(DHT11_PIN);
switch (chk)
{
case DHTLIB_OK:
// Serial.print("OK,\t");
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.print("Checksum error,\t");
break;
case DHTLIB_ERROR_TIMEOUT:
// Serial.print("Time out error,\t");
break;
default:
Serial.print("Unknown error,\t");
break;
}
/* ------------------Actions -------------------*/
/*********************************************************************************
* 5. DISPLAY DATA *
* Pushbutton not pressed: show measurements *
* Pushbutton pressed: show time *
**********************************************************************************/
// lcd.clear();
lcd.setCursor(0, 0); //set cursor left on first line (line 0)
//lcd.print(char(2)); //prints thermometer
lcd.print("Temperatuur ");
lcd.print((float)DHT.temperature, 0);
lcd.print (char(1)); // prints degree sign
lcd.print("C");
lcd.setCursor(0,1);
// lcd.print(char(3));// droplet
lcd.print("Vochtigheid ");
lcd.print((float)DHT.humidity, 0);
lcd.print("%");
/**************************************************
* now we measure temperature and air humidity * *
* and if necessary switch on heating or fan *
* temp kept at minimally 20 degrees *
* humidity is kept below 60% *
**************************************************/
// ---------------5. Action on temperature ------
c = (DHT.temperature);
if (c <= setLow)
{
// switch on heating
digitalWrite(hotPin, HIGH);
}
if (c >= setHigh)
{
digitalWrite(hotPin, LOW);
}
//--------------6. Action on Humidity -----------
if (DHT.humidity >= 60)
{
// Switch on Fan
digitalWrite(fanPin, HIGH);
// print fan-sign only if pushbutton not pressed
if(push == 1)
{
lcd.setCursor(10, 1);
lcd.print(char(0)); // fan sign
}
}
else
{
digitalWrite(fanPin, LOW);
// print fan-sign only if pushbutton not pressed
if(push == 1)
{
lcd.setCursor(10, 1);
lcd.print(' ');
}
}
//}
/**********************************************************************
* If probe loose sound alarm and switch off heating *
* ********************************************************************/
}
//------- End of Main program-----------
//
//-------- Start of functions------------
/**********************************************************************
* This function adds a leading zero on Serial port *
***********************************************************************/
void printDigits(int digits) //this adds a 0 before single digit numbers
{
//if (digits >= 0 && digits < 10) {
if (digits < 10)
{
// lcd.print('0');
Serial.print('0');
}
//lcd.print(digits);
Serial.print(digits);
}
/**********************************************************************
* This function adds a leading zero on LCD *
***********************************************************************/
void printDigitLCD(int digits) //this adds a 0 before single digit numbers
{
//if (digits >= 0 && digits < 10) {
if (digits < 10)
{
lcd.print('0');
}
lcd.print(digits);
}
/**********************************************************************
* This function converts Celsius to Fahrenheit *
***********************************************************************/
float tempConvert(float celsius)
{
float fahrenheit = 0;
fahrenheit = (1.8 * celsius) + 32;
return fahrenheit;
}
/**********************************************************************
* This is the timer interrupt function that sets a flag every 4 min *
***********************************************************************/
ISR(TIMER1_COMPA_vect)
{
seconds++;
if(seconds == 240)
{
seconds = 0;
// leest elke 240 seconden (4 minuten) een sensor
// readSensor();
// moist=sample(moisturePin); //read soil humiditySensor
// of kies ervoor een flag te zetten
ready_to_read = 1;
}
}
/**********************************************************************
* This function calculates dewpoint *
***********************************************************************/
double dewPointFast(double celsius, double humidity)
{
double a = 17.271;
double b = 237.7;
double temp = (a * celsius) / (b + celsius) + log(humidity / 100);
double Td = (b * temp) / (a - temp);
return Td;
}
//===========================================================================
/**********************************************************************
* These are various other user defined symbols *
***********************************************************************
/*
//icon for solar panel
{
0b11111,0b10101,0b11111,0b10101,0b11111,0b10101,0b11111,0b00000
};
//icon for battery
{
0b01110,0b11011,0b10001,0b10001,0b10001,0b10001,0b10001,0b11111
};
// icon for power
{
0b00010,0b00100,0b01000,0b11111,0b00010,0b00100,0b01000,0b00000
};
// icon for alarm
{
0b00000,0b00100,0b01110,0b01110,0b01110,0b11111,0b00000,0b00100
};
//icon for termometer
{
0b00100,0b01010,0b01010,0b01110,0b01110,0b11111,0b11111,0b01110
};
// icon for battery charge
{
0b01010,0b11111,0b10001,0b10001,0b10001,0b01110,0b00100,0b00100,
};
// icon for not charge
{
0b00000,0b10001,0b01010,0b00100,0b01010,0b10001,0b00000,0b00000,
};
//---------------------------------------
byte customChar[8] = {
0b00100, // --X--
0b01110, // -XXX-
0b01010, // -X-X-
0b01010, // -X-X-
0b01010, // -X-X-
0b01010, // -X-X-
0b01010, // -X-X-
0b00000 // -----
};
//--------------------------------------------------------------
*/
int CO2ppm()
/*********************************
* <NAME> *
* ppm=2000*(Th-2)/(TH+TL-4) *
* TH+TL=1000 *
* *******************************/
{
int ppm = pulseIn(CO2Pin, HIGH);
ppm = (2 * (ppm - 2));
return ppm;
}
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return( (val / 10 * 16) + (val % 10) );
}
// Combine 2 bytes into an integer
int bytesToInteger(byte lsb, byte msb)
{
return (msb << 8 | lsb);
}
<file_sep>/Broeikas2.1.ino
/* =======================================================
meet de vochtigheid
als minder dan ingestelde waarde, pomp aan
meet temperatuur
als lager dan ingestelde waarde, verwarming aan
meet humidity
als hoger dan ingestelde waarde zet ventilator aan
ventilator ook aan snachts
http://www.quickgrow.com/gardening_articles/fans_air_movement.html
LCD commands:
lcd.setBacklight(LED_OFF);
lcd.noBacklight();
lcd.setBacklight(HIGH);
lcd.setBacklight(LOW);
lcd.clear();
lcd.home();
lcd.setCursor(positie, regel);
convert floats to strings:
float myFloat;
char buffer[5];
String s = dtostrf(myFloat, 1, 4, buffer);
But Serial.print() sends floats as strings too
========================================================= */
/*
abbreviations
*/
/**********************************************************************
* Import needed libraries *
* LiquidCrystal_I2C is from <NAME> *
* dht library http://arduino.cc/playground/Main/DHTLib <NAME> *
* RTClib from Adafruit *
* If the library is in the sketch folder change #include <name> to *
* #include "name" *
* this tells the compiler to look in the sketch directory first. *
***********************************************************************/
//---------------------------------------
#include <Wire.h>
#include <LiquidCrystal_I2C.h> //Malpertida
#include <dht.h>
#include "RTClib.h" //Adafruit
/*************************************************************
* Declare objects *
* RTC *
* DHT *
* LCD *
**************************************************************/
//RTC_DS1307 rtc;
RTC_DS1307 RTC; //declare object RTC
dht DHT; //declare object DHT11
//*************************************************************
// ------ ( declare LCD data)------------------------- *
// set the LCD address to 0x27 for a 20 chars 4 line display *
// Set the pins on the I2C chip used for LCD connections: *
// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol *
//*************************************************************
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address
//
/*-----( Declare pins )------*/
//analogue pins
byte moisturePin=0; //read soil moisture
byte LDRPin=3;// analog pin for LDR
//digital pins
byte levelPin= 1; //set level for irrigation
byte humidPin=2; //Humidity sensor
byte lightPin=5; //Switches on light
byte fanPin=6; //Switches fan
byte pumpPin =7; //Switches pump
byte hotPin= 8; //Switches heater
byte buzPin=9; //Switches buzzer
byte emptyPin=10; //digital Pin10 guards waterlevel
byte spikePin=12; //Digital Pin12 ->for intermittent switching of spike
byte PushButton=4; // PushButton
byte SwitchButton=3;// Make Switch
#define DHT11_PIN humidPin // in fact a bit double
#define DS1307_I2C_ADDRESS 0x68 // each I2C object has a unique bus address, the DS1307 is 0x68
/* Variable setting */
// variables -placeholders for various readings
volatile byte seconds;
byte push=0; // contains the state of the pushbutton
byte sButton=0; // contains the state of the throw switch
byte light; // contains the value for LDR reading
byte pump=0; // contains the pump state
unsigned int moist=0; // contains the soil moisture level
unsigned int irrigate=0; // contains the set level for irrigation in case no potmeter
byte level=0; // contains level of the waterlevel (HIGH or LOW)
int c; // contains the temperature reading
boolean ready_to_read=1; // is set every 4 minutes
// Constants
// these constants won't change:
const int sensorMin = 40; // LDR minimum, discovered through experiment
const int sensorMax = 1012; // LDR maximum, discovered through experiment
//************************************************************
//---------------- Define Special Characters-----------------*
// Create a set of new characters *
// 0=fan *
// 1=degree sign *
// 2=termometer *
// 3=waterdruppel *
// 4=spikes *
// 5=pump *
// 6=up arrow *
// 7=down arrow *
//************************************************************
const uint8_t charBitmap[][8] = {
{
B00000,
B10001,
B01010,
B00100,
B01010,
B10001,
B00000,
B00000 }
,
{
0x6, 0x9, 0x9, 0x6, 0, 0, 0, 0 }
,
{
B00100,
B01010,
B01010,
B01110,
B01110,
B11111,
B11111,
B01110 }
,
{
B00100,
B00100,
B01010,
B01010,
B10001,
B10001,
B10001,
B01110 }
,
{
B10001,
B10001,
B11111,
B10001,
B10001,
B10001,
B10001,
B10001 }
,
{
B01010,
B00100,
B00100,
B00100,
B11111,
B11111,
B11111 }
,
{
0x0, 0x4, 0xE, 0x15, 0x4, 0x4, 0x4, 0x0 }
,
{
0x4,0x4,0x4, 0x4, 0x15, 0xE,0x4,0x0 }
};
/// -------- end creation--------------
//The following function, "setup", must always be present
void setup()
{
/* **********************************************************
** The timer is being set up in order to have a 4 minute *
** event in the ISR(TIMER1_COMPA_vect) routine for reading *
** of a sensor... should one wish that *
************************************************************/
// initialize Timer1
cli(); // disable global interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
// set compare match register to desired timer count:
OCR1A = 15624;
// turn on CTC mode:
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS10);
TCCR1B |= (1 << CS12);
// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
// enable global interrupts:
sei();
//---------------end timer initialisation *
//***********************************************************
Serial.begin(115200);
//***********************************************************
// Set up the RTC *
//***********************************************************
#ifdef AVR
Wire.begin();
#else
Wire1.begin(); // Shield I2C pins connect to alt I2C bus on Arduino Due
#endif
RTC.begin(); // Start RTC
/*
if (! rtc.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// This line sets the RTC with an explicit date & time, for example to set
// January 21, 2014 at 3am you would call:
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}
*/
//above code replaced by:
DateTime now = RTC.now();
DateTime compiled = DateTime(__DATE__, __TIME__);
if (now.unixtime() < compiled.unixtime()) {
Serial.println("RTC is older than compile time! Updating");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
//----Set sqw to 1 Hz---
// no practical function yet
Wire.beginTransmission(0x68);
Wire.write(0x07); //move pointer to SQW address
Wire.write(0x10); // sends 0×10 (hex) 00010000 (binary)
Wire.endTransmission();
//---end sqw-----
//*********************************************************
// Set up the in and output pins *
//*********************************************************
pinMode(levelPin,INPUT); // set level
pinMode(humidPin,INPUT); // measures humidity
pinMode(emptyPin,INPUT); // measures reservoir
pinMode(SwitchButton, INPUT); // make Switch
pinMode(PushButton, INPUT); // PushButton
pinMode(spikePin,OUTPUT); // for alternative supply to spikes
pinMode(pumpPin,OUTPUT); // Output for Relay
pinMode(fanPin, OUTPUT); // Output for fan
pinMode(hotPin, OUTPUT); // Output for heater
pinMode(lightPin, OUTPUT);// Output for light
pinMode(buzPin, OUTPUT); // Output for buzzer
digitalWrite(pumpPin, LOW);// Pump off
digitalWrite(spikePin, LOW);// moisture sensor off
digitalWrite(fanPin,LOW); // fan Off
digitalWrite(hotPin,LOW); // heater off
digitalWrite(lightPin, LOW); // light Off
digitalWrite(buzPin, LOW); // buzzer off
/* Now LCD */
//********************************************************
//---------------Set up LCD *
// initialize the lcd for 16 chars 2 lines *
// load the character definitions *
// print some messages and blink the backlight *
//********************************************************
lcd.begin(16,2);
//upload defined characters to LCD
int charBitmapSize = (sizeof(charBitmap ) / sizeof (charBitmap[0]));
for ( int i = 0; i < charBitmapSize; i++ )
{
lcd.createChar ( i, (uint8_t *)charBitmap[i] );
}
//---------------end upload----------------
lcd.backlight();
// Print a message to the LCD.
lcd.setCursor(0, 0);// topleft
lcd.print("Greenhouse");
// ------- Quick 2 blinks of backlight -------------
flash(2);
// ------- Quick buzz--------------------------------
// buzz(1);
//************************************************************
// Start RTC *
//************************************************************
Wire.begin(); //needed for RTC, not for LCD
RTC.begin();
/* Set the date / time to the time this program was compiled.
Comment this OUT, AND upload, to let the clock just run. */
// RTC.adjust(DateTime(__DATE__, __TIME__));
RTC.writeSqwPinMode(SquareWave1HZ);// double?
//************************************************************
// Check buttons at startup *
//************************************************************
if(digitalRead(PushButton)==0){
buzz(3);
}
}
/*----------------------------(end setup )---------------------*/
/* *************************************************************
* Main loop *
* get and print Date/time *
* Check if the reservoir is full *
* Read soil humidity *
* Switch pump *
* Read Air Humidity and temperature *
* Read light *
* Display data *
* Switch heating on or off *
* Switch fan on or off *
***************************************************************/
void loop()
{
DateTime now = RTC.now(); //Get the current data
Serial.print(now.day(), DEC);
Serial.print("-");
Serial.print(now.month(), DEC);
Serial.print("-");
Serial.print(now.year(), DEC);
Serial.print(" ");
Serial.print(now.hour(), DEC);
Serial.print(':');
if (now.minute()<10)
{
Serial.print("0");
}
Serial.print(now.minute(), DEC);
Serial.print(':');
//Serial.print(now.second(), DEC);
if (now.second()<10)
{
Serial.print("0");
}
Serial.println(now.second(), DEC);
//------------end of RTC
/********************************************************************************
* ---------- 1. Check if there is enough water ------------- *
* check if there is water *
* if not sound the buzzer *
* later in the program the pump will be disabled if water level too low *
*********************************************************************************/
level= digitalRead(emptyPin);//Switch closed = empty
if (level==0) {
digitalWrite(buzPin, HIGH);
delay (50);
digitalWrite(buzPin, LOW);
delay(500);
}
/*********************************************************************************
* ------------2. Read the soil moisture content/switch pump---------------- *
* First read the level set with P1 on the levelPin and store that in 'irrigate' *
* Then we read the soil humidity sensor. *
* We'll first have to set the spikePin to HIGH, in case that is used to feed *
* the sensor. After the reading we set it back) *
* If the value read ('moist') is smaller than what is considered dry ('irrigate')*
* then the pump should be switched on for a specific time. *
* This is done by indicating a higher treshhold for switching the pump off *
* Could be made conditional by testing the ready_to_read boolean *
* that is set every 4 minutes in order to spare the spikes *
* *
**********************************************************************************/
irrigate=sample(levelPin);
digitalWrite(spikePin, HIGH);// put voltage on the humidity sensor
delay(100); //wait a short while
moist=sample(moisturePin); //read soil humiditySensor
//
digitalWrite(spikePin, LOW);
if (moist <= irrigate){
pump=1;
digitalWrite(pumpPin, level); // if the reservoir is empty a 0 will be written
}
if (moist >= irrigate+5) {
pump=0;
digitalWrite(pumpPin, LOW); // prevents Jitter
ready_to_read=0; // needed to read onece every 4 min
}
/*********************************************************************************
*-------------3. test the DHT11 humidity/temp sensor----------------- *
**********************************************************************************/
// Serial.print("DHT11, \t");
int chk = DHT.read11(DHT11_PIN);
switch (chk)
{
case DHTLIB_OK:
// Serial.print("OK,\t");
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.print("Checksum error,\t");
break;
case DHTLIB_ERROR_TIMEOUT:
// Serial.print("Time out error,\t");
break;
default:
Serial.print("Unknown error,\t");
break;
}
/*********************************************************************************
*-------------4. Read LDR ---------------------------------------- *
* no actions for the time being, but can be used to e.g. only irrigate at night *
* or to add artificial light to the day *
**********************************************************************************/
light=Map(LDRPin);
/* ------------------Actions -------------------*/
/*********************************************************************************
*-------------5. DISPLAY DATA ------------------------------------ *
**********************************************************************************/
// Serial.print(DHT.humidity,1);
// Serial.print(",\t \t");
//Serial.println(DHT.temperature,0);
/* Display data on LCD */
push=digitalRead(PushButton);
if (push==1) // pushbutton not pressed
{
lcd.clear();
lcd.setCursor(0, 0); //set cursor left on first line (line 0)
lcd.print(char(2)); //prints thermometer
lcd.print(" ");
lcd.print((float)DHT.temperature, 0);
lcd.print (char(1)); // prints degree sign
lcd.print("C");
lcd.print(" ");
lcd.print(char(3));// droplet
lcd.print(" ");
lcd.print((float)DHT.humidity, 0);
lcd.print("%");
lcd.print(" ");
lcd.print (char(7-level));//prints up or down arrow (char 7 or 6)
if(level+pump==2){
lcd.print(" ");
lcd.print(char(5));
}
else {
lcd.print(" ");
}
lcd.setCursor(0,1);// set cursor left on line 1 (=2nd line)
lcd.print(char(4)); // spikes
lcd.print(" ");
lcd.print(moist);
lcd.print("/");
lcd.print(irrigate);
// lcd.print("=>");
// lcd.print((float)moist/irrigate);//integer kan contain no fraction so use the cast-operator to make it float
}
if (push==0) // pushbutton pressed
{
lcd.clear();
lcd.setCursor(0,0);//topleft
//--------------
DateTime now = RTC.now();
lcd.print(now.day(), DEC);
lcd.print('-');
lcd.print(now.month(), DEC);
lcd.print('-');
lcd.print(now.year(), DEC);
lcd.print(" ");
lcd.print(now.hour(), DEC);
lcd.print(':');
if (now.minute()<10)
{
lcd.print("0");
}
lcd.print(now.minute(), DEC);
/* geen seconden
lcd.print(':');
if (now.second()<10)
{
lcd.print("0");
}
lcd.print(now.second(), DEC);
//---end no secs
*/
//---end rtc
//-----------
// lcd.print(" ");
lcd.setCursor(0,1);
lcd.print("licht niv.: ");
lcd.print(analogRead(LDRPin));
//buzz(1);
}
/**************************************************
* now we measure temperature and air humidity * *
* and if necessary switch on heating or fan *
* temp kept at minimally 20 degrees *
* humidity is kept below 60% *
**************************************************/
// ---------------5. Action on temperature ------
c=(DHT.temperature);
// Serial.println(c);
if (c<=19)
//Serial.println(c);
{// switch on heating
digitalWrite(hotPin,HIGH);
}
else
{
digitalWrite(hotPin,LOW);
}
//--------------6. Action on Humidity -----------
if (DHT.humidity >=60)
{
// zet ventilator aan
digitalWrite(fanPin, HIGH);
// print fan-sign only if pushbutton not pressed
if(push==1){
lcd.setCursor(10,1);
lcd.print(char(0)); // fan sign
}
}
else
{
digitalWrite(fanPin,LOW);
// print fan-sign only if pushbutton not pressed
if(push==1){
lcd.setCursor(10,1);
lcd.print(' ');
}
}
delay(500);
//end dht
//end loop
}
//------- End of Main program-----------
//
//-------- Start of functions------------
int sample(int z)
/**********************************************************************
* This function will read the Pin 'z' 5 times and take an average. *
* Afterwards it will be mapped to 8 bits by dividing by 4 *
* Could ofcourse immediately divided by 20 *
***********************************************************************/
{
byte i;
int sval = 0;
for (i = 0; i < 5; i++){
sval = sval + analogRead(z);// sensor on analog pin 'z'
}
//sval = sval / 5; // average
//sval = sval / 4; // scale to 8 bits (0 - 255)
sval=sval / 20;
return sval;
}
/**********************************************************************
* This function willflash the backlight a number of times *
***********************************************************************/
void flash(byte y)
{
byte j;
for (j=0; j<y;j++)
{
lcd.backlight();
delay(250);
lcd.noBacklight();
delay(250);
}
lcd.backlight(); // finish with backlight on
return;
}
/**********************************************************************
* This function will sound the buzzer "u" times *
***********************************************************************/
void buzz(byte u)
{
byte k;
for (k=0; k<u;k++)
{
digitalWrite(buzPin, HIGH);
delay(200);
digitalWrite(buzPin, LOW);
delay(200);
}
return;
}
/****************************************************************************
* This function will blink an LED a number of times for a specific duration *
*****************************************************************************/
void ledblink(int times, int lengthms, int pinnum){
for (int x=0; x<times;x++){
digitalWrite(pinnum, HIGH);
delay (lengthms);
digitalWrite(pinnum, LOW);
delay(lengthms);
}
}
/**********************************************************************
* This function maps the LDR reading into nrs 0-3 *
***********************************************************************/
int Map(byte sens) {
// read the sensor:
int sensorReading = analogRead(sens);
// map the sensor range to a range of four options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 3);
// do something different depending on the
// range value:
switch (range) {
case 0: //
// Serial.println("dark");
// lcd.backlight();
break;
case 1: //
// Serial.println("dim");
// lcd.backlight();
break;
case 2: //
// Serial.println("medium");
// lcd.noBacklight();
break;
case 3: //
// Serial.println("bright");
// lcd.noBacklight();
break;
}
return range;
}
/**********************************************************************
* This function adds a leading zero *
***********************************************************************/
void printDigits(int digits) { //this adds a 0 before single digit numbers
//if (digits >= 0 && digits < 10) {
if (digits <10) {
lcd.print('0');
Serial.print('0');
}
lcd.print(digits);
Serial.print(digits);
}
/**********************************************************************
* This function converts Celsius to Fahrenheit *
***********************************************************************/
float tempConvert(float celsius)
{
float fahrenheit = 0;
fahrenheit = (1.8 * celsius) + 32;
return fahrenheit;
}
/**********************************************************************
* This function writes bytes to RTC non volatile RAM *
***********************************************************************/
byte nvrWrite(byte a,byte lstat){
a=a+7;
Wire.beginTransmission(0x68);
Wire.write(a); // move pointer to RAM address
Wire.write(lstat);// send 1
Wire.endTransmission();
}
/**********************************************************************
* This function reads bytes from RTC non volatile RAM *
***********************************************************************/
byte nvrLees(byte a){
a=a+7;
byte lstat;
Wire.beginTransmission(0x68);
Wire.write(a); // move pointer to RAM address
Wire.endTransmission();
Wire.requestFrom(0x68,1);
lstat=Wire.read();
//Serial.println(lstat);
return lstat;
}
/**********************************************************************
* This is the timer interrupt function that sets a flag every 4 min *
***********************************************************************/
ISR(TIMER1_COMPA_vect)
{
seconds++;
if(seconds == 240)
{
seconds = 0;
// leest elke 240 seconden (4 minuten) een sensor
//readSensor();
moist=sample(moisturePin); //read soil humiditySensor
// of kies ervoor een flag te zetten
ready_to_read=1;
}
}
/**********************************************************************
* This function calculates dewpoint *
***********************************************************************/
double dewPointFast(double celsius, double humidity)
{
double a = 17.271;
double b = 237.7;
double temp = (a * celsius) / (b + celsius) + log(humidity/100);
double Td = (b * temp) / (a - temp);
return Td;
}
/**********************************************************************
* These are various other user defined symbols *
***********************************************************************
/*
//icon for solar panel
{
0b11111,0b10101,0b11111,0b10101,0b11111,0b10101,0b11111,0b00000
};
//icon for battery
{
0b01110,0b11011,0b10001,0b10001,0b10001,0b10001,0b10001,0b11111
};
// icon for power
{
0b00010,0b00100,0b01000,0b11111,0b00010,0b00100,0b01000,0b00000
};
// icon for alarm
{
0b00000,0b00100,0b01110,0b01110,0b01110,0b11111,0b00000,0b00100
};
//icon for termometer
{
0b00100,0b01010,0b01010,0b01110,0b01110,0b11111,0b11111,0b01110
};
// icon for battery charge
{
0b01010,0b11111,0b10001,0b10001,0b10001,0b01110,0b00100,0b00100,
};
// icon for not charge
{
0b00000,0b10001,0b01010,0b00100,0b01010,0b10001,0b00000,0b00000,
};
*/
<file_sep>/README.md
Greenhouse
==========
Arduino code for a greenhouse
| 981effd992d44e9f5efea312b804e2e218047eb4 | [
"Markdown",
"C++"
] | 3 | C++ | consolacion/Greenhouse | 84b412d402d1b05b6b825d5c7aa2bbf8ba59899d | 9e507fb36d74b960cc218ca177232f560eb7291c |
refs/heads/master | <repo_name>Natalia21/wp_test_plugin<file_sep>/natasha_test_plugin.php
<?php
/*
Plugin Name: Natasha test plugin
Plugin URI: http://www.yourpluginurlhere.com/
Description: testing how to create wp plugins
Version: 0.1
Author: Natasha
*/
define('MSP_HELLOWORLD_DIR', plugin_dir_path(__FILE__));
define('MSP_HELLOWORLD_URL', plugin_dir_url(__FILE__));
function show_form () {
if ( isset($_POST['number']) ) {
if ( $_POST['number'] < 10 ) {
$color = 'red';
} else {
$color = 'green';
}
echo '
<style>
.entry-title {
color:' . $color . '!important;
}
</style>
';
}
echo file_get_contents(MSP_HELLOWORLD_URL . "views/form.php");
}
function add_css() {
wp_register_style( 'natashaPluginStylesheet', plugins_url('assets/css/natasha_test_plugin.css', __FILE__) );
wp_enqueue_style( 'natashaPluginStylesheet' );
}
add_css();
add_shortcode('natasha_plugin_form', 'show_form');
?><file_sep>/views/form.php
<?php ?>
<div>
<div>
<form action='' method='post' class="test_form">
<div>
<label> Enter any number </label>
<input type='number' name='number'/>
</div>
<button> Submit </button>
</form>
</div>
<div class="display">
</div>
</div>
| 540e0898953d6a3735dc1bcd301d8fdba1c8615a | [
"PHP"
] | 2 | PHP | Natalia21/wp_test_plugin | 309f2b46b5c15489f8cb64653e62c97d482c9528 | 63cfd3184135295d6e47300f4355ba7a9830a31e |
refs/heads/master | <repo_name>donaldb/twitterfeed<file_sep>/app.rb
require 'sinatra'
require 'twitter'
helpers do
def twitter
@twitter ||= Twitter::REST::Client.new do |config|
config.consumer_key = ENV.fetch("TWITTER_CONSUMER_KEY")
config.consumer_secret = ENV.fetch("TWITTER_CONSUMER_SECRET")
end
end
end
get "/tweets.css" do
content_type "text/css"
code =
"@media only screen and (-webkit-min-device-pixel-ratio: 0), (min--moz-device-pixel-ratio: 0), (min-width:0\\0) {
.tweet .copy:before {
white-space: pre-wrap;
}
<% tweets = twitter.search(ENV.fetch(\"TWITTER_SEARCH_STRING\")) %>
<% tweets.take(15).map.with_index do |tweet, i| %>
#<%= \"tweet\" %>-<%=i+1%> .copy::before { content: \"<%= tweet.text %>\" ;
}
#<%= \"tweet\" %>-<%=i+1%> .avatar { background: url(\"<%= tweet.user.profile_image_url %>\") ;
}
#<%= \"tweet\" %>-<%=i+1%> .name::before { content: \"<%= tweet.user.name %>\" ;
}
#<%= \"tweet\" %>-<%=i+1%> .handle::after { content: \"@<%= tweet.user.screen_name %>\" ;
}
#<%= \"tweet\" %>-<%=i+1%> .timestamp::after { content: \"<%= tweet.created_at %>\" ;
}
<% end %>
}"
erb code
end
| f8e2333ee1cf9fa509c88de233ed6f0045f792af | [
"Ruby"
] | 1 | Ruby | donaldb/twitterfeed | 3f47a128265f5411501f5c30debbc56c2f4ae3ad | 610fec579ffadf8f4f9707f929885aef853308fb |
refs/heads/master | <repo_name>qibinjin/Django_blog_0.1<file_sep>/article/migrations/0003_comment_article_id.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('article', '0002_comment'),
]
operations = [
migrations.AddField(
model_name='comment',
name='article_id',
field=models.ForeignKey(to='article.Article', default=-1),
preserve_default=False,
),
]
<file_sep>/article/models.py
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
category = models.CharField(max_length=50, blank=True)
date_time = models.DateTimeField(auto_now_add=True)
content = models.TextField(blank=True, null=True)
def __str__(self):
return self.title
class Meta(object):
ordering = ['-date_time']
class Comment(models.Model):
author = models.CharField(max_length=30)
content = models.TextField(blank=True, null=True)
date_time = models.DateTimeField(auto_now_add=True)
article_id = models.ForeignKey(Article)
def __str__(self):
return self.author
class Meta(object):
ordering = ['date_time']
class User(models.Model):
username = models.CharField(max_length=20)
password = models.CharField(max_length=30)
birth_date = models.DateField(blank=True)
<file_sep>/article/views.py
from django.shortcuts import render, redirect
from article.models import Article, Comment, User
from django.contrib.auth.models import User as Admin, Group
from django.http import Http404, HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.contenttypes.models import ContentType
import re
# Create your views here.
def home(request):
user = request.user
if user.is_authenticated():
post_list = Article.objects.all()[:2]
return render(request, "home.html", {'post_list': post_list, 'username': user})
else:
post_list = Article.objects.all()[:2]
return render(request, "home.html", {'post_list': post_list})
def detail(request, id):
user=request.user
if user.is_authenticated():
if request.method == 'POST':
if re.match(r'<p><br></p>', request.POST['text2']):
return HttpResponse("<script>alert('评论框为空');window.location.href='/%s'</script>" % id)
Comment.objects.create(author=user, content=request.POST['text2'],
article_id=Article.objects.get(id=str(id)))
return redirect('/%s' % id)
else:
try:
post = Article.objects.get(id=str(id))
comment_list = Comment.objects.filter(article_id=str(id))
except Article.DoesNotExist:
raise Http404
return render(request, 'post_with_comment.html', {'post': post, 'comment_list': comment_list, 'username': user})
else:
try:
post = Article.objects.get(id=str(id))
comment_list = Comment.objects.filter(article_id=str(id))
except Article.DoesNotExist:
raise Http404
return render(request, 'post_without_comment.html', {'post': post, 'comment_list': comment_list})
def pages(request):
user = request.user
if user.is_authenticated():
post_list = Article.objects.all()
return render(request, "home.html", {'post_list': post_list, 'username': user})
else:
post_list = Article.objects.all()
return render(request, "home.html", {'post_list': post_list})
def log(request):
if request.method == 'POST':
user = authenticate(username=request.POST['username'], password=request.POST['<PASSWORD>'])
if user is not None:
# 用户通过验证
if user.is_active:
login(request, user)
return HttpResponse("<script>alert('登陆成功');window.location.href='/';</script>")
else:
return HttpResponse("<script>alert('用户名或密码无效,请重新登陆');\
window.history.back();</script>")
else:
return HttpResponse("<script>alert('用户名或密码无效,请重新登陆');window.history.back()</script>")
def user_info(request):
user = request.user
if user.is_authenticated():
return render(request, 'user_info.html',{'username': user, 'last_name':user.last_name, 'first_name': user.first_name, 'email': user.email})
else:
pass
def log_out(request):
user = request.user
if user.is_authenticated():
logout(request)
return HttpResponse("<script>alert('登出成功');window.history.back();</script>")
else:
return HttpResponse("<script>alert('登出成功');window.history.back();</script>")
def regist(request):
user = request.user
if user.is_authenticated():
return HttpResponse("<script>alert('请先退出登陆状态');window.history.back();</script>")
else:
if request.method == 'POST':
try:
user = Admin.objects.create_user(request.POST['username'], request.POST['email_add'],
request.POST['passwd'], first_name=request.POST['first_name'],
last_name=request.POST['last_name'])
user.save()
normal_group = Group.objects.all()[0]
print(normal_group)
user.groups.add(normal_group)
# content_type = ContentType.objects.get_for_model(Comment)
# permission = Permission.objects.create(
# codename='can_publish',
# name='Can Publish Posts',
# content_type=content_type,
# )
except Exception as e:
print(e)
return HttpResponse("<script>alert('用户名已存在');window.location.href='/regist';</script>")
else:
return HttpResponse("<script>alert('注册成功');window.location.href='/accounts/login/';</script>")
else:
return render(request, 'regist.html')
def date(request, date):
article_list = Article.objects.filter(date_time__startswith=date.split(' ')[0])
return render(request,'home.html', {'post_list':article_list})
<file_sep>/README.md
# Django_Blog_project_0.1
## Web front-end:pure templates
## FrameWork:Django
## editor:wangeditor
| 9bf9fb454f0d8622b073010f1db82b995ed0c83d | [
"Markdown",
"Python"
] | 4 | Python | qibinjin/Django_blog_0.1 | 7a213d9726489897098f880ed3fb21a7db479420 | b56cfde92b145f4441c45a220714d86f52e210a7 |
refs/heads/master | <repo_name>LinziYuann/CV-loss-functions-and-designs<file_sep>/dynamic_filter_pytorch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
## refer: Dynamic filter networks - theano implementation
class DynamicFilter(nn.Module):
def __init__(self, Cin, k_size=3):
super(DynamicFilter, self).__init__()
self.k_size = k_size
# define filter_geneM for filter computation
self.filter_geneM = torch.nn.Sequential(
nn.Conv2d(Cin, 32, kernel_size=5, stride=1, padding=2),
nn.LeakyReLU(negative_slope=0.1, inplace=False),
nn.Conv2d(32, self.k_size*self.k_size, kernel_size=5, stride=1, padding=2))
def forward(self, tensorInput):
image = tensorInput[0]
refer = tensorInput[1]
tensorIn = torch.cat([image, refer], dim=1)
filters = self.filter_geneM(tensorIn) # filters (B, k_size*k_size, H, W)
filter_size = filters.size()
filter_localexpand_np = np.reshape(np.eye(np.prod(filter_size), np.prod(filter_size)), (np.prod(filter_size), filter_size[2], filter_size[0], filter_size[1]))
filter_localexpand = torch.from_numpy(filter_localexpand_np).float()
input_localexpanded = F.conv2d(image, filter_localexpand, padding=1)
output = input_localexpanded * filters
output = torch.sum(output, dim=1, keepdim=True)
return output
<file_sep>/README.md
# CV-loss-functions | 681d0df3fc0fbb037d88f81df7236c049066c0f1 | [
"Markdown",
"Python"
] | 2 | Python | LinziYuann/CV-loss-functions-and-designs | 7a6674d61aa3c30095b2aa18ac03dcd9240b6695 | ac497735350fe86c4f187e8d5254c2d23f14676a |
refs/heads/master | <file_sep>#region license
// Copyright (c) 2016, Wm. <NAME>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ProjectRoller
{
class Program
{
static int Main(string[] args)
{
if (args.Length == 0 || (args[0] != "v1" && args[0] != "v2"))
{
Usage();
return -1;
}
ValidateArgs(args);
CodePuller cp = new CodePuller();
cp.GetCode(args[0], args[1]);
return 0;
}
static void ValidateArgs(string[] arg)
{
if (arg[1].Contains(' '))
throw new ArgumentException("Project cannot contain spaces");
}
static void Usage()
{
Console.WriteLine("Usage: ProjectRoller <v1|v2> <ProjectName>");
Console.WriteLine("Example: ProjectRoller v1 MyCoolProject");
}
}
}
<file_sep> ProjectRoller
Use this to create an ASP NET MVC EF Unity project from this project base: [BaseAspNetAngularUnity](http://wbsimms.github.io/BaseAspNetAngularUnity)
The base project has alot of opinionated stuff in it. You can find out more about the base project at
Version 1: [BaseAspNetAngularUnity](http://wbsimms.github.io/BaseAspNetAngularUnity)
Version 2: [CoreAspNetAngular](http://github.com/wbsimms/CoreAspNetAngular)
Specify V1 or V2 for the desired version.
```
Usage: ProjectRoller <v1|v2> <ProjectName>
Example: ProjectRoller v1 MyCoolProject
<file_sep>#region license
// Copyright (c) 2016, Wm. <NAME>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using LibGit2Sharp;
namespace ProjectRoller
{
public class CodePuller
{
private string baseName, baseNameV1 = "BaseAspNetAngularUnity";
private string baseNameV2 = "CoreAspNetAngular";
public CodePuller()
{
}
public string GetCode(string version, string projectName)
{
if (Directory.Exists(projectName))
{
throw new ArgumentException("Directory : " + projectName + " exists. You must delete the directory");
}
Directory.CreateDirectory(projectName);
var repo = "https://github.com/wbsimms/BaseAspNetAngularUnity.git";
baseName = baseNameV1;
if (version == "v2")
{
repo = "https://github.com/wbsimms/CoreAspNetAngular.git";
baseName = baseNameV2;
}
var retval = Repository.Clone(repo, projectName);
try
{
Directory.Delete(projectName + "/.git", true);
}
catch {}
RenameDirectories(projectName);
RenameFiles(projectName);
RewriteFiles(projectName);
return retval;
}
private void RenameDirectories(string projectName)
{
var directories = Directory.GetDirectories(projectName,"*",SearchOption.AllDirectories);
foreach (var directory in directories)
{
if (directory.Contains(".git")) continue;
if (directory.Contains(baseName))
{
string newName = directory.Replace(baseName, projectName);
if (!Directory.Exists(newName))
Directory.Move(directory,newName);
}
}
}
public void RenameFiles(string projectName)
{
string[] files = Directory.GetFiles(projectName, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
if (file.Contains(".git")) continue;
if (file.Contains(baseName))
{
string newFileName = file.Replace(baseName, projectName);
File.Move(file,newFileName);
}
}
}
public void RewriteFiles(string projectName)
{
string[] files = Directory.GetFiles(projectName, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
if (file.Contains(".git") || Path.GetExtension(file) == ".exe") continue;
File.WriteAllText(file,File.ReadAllText(file).Replace(baseName,projectName));
}
}
}
}
<file_sep>#region license
// Copyright (c) 2016, Wm. <NAME>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#endregion
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ProjectRoller.Test
{
[TestClass]
public class CodePullerTest
{
[TestMethod]
public void ConstructorTest()
{
CodePuller cp = new CodePuller();
Assert.IsNotNull(cp);
}
[TestMethod]
public void GetCodeTest()
{
CodePuller cp = new CodePuller();
cp.GetCode("v1","test1");
}
}
}
| 92918d574d3d7c28e9531ea3b1ed3a04943eef79 | [
"Markdown",
"C#"
] | 4 | C# | wbsimms/ProjectRoller | 79d5fb6ca201784ec288634f98fefb5cd40b66ae | 95e0670c39d37dc1c89bd4eb038ab7c90fb5585d |
refs/heads/main | <repo_name>parth-shettiwar/CS347-Operating-Systems<file_sep>/170070021-lab1/170070021-lab1/p_3.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include <sys/wait.h>
int main()
{
int r1;
r1 = fork();
if(r1!=0)
{
wait(NULL);
}
if(r1==0)
{
char *args[] = {NULL};
execv("./runme",args);
}
return 0;
}
<file_sep>/170070021-lab1/170070021-lab1/p_5.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include <sys/wait.h>
#include<fcntl.h>
#include <sys/types.h>
#include <string.h>
int main(int argc,char **argv)
{
int r1,b;
close(0);
b = open(argv[1],O_RDWR|O_CREAT);
r1 = fork();
if(r1!=0)
{
wait(NULL);
}
if(r1==0)
{
char *args[] = {NULL};
execv("./sample",args);
}
return 0;
} <file_sep>/170070021-lab3/lab3/Barrier.c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int a,left;
void *critical_section(int i);
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
printf("Number of Threads:");
int num;
scanf("%d",&num);
printf("\n");
left = num;
pthread_t thread[num];
for (int i = 0; i < num; i++)
{ pthread_create(&thread[i], NULL, &critical_section, i);}
for(int i=0;i<num;i++)
{
pthread_join( thread[i], NULL);
}
exit(0);
}
void *critical_section(int i) {
// Task 1
for (int x = 1; x < 200; x++)
{a = 1;}
pthread_mutex_lock(&mutex);
printf("%d Threads remaining to come\n",left);
left = left - 1;
if (left == 0) {
printf("Last thread has arrived\n");
pthread_cond_broadcast(&cond);
}
else {
while (left != 0) {
printf("Thread %d sleeping after Task 1 completion\n",i);
pthread_cond_wait(&cond, &mutex);
}
}
pthread_mutex_unlock(&mutex);
printf("Thread %d wakes up and goes to Task2\n",i);
// Task 2
for (int x = 1; x < 200; x++)
{a = 1;}
}<file_sep>/170070021-lab1/170070021-lab1/p_1b.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include <sys/wait.h>
int main()
{
int r;
r = fork();
if(r!=0)
{
wait(NULL);
printf("The child process with process ID %d has terminated\n",r);
}
if(r==0)
{
printf("Child process ID: %d\n",getpid());
}
return 0;
}
<file_sep>/170070021-lab3/lab3/Ordering.c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int count = 0;
pthread_mutex_t m;;
struct arg_struct {
int arg1;
int arg2;
};
void *critical_section(void *arguments)
{
struct arg_struct *args1 = arguments;
pthread_mutex_lock( &m );
count = count + 1;
printf("Critical section count: %d\n",count);
printf("Thread number %d with order number %d executed\n",args1-> arg1,args1-> arg2);
pthread_mutex_unlock( &m );
}
main()
{
pthread_mutex_init(&m, NULL);
printf("Number of Threads: ");
int num;
scanf("%d",&num);
pthread_t thread[num];
int Ordering[num];
struct arg_struct args[num];
int temp;
printf("Enter Order of Threads: ");
for(int i=0;i<num;i++)
{
scanf("%d",&temp);
Ordering[temp-1] = i;
}
printf("\n");
for(int i=0;i<num;i++)
{
args[i].arg1 = Ordering[i];
args[i].arg2 = i+1;
pthread_create( &thread[Ordering[i]], NULL, &critical_section,(void *)&args[i]);
pthread_join( thread[Ordering[i]], NULL);
}
exit(0);
}
<file_sep>/170070021-lab1/lab1-cs347m/lab1-cs347m/runme.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
printf(" _\n /(|\n ( :\n __\\ \\ _____\n (____) `|\n(____)| |\n (____).__|\n (___)__.|_____\n");
return 0;
}
<file_sep>/170070021-lab1/170070021-lab1/p_7.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include <sys/wait.h>
int main(int argc,char **argv)
{
int r1;
r1 = fork();
if(r1==0)
{
printf("Child: %d\n",getpid());
getchar();
}
if(r1!=0)
{ printf("Parent: %d\n",getpid());
sleep(60);
wait(NULL);
printf("Exiting Parent: %d\n", getpid());
}
return 0;
}
<file_sep>/170070021-lab3/lab3/Subset_Thread.c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex,mutex2;
pthread_cond_t cond;
int a,left;
void *critical_section(int i);
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_mutex_init(&mutex2, NULL);
pthread_cond_init(&cond, NULL);
printf("Number of Threads: ");
int num;
scanf("%d",&num);
printf("Number of Subset of Threads working at one time: ");
scanf("%d",&left);
printf("\n");
pthread_t thread[num];
for (int i = 0; i < num; i++)
{ pthread_create(&thread[i], NULL, &critical_section, i);}
for(int i=0;i<num;i++)
{
pthread_join( thread[i], NULL);
}
exit(0);
}
void *critical_section(int i) {
// Task 1
for (int x = 1; x < 1000; x++)
{a = 1;}
pthread_mutex_lock(&mutex);
while (left == 0) {
printf("Thread %d sleeping after Task 1 completion\n",i);
pthread_cond_wait(&cond, &mutex);
}
if(left!=0)
{
left = left - 1;
}
printf("Thread %d running. Buffer Size = %d\n",i,left);
pthread_mutex_unlock(&mutex);
// Task 2
for (int x = 1; x < 100000; x++)
{a = 1;}
pthread_mutex_lock(&mutex2);
left = left + 1;
printf("Thread %d Finished. Buffer Size = %d\n",i,left);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex2);
}<file_sep>/170070021-lab3/lab3/Priority11.c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t m,m2,m3,m4 ;
pthread_cond_t cv,cv2;
int a,aaa;
struct arg_struct {
int arg1;
int arg2;
};
int remain = 0;
int remain1 = 0;
void *critical_section(void *arguments);
int main()
{
int temp;
pthread_mutex_init(&m, NULL);
pthread_mutex_init(&m2, NULL);
pthread_mutex_init(&m3, NULL);
pthread_mutex_init(&m4, NULL);
pthread_cond_init(&cv, NULL);
pthread_cond_init(&cv2, NULL);
printf("Number of Threads: ");
int num;
scanf("%d",&num);
pthread_t thread[num];
int Priority[num];
printf("Enter Priority of Threads: ");
remain = num;
for(int i=0;i<num;i++)
{
scanf("%d",&temp);
Priority[i] = temp;
}
printf("\n");
struct arg_struct args[num];
for(int i=0;i<num;i++)
{
args[i].arg1 = i;
args[i].arg2 = Priority[i];
pthread_create( &thread[i], NULL, &critical_section,(void *)&args[i]);
}
for(int i=0;i<num;i++)
{
pthread_join( thread[i], NULL);
}
return 0;
exit(0);
}
void *critical_section(void *arguments)
{
pthread_mutex_lock(&m);
remain = remain - 1;
if (remain == 0) {
pthread_cond_broadcast(&cv);
}
else {
while (remain != 0) {
pthread_cond_wait(&cv, &m);
}
}
pthread_mutex_unlock(&m);
struct arg_struct *args1 = arguments;
pthread_mutex_lock(&m4);
printf("Thread %d arrirrves\n",args1 -> arg1);
if(args1 -> arg2 == 1)
{
remain1 = remain1 + 1;
}
printf("Number of current High priority threads in queue or execution = %d\n",remain1);
pthread_mutex_unlock(&m4);
pthread_mutex_lock(&m2);
//
while(remain1 != 0 && args1 -> arg2==0) {
printf("Thread %d sleep with priority %d\n",args1 -> arg1,args1 -> arg2);
pthread_cond_wait(&cv2, &m2); }
pthread_mutex_lock(&m3);
printf("Thread %d acquires lock with priority %d\n",args1 -> arg1,args1 -> arg2);
for(int jj = 0;jj<20000;jj++)
{
aaa=1;
}
if(args1 -> arg2==1)
{remain1 = remain1 - 1;
}
printf("Thread %d work done with priority %d. High priority threads in queue or execution = %d\n",args1 -> arg1,args1 -> arg2,remain1);
pthread_mutex_unlock(&m3);
if (remain1 == 0) {
pthread_cond_broadcast(&cv2);
}
pthread_mutex_unlock(&m2);
}<file_sep>/170070021-lab2/lab2-resources/p_2a/helloxv6.c
#include "types.h"
#include "stat.h"
#include "user.h"
int
main(int argc, char *argv[])
{
// Add in your code here using the hello() system call
exit();
}
<file_sep>/170070021-lab1/170070021-lab1/p_2.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include <sys/wait.h>
int main()
{
int r1,r2,r3;
r1 = fork();
if(r1!=0)
{
printf("I am parent with PID %d\n",getpid());
r2 = fork();
if(r2!=0)
{
r3=fork();
if(r3==0)
{
printf("I am child with PID %d from PPID %d\n",getpid(),getppid());
}
}
if(r2==0)
{
printf("I am child with PID %d from PPID %d\n",getpid(),getppid());
}
wait(NULL);
}
if(r1==0)
{
printf("I am child with PID %d from PPID %d\n",getpid(),getppid());
}
return 0;
}
<file_sep>/170070021-lab1/170070021-lab1/p_4.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include <sys/wait.h>
#include<fcntl.h>
#include <sys/types.h>
#include <string.h>
int main(int argc,char **argv)
{
int r1;
int b;
b = open(argv[1],O_RDWR|O_CREAT);
r1 = fork();
if(r1==0)
{
write(b,"Hello world! I am child",strlen("Hello world! I am child"));
}
if(r1!=0)
{
write(b,"Hello world! I am parent\n",strlen("Hello world! I am parent\n"));
wait(NULL);
printf("The child process with process ID %d has terminated\n",r1);
}
return 0;
}
<file_sep>/170070021-lab1/lab1-cs347m/lab1-cs347m/sample.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
char buf[512];
int n;
while(1) {
n = read(0, buf, sizeof(buf));
if(n==0) break;
if(n<0) {
fprintf(stdout, "Main; read error\n");
exit(-1);
}
if(write(1, buf, n) != n) {
fprintf(stdout, "Main; write error\n");
exit(-1);
}
}
return 0;
}<file_sep>/170070021-lab1/170070021-lab1/p_6.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include <sys/wait.h>
int main(int argc,char **argv)
{
int r1;
r1 = fork();
if(r1==0)
{
printf("Child: Child process ID:%d\n",getpid());
printf("Child: Parent process ID:%d\n",getppid());
sleep(2);
printf("Child: Child process ID:%d\n",getpid());
printf("Child: Parent process ID:%d\n",getppid());
}
if(r1!=0)
{
sleep(1);
printf("Parent: Parent process ID:%d\n",getpid());
}
return 0;
}
<file_sep>/170070021-lab1/170070021-lab1/p_1a.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include <sys/wait.h>
int main()
{
int r;
r = fork();
if(r!=0)
{
printf("Parent: My process ID: %d\n",getpid());
printf("Parent: Child’s process ID: %d\n",r);
getchar();
}
if(r==0)
{
printf("Child: My process ID: %d\n",getpid());
printf("Child: Parent’s process ID: %d\n",getppid());
}
return 0;
}
| 354b41c3efe12fd3e62586706299192c3c4444eb | [
"C"
] | 15 | C | parth-shettiwar/CS347-Operating-Systems | b66ace6dbce01feba4d8460d0d294785488bdd48 | 4895031e4adde3073d143daef3cad8e91ead1a77 |
refs/heads/master | <repo_name>miracozal/FutbolMaciSimulasyonu<file_sep>/README.md
# FutbolMaciSimulasyonu
Belirli sayı aralığında random atanan oyuncu özellikleri ve hesaplama formülleri üzerine kurulmuş metotlar ile C# konsol üzerinden tasarlanmış 30 saniyelik futbol maçı simülasyonu
<file_sep>/FutbolMaciSimulasyonu/Program.cs
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApp2
{
abstract class Futbolcu // Oluşturulacak tüm sınıfların ortak özelliklerini barındıran Futbolcu isimli taban class'ımızı abstract class ile oluşturduk.
{
public string AdSoyad; //Futbolcunun ad ve soyad bilgilerini tutacak string değişkenimiz
public int FormaNo; //Futbolcunun forma numarası bilgisini tutacak int değişkenimiz
public int Hiz { get; set; } //Futbolcunun rastgele atanacak olan hız bilgisini tutacak int değişkenimiz
public int Dayaniklik { get; set; } //Futbolcunun rastgele atanacak olan dayanıklılık niteliği bilgisini tutacak int değişkenimiz
public int Pas { get; set; } //Futbolcunun rastgele atanacak olan pas niteliği bilgisini tutacak int değişkenimiz
public int Sut { get; set; } //Futbolcunun rastgele atanacak olan şut niteliği bilgisini tutacak int değişkenimiz
public int Yetenek { get; set; } //Futbolcunun rastgele atanacak olan yetenek niteliği bilgisini tutacak int değişkenimiz
public int Kararlik { get; set; } //Futbolcunun rastgele atanacak olan kararlılık niteliği bilgisini tutacak int değişkenimiz
public int DogalForm { get; set; } //Futbolcunun rastgele atanacak olan doğal form niteliği bilgisini tutacak int değişkenimiz
public int Sans { get; set; } //Futbolcunun rastgele atanacak olan şans niteliği bilgisini tutacak int değişkenimiz
public Futbolcu(string adSoyad, int formaNo) //Her futbolcunun ortak niteliğini yansıtacak olan, temel olarak adSoyad ve formaNo bilgilerini parametre olarak alacak metodumuz
{
Random degerAtama = new Random(); //Rastgeleliği sağlayacak fonksiyon
AdSoyad = adSoyad; //Parametreler aracılığıyla AdSoyad niteliği metoda atanacak
FormaNo = formaNo; //Parametreler aracılığıyla FormaNo niteliği metoda atanacak
Hiz = degerAtama.Next(50, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
Dayaniklik = degerAtama.Next(50, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
Pas = degerAtama.Next(50, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
Sut = degerAtama.Next(50, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
Yetenek = degerAtama.Next(50, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
Kararlik = degerAtama.Next(50, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
DogalForm = degerAtama.Next(50, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
Sans = degerAtama.Next(50, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
}
public bool PasSkor() //Gerekli hesaplamalar ve kıyaslar sonucu true ya da false döndürecek olan ezilebilir metot
{
double passkor = Pas * 0.3 + Yetenek * 0.3 + Dayaniklik * 0.1 + DogalForm * 0.1 + Sans * 0.2;
int PasSkor = Convert.ToInt32(passkor); //double değişken değeri int değişken tipine çevrilir
if (60 <= PasSkor) //Hesaplanan PasSkor değişkeninin değerine göre true ya da false döndürecek olan yapı
{
return true;
}
else
{
return false;
}
}
public virtual bool GolSkor() //Gerekli hesaplamalar ve kıyaslar sonucu true ya da false döndürecek olan ezilebilir metot
{
double golskor = Yetenek * 0.3 + Sut * 0.2 + Kararlik * 0.1 + DogalForm * 0.1 + Hiz * 0.1 + Sans * 0.2;
int GolSkor = Convert.ToInt32(golskor); //double değişken değeri int değişken tipine çevrilir
if (70 <= GolSkor) //Hesaplanan GolSkor değişkeninin değerine göre true ya da false döndürecek olan yapı
{
return true;
}
else
{
return false;
}
}
}
class Defans : Futbolcu //Futbolcu class'ından kalıtım alan Defans class'ı
{
public int PozisyonAlma { get; set; } //Defans oyuncusunun rastgele atanacak olan pozisyon alma niteliği bilgisini tutacak int değişkenimiz
public int Kafa { get; set; } //Defans oyuncusunun rastgele atanacak olan kafa vuruşu niteliği bilgisini tutacak int değişkenimiz
public int Sicrama { get; set; } //Defans oyuncusunun rastgele atanacak olan sıçrama niteliği bilgisini tutacak int değişkenimiz
public Defans(string adSoyad, int formaNo) : base(adSoyad, formaNo) //Futbolcu class'ından adSoyad ve formaNo bilgilerini kalıtım alacak metodumuz
{
Random degerAtama = new Random(); //Rastgeleliği sağlayacak fonksiyon
int PozisyonAlma = degerAtama.Next(50, 91); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int Kafa = degerAtama.Next(50, 91); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int Sicrama = degerAtama.Next(50, 91); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
}
public bool PasSkor() //Gerekli hesaplamalar ve kıyaslar sonucu true ya da false döndürecek olan ezici metot
{
double passkor = Pas * 0.3 + Yetenek * 0.3 + Dayaniklik * 0.1 + DogalForm * 0.1 + PozisyonAlma * 0.1 + Sans * 0.2;
int PasSkor = Convert.ToInt32(passkor); //double değişken değeri int değişken tipine çevrilir
if (60 <= PasSkor) //Hesaplanan PasSkor değişkeninin değerine göre true ya da false döndürecek olan yapı
{
return true;
}
else
{
return false;
}
}
public override bool GolSkor() //Gerekli hesaplamalar ve kıyaslar sonucu true ya da false döndürecek olan ezici metot
{
double golskor = Yetenek * 0.3 + Sut * 0.2 + Kararlik * 0.1 + DogalForm * 0.1 + Kafa * 0.1 + Sicrama * 0.1 + Sans * 0.1;
int GolSkor = Convert.ToInt32(golskor); //double değişken değeri int değişken tipine çevrilir
if (70 <= GolSkor) //Hesaplanan GolSkor değişkeninin değerine göre true ya da false döndürecek olan yapı
{
return true;
}
else
{
return false;
}
}
}
class OrtaSaha : Futbolcu //Futbolcu class'ından kalıtım alan OrtaSaha class'ı
{
public int UzunTop { get; set; } //Orta saha oyuncusunun rastgele atanacak olan uzun top niteliği bilgisini tutacak int değişkenimiz
public int IlkDokunus { get; set; } //Orta saha oyuncusunun rastgele atanacak olan ilk dokunuş niteliği bilgisini tutacak int değişkenimiz
public int Uretkenlik { get; set; } //Orta saha oyuncusunun rastgele atanacak olan üretkenlik niteliği bilgisini tutacak int değişkenimiz
public int TopSurme { get; set; } //Orta saha oyuncusunun rastgele atanacak olan top sürme niteliği bilgisini tutacak int değişkenimiz
public int OzelYetenek { get; set; } //Orta saha oyuncusunun rastgele atanacak olan özel yetenek niteliği bilgisini tutacak int değişkenimiz
public OrtaSaha(string adSoyad, int formaNo) : base(adSoyad, formaNo) //Futbolcu class'ından adSoyad ve formaNo bilgilerini kalıtım alacak metodumuz
{
Random degerAtama = new Random(); //Rastgeleliği sağlayacak fonksiyon
int UzunTop = degerAtama.Next(60, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int IlkDokunus = degerAtama.Next(60, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int Uretkenlik = degerAtama.Next(60, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int TopSurme = degerAtama.Next(60, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int OzelYetenek = degerAtama.Next(60, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
}
public bool PasSkor() //Gerekli hesaplamalar ve kıyaslar sonucu true ya da false döndürecek olan ezici metot
{
double passkor = Pas * 0.3 + Yetenek * 0.2 + OzelYetenek * 0.2 + Dayaniklik * 0.1 + DogalForm * 0.1 + UzunTop * 0.1 + TopSurme * 0.1 + Sans * 0.1;
int PasSkor = Convert.ToInt32(passkor); //double değişken değeri int değişken tipine çevrilir
if (60 <= PasSkor) //Hesaplanan PasSkor değişkeninin değerine göre true ya da false döndürecek olan yapı
{
return true;
}
else
{
return false;
}
}
public override bool GolSkor() //Gerekli hesaplamalar ve kıyaslar sonucu true ya da false döndürecek olan ezici metot
{
double golskor = Yetenek * 0.3 + OzelYetenek * 0.2 + Sut * 0.2 + IlkDokunus * 0.1 + Kararlik * 0.1 + DogalForm * 0.1 + Sans * 0.1;
int GolSkor = Convert.ToInt32(golskor); //double değişken değeri int değişken tipine çevrilir
if (70 <= GolSkor) //Hesaplanan GolSkor değişkeninin değerine göre true ya da false döndürecek olan yapı
{
return true;
}
else
{
return false;
}
}
}
class Forvet : Futbolcu //Futbolcu class'ından kalıtım alan Forvet class'ı
{
public int Bitiricilik { get; set; } //Forvet oyuncusunun rastgele atanacak olan bitiricilik niteliği bilgisini tutacak int değişkenimiz
public int IlkDokunus { get; set; } //Forvet oyuncusunun rastgele atanacak olan ilk dokunuş niteliği bilgisini tutacak int değişkenimiz
public int Kafa { get; set; } //Forvet oyuncusunun rastgele atanacak olan kafa vuruşu niteliği bilgisini tutacak int değişkenimiz
public int SogukKanlilik { get; set; } //Forvet oyuncusunun rastgele atanacak olan soğukkanlılık niteliği bilgisini tutacak int değişkenimiz
public int OzelYetenek { get; set; } //Forvet oyuncusunun rastgele atanacak olan özel yetenek niteliği bilgisini tutacak int değişkenimiz
public Forvet(string adSoyad, int formaNo) : base(adSoyad, formaNo) //Futbolcu class'ından adSoyad ve formaNo bilgilerini kalıtım alacak metodumuz
{
Random degerAtama = new Random(); //Rastgeleliği sağlayacak fonksiyon
int Bitiricilik = degerAtama.Next(70, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int IlkDokunus = degerAtama.Next(70, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int Kafa = degerAtama.Next(70, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int SogukKanlilik = degerAtama.Next(70, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
int OzelYetenek = degerAtama.Next(70, 101); //Değişkene belirtilen değerler arasında rastgele bir değer atanacak
}
public bool PasSkor() //Gerekli hesaplamalar ve kıyaslar sonucu true ya da false döndürecek olan ezici metot
{
double passkor = Pas * 0.3 + Yetenek * 0.2 + OzelYetenek * 0.2 + Dayaniklik * 0.1 + DogalForm * 0.1 + Sans * 0.1;
int PasSkor = Convert.ToInt32(passkor); //double değişken değeri int değişken tipine çevrilir
if (60 <= PasSkor) //Hesaplanan PasSkor değişkeninin değerine göre true ya da false döndürecek olan yapı
{
return true;
}
else
{
return false;
}
}
public override bool GolSkor() //Gerekli hesaplamalar ve kıyaslar sonucu true ya da false döndürecek olan ezici metot
{
double golskor = Yetenek * 0.2 + OzelYetenek * 0.2 + Sut * 0.1 + Kafa * 0.1 + IlkDokunus * 0.1 + Bitiricilik * 0.1 + SogukKanlilik * 0.1 + Kararlik * 0.1 + DogalForm * 0.1 + Sans * 0.1;
int GolSkor = Convert.ToInt32(golskor); //double değişken değeri int değişken tipine çevrilir
if (70 <= GolSkor) //Hesaplanan GolSkor değişkeninin değerine göre true ya da false döndürecek olan yapı
{
return true;
}
else
{
return false;
}
}
}
class Program
{
static void Main(string[] args)
{
List<Futbolcu> takim1 = new List<Futbolcu>(); //takim1 isimli Futbolcu tipinden liste oluşturuluyor
takim1.Add(new Defans("<NAME>", 0)); //takim1 listesine eleman ekleniyor
takim1.Add(new Defans("Zanka", 1)); //takim1 listesine eleman ekleniyor
takim1.Add(new Defans("<NAME>", 2)); //takim1 listesine eleman ekleniyor
takim1.Add(new Defans("<NAME>", 3)); //takim1 listesine eleman ekleniyor
takim1.Add(new OrtaSaha("<NAME>", 4)); //takim1 listesine eleman ekleniyor
takim1.Add(new OrtaSaha("<NAME>", 5)); //takim1 listesine eleman ekleniyor
takim1.Add(new OrtaSaha("<NAME>", 6)); //takim1 listesine eleman ekleniyor
takim1.Add(new OrtaSaha("<NAME>", 7)); //takim1 listesine eleman ekleniyor
takim1.Add(new Forvet("<NAME>", 8)); //takim1 listesine eleman ekleniyor
takim1.Add(new Forvet("<NAME>", 9)); //takim1 listesine eleman ekleniyor
List<Futbolcu> takim2 = new List<Futbolcu>(); //takim2 isimli Futbolcu tipinden liste oluşturuluyor
takim2.Add(new Defans("Mariano", 0)); //takim2 listesine eleman ekleniyor
takim2.Add(new Defans("<NAME>", 1)); //takim2 listesine eleman ekleniyor
takim2.Add(new Defans("Marcao", 2)); //takim2 listesine eleman ekleniyor
takim2.Add(new Defans("<NAME>", 3)); //takim2 listesine eleman ekleniyor
takim2.Add(new OrtaSaha("<NAME>", 4)); //takim2 listesine eleman ekleniyor
takim2.Add(new OrtaSaha("<NAME>", 5)); //takim2 listesine eleman ekleniyor
takim2.Add(new OrtaSaha("<NAME>", 6)); //takim2 listesine eleman ekleniyor
takim2.Add(new OrtaSaha("<NAME>", 7)); //takim2 listesine eleman ekleniyor
takim2.Add(new Forvet("<NAME>", 8)); //takim2 listesine eleman ekleniyor
takim2.Add(new Forvet("<NAME>", 9)); //takim2 listesine eleman ekleniyor
Random aralikBelirleme = new Random(); //Rastgeleliği sağlayacak fonksiyon
int hangiTakim = aralikBelirleme.Next(1, 3); //Maça başlayacak takımın rastgele seçilmesini sağlayacak değişken değeri atanıyor.
int oyuncuNo = -1; //
int basariliPas = 0; //Arka arkaya yapılan başarılı pas sayısını tutacak değişken
int EvGol = 0; //Ev sahibi takımın(1. takım) attığı gol sayısını tutacak, atamadığı takdirde 0 döndürecek değişken
int DepGol = 0; //Dış sahibi takımın(2. takım) attığı gol sayısını tutacak, atamadığı takdirde 0 döndürecek değişken
int sure = 0; //İşlem saniyesini tutacak değişken
int[] KontrolDizisi = new int[1]; //Arka arkaya üretilen iki sayının aynı olmamasını kontrol için, üretilen sayıyı sonraki üretilecekle karşılaştırmak üzere ekleyeceğimiz tek elemanlık dizi
while (sure < 30) //Maç süresi 30 saniyeyi geçtiği takdirde karşılaşma sona erecek ve maç skoru ekrana yazılacak. Tam 30 saniyede bitirmememin sebebi, atak esnasında maçın kesilmesini önleyerek programa biraz olsun gerçeklik kazandırma
{
if (hangiTakim == 1)
{
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine("Ev sahibi ekip oyunu hareketlendirecek.");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
for (int i = 1; i <= 3; i++) //Arka arkaya 3 başarılı pas olup olmayacağını kontrol amaçlı kurulan döngü
{
for (i = 0; i < 1; i++)
while (i < 1)
{
oyuncuNo = aralikBelirleme.Next(1, 10);
if (Array.IndexOf(KontrolDizisi, oyuncuNo) == -1) //Arka arkaya atanan iki değerin aynı olup olmadığını kontrol eden yapı
KontrolDizisi[i++] = oyuncuNo;
}
if (takim1[oyuncuNo].PasSkor() == false)
{
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine(takim1[oyuncuNo].AdSoyad + " adli oyuncudan kotu pas, top kaybedildi.\n");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
basariliPas = 0; //Hatalı pas atılması durumunda başarılı pasları tutan değişken sıfırlanacak
hangiTakim = 2; //Top takim2'ye geçecek
break;
}
else
{
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine(takim1[oyuncuNo].AdSoyad + " adli futbolcudan basarili pas!");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
basariliPas++; //Atılan pasın başarılı olması durumunda basariliPas değişkeni 1 arttırılacak
if (basariliPas == 3) //Arka arkaya başarılı pas sayısını tutan değişken değerinin 3'e eşit olması durumunda şut çekilecek
{
if (takim1[oyuncuNo].GolSkor() == true) //Eğer oyuncunun niteliklerinin değerlerinden yapılan hesaplamalar sonucu GolSkor() metodu true değer döndürürse takim1'in gol attığı işlenecek
{
for (i = 0; i < 1; i++)
while (i < 1)
{
oyuncuNo = aralikBelirleme.Next(1, 10);
if (Array.IndexOf(KontrolDizisi, oyuncuNo) == -1) //Arka arkaya atanan iki değerin aynı olup olmadığını kontrol eden yapı
KontrolDizisi[i++] = oyuncuNo;
}
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine("Gooooooooool ! Topu aglara gonderen oyuncu " + takim1[oyuncuNo].AdSoyad + " !\n");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
basariliPas = 0; //Şut çekilmesi durumunda başarılı pasları tutan değişken sıfırlanacak
EvGol++; //Ev sahibi takımın attığı gol sayısını tutan değişken 1 arttırılacak
hangiTakim = 2; //Top takim2'ye geçecek
break;
}
else
{
for (i = 0; i < 1; i++)
while (i < 1)
{
oyuncuNo = aralikBelirleme.Next(1, 10);
if (Array.IndexOf(KontrolDizisi, oyuncuNo) == -1) //Arka arkaya atanan iki değerin aynı olup olmadığını kontrol eden yapı
KontrolDizisi[i++] = oyuncuNo;
}
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine(takim1[oyuncuNo].AdSoyad + " isimli oyuncunun sutu golle sonuclanmadi.\n");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
basariliPas = 0; //Şut çekilmesi durumunda başarılı pasları tutan değişken sıfırlanacak
hangiTakim = 2; //Top takim2'ye geçecek
break;
}
}
}
}
}
else if (hangiTakim == 2)
{
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine("Konuk ekip oyunu hareketlendirecek.");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
for (int i = 1; i <= 3; i++) //Arka arkaya 3 başarılı pas olup olmayacağını kontrol amaçlı kurulan döngü
{
for (i = 0; i < 1; i++)
while (i < 1)
{
oyuncuNo = aralikBelirleme.Next(1, 10);
if (Array.IndexOf(KontrolDizisi, oyuncuNo) == -1) //Arka arkaya atanan iki değerin aynı olup olmadığını kontrol eden yapı
KontrolDizisi[i++] = oyuncuNo;
}
if (takim2[oyuncuNo].PasSkor() == false)
{
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine(takim2[oyuncuNo].AdSoyad + " adli oyuncudan kotu pas, top kaybedildi.\n");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
hangiTakim = 1; //Top takim1'e geçecek
basariliPas = 0; //Hatalı pas atılması durumunda başarılı pasları tutan değişken sıfırlanacak
break;
}
else
{
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine(takim2[oyuncuNo].AdSoyad + " adli futbolcudan basarili pas!");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
basariliPas++; //Atılan pasın başarılı olması durumunda basariliPas değişkeni 1 arttırılacak
if (basariliPas == 3) //Arka arkaya başarılı pas sayısını tutan değişken değerinin 3'e eşit olması durumunda şut çekilecek
{
if (takim2[oyuncuNo].GolSkor() == true) //Eğer oyuncunun niteliklerinin değerlerinden yapılan hesaplamalar sonucu GolSkor() metodu true değer döndürürse takim2'nin gol attığı işlenecek
{
for (i = 0; i < 1; i++)
while (i < 1)
{
oyuncuNo = aralikBelirleme.Next(1, 10);
if (Array.IndexOf(KontrolDizisi, oyuncuNo) == -1) //Arka arkaya atanan iki değerin aynı olup olmadığını kontrol eden yapı
KontrolDizisi[i++] = oyuncuNo;
}
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine("Gooooooooool ! Topu aglara gonderen oyuncu " + takim2[oyuncuNo].AdSoyad + " !\n");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
basariliPas = 0;//Şut çekilmesi durumunda başarılı pasları tutan değişken sıfırlanacak
DepGol++; //Deplasman takımın attığı gol sayısını tutan değişken 1 arttırılacak
hangiTakim = 1; //Top takim1'e geçecek
break;
}
else
{
for (i = 0; i < 1; i++)
while (i < 1)
{
oyuncuNo = aralikBelirleme.Next(1, 10);
if (Array.IndexOf(KontrolDizisi, oyuncuNo) == -1) //Arka arkaya atanan iki değerin aynı olup olmadığını kontrol eden yapı
KontrolDizisi[i++] = oyuncuNo;
}
System.Threading.Thread.Sleep(1000); //Kullanıcının takibini kolaylaştırmak adına işlemi 1 saniye bekleyerek ekrana yazdıracak fonksiyon
Console.WriteLine(takim2[oyuncuNo].AdSoyad + " isimli oyuncunun sutu golle sonuclanmadi.\n");
sure++; //İşlem sonucu 1 saniyenin geçtiği, süre niteliğini tutan değişkene eklenecek
basariliPas = 0; //Şut çekilmesi durumunda başarılı pasları tutan değişken sıfırlanacak
hangiTakim = 1; //Top takim1'e geçecek
break;
}
}
}
}
}
}
Console.WriteLine("Ev sahibi takim : " + EvGol + "-" + DepGol + " : Deplasman takim"); //Maç sonucu ekrana basılacak
Console.ReadKey();
}
}
}
| cb1adc0c2b7de2a1706e08fde777b0e661cad65a | [
"Markdown",
"C#"
] | 2 | Markdown | miracozal/FutbolMaciSimulasyonu | fba7512b349907aa5c858a54c1d96ea44b900a86 | 2825050bb945103326fbe6fd49e64f5e1b908aa6 |
refs/heads/master | <repo_name>AmolPardeshi99/RxJavaOperators<file_sep>/app/src/main/java/com/example/rxjavaproject/MainActivity3.java
package com.example.rxjavaproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class MainActivity3 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
// RxJava-|| You Part
Observable<Task> taskObservable = Observable.create(new ObservableOnSubscribe<Task>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Task> emitter) throws Throwable {
List<Task> taskList = getTaskList();
for (Task task :taskList){
if (!emitter.isDisposed())emitter.onNext(task);
}
emitter.onComplete();
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
Observer<Task> observer = new Observer<Task>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull Task task) {
// Log.d("Amol", "onNext: "+task.getName());
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
};
taskObservable.subscribe(observer);
//using map
StudentResponse studentResponse = new StudentResponse(getStudentList());
Observable<Student> studentObservable = Observable.just(studentResponse)
.flatMap(new Function<StudentResponse, Observable<Student>>() {
@Override
public Observable<Student> apply(StudentResponse studentResponse) throws Throwable {
List<Student> studentList= studentResponse.getStudentList();
return Observable.fromIterable(studentList).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
}).filter(new Predicate<Student>() {
@Override
public boolean test(Student student) throws Throwable {
return student.getMarks()>75;
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
Observer<Student> studentObserver = new Observer<Student>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull Student student) {
Log.d("Amol", "onNext: "+student.getStudentName()+" "+student.getMarks());
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
};
studentObservable.subscribe(studentObserver);
}
private List<Student> getStudentList(){
List<Student> studentList = new ArrayList<>();
for (int i=0; i<5; i++){
Student student1 = new Student(i+10, "Amol"+i,100); studentList.add(student1);
Student student2 = new Student(i+20, "Kunal"+i,70); studentList.add(student2);
Student student3 = new Student(i+30, "Deepak"+i,80); studentList.add(student3);
Student student4 = new Student(i+40, "Piyush"+i,90); studentList.add(student4);
Student student5 = new Student(i+50, "Akash"+i,60); studentList.add(student5);
Student student6 = new Student(i+60, "Abhishek"+i,95); studentList.add(student6);
}
return studentList;
}
private List<Task> getTaskList() {
List<Task> taskList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
Task task = new Task(i, "Task - " + i, true);
taskList.add(task);
} else {
Task task = new Task(i, "Task - " + i, false);
taskList.add(task);
}
}
return taskList;
}
}<file_sep>/app/src/main/java/com/example/rxjavaproject/Student.kt
package com.example.rxjavaproject
data class Student(
val studentId:Int,
val studentName:String,
val marks:Int
)
<file_sep>/app/src/main/java/com/example/rxjavaproject/Task.kt
package com.example.rxjavaproject
data class Task(
var id:Int,
var name:String,
var isCompleted:Boolean
)
<file_sep>/app/src/main/java/com/example/rxjavaproject/StudentResponse.kt
package com.example.rxjavaproject
class StudentResponse(
val studentList: List<Student>
) | 929ff60f79f2bfed6492aec4c30ebc09078055cc | [
"Java",
"Kotlin"
] | 4 | Java | AmolPardeshi99/RxJavaOperators | 44432c17c91edcd019b56f725265bed23948d943 | b30446c02eed57a84408c0bad6e55397b64ce6c9 |
refs/heads/master | <file_sep>import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
const Clubs = (props) => {
return (
<TouchableOpacity onPress={()=>console.log(props.clubname.name)}>
<Text style={styles.row} >{props.clubname.name}</Text>
</TouchableOpacity>
);
}
export default Clubs;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'stretch',
},
row:{
// flex:,
backgroundColor: 'red',
borderWidth: 4,
borderColor: "#20232a",
borderRadius: 6,
backgroundColor: "#61dafb",
color: "#20232a",
textAlign: "center",
fontSize: 30,
fontWeight: "bold",
marginTop: 20
},
});
<file_sep>import { StatusBar } from 'expo-status-bar';
import React, {useEffect, useState} from 'react';
import { StyleSheet, Text, View, FlatList, Button,TouchableOpacity } from 'react-native';
import Data from './data.json'
import Clubs from './components/Clubs';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function DetailsScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
}
function HomeScreen({navigation}) {
const [data, setData] = useState(Data.all)
return (
<View style={styles.container}>
{/* {
data.map(club =>{
return <Clubs clubname={club.name}/>
})
} */}
<FlatList
data={data}
renderItem={({item})=>(
<Clubs clubname={item} />
)}
/>
<Button
title="eloo" onPress={() => navigation.navigate('Details')} />
</View>
);
}
export default function App() {
useEffect(()=>{
// fetch("https://reqres.in/api/users?page=2")
// .then( res=> res.json())
// .then( res=> setData(res.data))
// .catch(err => console.log(err))
// // console.log(data)
// console.log(data)
},[])
const Stack = createStackNavigator();
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'stretch',
},
});
| fa98fd3eec1721c3f74829d4eb519ff449d3fa85 | [
"JavaScript"
] | 2 | JavaScript | Precho/club | f846a9f8fc3e230edb1ebed35f3041529acc513e | 46016e263c85722662ac95b1fa358b51e0b0237a |
refs/heads/master | <repo_name>JohnDeVone/CTI110<file_sep>/P2HW1_MealTipTax_JohnDevone.py
# This is an assignment calculating the tip of a meal including tax as well
# Sept 3, 2019
# CTI-110 P2HW1 - Meal Tip Tax Calculator
# <NAME>
#
# Ask for the charge of food
subtotal = float(input('Enter the total cost of the food: '))
# Ask for the percentage the customer would like to tip
tip_percent = float(input('What is the percentage you want to tip? (Enter it as a decimal. Example: 23% = .23):'))
# Ask for the tax amount of the transaction
tax_percent = float(input('What is the tax percentage of the transaction? (Use the same decimal format as the last question.):'))
# Calculate the tip and tax
calc_tip = tip_percent * subtotal
calc_tax = tax_percent * subtotal
total = subtotal + calc_tip + calc_tax
# Display the calculations
print('The total tip amount will is $ ', format(calc_tip, ',.2f'))
print('The total tax amount will is $ ', format(calc_tax, ',.2f'))
print('The total of your meal including tax and tip will is $ ', format(total, ',.2f'))
<file_sep>/README.md
# CTI110
CTI 110 Repository
Created for P2LAB1
<NAME>
Sept 9, 2019
<file_sep>/P2HW2_TurtleGraphic_JohnDevone.py
# In this assignment i will practice how to use libraries and draw on a canvas
# Sept 9,2019
# CTI-110 P2HW2 - Turtle Graphic
# <NAME>
# Import the TURTLE DARNIT
import turtle
# ONE square coming up HOT AND READY
turtle.right(45)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
# Next square coming RIGHT on up!!!
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.exitonclick()
| d0f2e3b4525a5a2fa4c798841ad0491272ca6b7d | [
"Markdown",
"Python"
] | 3 | Python | JohnDeVone/CTI110 | 9ba15b643c44d245e68da8cdd9fab09356016425 | 0ace27ec5f0a268b7b4962465f4bd11f57abf6df |
refs/heads/master | <repo_name>pedroverceze/MinhaAppAngular<file_sep>/src/app/produtos/detalhes-produto/detalhes-produto.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Produto } from '../produto';
import { ProdutoService } from '../produtos.service';
@Component({
selector: 'app-detalhes-produto',
templateUrl: './detalhes-produto.component.html'
})
export class DetalhesProdutoComponent implements OnInit {
constructor(private produtoService: ProdutoService, private activatedRoute : ActivatedRoute) { }
public produtoDetalhes: Produto;
private _id = this.activatedRoute.snapshot.params.id;
ngOnInit(): void {
console.log(this._id);
this.produtoService.obterDetalhes(this._id)
.subscribe(
detalhes => {
this.produtoDetalhes = detalhes;
},
error => console.log(error)
);
}
}
| 67e720dc1ba22b72d0400994bcbe7e6beee03ab0 | [
"TypeScript"
] | 1 | TypeScript | pedroverceze/MinhaAppAngular | 65dede91f70b62da5ff65c465e2e1bcc111f97af | 6ed2c7f0810b3f26a8089303d871f1c959b2d0e6 |
refs/heads/master | <repo_name>PressmanMatthew/Natural-Selection-Simulation-in-Dont-Starve<file_sep>/Natural Selection/scripts/prefabs/pig.lua
--Prefab Assets--
local assets=
{
Asset("ANIM", "anim/pig.zip"), -- Spriter file name
}
--Misc. Variables--
local PIG_HEALTH = 250;
local PIG_RUN_SPEED = 3;
--Create a New Prefab Entity--
local function init_prefab()
local brain = require "brains/pigbrain"
local inst = CreateEntity() -- Create the entity
local trans = inst.entity:AddTransform() -- Component that allows the enitity to be placed in the world
local anim = inst.entity:AddAnimState() -- Component that allows the entity to be animated
local shadow = inst.entity:AddDynamicShadow() -- Component that gives the entity a dynamic shadow
--Shadow dimensions--
shadow:SetSize( 1, .75 )
--Spriter File Name--
anim:SetBank("pig")
--Spriter Animation Folder Name--
anim:SetBuild("pig")
--Combat Components--
inst:AddComponent("combat")
inst.components.combat.hiteffectsymbol = "chest"
inst:AddComponent("health")
inst.components.health:SetMaxHealth(PIG_HEALTH)
--Movement Components--
inst:AddComponent("locomotor") -- Component that allows the entity to move around the world
inst.components.locomotor.runspeed = PIG_RUN_SPEED -- Entity speed (7+ outruns the player)
--Eating Compoents--
inst:AddComponent("eater")
inst.components.eater:SetVegetarian()
--Misc. Components--
inst:AddTag("animal")
inst:AddTag("prey")
inst:AddTag("pig")
inst:AddComponent("inspectable")
--Character Physics--
MakeCharacterPhysics(inst, 20, .5) -- Allows the physics engine to recognize the entity. Also sets up collision tags, collision masks, friction etc. [Three values(entity, mass, radius)]
--Attach Stategraph--
inst:SetStateGraph("pigstategraph")
--Attach Brain--
inst:SetBrain(brain)
--Create Entity--
return inst
end
--Register Prefab for use in Game--
return Prefab( "monsters/pig", init_prefab, assets, nil) -- Order is: folder to be housed in, function to be run, assets, ???
<file_sep>/Natural Selection/modmain.lua
--New Prefabs--
PrefabFiles = {
"pig",
"bear",
}
function SpawnCreature(player) -- Spawn the creature at the player's coordinates
local x, y, z = player.Transform:GetWorldPosition() -- Player coordinates
local creature = GLOBAL.SpawnPrefab("pig") -- Spawn creature at world origin
local creature2 = GLOBAL.SpawnPrefab("bear")
creature.Transform:SetPosition( x, y, z ) -- Move creature to player's position
creature2.Transform:SetPosition( x, y, z )
end
AddSimPostInit(SpawnCreature) -- Run after player spawns in world<file_sep>/README.md
Natural-Selection-Simulation-in-Don-t-Starve
============================================
The repository for my senior high school project where I will be creating a small scale simulation of natural selection in the survival game called Don't Starve
============================================
Installation of the Mod
1. First you must have Don't Starve installed on your computer
2. Navigate to where Don't Starve is installed on your computer
3. Once found navigate to /dont_starve/mods
4. Copy the Natural Selection folder in its entirety into the mods folder.
5. Launch Don't Starve and Enjoy!
<file_sep>/Proof of Concept/Anthropophagi/scripts/brains/brain.lua
local AVOID_PLAYER_DIST = 8 -- Start fleeing distance
local AVOID_PLAYER_STOP = 18 -- Stop fleeing distance
--Brain Creation--
local brain = Class(Brain, function(self, inst)
Brain._ctor(self, inst)
end)
--Set up the Behavior Tree--
function brain:OnStart()
local root = PriorityNode( -- Add more actions for more complexity
{
RunAway(self.inst, "scarytoprey", AVOID_PLAYER_DIST, AVOID_PLAYER_STOP), -- First action of the Priority Node
StandStill(self.inst, function() return true end), -- Second action of the Priority Node/if it's not doing any others do this
}, .25) -- Check every 0.25 seconds which behavior it should be doing.
self.bt = BT(self.inst, root) -- attach the behavior tree to the brain
end
--Register Brain--
return brain<file_sep>/Natural Selection/modinfo.lua
--Mod Info--
name = "Natural selection"
description = "A small scale simulation for natural selection in Don't Starve"
author = "<NAME>"
version = "0.1"
<file_sep>/Natural Selection/scripts/brains/pigbrain.lua
require "behaviours/runaway" -- Used for the runaway action
require "behaviours/doaction" -- Used for the Doaction actions
local AVOID_PLAYER_DIST = 3 -- Start fleeing distance
local AVOID_PLAYER_STOP = 12 -- Stop fleeing distance
local SEE_FOOD_DIST = 20
--Brain Creation--
local brain = Class(Brain, function(self, inst)
Brain._ctor(self, inst)
end)
--Food Eating Function--
local function EatFoodAction(inst)
local target = FindEntity(inst, SEE_FOOD_DIST, function(item) return inst.components.eater:CanEat(item) and item.components.bait and not item:HasTag("planted") and not (item.components.inventoryitem and item.components.inventoryitem:IsHeld()) end) -- Checks for correct kinds of food
if target then
local act = BufferedAction(inst, target, ACTIONS.EAT) -- Uses a buffered action that is in the scripts/actions.lua file
act.validfn = function() return not (target.components.inventoryitem and target.components.inventoryitem:IsHeld()) end -- Tests whether the object to be eaten is being held
return act
end
end
--Set up the Behavior Tree--
function brain:OnStart()
local root = PriorityNode( -- Add more actions for more complexity
{
RunAway(self.inst, "scarytoprey", AVOID_PLAYER_DIST, AVOID_PLAYER_STOP), -- First action of the Priority Node
DoAction(self.inst, EatFoodAction), -- Eat action of the priority node
StandStill(self.inst, function() return true end), -- Last action of the Priority Node/if it's not doing any others do this
}, .25) -- Check every 0.25 seconds which behavior it should be doing.
self.bt = BT(self.inst, root) -- attach the behavior tree to the brain
end
--Register Brain--
return brain<file_sep>/Proof of Concept/Anthropophagi/modmain.lua
--New Prefabs--
PrefabFiles = {
"anthropophagi",
}
function SpawnCreature(player) -- Spawn the creature at the player's coordinates
local x, y, z = player.Transform:GetWorldPosition() -- Player coordinates
local creature = GLOBAL.SpawnPrefab("anthropophagi") -- Spawn creature at world origin
creature.Transform:SetPosition( x, y, z ) -- Move creature to player's position
end
AddSimPostInit(SpawnCreature) -- Run after player spawns in world<file_sep>/Natural Selection/scripts/stategraphs/bearstategraph.lua
--A stategraph is one giant handler for if/then situations--
require("stategraphs/commonstates")
--Feedback to the Player based on the "state" the creature is in-- (This is the then of an if/then statement)
local states=
{
--Death State--
State{
name = "death",
tags = {"busy"},
onenter = function(inst)
-- inst.SoundEmitter:PlaySound(SoundPath(inst, "die"))
inst.AnimState:PlayAnimation("run")
inst.Physics:Stop()
RemovePhysicsColliders(inst)
inst.components.lootdropper:DropLoot(Vector3(inst.Transform:GetWorldPosition()))
end,
},
--Attack State--
State{
name = "attack",
tags = {"attack", "busy", "canrotate"},
onenter = function(inst, target)
inst.sg.statemem.target = target
-- inst.SoundEmitter:PlaySound(inst.sounds.angry)
inst.components.combat:StartAttack()
inst.components.locomotor:StopMoving()
inst.AnimState:PlayAnimation("atk")
end,
timeline=
{
TimeEvent(15*FRAMES, function(inst) inst.components.combat:DoAttack(inst.sg.statemem.target) end),
},
events=
{
EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end),
},
},
--Hit State--
State{
name = "hit",
tags = {"busy", "canrotate"},
onenter = function(inst)
inst.AnimState:PlayAnimation("hit")
inst.Physics:Stop()
end,
events=
{
EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ),
},
},
--Idle State--
State{
name = "idle",
tags = {"idle", "canrotate"}, -- Classification of the state (idle = new, canrotate = animation can rotate)
onenter = function(inst, playanim) -- Once we enter the state
inst.AnimState:PlayAnimation("idle", true) -- Loop the idle animation
end,
},
--Running State
State{
name = "run",
tags = {"run", "canrotate" }, -- Classification of the state (run = new, canrotate = animation can rotate)
onenter = function(inst, playanim) -- Once we enter the state
inst.AnimState:PlayAnimation("run", true) -- Loop the run animation
inst.components.locomotor:RunForward() -- Locomotor moves the creature forward
end,
},
--Eating State--
State{
name = "eat",
onenter = function(inst)
inst.Physics:Stop()
inst.AnimState:PlayAnimation("idle", false)
inst.AnimState:PushAnimation("idle", true)
inst.sg:SetTimeout(2+math.random()*4)
end,
ontimeout= function(inst)
inst:PerformBufferedAction()
inst.sg:GoToState("idle", "idle")
end,
},
}
--Grabs actions to go to certain states--
local actionhandlers =
{
--Eating Action Handler--
ActionHandler(ACTIONS.EAT, "eat"),
}
--Grabs events to then go to a certain state-- (This is the if of an if/then statement)
local event_handlers=
{
--Attack Event Handler--
EventHandler("doattack", function(inst, data)
if not inst.components.health:IsDead() and not inst.sg:HasStateTag("busy") and data and data.target then
inst.sg:GoToState("attack", data.target)
end
end),
EventHandler("attacked", function(inst) if inst.components.health:GetPercent() > 0 and not inst.sg:HasStateTag("attack") then inst.sg:GoToState("hit") end end),
--Death Event Handler--
EventHandler("death", function(inst) inst.sg:GoToState("death") end),
--Locomote Event Handler--
EventHandler("locomote", -- Grabs an event from the locomotor called locomote
function(inst) -- Unnecessary to name the function if it is being called as we go
--Locomotor check--
if inst.components.locomotor:WantsToMoveForward() then -- Check for locomotor trying to move creature
if inst.sg:HasStateTag("idle") then -- Check if creature isn't moving
inst.sg:GoToState("run") -- If not, go to the running state
end
--Stationary--
else
if not inst.sg:HasStateTag("idle") then -- Check if creature is moving
inst.sg:GoToState("idle") -- If not, go to the Idle state
end
end
end),
}
--Register Stategraph and Make Default State Idle--
return StateGraph("bearstategraph", states, event_handlers, "idle", {})<file_sep>/Proof of Concept/Anthropophagi/modinfo.lua
--Mod Info--
name = "Anthropophagi"
description = "Creates a Creature called Anthropophagi in the World"
author = "<NAME>"
version = "0.1"
api_version = 4 -- Game API Version
forumthread = ""<file_sep>/Natural Selection/scripts/prefabs/bear.lua
--Prefab Assets--
local assets=
{
Asset("ANIM", "anim/bear.zip"), -- Spriter file name
}
--Misc. Variables--
local BEAR_HEALTH = 250;
local BEAR_RUN_SPEED = 5;
local BEAR_DAMAGE = 20;
local BEAR_FLAMMIBILITY = .5;
local BEAR_ATTACK_PERIOD = 3;
local function OnAttacked(inst, data)
inst.components.combat:SetTarget(data.attacker)
inst.components.combat:ShareTarget(data.attacker, 30, function(dude)
return dude:HasTag("bear")
and not dude.components.health:IsDead()
end, 10)
end
local function keeptargetfn(inst, target)
return target
and target.components.combat
and target.components.health
and not target.components.health:IsDead()
end
--Create a New Prefab Entity--
local function init_prefab()
local brain = require "brains/bearbrain"
local inst = CreateEntity() -- Create the entity
local trans = inst.entity:AddTransform() -- Component that allows the enitity to be placed in the world
local anim = inst.entity:AddAnimState() -- Component that allows the entity to be animated
local shadow = inst.entity:AddDynamicShadow() -- Component that gives the entity a dynamic shadow
--Shadow dimensions--
shadow:SetSize( 1, .75 )
--Spriter File Name--
anim:SetBank("bear")
--Spriter Animation Folder Name--
anim:SetBuild("bear")
--Lootdropper Components--
inst:AddComponent("lootdropper")
inst.components.lootdropper:AddRandomLoot("monstermeat", 1)
inst.components.lootdropper:AddRandomLoot("chester_eyebone", 1)
inst.components.lootdropper:AddRandomLoot("spidergland", .5)
inst.components.lootdropper.numrandomloot = 1
--Combat Components--
inst:AddComponent("combat")
inst.components.combat:SetDefaultDamage(BEAR_DAMAGE)
inst.components.combat:SetKeepTargetFunction(keeptargetfn)
inst.components.combat:SetAttackPeriod(BEAR_ATTACK_PERIOD)
inst:ListenForEvent("attacked", OnAttacked)
inst.components.combat.hiteffectsymbol = "chest"
inst:AddComponent("health")
inst.components.health:SetMaxHealth(BEAR_HEALTH)
--Burning Components--
MakeMediumBurnableCharacter(inst, "body")
MakeMediumFreezableCharacter(inst, "body")
inst.components.burnable.flammability = BEAR_FLAMMIBILITY
--Movement Components--
inst:AddComponent("locomotor") -- Component that allows the entity to move around the world
inst.components.locomotor.runspeed = BEAR_RUN_SPEED -- Entity speed (7+ outruns the player)
--Eating Compoents--
inst:AddComponent("eater")
inst.components.eater:SetCarnivore()
inst.components.eater:SetCanEatHorrible()
inst.components.eater.strongstomach = true -- can eat monster meat
--Misc. Components--
inst:AddTag("animal")
inst:AddTag("hostile")
inst:AddTag("scarytoprey")
inst:AddTag("canbetrapped")
inst:AddTag("bear")
inst:AddComponent("inspectable")
--Character Physics--
MakeCharacterPhysics(inst, 20, .5) -- Allows the physics engine to recognize the entity. Also sets up collision tags, collision masks, friction etc. [Three values(entity, mass, radius)]
--Attach Stategraph--
inst:SetStateGraph("bearstategraph")
--Attach Brain--
inst:SetBrain(brain)
--Create Entity--
return inst
end
--Register Prefab for use in Game--
return Prefab( "monsters/bear", init_prefab, assets, nil) -- Order is: folder to be housed in, function to be run, assets, ???
<file_sep>/Proof of Concept/Anthropophagi/scripts/prefabs/anthropophagi.lua
--Prefab Assets--
local assets=
{
Asset("ANIM", "anim/anthropophagi.zip"), -- Spriter file name
}
--Create a New Prefab Entity--
local function init_prefab()
local brain = require "brains/brain"
local inst = CreateEntity() -- Create the entity
local trans = inst.entity:AddTransform() -- Component that allows the enitity to be placed in the world
local anim = inst.entity:AddAnimState() -- Component that allows the entity to be animated
--Spriter File Name--
anim:SetBank("anthropophagi")
--Spriter Animation Folder Name--
anim:SetBuild("anthropophagi")
--Misc. Components--
inst:AddComponent("locomotor") -- Component that allows the entity to move around the world
inst.components.locomotor.runspeed = 7 -- Entity speed (7+ outruns the player)
--Character Physics--
MakeCharacterPhysics(inst, 10, .5) -- Allows the physics engine to recognize the entity. Also sets up collision tags, collision masks, friction etc. [Three values(entity, mass, radius)]
--Attach Stategraph--
inst:SetStateGraph("stategraph")
--Attach Brain
inst:SetBrain(brain)
--Create Entity
return inst
end
--Register Prefab for use in Game--
return Prefab( "monsters/anthropophagi", init_prefab, assets, nil)
<file_sep>/Natural Selection/scripts/brains/bearbrain.lua
require "behaviours/doaction" -- Used for the Doaction actions
require "behaviours/chaseandattack" -- Used for the ChaseAndAttack action
require "behaviours/attackwall"
local SEE_FOOD_DIST = 20
local RUN_AWAY_DIST = 10
local SEE_FOOD_DIST = 10
local SEE_TARGET_DIST = 6
local START_FACE_DIST = 4
local KEEP_FACE_DIST = 6
local MIN_FOLLOW_DIST = 2
local MAX_CHASE_TIME = 8
--Brain Creation--
local bearbrain = Class(Brain, function(self, inst)
Brain._ctor(self, inst)
end)
local function GetFaceTargetFn(inst)
local target = GetClosestInstWithTag("player", inst, START_FACE_DIST)
if target and not target:HasTag("notarget") then
return target
end
end
local function KeepFaceTargetFn(inst, target)
return inst:GetDistanceSqToInst(target) <= KEEP_FACE_DIST*KEEP_FACE_DIST and not target:HasTag("notarget")
end
--Food Eating Function--
local function EatFoodAction(inst)
local target = FindEntity(inst, SEE_FOOD_DIST, function(item) return inst.components.eater:CanEat(item) and item:IsOnValidGround() end)
if target then
return BufferedAction(inst, target, ACTIONS.EAT)
end
end
--Set up the Behavior Tree--
function bearbrain:OnStart()
local root = PriorityNode( -- Add more actions for more complexity
{
WhileNode( function() return self.inst.components.health.takingfiredamage end, "OnFire", Panic(self.inst)),
IfNode( function() return self.inst.components.combat.target ~= nil end, "hastarget", AttackWall(self.inst)),
ChaseAndAttack(self.inst, MAX_CHASE_TIME),
FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn),
AttackWall(self.inst),
DoAction(self.inst, EatFoodAction), -- Eat action of the priority node
StandStill(self.inst, function() return true end), -- Last action of the Priority Node/if it's not doing any others do this
}, .25) -- Check every 0.25 seconds which behavior it should be doing.
self.bt = BT(self.inst, root) -- attach the behavior tree to the brain
end
--Register Brain--
return bearbrain<file_sep>/Natural Selection/scripts/stategraphs/pigstategraph.lua
--A stategraph is one giant handler for if/then situations--
require("stategraphs/commonstates")
--Feedback to the Player based on the "state" the creature is in-- (This is the then of an if/then statement)
local states=
{
--Idle State--
State{
name = "idle",
tags = {"idle", "canrotate"}, -- Classification of the state (idle = new, canrotate = animation can rotate)
onenter = function(inst, playanim) -- Once we enter the state
inst.AnimState:PlayAnimation("idle", true) -- Loop the idle animation
end,
},
--Running State
State{
name = "run",
tags = {"run", "canrotate" }, -- Classification of the state (run = new, canrotate = animation can rotate)
onenter = function(inst, playanim) -- Once we enter the state
inst.AnimState:PlayAnimation("run", true) -- Loop the run animation
inst.components.locomotor:RunForward() -- Locomotor moves the creature forward
end,
},
--Eating State--
State{
name = "eat",
onenter = function(inst)
inst.Physics:Stop()
inst.AnimState:PlayAnimation("idle", false)
inst.AnimState:PushAnimation("idle", true)
inst.sg:SetTimeout(2+math.random()*4)
end,
ontimeout= function(inst)
inst:PerformBufferedAction()
inst.sg:GoToState("idle", "idle")
end,
},
}
--Grabs actions to go to certain states--
local actionhandlers =
{
--Eating Action Handler--
ActionHandler(ACTIONS.EAT, "eat"),
}
--Grabs events to then go to a certain state-- (This is the if of an if/then statement)
local event_handlers=
{
--Locomote Event Handler--
EventHandler("locomote", -- Grabs an event from the locomotor called locomote
function(inst) -- Unnecessary to name the function if it is being called as we go
--Locomotor check--
if inst.components.locomotor:WantsToMoveForward() then -- Check for locomotor trying to move creature
if inst.sg:HasStateTag("idle") then -- Check if creature isn't moving
inst.sg:GoToState("run") -- If not, go to the running state
end
--Stationary--
else
if not inst.sg:HasStateTag("idle") then -- Check if creature is moving
inst.sg:GoToState("idle") -- If not, go to the Idle state
end
end
end),
}
--Register Stategraph and Make Default State Idle--
return StateGraph("pigstategraph", states, event_handlers, "idle", {}) | 7db041f7eeae9040fd34824b3dc92aee4e3d7dfd | [
"Markdown",
"Lua"
] | 13 | Lua | PressmanMatthew/Natural-Selection-Simulation-in-Dont-Starve | 5874db12965f51a3fdbfe04174e865b8a53c38a5 | d606c1e26bfa366f0db5b5c7dc1bca4fe29c5240 |
refs/heads/master | <repo_name>Goff-Davis/Watchr_Bot<file_sep>/watcher.py
import datetime
import json
import praw
with open("config.json") as json_data_file:
data = json.load(json_data_file)
SEARCH_STRINGS = data["search_strings"]
CATEGORY = data["search_category"]
USER = data["user"]
SUBREDDIT = data["subreddit"]
TIME_FILTER = data["time_filter"]
def main():
reddit = create_reddit()
destination_user = reddit.redditor(USER)
subreddit_to_search = reddit.subreddit(SUBREDDIT)
search_results = search(subreddit_to_search)
if found_submissions(search_results):
message = create_message(search_results)
send_message(message, destination_user)
def create_reddit():
return praw.Reddit(
"watcher",
user_agent="web:watcher:v1.0.0 (by u/MrGamer00)"
)
def search(subreddit):
results = {}
for keyword in SEARCH_STRINGS:
query = subreddit.search(
keyword,
sort="new",
time_filter=TIME_FILTER
)
query_results = []
for submission in query:
query_results.append(submission)
if len(query_results) > 0:
results[keyword] = query_results
return results
def found_submissions(search_results):
return bool(search_results)
def create_message(search_results):
keywords = list(search_results)
category_list = ""
links = ""
i=0
for keyword in keywords:
if (i < len(keywords) - 1):
category_list += f"**{keyword}**, "
else:
category_list += f"**{keyword}** "
links += f"\n\n## {keyword}\n"
for submission in search_results[keyword]:
date_created = generate_date_string(submission)
links += f"- [{submission.title}]({submission.permalink}) ({date_created})\n"
i += 1
header = f"# New Submissions Found\n\n{CATEGORY} matching the search string{'s' if len(category_list) > 1 else ''} {category_list} have been found."
body = f"Links to the postings: {links}"
return f"{header}\n\n{body}"
def generate_date_string(submission):
date = datetime.datetime.fromtimestamp(submission.created_utc)
return date.strftime("%m-%d-%Y %H:%M")
def send_message(message, user):
user.message(
f"{CATEGORY} has been posted.",
message
)
if __name__ == "__main__":
main()
<file_sep>/README.md
# Watchr_Bot

A reddit search bot I created that searches a specific subreddit for keywords. It will message an account with a listing of what has been found. This can be useful for watching for posts. Personally I am using it to check r/watchexchange for watches that I want and notify me when they are listed.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See usage/deployment for notes on how to deploy the project on a live system.
### Prerequisites
#### Software
* [Python 3.6+](https://www.python.org/)
* [praw](https://praw.readthedocs.io/en/latest/)
```
pip install praw
```
Depending on your system you may need to do
```
pip3 install praw
```
#### Configuration
You will need a `praw.ini` file with the following information:
```
[watcher]
client_id=<Your reddit client id>
client_secret=<Your reddit secret>
username=<Yours or your bot's reddit username>
password=<<PASSWORD> or your bot's reddit <PASSWORD>>
```
To obtain a client id and secret you will need to [register your app with reddit.](https://www.reddit.com/prefs/apps) Notify them [here.](https://docs.google.com/forms/d/e/1FAIpQLSezNdDNK1-P8mspSbmtC2r86Ee9ZRbC66u929cG2GX0T9UMyw/viewform)
You will also need a `config.json` file with the following structure:
```
{
"search_strings": ["<array of strings you want to search for>"],
"search_category": "<Name of what you are searching for (for message formatting)>"
"user": "<the username of the person you want to message>",
"subreddit": "<the subreddit you want to search>",
"time_filter": "<what time frame you want to search for>"
}
```
## Usage/Deployment
This script can be run manually. Alternatively you can execute it programmatically, for example as a cronjob. I personally am running it on a [Digital Ocean](https://www.digitalocean.com/) droplet as a cronjob once per hour.
## Example of found results message
```
# New Listings Found
Watches in the categories: **parts**, **repair**, **for repair** have been found.
Links to the postings:
## parts
- [[WTS] Orient Ray Gen 1, Timex E-Compass (T49531), Seiko Compatible Modded Bezel Part](/r/Watchexchange/comments/gch45v/wts_orient_ray_gen_1_timex_ecompass_t49531_seiko/) (05-02-2020 20:24)
## repair
- [[WTS] Vostok, Dumai and Gameboy Watch + Clocks for Repair](/r/Watchexchange/comments/gcr69z/wts_vostok_dumai_and_gameboy_watch_clocks_for/) (05-03-2020 10:07)
## for repair
- [[WTS] Vostok, Dumai and Gameboy Watch + Clocks for Repair](/r/Watchexchange/comments/gcr69z/wts_vostok_dumai_and_gameboy_watch_clocks_for/) (05-03-2020 10:07)
```
## Built With
* [Python](https://www.python.org/)
* [praw](https://praw.readthedocs.io/en/latest/) - Python wrapper for the Reddit API
* [Reddit API](https://www.reddit.com/dev/api/)
## Authors
* **<NAME>** - [Goff-Davis](https://github.com/Goff-Davis)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
| 89649e80868b489e779dd530902447321b68340b | [
"Markdown",
"Python"
] | 2 | Python | Goff-Davis/Watchr_Bot | ef51fee01ed133619ab6f7b5aa40556ffc9fe63b | 7ff54b86a9051527906933dac6abfa227ec66d1a |
refs/heads/master | <repo_name>nishimaru40/ProjectCS251<file_sep>/mysql/mydb.sql
-- phpMyAdmin SQL Dump
-- version 4.8.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 11, 2018 at 11:37 PM
-- Server version: 10.1.32-MariaDB
-- PHP Version: 7.2.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `mydb`
--
-- --------------------------------------------------------
--
-- Table structure for table `admins`
--
CREATE TABLE `admins` (
`ID` int(3) UNSIGNED ZEROFILL NOT NULL,
`adminID` varchar(20) NOT NULL,
`Password` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `admins`
--
INSERT INTO `admins` (`ID`, `adminID`, `Password`) VALUES
(001, 'admin123', '<PASSWORD>');
-- --------------------------------------------------------
--
-- Table structure for table `advertise`
--
CREATE TABLE `advertise` (
`photo_Path` varchar(255) NOT NULL,
`photoID` varchar(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `advertise`
--
INSERT INTO `advertise` (`photo_Path`, `photoID`) VALUES
('images/promo.gif', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `books`
--
CREATE TABLE `books` (
`checkIn` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`endOfContract` varchar(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(25) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`idCard` varchar(13) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`adults` varchar(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`children` varchar(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(25) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `books`
--
INSERT INTO `books` (`checkIn`, `endOfContract`, `name`, `idCard`, `adults`, `children`, `email`, `phone`) VALUES
('15*16*54', '3 yea', '<NAME>', '1234567899874', '2', '1', '<EMAIL>', '916985394'),
('15-12-61', '3 yea', 'eqweqweqwerrge', '1511187145', '2', '2', '<EMAIL>', '888888888'),
('15*16*54', '2 yea', '<NAME>', '2222222222222', '3', '2', '<EMAIL>', '916985394'),
('15*16*54', '2 yea', 'hahahahahah', '999999999999', '3', '1', '<EMAIL>', '916985394'),
('15*16*54', '2 yea', 'eqweqweqw', 'sssssss', '3', '2', '<EMAIL>', '888888888');
-- --------------------------------------------------------
--
-- Table structure for table `room`
--
CREATE TABLE `room` (
`roomID` varchar(6) NOT NULL,
`type` varchar(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `room`
--
INSERT INTO `room` (`roomID`, `type`) VALUES
('01', 'Single Room'),
('02', 'Double Room');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
ADD PRIMARY KEY (`ID`),
ADD UNIQUE KEY `adminID` (`adminID`);
--
-- Indexes for table `advertise`
--
ALTER TABLE `advertise`
ADD PRIMARY KEY (`photo_Path`);
--
-- Indexes for table `books`
--
ALTER TABLE `books`
ADD PRIMARY KEY (`idCard`) USING BTREE;
--
-- Indexes for table `room`
--
ALTER TABLE `room`
ADD PRIMARY KEY (`roomID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
MODIFY `ID` int(3) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/table.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Table V04</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--===============================================================================================-->
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/perfect-scrollbar/perfect-scrollbar.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="css/utilf.css">
<link rel="stylesheet" type="text/css" href="css/mainf.css">
<!--===============================================================================================-->
</head>
<body>
<div class="limiter">
<div class="container-table100">
<div class="wrap-table100">
<div class="table100 ver1 m-b-110">
<div class="table100-head">
<table>
<thead>
<tr class="row100 head">
<th class="cell100 column1">Name</th>
<th class="cell100 column2">IDCard</th>
<th class="cell100 column3">Phone</th>
<th class="cell100 column4">Email</th>
<th class="cell100 column5">Check-in</th>
<th class="cell100 column6">Delete</th>
</tr>
</thead>
</table>
</div>
<div class="table100-body js-pscroll">
<table>
<tbody>
<?php
require("mysql/connect.php");
$sql="select * from books ";
$result=mysqli_query($con,$sql);
if($result){
while($record=mysqli_fetch_array($result,MYSQLI_ASSOC)){
$name=$record['name'];
$card=$record['idCard'];
$phone=$record['phone'];
$email=$record['email'];
$chIn=$record['checkIn'];
echo'
<tr class="row100 body">
<td class="cell100 column1">'.$name.'</td>
<td class="cell100 column2">'.$card.'</td>
<td class="cell100 column3">'.$phone.'</td>
<td class="cell100 column4">'.$email.'</td>
<td class="cell100 column5">'.$chIn.'</td>
<form method="post" action="delete.php">
<input type="hidden" name="idCard" value='.$record['idCard'].'>
<td class="cell100 column6"><input name="submit" type="submit" value="Delete" onclick= window.location.reload()/></td>
</form>
</tr>
';
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!--===============================================================================================-->
<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/bootstrap/js/popper.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/select2/select2.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script>
$('.js-pscroll').each(function(){
var ps = new PerfectScrollbar(this);
$(window).on('resize', function(){
ps.update();
})
});
</script>
<!--===============================================================================================-->
<script src="js/main.js"></script>
</body>
</html><file_sep>/photoCtrl.php
<?php
session_start();
class photoCtrl
{
private $error;
private $con;
// ประกาศปุ๊บ connect db เลย
function __construct()
{
$serverName = "localhost";
$userName = "root";
$passWord ="";
$dbName = "mydb";
$this->con = mysqli_connect($serverName,$userName,$passWord,$dbName);
if($this->con->connect_error){
die("Connection failed: " . $this->conn->connect_error);
}
}
public function update($path){
$sql = "UPDATE advertise SET photo_Path = '$path' ";
$this->con->query($sql) ;
}
public function select(){
$sql = "SELECT * FROM advertise ";
$query = mysqli_query($this->con,$sql);
$result = $query->fetch_assoc();
return $result['photo_Path'];
$con->close();
}
}
?>
<file_sep>/Home.php
<?php
include("photoCtrl.php");
$ctrl = new photoCtrl;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="utf-8">
<meta name = "format-detection" content = "telephone=no" />
<link rel="icon" href="images/favicon.ico">
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="css/camera.css">
<link rel="stylesheet" href="css/component.css" />
<link rel="stylesheet" type="text/css" href="css/tooltipster.css" />
<link rel="stylesheet" href="css/style.css">
<script src="js/jquery.js"></script>
<script src="js/jquery-migrate-1.2.1.js"></script>
<script src="js/script.js"></script>
<script src="js/superfish.js"></script>
<script src="js/jquery.ui.totop.js"></script>
<script src="js/jquery.equalheights.js"></script>
<script src="js/jquery.mobilemenu.js"></script>
<script src="js/jquery.easing.1.3.js"></script>
<script src="js/jquery.tooltipster.js"></script>
<script src="js/camera.js"></script>
<!--[if (gt IE 9)|!(IE)]><!-->
<script src="js/jquery.mobile.customized.min.js"></script>
<!--<![endif]-->
<script src="js/modernizr.custom.js"></script>
<script>
$(document).ready(function(){
jQuery('#camera_wrap').camera({
loader: 'pie',
pagination: true ,
minHeight: '200',
thumbnails: true,
height: '40.85106382978723%',
caption: true,
navigation: true,
fx: 'mosaic'
});
$().UItoTop({ easingType: 'easeOutQuart' });
$('.tooltip').tooltipster();
});
</script>
<!--[if lt IE 9]>
<div style=' clear: both; text-align:center; position: relative;'>
<a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
<img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" height="42" width="820" alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today." />
</a>
</div>
<script src="js/html5shiv.js"></script>
<link rel="stylesheet" media="screen" href="css/ie.css">
<![endif]-->
</head>
<body class="page1" id="top">
<!--==============================header=================================-->
<header>
<div class="container_12">
<div class="grid_12">
<h1>
<a href="home.php">
<img src="images/logo.png" alt="Your Happy Family">
</a>
</h1>
<div class="menu_block ">
<nav class="horizontal-nav full-width horizontalNav-notprocessed">
<ul class="sf-menu">
<li class="current"><a href="home.php">Home</a></li>
<li><a href="Room.php">Room</a></li>
<li><a href="Gallery.php">Gallery</a></li>
<li><a href="Booking.php">Booking</a></li>
<li><a href="Contacts.php">Contacts</a></li>
</ul>
</nav>
<div class="clear"></div>
</div>
</div>
</div>
</header>
<div class="container_12">
<div class="grid_12">
<div class="slider_wrapper ">
<div class="camera_wrap" id="camera_wrap">
<div data-thumb="images/thumb.png" data-src="images/slide.jpg">
<div class="caption fadeFromBottom">
Clever interior projects for your room
</div>
</div>
<div data-thumb="images/thumb1.jpg" data-src="images/slide1.jpg">
<div class="caption fadeFromBottom">
room improvement ideas for you
</div>
</div>
<div data-thumb="images/thumb2.png" data-src="images/slide2.jpg">
<div class="caption fadeFromBottom">
Premium design tips
</div>
</div>
<div data-thumb="images/thumb3.png" data-src="images/slide3.jpg">
<div class="caption fadeFromBottom">
Only creative ideas
</div>
</div>
</div>
</div>
</div>
</div>
<div class="page1_block">
<div class="container_12">
<div class="grid_12">
<div class="center">
<h2>Lucifer Apartment</h2>
<br>
<?php
$photo = $ctrl->select();
echo '<img src="'.$photo.'" height="500" width="700" >'
?>
<div class="alright">
</div>
</div>
</div>
</div>
</div>
<!--==============================Content=================================-->
<div class="content"><div class="ic">More Website Templates @ TemplateMonster.com - March 10, 2014!</div>
<div class="container_12">
<div class="grid_12 center">
<h3>Featured Works</h3>
<section class="tt-grid-wrapper">
<ul class="tt-grid tt-effect-stackback tt-effect-delay">
<li><a href="#"><img src="images/feat1.jpg" alt="img01"></a></li>
<li><a href="#"><img src="images/feat2.jpg" alt="img02"></a></li>
<li><a href="#"><img src="images/feat3.jpg" alt="img03"></a></li>
<li><a href="#"><img src="images/feat4.jpg" alt="img04"></a></li>
<li><a href="#"><img src="images/feat5.jpg" alt="img05"></a></li>
<li><a href="#"><img src="images/feat6.jpg" alt="img06"></a></li>
</ul>
<nav>
<a class="tt-current"></a><a></a><a></a><a></a>
</nav>
</section>
<div class="clear"></div>
<div class="alright">
</div>
</div>
</div>
<div class="hor"></div>
<div class="container_12">
<div class="grid_12 center">
<h3>Services</h3>
</div>
<div class="grid_2">
<ul class="list">
<li><a href="#">รถตู้รับส่งฟรี 6.30 - ตี 1</a></li>
<li><a href="#">7 - 11</a></li>
<li><a href="#">Food Plaza</a></li>
<li><a href="#">ตู้ATM</a></li>
</ul>
</div>
<div class="grid_2">
<ul class="list">
<li><a href="#">สระว่ายน้ำ </a></li>
<li><a href="#">ฟิตเนสเซ็นเตอร์</a></li>
<li><a href="#">สนามแบดมินตัน</a></li>
<li><a href="#">สนามฟุตซอล</a></li>
</ul>
</div>
</div>
</div>
<!--==============================footer=================================-->
<footer>
<div class="container_12">
<div class="grid_12">
<div class="socials">
<section id="facebook">
<a href="#" target="_blank"><span id="fackbook" class="tooltip" title="Link us on Facebook">f</span></a>
</section>
<section id="twitter">
<a href="#" target="_blank"><span id="twitter-default" class="tooltip" title="Follow us on Twitter">t</span></a>
</section>
<section id="google">
<a href="#" target="_blank"><span id="google-default" class="tooltip" title="Follow us on Google Plus">g<span>+</span></span></a>
</section>
<section id="rss">
<a href="#" target="_blank"><span id="rss-default" class="tooltip" title="Follow us on Dribble">d</span></a>
</section>
</div>
<div class="copy">
Lucifer Apartment © 2014 | <a href="#">Privacy Policy</a> <br> Website designed by <a href="http://www.templatemonster.com/" rel="nofollow">TemplateMonster.com </a>
</div>
</div>
</div>
</footer>
<script src="js/classie.js"></script>
<script src="js/thumbnailGridEffects.js"></script>
</body>
</html>
<file_sep>/delete.php
<?php
require 'mysql/connect.php';
$id = $_POST['bookID'];
$sql="delete from book where bookID=$id ";
$result=mysqli_query($con,$sql);
if($result){
header("Refresh:0; url=table.php");
}else{
echo mysqli_error($con);
}
?> | 8ac9e5654ebbd326a27f54edcda5fd6fdfcf8d0e | [
"SQL",
"PHP"
] | 5 | SQL | nishimaru40/ProjectCS251 | 6f9b5c1bbdda8053f77cabca4c38547d295f47c2 | ac53626c626b46ac8624e098b34994d7e12437ef |
refs/heads/master | <repo_name>LunaChevalier/vs-zenn<file_sep>/src/type.ts
interface Header {
emoji: string;
title: string;
chapters: string[];
}<file_sep>/src/util.ts
import * as yaml from "js-yaml";
import * as fs from 'fs';
import * as path from 'path';
export function getHeader(text: string): Header {
const newLineHex = /\r\n|\n/;
const separate = "---";
const startIndex = text.split(newLineHex).indexOf(separate) + 1;
const endIndex = text.split(newLineHex).indexOf(separate, startIndex);
return yaml.safeLoad(text.split(newLineHex).slice(startIndex, endIndex).join('\n')) as Header;
}
export function isExistsPath(p: string): boolean {
try {
fs.accessSync(p);
} catch (err) {
return false;
}
return true;
}
export function getBookConfig(filepath: string): Header {
return yaml.safeLoad(fs.readFileSync(filepath).toString()) as Header;
}
export function generateBookConfigFile(conf: Header) {
return yaml.dump(conf);
}
export function getFileNameLatest(filepath: string): string {
return fs.readdirSync(filepath).map(filename => {
return {
filename: filename,
mtime: fs.statSync(path.join(filepath, filename)).mtime.getTime(),
};
}).sort((a, b) => b.mtime - a.mtime)[0].filename;
}<file_sep>/src/extension.ts
import * as vscode from 'vscode';
import { ArticleProvider } from './article';
import { Book, BookProvider } from './book';
import * as file from './file';
import * as cp from 'child_process';
import * as util from "./util";
import * as path from "path";
export function activate(context: vscode.ExtensionContext) {
const config = vscode.workspace.getConfiguration("vs-zenn");
if (!config.rootDir || !util.isExistsPath(config.rootDir)) {
vscode.window.showInformationMessage("Don't exist workspace");
return;
}
const articleProvider = new ArticleProvider(config.rootDir);
vscode.window.registerTreeDataProvider('vs-zenn-article', articleProvider);
const bookProvider = new BookProvider(config.rootDir);
vscode.window.registerTreeDataProvider('vs-zenn-book', bookProvider);
context.subscriptions.push(vscode.commands.registerCommand('vs-zenn.new.article', async () => {
if (!config.rootDir || !util.isExistsPath(config.rootDir)) {
vscode.window.showInformationMessage("Don't exist workspace");
return;
}
const title = await vscode.window.showInputBox({ prompt: "input article title"});
const type = await vscode.window.showQuickPick(["tech", "idea"], {canPickMany: false});
process.chdir(config.rootDir);
cp.execSync(`${config.usingCommand} zenn new:article --title ${title} --type ${type}`);
const newFile = util.getFileNameLatest(path.join(config.rootDir, 'articles'));
file.tryOpenFile(path.join(config.rootDir, 'articles', newFile));
articleProvider.refresh();
}));
context.subscriptions.push(vscode.commands.registerCommand('vs-zenn.new.book', async () => {
if (!config.rootDir || !util.isExistsPath(config.rootDir)) {
vscode.window.showInformationMessage("Don't exist workspace");
return;
}
const title = await vscode.window.showInputBox({ prompt: "input article title"});
process.chdir(config.rootDir);
cp.execSync(`${config.usingCommand} zenn new:book --title ${title}`);
bookProvider.refresh();
}));
vscode.commands.registerCommand('vs-zenn.openFile', filePath => file.tryOpenFile(filePath));
vscode.commands.registerCommand('vs-zenn.refresh', () => {
articleProvider.refresh();
bookProvider.refresh();
});
context.subscriptions.push(vscode.commands.registerCommand("vs-zenn.add.chapter", async () => {
if (!config.rootDir || !util.isExistsPath(config.rootDir)) {
vscode.window.showInformationMessage("Don't exist workspace");
return;
}
const items = Book.getTitles();
const type = await vscode.window.showQuickPick(
items.map((obj) => obj.title),
{
canPickMany: false,
placeHolder: "select title you want to add chapter",
}
);
if (!type) {
return;
}
const newTitle = await vscode.window.showInputBox({
placeHolder: "input new article title",
});
if (!newTitle){
return;
}
const bookSlug = items.filter((obj) => obj.title === type)[0].slug;
const chapters = Book.getChapters(bookSlug);
const chapter = await vscode.window.showQuickPick(chapters, {
canPickMany: false,
placeHolder: "input or select number you want to add chapter",
});
if (!chapter) {
return;
}
const newSlug = await vscode.window.showInputBox({
prompt: "input new chapter name",
});
if (!newSlug) {
return;
}
Book.addChapter(bookSlug, parseInt(chapter), newTitle, newSlug);
vscode.window.showInformationMessage("vs-zenn.add chapter books");
bookProvider.refresh();
})
);
context.subscriptions.push(vscode.workspace.onDidSaveTextDocument(() => {
vscode.commands.executeCommand("vs-zenn.refresh");
}));
}
export function deactivate() {}
<file_sep>/src/book.ts
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import * as util from './util';
export class BookProvider implements vscode.TreeDataProvider<Book> {
private _onDidChangeTreeData: vscode.EventEmitter<Book | undefined> = new vscode.EventEmitter<Book | undefined>();
readonly onDidChangeTreeData?: vscode.Event<Book | undefined> = this._onDidChangeTreeData.event;
constructor(private workspaceRoot: string) {
}
refresh(): void {
this._onDidChangeTreeData.fire(undefined);
}
getTreeItem(element: Book): vscode.TreeItem | Thenable<vscode.TreeItem> {
return element;
}
getChildren(element?: Book): vscode.ProviderResult<Book[]> {
if (element && element.filePath) {
return Promise.resolve(this.getBooks(element.filePath));
} else {
return Promise.resolve(this.getBooks(path.join(this.workspaceRoot, "books")));
}
}
private getBooks(booksPath: string): Book[] {
let items: Array<Book> = [];
if (util.isExistsPath(booksPath)) {
if (/.*books$/.test(booksPath)) {
items = fs.readdirSync(booksPath, "utf-8").map((fileName) => {
const filePath = path.join(booksPath, fileName, "config.yaml");
const bookData = fs.readFileSync(filePath).toString();
return new Book(
`📖${util.getHeader(bookData)?.title}`,
path.join(booksPath, fileName),
vscode.TreeItemCollapsibleState.Collapsed
);
});
} else {
items = fs
.readdirSync(booksPath, "utf-8")
.filter(
(name) =>
/.*\.md$/.test(name) ||
/.*\.yaml$/.test(name) ||
/.*\.yml$/.test(name)
).map((fileName) => {
const filePath = path.join(booksPath, fileName);
const articleData = fs.readFileSync(filePath).toString();
const header = util.getHeader(articleData);
return new Book(
`${/.*\.md$/.test(filePath) ? "📝" + header?.title : "⚙設定"}`,
filePath,
vscode.TreeItemCollapsibleState.None,
{
command: "vs-zenn.openFile",
title: "",
arguments: [filePath],
}
);
});
if (items.length === 0) {
vscode.window.showErrorMessage('failed get book items.');
return [];
}
const bookConfigPath = items.filter((item) => item.filePath?.includes("config.yaml"))[0].filePath;
if (!bookConfigPath) {
vscode.window.showErrorMessage("failed get book config.");
return [];
}
const bookConfig = fs.readFileSync(bookConfigPath).toString();
const chapters = util.getHeader(bookConfig).chapters;
items = items.sort((a, b) => {
if (!a.filePath || !b.filePath) {
return -1;
}
return chapters.indexOf(a.filePath.split('\\').slice(-1)[0].split('.')[0]) - chapters.indexOf(b.filePath.split('\\').slice(-1)[0].split('.')[0]);
});
}
}
return items;
}
}
export class Book extends vscode.TreeItem {
constructor(
public readonly label: string,
public readonly filePath?: string,
public readonly collapsibleState?: vscode.TreeItemCollapsibleState,
public readonly command?: vscode.Command
) {
super(label, collapsibleState || vscode.TreeItemCollapsibleState.None);
}
static getTitles() {
const config = vscode.workspace.getConfiguration("vs-zenn");
const rootDirBook = path.join(config.rootDir, "books");
const items = fs.readdirSync(rootDirBook, "utf-8").map((dirName) => {
const filePath = path.join(rootDirBook, dirName, "config.yaml");
const articleData = fs.readFileSync(filePath).toString();
const header = util.getHeader(articleData);
return {
slug: dirName,
title: header.title
};
});
return items;
}
static getChapters(slug: string) {
const config = vscode.workspace.getConfiguration("vs-zenn");
const rootDirBook = path.join(config.rootDir, "books", slug);
const files = fs.readdirSync(rootDirBook, "utf-8");
return Array(files.length).fill(0).map((v,i)=>++i).map((i) => i.toString());
}
static addChapter(bookSlug: string, chapterIndex: number, title: string, chapter: string) {
if (!Book.validateChapter(chapter)) {
vscode.window.showErrorMessage(
`Error: Chapter name must be named with a-z, 1-9 or '-'.\n You inputted ${chapter}`
);
return;
}
const config = vscode.workspace.getConfiguration("vs-zenn");
const rootDirBook = path.join(config.rootDir, "books", bookSlug);
const header = util.getBookConfig(path.join(rootDirBook, "config.yaml"));
header.chapters.splice(chapterIndex - 1, 0, chapter);
fs.writeFileSync(
path.join(rootDirBook, "config.yaml"),
util.generateBookConfigFile(header)
);
const content = `---\ntitle: ${title}\n---\n`;
fs.writeFileSync(path.join(rootDirBook, `${chapter}.md`), content);
}
private static validateChapter(chapter: string):boolean {
return /^[a-z0-9-]+$/.test(chapter);
}
}
<file_sep>/README.md
# vs-zenn README
This vscode extension will make [zenn](https://zenn.dev/) writing easier locally.
This vscode extension is **unofficial**.
## Features
comming soon...
## Requirements
If you haven't yet installed `zenn-cli`, you need to install it.
[hot to install](https://zenn.dev/zenn/articles/install-zenn-cli)
## Extension Settings
Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.
For example:
This extension contributes the following settings:
* `va-zenn.usingCommand`: executing the zenn-cli commands(`npx` or `yarn`)
<file_sep>/src/article.ts
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import * as util from './util';
export class ArticleProvider implements vscode.TreeDataProvider<Article> {
private _onDidChangeTreeData: vscode.EventEmitter<Article | undefined> = new vscode.EventEmitter<Article | undefined>();
readonly onDidChangeTreeData?: vscode.Event<Article | undefined> = this._onDidChangeTreeData.event;
constructor(private workspaceRoot: string) {
}
refresh(): void {
this._onDidChangeTreeData.fire(undefined);
}
getTreeItem(element: Article): vscode.TreeItem | Thenable<vscode.TreeItem> {
return element;
}
getChildren(element?: Article): vscode.ProviderResult<Article[]> {
return Promise.resolve(this.getArticles(path.join(this.workspaceRoot, 'articles')));
}
private getArticles(articlesPath: string): Article[] {
let items = [new Article("labels")];
if (util.isExistsPath(articlesPath)) {
return fs.readdirSync(articlesPath, "utf-8").map((file) => {
const filePath = path.join(articlesPath, file);
const data = fs.readFileSync(filePath, "utf-8");
const header = util.getHeader(data);
return new Article(`${header?.emoji}${header?.title}`, filePath, {
command: "vs-zenn.openFile",
title: "",
arguments: [filePath],
});
});
}
return items;
}
}
export class Article extends vscode.TreeItem {
constructor(
public readonly label: string,
public readonly filePath?: string,
public readonly command?: vscode.Command
) {
super(label);
}
}
<file_sep>/src/file.ts
import * as vscode from 'vscode';
export async function tryOpenFile(workspaceUri: string): Promise<void> {
await openFile(workspaceUri);
}
async function openFile(fileName: string): Promise<void> {
const doc = await vscode.workspace.openTextDocument(fileName);
vscode.window.showTextDocument(doc);
}
| 345028cdff54c839289e2e3d725a43dcdbd3cd25 | [
"Markdown",
"TypeScript"
] | 7 | TypeScript | LunaChevalier/vs-zenn | 89b76587fa4074a6b4598731ee38dae62f9d0b52 | 43f933adfd87934d19db3393a2c99c63b692be0c |
refs/heads/master | <file_sep>MyApp
.service('itemService', function ($timeout, $interval, groundsService) {
var bombExploding = false;
var potionUsed = false;
var Item = function(){
this.speedModifier = (s)=>s;
this.setRemove = () =>{};
this.update = () => {};
};
var Boots = function(m, t){
this.name = 'Boots';
var self = this;
var modifier = m || 100;
var timeout = t || 5000;
this.frame = 342;
this.timeLeft = 0;
Item.apply(this, arguments);
this.speedModifier = (speed)=> speed+modifier;
this.setRemove = function(f){
if(timeout>0){
self.timeLeft = timeout;
var i =$interval(function(){
if(self.timeLeft <=0){
$interval.cancel(i);
}
else{
self.timeLeft -=1000;
}
}, 1000);
$timeout(function(){
f();
},timeout)
}
};
};
var TrickBoots = function(t){
this.name = 'TrickBoots';
var self = this;
this.frame = 341;
var timeout = t || 5000;
this.timeLeft = 0;
Item.apply(this, arguments);
this.speedModifier = (speed)=> -speed;
this.setRemove = function(f){
self.timeLeft = timeout;
var i =$interval(function(){
if(self.timeLeft <=0){
$interval.cancel(i);
}
else{
self.timeLeft -=1000;
}
}, 1000);
if(timeout>0){
$timeout(function(){
f();
},timeout)
}
};
};
var Dynamite = function(){
var self = this;
this.name = 'Dynamite';
this.frame = 230;
Item.apply(this, arguments);
this.update = function(keyboard,game, player){
if(keyboard.space.isDown && !bombExploding){
bombExploding = true;
this.removeFunction();
var dynamite = game.add.sprite(player.position.x,player.position.y, 'items');
var x = player.position.x;
var y = player.position.y;
dynamite.scale.setTo(1.5,1.5);
dynamite.animations.add('willExplode', [230,228], 4, true);
dynamite.animations.play('willExplode');
var playerDied = false;
$timeout(function(){
var explosion = game.add.sprite(x-32,y-32, 'explosion');
explosion.scale.setTo(0.5,0.5);
explosion.animations.add('explosion', [1,2,3,4,5], 10, true);
explosion.animations.play('explosion');
dynamite.destroy();
if(player.position.x > x-45 && player.position.x < x + 45 && player.position.y > y-45 && player.position.y < y + 45 ) {
player.destroy();
var diedText = game.add.text(game.world.centerX, game.world.centerY, 'You died !', {
fontSize: '40px',
fill: '#000'
});
playerDied = true;
}
var destroy = [];
var finalDestroy = [];
destroy.push({
wall : !game.map[Math.round(y/32)-1][Math.round(x/32)].value,
x : Math.round(x/32),
y : Math.round(y/32)-1
});
destroy.push({
wall : !game.map[Math.round(y/32)+1][Math.round(x/32)].value,
x : Math.round(x/32),
y : Math.round(y/32)+1
});
destroy.push({
wall : !game.map[Math.round(y/32)][Math.round(x/32)-1].value,
x : Math.round(x/32)-1,
y : Math.round(y/32)
});
destroy.push({
wall : !game.map[Math.round(y/32)][Math.round(x/32)+1].value,
x : Math.round(x/32)+1,
y : Math.round(y/32)
});
destroy.push({
wall : !game.map[Math.round(y/32)-1][Math.round(x/32)-1].value,
x : Math.round(x/32)-1,
y : Math.round(y/32)-1
});
destroy.push({
wall : !game.map[Math.round(y/32)-1][Math.round(x/32)+1].value,
x : Math.round(x/32)+1,
y : Math.round(y/32)-1
});
destroy.push({
wall : !game.map[Math.round(y/32)+1][Math.round(x/32)-1].value,
x : Math.round(x/32)-1,
y : Math.round(y/32)+1
});
destroy.push({
wall : !game.map[Math.round(y/32)+1][Math.round(x/32)+1].value,
x : Math.round(x/32)+1,
y : Math.round(y/32)+1
});
destroy.map(function(e){
if(e.wall && e.x && e.y && e.x && e.y<game.sizeMap.y && e.x<game.sizeMap.x){
finalDestroy.push(e);
}
});
finalDestroy.map(function(e){
var wall = game.currentMap[e.y][e.x];
wall.destroy();
groundsService.addGroundToGame(game, e.x*32, e.y*32);
});
$timeout(function(){
bombExploding = false;
explosion.destroy();
if(playerDied){
$timeout(function () {
game.reset();
}, 2000);
}
},500);
},3000)
}
};
this.setRemove = function(f){
this.removeFunction = f;
};
};
var Potion = function(){
var self = this;
this.name = 'Potion';
this.frame = 361;
Item.apply(this, arguments);
this.setRemove = function(f){
this.removeFunction = f;
};
this.update = function(keyboard,game, player){
if(keyboard.enter.isDown && !potionUsed){
self.removeFunction();
var g = groundsService.ground();
var t = Math.floor(Math.random()*g.children.length);
var w = g.children[t];
player.body.position = new Phaser.Point(w.x, w.y)
potionUsed = true;
$timeout(function(){
potionUsed = false;
},1500)
}
};
};
return {
Boots : Boots,
TrickBoots : TrickBoots,
Dynamite : Dynamite,
Potion : Potion
}
});<file_sep>MyApp
.service('wallsService', function () {
var wallGroup;
var wallListImgs = [1,3,5,7,9,11,13,15,81,83,85,87,89,91,93,95,161,163,165,167,169,171,173,175];
var wallId;
var generateGroup = function(game){
wallGroup = game.add.group();
wallGroup.enableBody = true;
wallId = wallListImgs[Math.floor(Math.random() * (wallListImgs.length-1))];
};
var addWallToGame = function(game,x,y){
var w = game.add.sprite(x, y, 'wall');
w.frame = wallId;
wallGroup.add(w);
w.body.immovable = true;
return w;
};
return {
generateGroup : generateGroup,
addWallToGame : addWallToGame,
walls : function(){
return wallGroup;
}
}
});<file_sep>MyApp
.service('mazeService', function () {
const CONSTANTS = {
WALL : 0,
PATH : 1
};
var Tile = function(value){
this.value = value;
};
var Wall = function(tile1, tile2){
this.tile1 = tile1;
this.tile2 = tile2;
};
var WallMap = function(){
this.wallList = [];
this.addWall = function(wall){
this.wallList.push(wall);
};
this.getWall = function(tile1,tile2){
for(var i = 0; i< this.wallList.length; i++){
var w = this.wallList[i];
if((w.tile1 == tile1 && w.tile2 == tile2)||(w.tile1 == tile2 && w.tile2 == tile1)){
return w;
}
}
return null;
};
this.deleteWall = function(index){
this.wallList.splice(index,1);
};
this.findWallWithDifferentTileValues = function(){
var wallsWithDifferentValues = [];
for(var i = 0; i< this.wallList.length; i++){
var w = this.wallList[i];
if(w.tile1.value != w.tile2.value){
wallsWithDifferentValues.push({
wall : w,
index : i
});
}
}
return wallsWithDifferentValues.length?wallsWithDifferentValues[Math.floor(Math.random()*wallsWithDifferentValues.length)]:null;
};
};
function generateTheMap(mapWidth, mapHeight,lastExit){
if(!mapHeight){
mapHeight = mapWidth;
}
var map = [];
var wallMap = new WallMap();
for(var i = 0; i<mapHeight; i++){
var tmpMap = [];
for(var j = 0; j<mapWidth; j++){
var t = new Tile((mapWidth*i) + j);
//top wall
if(i>0){
wallMap.addWall(new Wall(t, map[i-1][j]));
}
//left wall
if(j>0){
wallMap.addWall(new Wall(t, tmpMap[j-1]));
}
tmpMap.push(t)
}
map.push(tmpMap);
}
function processMap(){
function flattenTiles(a, b){
for(var i = 0; i<mapHeight; i++){
for(var j = 0; j<mapWidth; j++){
if(map[i][j].value == a){
map[i][j].value = b;
}
}
}
}
var w;
while(w = wallMap.findWallWithDifferentTileValues()){
flattenTiles(w.wall.tile1.value, w.wall.tile2.value);
wallMap.deleteWall(w.index);
}
}
function generateMap(){
var entrance =lastExit?(lastExit.i-1)/2 : Math.floor(Math.random()*mapHeight);
var exit = Math.floor(Math.random()*mapHeight);
var entranceCoordinates, exitCoordinates;
var generatedMap = [];
for(var i = 0; i<mapHeight; i++){
var rowWall = [];
var rowNumber = [];
for(var j = 0; j<mapWidth; j++){
var t = map[i][j];
//left wall
if(j == 0 || (j>0 && wallMap.getWall(t, map[i][j-1]))){
rowWall.push(new Tile(CONSTANTS.WALL));
if(i == entrance && j == 0){
entranceCoordinates = {
i : (entrance*2)+1,
j : 0
};
rowNumber.push(new Tile(CONSTANTS.PATH));
}
else{
rowNumber.push(new Tile(CONSTANTS.WALL));
}
}
else{
if(i>0){
rowWall.push(new Tile(CONSTANTS.PATH));
}
else{
rowWall.push(new Tile(CONSTANTS.WALL));
}
rowNumber.push(new Tile(CONSTANTS.PATH));
}
//top wall
if(i == 0 || (i>0 && wallMap.getWall(t, map[i-1][j]))){
rowWall.push(new Tile(CONSTANTS.WALL));
}
else{
rowWall.push(new Tile(CONSTANTS.PATH));
}
//right wall
rowNumber.push(new Tile(CONSTANTS.PATH));
if(j+1 == mapWidth){
rowWall.push(new Tile(CONSTANTS.WALL));
if(i == exit){
exitCoordinates = {
i : (exit*2)+1,
j : (mapWidth*2)
};
rowNumber.push(new Tile(CONSTANTS.PATH));
}
else{
rowNumber.push(new Tile(CONSTANTS.WALL));
}
}
}
generatedMap.push(rowWall);
generatedMap.push(rowNumber);
}
var tmp = [];
for(var i = 0; i<mapWidth; i++){
tmp.push(new Tile(CONSTANTS.WALL));
tmp.push(new Tile(CONSTANTS.WALL));
}
tmp.push(new Tile(CONSTANTS.WALL));
generatedMap.push(tmp);
return {
map : generatedMap,
entrance : entranceCoordinates,
exit : exitCoordinates
};
}
processMap();
return generateMap();
}
return {
generateMap : generateTheMap
}
});<file_sep>MyApp
.service('trapsService', function () {
var trapGroup;
var deathGroup;
var generateGroup = function(game){
};
var addTrapToGame = function(orientation, game, x,y){
};
return {
generateGroup : generateGroup,
addTrapToGame : addTrapToGame,
traps : function(){
return trapGroup;
},
death : function(){
return trapGroup;
}
}
});<file_sep>module.exports = function(tile1, tile2){
this.tile1 = tile1;
this.tile2 = tile2;
};<file_sep>module.exports = function(width, height){
this.wallList = [];
this.addWall = function(wall){
this.wallList.push(wall);
};
this.getWall = function(tile1,tile2){
for(var i = 0; i< this.wallList.length; i++){
var w = this.wallList[i];
if((w.tile1 == tile1 && w.tile2 == tile2)||(w.tile1 == tile2 && w.tile2 == tile1)){
return w;
}
}
return null;
};
this.deleteWall = function(index){
this.wallList.splice(index,1);
};
this.findWallWithDifferentTileValues = function(){
var wallsWithDifferentValues = [];
for(var i = 0; i< this.wallList.length; i++){
var w = this.wallList[i];
if(w.tile1.value != w.tile2.value){
wallsWithDifferentValues.push({
wall : w,
index : i
});
}
}
return wallsWithDifferentValues.length?wallsWithDifferentValues[Math.floor(Math.random()*wallsWithDifferentValues.length)]:null;
};
};<file_sep>MyApp
.service('groundsService', function ($interval, $timeout) {
var groundGroup;
var groundId;
var generateGroup = function(game){
groundGroup = game.add.group();
groundGroup.enableBody = true;
groundId = Math.floor(Math.random() * 48);
};
var addGroundToGame = function(game,x,y){
var w = game.add.sprite(x, y, 'ground');
w.frame = groundId;
groundGroup.add(w);
w.body.immovable = true;
return w;
};
return {
generateGroup : generateGroup,
addGroundToGame : addGroundToGame,
ground : function(){
return groundGroup;
}
}
}); | 832f0ed01ed1effbf38f2e6e8c73ccb134fdb8c7 | [
"JavaScript"
] | 7 | JavaScript | Chupsy/Escape-it | f32ef015be2b117fad9abd157c293c9b96db5d78 | 04b504703506c38e68783831871906d059557e2f |
refs/heads/master | <file_sep>import _ from 'underscore'
import formatDate from './format-date'
import trashBucketSvg from './trash-icon.js'
import { submitAuthForm, signOut, initFirebase, synchronization } from './synchronization'
function getTime (note) {
return formatDate(note.creationTime)
}
class Note {
constructor (text, id) {
this.id = id;
this.text = text;
this.creationTime = new Date();
this.checked = false;
}
}
const renderNotesList = (state, activeNote) => {
let result = state.notes.reduce((acc, currentNote) => {
const text = currentNote.text.slice(0, 16);
const checkboxValue = currentNote.checked === true? 'checked' : ''
if (currentNote === activeNote){
return acc = `
<li class="select-note note-href selected" id="${currentNote.id}">
<strong><a href="#${currentNote.id}">${text}
<input type="checkbox" class="checkbox" ${checkboxValue}>
<p class="time">${getTime(currentNote)}</p></a></strong>
</li>
` + acc
}
return acc = `
<li class="select-note note-href" id="${currentNote.id}">
<strong><a href="#${currentNote.id}">${text}
<input type="checkbox" class="checkbox" ${checkboxValue}>
<p class="time">${getTime(currentNote)}</p></a></strong>
</li>` + acc
}, '');
return `<li class="add note-href"><strong><a href="#">
<button class="add-button mui-btn mui-btn--fab mui-btn--primary">+</button>
<button class="delete-button mui-btn mui-btn--fab mui-btn--primary">${trashBucketSvg}</button>
<button class="check-all-button mui-btn mui-btn--fab mui-btn--primary">✓</button>
</a></strong></li>` + result + `<button class="logout-button mui-btn mui-btn--flat mui-btn--primary">выйти из аккаунта</button>`;
}
const renderForm = (state, currentNote) => {
const form = document.createElement('form');
form.classList.add('mui-form');
const div = document.createElement('div')
div.classList.add('mui-textfield');
const input = document.createElement('textarea');
if (currentNote) {
input.insertAdjacentHTML('afterbegin', currentNote.text);
}
input.classList.add('form-text-input');
input.placeholder = 'Новая заметка';
div.appendChild(input)
form.appendChild(div);
const submit = document.createElement('input');
submit.classList.add('mui-btn')
submit.type = 'submit';
submit.value = 'Save';
form.appendChild(submit);
return form;
}
const renderNote = (state, currentNote) => {
if (!currentNote) return `
<br>
<h1>Заметки</h1>
<p>В этом веб-приложении можно создавать заметки, сохранять их, редактировать и удалять.</p>
<p>Такой невообразимый функционал стал возможен благодаря использованию JS, библиотек MUI и Underscore. Аутентификация работает через Google Firebase.
</p>
<p>Для сохранения заметки можно просто убрать фокус с поля ввода. Для удаления заметки отметьте ее галочкой, и нажмите на соответствующую кнопку.
</p>
`
return `<p class="editable-note">${currentNote.text}</p>
<p class="time">${getTime(currentNote)}</p>`
}
const renderLoginPage = (state) => {
const modalEl = document.createElement('div');
modalEl.style.width = '400px';
modalEl.style.height = '300px';
modalEl.style.margin = '100px auto';
modalEl.style.padding = '20px';
modalEl.style.backgroundColor = '#fff';
const welcomePhrase = state.user.registered? `введите свои данные` : `зарегистрируйтесь`;
const buttonPhrase = state.user.registered? `нет аккаунта` : `есть аккаунт`;
// show modal
modalEl.innerHTML = `
<form class="mui-form">
<legend class="">Пожалуйста, ${welcomePhrase}</legend>
<div class="mui-textfield mui-textfield--float-label">
<input type="email" id="email" class="email">
<label>email</label>
</div>
<div class="mui-textfield mui-textfield--float-label">
<input type="password" id="password" class="password">
<label>пароль</label>
</div>
<button type="submit" class="register mui-btn mui-btn--raised">Вперед!</button>
<button class="login mui-btn mui-btn--raised">У меня ${buttonPhrase}</button>
</form>`
//mui.overlay('on', modalEl);
return modalEl;
}
const renderError = (error) => {
const errorPanel = document.createElement('div');
errorPanel.classList.add('mui-panel');
errorPanel.style.backgroundColor = '#f17878';
errorPanel.innerHTML = `${error}`
return errorPanel;
}
const render = async (state, elem, components) => { //<= РЕНДЕР
//console.log('rendering:', state)
components.noteContainer.innerHTML = '';
let currentNote = state.activeNote;
switch (state.page) {
case 'editing':
components.notesList.innerHTML = renderNotesList(state, currentNote);
components.noteContainer.appendChild(renderForm(state, currentNote));
initialize(state, components)
break;
case 'reading':
components.noteContainer.innerHTML = await renderNote(state, currentNote);
components.notesList.innerHTML = await renderNotesList(state, currentNote)
initialize(state, components)
break;
case 'login':
components.notesList.innerHTML = '';
components.noteContainer.appendChild(renderLoginPage(state));
if (state.error) {
components.noteContainer.appendChild(renderError(state.error))
}
break;
default:
break;
}
}
const initialize = async (state, components) => {
// ограничение доступа
if (!state.user.isAuth || state.page === 'login') {
state.page = 'login';
await render(state, null, components);
const submit = document.querySelector('.register');
if (submit) {
const form = document.querySelector('form');
form.addEventListener('submit', async (e)=>{
e.preventDefault();
await submitAuthForm(state, form, components, e);
initialize(state, components)
});
document.querySelector('.login').addEventListener('click', ()=>{
state.user.registered = !state.user.registered;
//console.log(state.user.registered)
initialize(state, components)
});
}
return
};
// создает новую заметку
const addNoteButton = document.querySelector('.add-button')
if (addNoteButton) {
addNoteButton.addEventListener('click', async(e) => {
e.preventDefault();
const generateId = (x = 0) =>{
let id = _.uniqueId(`note_${x}`);
state.notes.forEach(note=>{
if(note.id === id) return id = generateId(x+1)
}, id)
return id;
}
const note = new Note('', generateId())
state.notes.push(note);
state.activeNote = note;
state.page = 'editing';
//await synchronization(state, components)
render(state, note, components);
})
}
const allNotes = document.querySelectorAll('.select-note');
allNotes.forEach((elem)=>{
const checkbox = elem.querySelectorAll("input[type='checkbox']")[0];
elem.addEventListener('click', (e)=> { //<= выбор заметки для показа, добавляем в стейт актив
e.preventDefault();
state.activeNote = _.find(state.notes, (note) => elem.id === note.id); // работает
state.page = 'reading';
render(state, state.activeNote, components);
})
if (checkbox) {
checkbox.addEventListener('click', (e)=>{
e.stopPropagation()
checkNote(state, checkbox, elem);
})
}
})
// удаляет выделенные заметки
const deleteBtn = document.querySelector('.delete-button')
if (deleteBtn) {
deleteBtn.addEventListener('click', async (e) => {
e.stopPropagation();
state.notes = _.filter(state.notes, (note) => note.checked === false);
if (_.find(state.notes, (note) => note.id === state.activeNote.id)) state.activeNote = null;
state.page = 'reading';
//closeForm(state, state.activeNote, '', components)
await synchronization(state, components);
render(state, null, components)
})
// выделяет все заметки
document.querySelector('.check-all-button').addEventListener('click', () => {
state.checkedAll = !state.checkedAll;
state.checkedAll ?
state.notes.map((note) => note.checked = false) :
state.notes.map((note) => note.checked = true);
render(state, null, components)
})
}
//обработчик клика по тексту заметки
const edit = components.noteContainer.querySelectorAll('.editable-note')[0];
if (edit) {
edit.addEventListener('click', ()=>{
state.page = 'editing';
render(state, state.activeNote, components);
})
}
// обработчики формы
const form = document.querySelector('form');
if (form) {
const input = document.querySelectorAll('.form-text-input')[0];
//if (!state.activeNote) state.activeNote = _.last(state.notes)
let currentNote = _.find(state.notes, (note) => note.id === state.activeNote.id);
if (!currentNote) {
state.activeNote = null;
state.page = 'reading'
render(state, null, components);
return
}
input.focus();
input.addEventListener('blur', async (e) => {
e.preventDefault();
//currentNote.text = input.value;
await closeForm(state, currentNote, input.value)
state.page = 'reading'
state.activeNote.text = input.value;
await synchronization(state, components)
render(state, currentNote, components)
})
}
const logOutBtn = document.querySelector('.logout-button');
if (logOutBtn){
logOutBtn.addEventListener('click', ()=>signOut(state, components));
}
}
const closeForm = (state, currentNote, value) => {
state.page = 'reading';
currentNote.text = value;
state.activeNote.text = value;
if (value === '') {
currentNote.text = 'Новая заметка...'
state.activeNote.text = 'Новая заметка...'
}
}
const app = async () => {
const state = {
user: {
id: '',
registered: false,
isAuth: false,
},
notes: [],
checkedAll: false,
activeNote: null,
page: 'login', //'editing', 'login', 'reading'
error: null,
}
const components = {
createNote: document.querySelector('.add'),
notesList: document.querySelector('.notes-list'),
noteContainer: document.querySelector('.note-container'),
}
await initFirebase(state, components);
}
// выбор заметок (чекбокс)
const checkNote = (state, checkbox, elem) => {
_.find(state.notes, (note) => note.id === elem.id).checked =
(checkbox.checked ? true : false);
}
export { app, render, initialize, Note, formatDate }<file_sep>import firebase from "firebase/app";
import "firebase/auth";
import "firebase/database";
import { render, initialize } from "./application";
//import "lodash";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "notes-app-6a955.firebaseapp.com",
databaseURL: "https://notes-app-6a955-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "notes-app-6a955",
storageBucket: "notes-app-6a955.appspot.com",
messagingSenderId: "1052288609593",
appId: "1:1052288609593:web:6a680242619f1038ab8ce8"
};
// инициализация бд
const initFirebase = (state, components) => {
firebase.initializeApp(firebaseConfig);
authStateListener(state, components);
}
function authStateListener(state, components) {
firebase.auth().onAuthStateChanged((user) => {
state.error = null;
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
state.user.isAuth = true;
state.user.id = user.uid;
state.page = 'reading'
stateChangeListener(user.uid, state, components)
initialize(state, components)
} else {
// User is signed out
state.user.isAuth = false;
state.page = 'login'
initialize(state, components)
}
});
}
//СЛУШАТЕЛЬ ИЗМЕНЕНИЯ СОСТОЯНИЯ НА СЕРВЕРЕ
function stateChangeListener(userId, state, components) {
var stateRef = firebase.database().ref('users/' + userId);
stateRef.on('value', (snapshot) => {
const data = snapshot.val();
if (data.notes) {
state.notes = JSON.parse( JSON.stringify(data.notes));
}
//console.log('local state changed:', state)
render(state, state.activeNote, components)
});
}
// логаут
function signOut(state, components) {
firebase.auth().signOut().then(() => {
// Sign-out successful.
state.user.isAuth = false;
state.page = 'login';
render(state, null, components)
}).catch((error) => {
state.error = error;
});
}
//сохранение состояния в бд
const synchronization = (state, components) => {
if (state.status != 'login') {
try {
updateData(state.user.id, state)
} catch (err) {
console.log(err)
}
}
}
//ЗАГРУЗКА СТЕЙСТА В БазуДанных
function updateData(userId, state) {
//const dbRef = firebase.database().ref('users/' + userId);
firebase.database().ref('users/' + userId).update(state);
}
// вход в аккаунт или рега
const submitAuthForm = (state, form, components, event) => {
state.user.email = form.querySelector('.email').value;
const pass = form.querySelector('.password').value;
if (state.user.registered === true) {
signInWithEmailPassword(state, pass, components);
} else {
signUpWithEmailPassword(state, pass, components);
}
}
// вход
function signInWithEmailPassword(state, password, components) {
const email = state.user.email;
firebase.auth().signInWithEmailAndPassword(String(email), String(password))
.then((userCredential) => {
// Signed in
let user = userCredential;
state.user.id = user;
state.user.isAuth = true;
state.page = 'reading'
stateChangeListener(user, state, components)
})
.catch((error) => {
state.error = error;
initialize(state, components)
});
}
// рега
function signUpWithEmailPassword(state, password, components) {
const email = String (state.user.email);
firebase.auth().createUserWithEmailAndPassword(email, String (password))
.then((user) => {
// Signed in
state.user.id = user;
state.user.isAuth = true;
state.page = 'reading'
})
.catch((error) => {
state.error = error;
initialize(state, components)
// ..
});
}
// пока не задействовано
function sendEmailVerification() {
firebase.auth().currentUser.sendEmailVerification()
.then(() => {
// Email verification sent!
// ...
});
}
export { submitAuthForm, signOut, initFirebase, synchronization }<file_sep># Заметки
_Фантастическое_ приложение для создания, сохранения и удаления заметок.
Запуск:
```
cd/директория
npm install
npm start
```
| 8e90a65c255a9fbdf1fc45bdd9623337fc4b50ca | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | janglz/notes_app | d3b6914f933c0de9a49dc376f1ea9fd55c55efb7 | 14c836a42ba6705dfa180c21c03f7cbee185fc09 |
refs/heads/main | <file_sep>from django.http import HttpResponse
from django.shortcuts import render
from .models import Fcuser
# Create your views here.
def register(request):
if request.method == 'GET':
return render (request,'register.html')
elif request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
re_password = request.POST['re-password']
res_data ={}
if password != re_password:
res_data['error'] = '비밀번호가 다릅니다.'
else:
fcuser = Fcuser(
username = username,
password = <PASSWORD>
)
fcuser.save()
return render(request,'register.html',res_data)
<file_sep># fc_community
fastcampus 인터넷 강의
비밀번호 암호화
<file_sep>from django.contrib import admin
# Register your models here.
from .models import Fcuser
class FcuserAdmin(admin.ModelAdmin):
list_display =('username','password',)
admin.site.register(Fcuser,FcuserAdmin)
| 35809f49c599c6ffe14472a27955a356237cf22e | [
"Markdown",
"Python"
] | 3 | Python | skbae5553/fc_community | 9d8e217c97d188c7c3f21a90fa9d20e1afc175e8 | 0761d14abe2af3c03f88db8d5d582d2baf3d9b37 |
refs/heads/main | <file_sep># def productOfAllDoubleLoop(arr):
# lista = []
# for i in range(len(arr)):
# total = 1
# for j in range(len(arr)):
# if (i != j):
# total *= arr[j]
#
# lista.append(total)
#
# return lista
# def getProduct(arr):
# result = 1
# for i in arr:
# result *= i
# return result
#
#
# def productNoDivision(arr):
# lista = []
# for i in range(len(arr)):
# temp = list(arr[:i] + arr[i + 1:])
# lista.append(getProduct(temp))
#
# return lista
def getFactors(arr):
product = 1
output_list = []
for dig in arr:
product *= dig
for i in range(len(arr)):
output_list.append(int(product / arr[i]))
return output_list
if __name__ == '__main__':
assert getFactors([1, 2, 3, 4, 5]) == [120, 60, 40, 30, 24]
assert getFactors([3, 2, 1]) == [2, 3, 6]
<file_sep>def firstNonRepeatingCharacter(string):
if len(string) == 0:
return '_'
dict = {}
for s in string:
if s in dict:
dict[s] += 1
else:
dict[s] = 1
for k, v in dict.items():
if v == 1:
return k
return '_'
if __name__ == '__main__':
assert(firstNonRepeatingCharacter('aaabcccdeeef') == 'b')
assert(firstNonRepeatingCharacter('abcbad') == 'c')
assert(firstNonRepeatingCharacter('abcabcabc') == '_')
assert (firstNonRepeatingCharacter('v') == 'v')
assert (firstNonRepeatingCharacter('') == '_')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
<file_sep>def solution303(time):
hour, minute = time.split(':')
firstPoint = int(hour) * (360 // 12) % 360
secondPoint = int(minute) * (360 / 60)
result = int(abs(firstPoint - secondPoint))
return result if result <180 else 360 - result
if __name__ == '__main__':
assert solution303('12:20') == 120
assert solution303('12:00') == 0
assert solution303('6:30') == 0
assert solution303('3:46') == 174
<file_sep># Daily-Coding-Problem
Bunch of coding problems from multiple platforms.
#### Given a string, find its first non-repeating character
Given a string, find the first non-repeating character in it. For example, if the input string is “aaabcccdeeef”, then the output should be ‘b’ and if the input string is “abcabcabc”, then the output should be ‘_’.
[**Solution**](solutions/firstNonRepeatingCharacter.py)
#### Problem 2
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Follow-up: what if you can't use division? - included but no O(n) solution
[Solution](solutions/problem_2.py)
---
#### Problem 216
This problem was asked by Facebook.
Given a number in Roman numeral format, convert it to decimal.
The values of Roman numerals are as follows:
```
{
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
```
In addition, note that the Roman numeral system uses subtractive notation for numbers such as `IV` and `XL`.
For the input `XIV`, for instance, you should return `14`.
[Solution](solutions/problem_216.py)
---
#### Problem 33
This problem was asked by Microsoft.
Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two middle numbers.
For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:
```
2
1.5
2
3.5
2
2
2
```
[Solution](solutions/problem_033.py)
---
#### Problem 10
This problem was asked by Apple.
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
[Solution](solutions/problem_10.py)
---
### Problem 303
This problem was asked by Microsoft.
Given a clock time in `hh:mm` format, determine, to the nearest degree, the angle between the hour and the minute hands.
Bonus: When, during the course of a day, will the angle be zero?
[Solution](solutions/problem_303.py)
---<file_sep>def roman(arr):
romans = {
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
arr = list(reversed(arr))
prev = arr[0]
total = romans[prev]
for i in range(1, len(arr)):
if romans[prev] <= romans[arr[i]]:
total += romans[arr[i]]
else:
total -= romans[arr[i]]
prev = arr[i]
return total
if __name__ == '__main__':
assert roman('MDCCI') == 1701
assert roman('IV') == 4
assert roman('IX') == 9
assert roman('XIX') == 19<file_sep>def getMedian(seq):
if(seq == 0):
return False
seq = sorted(seq)
if(len(seq) % 2 == 0):
return (seq[len(seq)//2-1] + seq[len(seq)//2]) / 2
else:
return seq[len(seq) // 2]
def generateSingleMedian(median):
medians = []
for i in range(0, len(median)):
medians.append(getMedian(median[:i+1]))
return medians
if __name__ == '__main__':
assert generateSingleMedian([2, 1, 5, 7, 2, 0, 5]) == [2, 1.5, 2, 3.5, 2, 2, 2]
assert not generateSingleMedian([])
#
# assert getMedian([3, 13, 7, 5, 21, 23, 23, 40, 23, 14, 12, 56, 23, 29]) == 22.0
# assert getMedian([3, 6, 5, 9]) == 5.5
# assert getMedian([3, 6, 5, 9, 12, 10, 7, 2, 2]) == 6
# assert getMedian([3, 6, 5, 10, 4, 9, 12, 10, 7, 2, 2]) == 6
# assert getMedian([3, 13, 7, 5, 21, 23, 39, 23, 40, 23, 14, 12, 56, 23, 29]) == 23
<file_sep>import time
def doSomething():
return 'hello world'
def delayFunction(func, delay):
time.sleep(delay / 1000) # s / 1000 > ms
return func()
if __name__ == '__main__':
assert delayFunction(doSomething, 2000) == 'hello world'
| 6bd4149504d4ee0fea66a4b8dbc9e4b807fe235b | [
"Markdown",
"Python"
] | 7 | Python | X00122527/Daily-Coding-Problem | fd1aed4ee3da033f15f325d579076cdfb8f8fdff | 811f8858ada4c527d1acb7e4ac8aadcdc74a63e0 |
refs/heads/master | <repo_name>cckmit/coins-2-validator<file_sep>/doc/config-yml.md
# Config.yml
The validation process is configured by the config.yml. This is a yml file. The most basic structure is:
```yaml
version: '2.0.8'
environment:
store:
type: virtuoso
config:
...
cleanUp: false
...
run:
containers:
- type: container
location:
type: file
path: override.ccr
variables:
...
graphs:
...
steps:
- type: FileSystemValidation
...
- type: DocumentReferenceValidation
...
- type: ProfileValidation
...
reports:
- type: html
location:
type: file
path: report.html
```
The version field is introduced since version 2.0.8.
## Environment
The **environment** section configures which rdf **store** to use and has some *general settings*.
Currently three types of stores are allowed:
#### RDF4J in-memory
```yaml
store:
type: rdf4j-sail-memory
```
#### Ontotext GraphDB
```yaml
store:
type: graphdb
config:
endpoint: http://localhost:7200
repositoryId: validator-repo
```
The repositoryId is optional, if it is left out the id ```'validator-generated'``` is used.
#### OpenLink Virtuoso
```yaml
store:
type: virtuoso
config:
endpoint: localhost:1111
user: dba
password: dba
```
#### General environment settings:
```yaml
cleanUp: false
```
Clean up the graphs that were created in the validation process.
```yaml
createRepo: true
```
If the no usable repo is found in the store create it (if possible for this store type).
```yaml
destroyRepo: false
```
After validation remove the repo that was used (if possible for this store type) even if it already existed. Also if the validation could not be finished.
## Run
The **run** section consists of three parts:
* The **containers** section goes into details which content from a container to use. It is possible here to inject custom files into the validation process.
* The **steps** section specifies which validation steps need to be executed during validation for all specified containers.
* The **reports** section configures which report files should be generated.
### Containers
During the validation process a container is considered in two ways:
* as a zip file consisting of rdf-files and attachments
* as a set of rdf contexts (graphs)
Which graphs are used in the validation process can be tuned. Graphs are mapped to variables. Also graphs can be copied to new graphs to make unions.
The definition of one container consists of four parts:
* **type** is either ```'container'``` or ```'virtual'``` (for composing a non-existing container)
* **location** to point to the location of the file for non-virtual type
* **variables** is the map of variables and initial uri's (these will updated depending of the configuration and content of the store)
* **graphs** mappings of sources to variables
#### type
The default configuration is
```yaml
- type: container
```
For custom usages this setting is also supported
```yaml
- type: virtual
```
#### Location
There are two options to point to non-virtual container file. By relative (or absolute) file path:
```yaml
location:
type: file
path: folder/container.ccr
```
Or to a network link:
```yaml
location:
type: online
uri: http://localhost:8080/container.ccr
```
#### Variables
The default configuration of variables. Specifying them here means the validation steps can guaranteed address them during validation steps. The uri's will be updated depending of the configuration and content of the store.
```yaml
variables:
- graphname: http://full/union
variable: FULL_UNION_GRAPH
- graphname: http://instances/union
variable: INSTANCE_UNION_GRAPH
- graphname: http://library/union
variable: SCHEMA_UNION_GRAPH
```
#### Graphs
Specifies which (file) sources should be uploaded to the store. This is the default configuration for a container:
```yaml
graphs:
- source:
type: container
path: bim/*
graphname: '*'
as:
- INSTANCE_UNION_GRAPH
- source:
type: container
path: bim/repository/*
graphname: '*'
as:
- SCHEMA_UNION_GRAPH
- source:
type: store
graph: INSTANCE_UNION_GRAPH
as:
- FULL_UNION_GRAPH
- source:
type: store
graph: SCHEMA_UNION_GRAPH
as:
- FULL_UNION_GRAPH
```
Each item in this array has one source and one or more ```as``` variables
```yaml
- source:
type: ...
...
as:
- ...
- ...
```
#### Source
To address a set of triples within an rdf source the ```graphname``` key is used. If ```'*'``` is given as ```graphname``` the source configuration is duplicated for all found graphnames.
A source can be of these four types:
```yaml
- source:
type: file
path: folder/file.rdf
graphname: 'http://w3c.com/lib'
```
Select the graph with the specified graphname from the rdf-file.
```yaml
- source:
type: online
uri: http://localhost:8080/file.rdf
graphname: 'http://w3c.com/lib'
```
Select the graph with the specified graphname from the online rdf source.
```yaml
- source:
type: container
path: bim/content.rdf
graphname: 'http://w3c.com/lib'
```
Wildcards can be used to import all graphs that are found in file(s) in the direct ```bim``` folder and the file(s) in the ```bim/repository``` folder. During the initialisation of the validation process this wildcards are replaced by real files and graphnames (uri's also called contexts). See the ```--yml-to-console``` cli argument.
Select the graph with the specified graphname from the rdf-file inside the container at hand.
```yaml
- source:
type: store
graph: VARIABLE
```
Select a graph in the store that is already identified by some VARIABLE.
### Steps
Any step gets access to content and statistics of the container zip-file and the prepared set of graphs in the store. The step then is executed and can both return the following:
* whether the container is **valid** (resulting in a green check mark in the html-report)
* whether the execution could be finished (needed for the exit code ```0```)
* variables that can be printed in the report
These steps are currently available:
#### File system validation
```yaml
- type: FileSystemValidation
lookIn: INSTANCE_UNION_GRAPH
```
This step checks all basic requirements of the coins container zip-file content wise.
#### Document reference validation
```yaml
- type: DocumentReferenceValidation
lookIn: INSTANCE_UNION_GRAPH
```
This looks for pointers to files and checks the values of these.
#### Profile validation
```yaml
- type: ProfileValidation
profile:
type: online
uri: http://localhost:9877/profile.lite-9.85-virtuoso.xml
maxResults: 100
reportInferenceResults: false
```
This step executes all the bundles in a profile.xml. Different validation profiles can be chosen. Also a profile.xml can be custom made. For official validation an certified profile should be used.
A profile.xml consists of (SPARQL) queries that can either create extra data (inference queries) or check requirements (validation queries). If a validation query has results this means the validator detected issues and the container is not valid.
Read more about the [profile.xml](https://github.com/sysunite/coins-2-validator/blob/develop/doc/profile-xml.md) in it's own section.
### Reports
Three types of reports are available. Each can be either saved to a file or be uploaded to a network location using a POST request.
```yaml
- type: html
location:
type: file
path: report.html
```
The html report uses freemarker templates to map all variables from the steps to readable html. Read more about in the [html-report](https://github.com/sysunite/coins-2-validator/blob/develop/doc/html-report.md) section.
```yaml
- type: xml
location:
type: file
path: report.xml
```
The xml report has the same structure of the config.yml and the profile.xml linked via the profileValidation step.
```yaml
- type: json
location:
type: online
uri: http://localhost:9911/validationStatistics
```
The json report is identical to the xml report.<file_sep>/doc/reference.md
# Code reference
## Contents
* [Brief overview](https://github.com/sysunite/coins-2-validator/blob/develop/doc/brief.md)
* [Connectors](https://github.com/sysunite/coins-2-validator/blob/develop/doc/connectors.md)
## Modules
The coins-validator project consinsts of these packages:
#### validator-core
Mainly contains java interfaces, as little dependencies as possible.
#### validator-cli
All the implementations, depends on graphdb api with rdf4j.
#### alidator-parser-config-yml
Parser for the config.yml. With pojo's that can be separatly used from the cli.
#### validator-parser-profile-xml
Parser for the profile.xml. With pojo's that can be separatly used from the cli.
<file_sep>/Changelog.md
# Changelog
## 2.3.0
- Allow wildcard usage inside container file path in config.yml
## 2.2.0
- Remove module structure inside source code
- Use resultFormat order inside xml report query results
## 2.1.0
- Do not load in import order to break import cycles<file_sep>/src/main/java/com/sysunite/coinsweb/steps/FileSystemValidation.java
package com.sysunite.coinsweb.steps;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.sysunite.coinsweb.filemanager.ContainerFile;
import com.sysunite.coinsweb.filemanager.ContainerFileImpl;
import com.sysunite.coinsweb.graphset.ContainerGraphSet;
import com.sysunite.coinsweb.parser.config.pojo.ConfigPart;
import com.sysunite.coinsweb.parser.config.pojo.GraphVarImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import static com.sysunite.coinsweb.parser.Parser.isNotNull;
import static com.sysunite.coinsweb.rdfutil.Utils.containsNamespace;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(Include.NON_NULL)
public class FileSystemValidation extends ConfigPart implements ValidationStep {
private static final Logger log = LoggerFactory.getLogger(FileSystemValidation.class);
public static final String REFERENCE = "FileSystemValidation";
// Configuration items
private String type = REFERENCE;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private GraphVarImpl lookIn;
public GraphVarImpl getLookIn() {
return lookIn;
}
public void setLookIn(GraphVarImpl lookIn) {
this.lookIn = lookIn;
}
// Result items
private boolean failed = true;
public boolean getFailed() {
return failed;
}
public void setFailed(boolean failed) {
this.failed = failed;
}
private boolean valid;
public boolean getValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
private Boolean fileFound;
public Boolean getFileFound() {
return fileFound;
}
public void setFileFound(Boolean fileFound) {
this.fileFound = fileFound;
}
private Boolean nonCorruptZip;
public Boolean getNonCorruptZip() {
return nonCorruptZip;
}
public void setNonCorruptZip(Boolean nonCorruptZip) {
this.nonCorruptZip = nonCorruptZip;
}
private Boolean forwardSlashes;
public Boolean getForwardSlashes() {
return forwardSlashes;
}
public void setForwardSlashes(Boolean forwardSlashes) {
this.forwardSlashes = forwardSlashes;
}
private Boolean oneBimFile;
public Boolean getOneBimFile() {
return oneBimFile;
}
public void setOneBimFile(Boolean oneBimFile) {
this.oneBimFile = oneBimFile;
}
private Boolean noCorruptContentFile;
public Boolean getNoCorruptContentFile() {
return noCorruptContentFile;
}
public void setNoCorruptContentFile(Boolean noCorruptContentFile) {
this.noCorruptContentFile = noCorruptContentFile;
}
private Boolean noWrongContentFile;
public Boolean getNoWrongContentFile() {
return noWrongContentFile;
}
public void setNoWrongContentFile(Boolean noWrongContentFile) {
this.noWrongContentFile = noWrongContentFile;
}
private Boolean noCorruptRepositoryFile;
public Boolean getNoCorruptRepositoryFile() {
return noCorruptRepositoryFile;
}
public void setNoCorruptRepositoryFile(Boolean noCorruptRepositoryFile) {
this.noCorruptRepositoryFile = noCorruptRepositoryFile;
}
private Boolean noWrongRepositoryFile;
public Boolean getNoWrongRepositoryFile() {
return noWrongRepositoryFile;
}
public void setNoWrongRepositoryFile(Boolean noWrongRepositoryFile) {
this.noWrongRepositoryFile = noWrongRepositoryFile;
}
private Boolean noSubsInBim;
public Boolean getNoSubsInBim() {
return noSubsInBim;
}
public void setNoSubsInBim(Boolean noSubsInBim) {
this.noSubsInBim = noSubsInBim;
}
private Boolean noOrphans;
public Boolean getNoOrphans() {
return noOrphans;
}
public void setNoOrphans(Boolean noOrphans) {
this.noOrphans = noOrphans;
}
private Boolean noCollidingNamespaces;
public Boolean getNoCollidingNamespaces() {
return noCollidingNamespaces;
}
public void setNoCollidingNamespaces(Boolean noCollidingNamespaces) {
this.noCollidingNamespaces = noCollidingNamespaces;
}
private Boolean isLoadableAsGraphSet;
public Boolean isLoadableAsGraphSet() {
return isLoadableAsGraphSet;
}
public void isLoadableAsGraphSet(Boolean isLoadableAsGraphSet) {
this.isLoadableAsGraphSet = isLoadableAsGraphSet;
}
private Boolean allImportsImportable;
public Boolean getAllImportsImportable() {
return allImportsImportable;
}
public void setAllImportsImportable(Boolean allImportsImportable) {
this.allImportsImportable = allImportsImportable;
}
private Boolean coreModelImported;
public Boolean getCoreModelImported() {
return coreModelImported;
}
public void setCoreModelImported(Boolean coreModelImported) {
this.coreModelImported = coreModelImported;
}
private Boolean oneOntologyIndividual;
public Boolean getOneOntologyIndividual() {
return oneOntologyIndividual;
}
public void setOneOntologyIndividual(Boolean oneOntologyIndividual) {
this.oneOntologyIndividual = oneOntologyIndividual;
}
@JsonInclude(Include.NON_EMPTY)
private List<String> imports = new ArrayList();
public List<String> getImports() {
return imports;
}
public void setImports(List<String> imports) {
this.imports = imports;
}
@JsonInclude(Include.NON_EMPTY)
private List<String> unmatchedImports = new ArrayList();
public List<String> getUnmatchedImports() {
return unmatchedImports;
}
public void setUnmatchedImports(List<String> unmatchedImports) {
this.unmatchedImports = unmatchedImports;
}
public void checkConfig() {
isNotNull(lookIn);
}
@Override
public void execute(ContainerFile containerCandidate, ContainerGraphSet graphSet) {
if(!(containerCandidate instanceof ContainerFileImpl)) {
throw new RuntimeException("Running the FileSystemValidation step does not make sense for a non-ContainerFileImpl container");
}
ContainerFileImpl container = (ContainerFileImpl) containerCandidate;
if(container.isScanned()) {
log.warn("This ContainerFileImpl was already scanned, please let FileSystemValidation be the first to do this");
}
if(!container.exists() || !container.isFile()) {
fileFound = false;
failed = true;
return;
}
fileFound = true;
if(container.isCorruptZip()) {
nonCorruptZip = false;
failed = true;
return;
}
nonCorruptZip = true;
if(container.hasWrongSlashes()) {
forwardSlashes = false;
failed = true;
return;
}
forwardSlashes = true;
oneBimFile = (container.getContentFiles().size() + container.getCorruptContentFiles().size() + container.getInvalidContentFiles().size()) == 1;
noWrongContentFile = container.getInvalidContentFiles().size() < 1;
noCorruptContentFile = container.getCorruptContentFiles().size() < 1;
noWrongRepositoryFile = container.getInvalidRepositoryFiles().size() < 1;
noCorruptRepositoryFile = container.getCorruptRepositoryFiles().size() < 1;
oneOntologyIndividual = container.getContentOntologiesCount() == 1;
// Should be no sub folders in bim
noSubsInBim = true;
for (String path : container.getContentFiles()) {
noSubsInBim &= (Paths.get(path).getNameCount() == 1);
}
// Should be no orphan files
noOrphans = container.getOrphanFiles().isEmpty();
noCollidingNamespaces = container.getCollidingNamespaces().isEmpty();
// Should be able to satisfy all ontology imports from repository folder
allImportsImportable = container.getInvalidImports().isEmpty();
coreModelImported = containsNamespace("http://www.coinsweb.nl/cbim-2.0.rdf", container.getResolvableImports());
unmatchedImports = container.getInvalidImports();
graphSet.load();
isLoadableAsGraphSet = !graphSet.loadingFailed();
valid = fileFound && nonCorruptZip && forwardSlashes && oneBimFile && noWrongContentFile && noWrongRepositoryFile && noSubsInBim && noOrphans && noCollidingNamespaces && allImportsImportable && coreModelImported && isLoadableAsGraphSet;
failed = !isLoadableAsGraphSet;
// Prepare data to transfer to the template
if(getFailed()) {
log.info("\uD83E\uDD49 failed");
} else {
if (getValid()) {
log.info("\uD83E\uDD47 valid");
} else {
log.info("\uD83E\uDD48 invalid");
}
}
}
@JsonIgnore
public FileSystemValidation clone() {
FileSystemValidation clone = new FileSystemValidation();
// Configuration
clone.setType(this.getType());
clone.setLookIn(this.getLookIn());
clone.setParent(this.getParent());
return clone;
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/runner/Describe.java
package com.sysunite.coinsweb.runner;
import com.sysunite.coinsweb.cli.CliOptions;
import com.sysunite.coinsweb.connector.Connector;
import com.sysunite.coinsweb.connector.ConnectorException;
import com.sysunite.coinsweb.filemanager.ContainerFileImpl;
import com.sysunite.coinsweb.graphset.QueryFactory;
import com.sysunite.coinsweb.parser.config.factory.ConfigFactory;
import com.sysunite.coinsweb.parser.config.pojo.ConfigFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author bastbijl, Sysunite 2017
*/
public class Describe {
private static final Logger log = LoggerFactory.getLogger(Describe.class);
public static String run(List<File> containers, boolean fullConfig, boolean useAbsolutePaths) {
if(containers.isEmpty()) {
throw new RuntimeException("No container file found");
}
Path localizeTo = null;
if(!useAbsolutePaths) {
localizeTo = CliOptions.resolvePath("");
}
ConfigFile configFile = ConfigFactory.getDefaultConfig(containers, localizeTo);
String yml;
if(fullConfig) {
yml = ConfigFactory.toYml(configFile);
} else {
yml = ConfigFactory.toYml(configFile.getRun().getContainers());
}
return yml;
}
public static String run(Connector connector) throws ConnectorException {
Map<Set<String>, Set<String>> map = connector.listSigmaGraphsWithIncludes();
String sigmaYml = ConfigFactory.toYml(map);
String imports = "";
for(Set<String> contexts : map.keySet()) {
for(String context : contexts) {
for(String inclusion : map.get(context)) {
if(inclusion.startsWith(QueryFactory.VALIDATOR_HOST)) {
imports += inclusion + " owl:imports\n";
Map<String, String> importsMap = connector.getImports(inclusion);
for(String importContext : importsMap.keySet()) {
imports += "- "+importContext + " ("+importsMap.get(importContext)+")\n";
}
}
}
}
}
List<Object> list = connector.listPhiGraphs();
String phiYml = ConfigFactory.toYml(list);
return sigmaYml + "\n" + imports + "\n" + phiYml;
}
public static String run(Connector connector, String context) throws ConnectorException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Map<String, String> imports = connector.exportPhiGraph(context, baos);
try {
return baos.toString("UTF-8") + "\nYou also need:\n"+"".join("\n", imports.keySet());
} catch (UnsupportedEncodingException e) {
return "";
}
}
public static void run(Connector connector, Path toCcr, String context) throws ConnectorException {
ContainerFileImpl containerFile = new ContainerFileImpl(toCcr.toString()+".tmp");
containerFile.setPendingContentContext(context);
containerFile.writeZip(toCcr, connector);
}
}
<file_sep>/src/test/java/com/sysunite/coinsweb/connector/graphdb/GraphDBTest.java
package com.sysunite.coinsweb.connector.graphdb;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.sysunite.coinsweb.connector.ConnectorException;
import com.sysunite.coinsweb.connector.ConnectorFactoryImpl;
import com.sysunite.coinsweb.filemanager.DescribeFactoryImpl;
import com.sysunite.coinsweb.parser.config.factory.ConfigFactory;
import com.sysunite.coinsweb.parser.config.pojo.ConfigFile;
import com.sysunite.coinsweb.parser.config.pojo.StepDeserializer;
import com.sysunite.coinsweb.parser.config.pojo.Store;
import com.sysunite.coinsweb.steps.StepFactoryImpl;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author bastbijl, Sysunite 2017
*/
public class GraphDBTest {
Logger log = LoggerFactory.getLogger(GraphDBTest.class);
@BeforeClass
public static void before() {
Store.factory = new ConnectorFactoryImpl();
StepDeserializer.factory = new StepFactoryImpl();
ConfigFactory.setDescribeFactory(new DescribeFactoryImpl());
}
@Test
public void testConnection() throws IOException, ConnectorException {
// Create the connection
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
File configYml = new File(getClass().getResource("minimal-graphdb.yml").getFile());
ConfigFile configFile = mapper.readValue(configYml, ConfigFile.class);
GraphDB connector = new GraphDB(configFile.getEnvironment());
assertTrue(connector.testConnection());
// Upload a file
File otl = new File(getClass().getClassLoader().getResource("otl-2.1/otl-2.1.ttl").getFile());
ArrayList<String> contexts = new ArrayList<>();
contexts.add("http://otl.rws.nl/");
String defaultFileName = "otl-2.1.ttl";
connector.uploadFile(new FileInputStream(otl), defaultFileName, contexts.get(0), contexts);
assertEquals(contexts.get(0), connector.getContexts().get(0));
assertEquals(455384, connector.quadCount("http://otl.rws.nl/"));
// Cleanup
connector.cleanup(contexts);
assertEquals(0, connector.getContexts().size());
}
}<file_sep>/src/test/java/application/run/Coins11Test.java
package application.run;
import com.sysunite.coinsweb.cli.Application;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
/**
* @author bastbijl, Sysunite 2017
*/
public class Coins11Test extends HostFiles {
Logger log = LoggerFactory.getLogger(Coins11Test.class);
File file = new File(getClass().getClassLoader().getResource("coins-1.1/coins11-9.85-generated.yml").getFile());
@Test
public void run() {
log.info("Read "+file.getPath());
System.setProperty("user.dir", file.getParent());
String[] args = {"run",
file.getPath(),
"-l",
// "--yml-to-console",
"VC1.ccr",
"VC2.ccr",
"VC3.ccr",
"VC4.ccr",
"VC5.ccr",
"VC6.ccr",
"VC7.ccr",
"VC8.ccr",
"VC9.ccr",
"VC10.ccr",
"VC11.ccr",
};
Application.main(args);
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/connector/graphdb/GraphDB.java
package com.sysunite.coinsweb.connector.graphdb;
import com.sysunite.coinsweb.connector.Rdf4jConnector;
import com.sysunite.coinsweb.parser.config.pojo.Environment;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.impl.TreeModel;
import org.eclipse.rdf4j.model.util.GraphUtil;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.repository.config.RepositoryConfig;
import org.eclipse.rdf4j.repository.config.RepositoryConfigSchema;
import org.eclipse.rdf4j.repository.manager.RemoteRepositoryManager;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
/**
* @author bastbijl, Sysunite 2017
*/
public class GraphDB extends Rdf4jConnector {
private static final Logger log = LoggerFactory.getLogger(GraphDB.class);
public static final String REFERENCE = "graphdb";
private String url;
RemoteRepositoryManager manager;
String repositoryId;
String user;
String password;
boolean createRepo;
public GraphDB(Environment config) {
if(config.getStore().getConfig() == null || !config.getStore().getConfig().containsKey("endpoint")) {
throw new RuntimeException("No endpoint url specified");
}
url = config.getStore().getConfig().get("endpoint");
if(config.getStore().getConfig().containsKey("repositoryId")) {
repositoryId = config.getStore().getConfig().get("repositoryId");
}
if(config.getStore().getConfig().containsKey("user")) {
user = config.getStore().getConfig().get("user");
}
if(config.getStore().getConfig().containsKey("password")) {
password = config.getStore().getConfig().get("password");
}
cleanUp = config.getCleanUp();
createRepo = config.getCreateRepo();
deleteRepo = config.getDestroyRepo();
}
public void setRepositoryId(String repositoryId) {
this.repositoryId = repositoryId;
}
public void init() {
if(initialized) {
return;
}
log.info("Initialize connector ("+REFERENCE+")");
manager = new RemoteRepositoryManager(url);
if(user != null && password != null) {
manager.setUsernameAndPassword(user, password);
}
manager.initialize();
try {
if(repositoryId == null){
repositoryId = "validator-generated";
}
if(manager.hasRepositoryConfig(repositoryId)) {
log.info("Found existing repository");
} else {
if(createRepo) {
manager.addRepositoryConfig(createRepositoryConfig(repositoryId));
} else {
log.warn("Not allowed to create repo, but needs to");
return;
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
repository = manager.getRepository(repositoryId);
initialized = true;
}
@Override
public void close() {
if(!initialized) {
return;
}
repository.shutDown();
if(deleteRepo) {
if (manager != null && repositoryId != null) {
manager.removeRepository(repositoryId);
}
}
}
private RepositoryConfig createRepositoryConfig(String repositoryId) throws IOException {
// see http://graphdb.ontotext.com/documentation/free/configuring-a-repository.html
String repoTurtle =
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.\n" +
"@prefix rep: <http://www.openrdf.org/config/repository#>.\n" +
"@prefix sr: <http://www.openrdf.org/config/repository/sail#>.\n" +
"@prefix sail: <http://www.openrdf.org/config/sail#>.\n" +
"@prefix owlim: <http://www.ontotext.com/trree/owlim#>.\n" +
"[] a rep:Repository ;\n" +
" rep:repositoryID \"" + repositoryId + "\" ;\n" +
" rdfs:label \"GraphDB Free repository\" ;\n" +
" rep:repositoryImpl [\n" +
" rep:repositoryType \"graphdb:FreeSailRepository\" ;\n" +
" sr:sailImpl [\n" +
" sail:sailType \"graphdb:FreeSail\" ;\n" +
" owlim:base-URL \"http://example.org/graphdb#\" ;\n" +
" owlim:defaultNS \"\" ;\n" +
" owlim:entity-index-size \"1000000000\" ;\n" +
" owlim:entity-id-size \"32\" ;\n" +
" owlim:imports \"\" ;\n" +
" owlim:repository-type \"file-repository\" ;\n" +
" owlim:ruleset \"empty\" ;\n" +
" owlim:storage-folder \"storage\" ;\n" +
" owlim:enable-context-index \"true\" ;\n" +
" owlim:enablePredicateList \"true\" ;\n" +
" owlim:in-memory-literal-properties \"true\" ;\n" +
" owlim:enable-literal-index \"true\" ;\n" +
" owlim:check-for-inconsistencies \"false\" ;\n" +
" owlim:disable-sameAs \"true\" ;\n" +
" owlim:query-timeout \"0\" ;\n" +
" owlim:query-limit-results \"0\" ;\n" +
" owlim:throw-QueryEvaluationException-on-timeout \"false\" ;\n" +
" owlim:read-only \"false\" ;\n" +
" owlim:nonInterpretablePredicates \"" +
"http://www.w3.org/2000/01/rdf-schema#label;" +
"http://www.w3.org/1999/02/22-rdf-syntax-ns#type;" +
"http://www.ontotext.com/owlim/ces#gazetteerConfig;" +
"http://www.ontotext.com/owlim/ces#metadataConfig\" ;\n" +
" ]\n" +
" ].";
// see http://graphdb.ontotext.com/documentation/free/using-graphdb-with-the-rdf4j-api.html
TreeModel graph = new TreeModel();
InputStream config = new ByteArrayInputStream(repoTurtle.getBytes(StandardCharsets.UTF_8));
RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE);
rdfParser.setRDFHandler(new StatementCollector(graph));
rdfParser.parse(config, RepositoryConfigSchema.NAMESPACE);
config.close();
Resource repositoryNode = GraphUtil.getUniqueSubject(graph, RDF.TYPE, RepositoryConfigSchema.REPOSITORY);
return RepositoryConfig.create(graph, repositoryNode);
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/report/ReportFile.java
package com.sysunite.coinsweb.report;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.sysunite.coinsweb.parser.config.pojo.Container;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(Include.NON_NULL)
public class ReportFile {
private static final Logger log = LoggerFactory.getLogger(ReportFile.class);
@JacksonXmlProperty(localName = "container")
@JacksonXmlElementWrapper(localName="containers")
private Container[] containers;
public Container[] getContainers() {
return containers;
}
public void setContainers(Container[] containers) {
this.containers = containers;
}
}
<file_sep>/services/graphdb/Dockerfile
FROM java:8
# Install maven
RUN apt-get update
RUN apt-get install -y zip
WORKDIR /opt
# Prepare by downloading dependencies
ADD graphdb-free-8.8.1-dist.zip /opt/graphdb-free-8.8.1-dist.zip
RUN ["unzip", "graphdb-free-8.8.1-dist.zip"]
RUN ["rm", "graphdb-free-8.8.1-dist.zip"]
CMD ["/opt/graphdb-free-8.8.1/bin/graphdb"]<file_sep>/doc/brief.md
## Brief overview
### cli
The cli can be started with a number of arguments. See the [documentation](https://github.com/sysunite/coins-2-validator/blob/develop/doc/command.md) page. The cli starts a runner from the `com.sysunite.coinsweb.runner` package. Either `Describe` for the **describe** mode and `Validation` for the **run** mode.
### ContainerFileImpl
A coins container is represented in two ways. As a file-archive consisting of triple files and attachments and as a set of graphs in a triple store (see next section).
By instantiating a ContainerFileImpl the file-archive can be read.
```java
ContainerFile containerFile = new ContainerFileImpl("/tmp/container.ccr");
Set<String> libraryFiles = containerFile.getRepositoryFiles();
```
### ContainerGraphSetImpl
A graphset is a selection of graphs (contexts) that represents the content of the coins container. Using a ```Connector``` a connection with a Graph Database is made. The graphs of the graphset are uploaded to this database. After this initialisation the graphset can be queried with SPARQL queries.
```java
ContainerGraphSet graphSet = ContainerGraphSetFactory.lazyLoad(containerFile, containerConfig, connector, inferencePreference);
List<Object> result = graphSet.select("SELECT * WHERE { GRAPH ?g { ?s ?p ?o } }");
```
The graphSet sends the query via the connector so the whole database is targetted. To be able to address the graphs belonging to this graphSet (and thus the specific container content) the graphSet keeps track of a map of GraphVar's to context uri's. These variables can be used in the queries in the profile.xml.
```java
Map<GraphVar, String> contexts = graphSet.contextMap();
```
```sparql
SELECT DISTINCT ?a ?b ?c
WHERE { GRAPH ${SCHEMA_UNION_GRAPH} {
?a ?b ?c
```
### Steps
In the package `com.sysunite.coinsweb.steps` a number of implementations of the interface `ValidationStep` are given. The config.yml can assign a number of steps to a validation run. Using the configuration the config.yml provides each step is instantiated and ran. Every validation step is provided with both the `ContainerFile` and the `ContainerGraphSet` so the step can addres every aspect of the container desired.
```java
public interface ValidationStep {
void execute(ContainerFile container, ContainerGraphSet graphSet);
```
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/profile/pojo/Query.java
package com.sysunite.coinsweb.parser.profile.pojo;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlCData;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.sysunite.coinsweb.parser.profile.util.IndentedCDATAPrettyPrinter;
import com.sysunite.coinsweb.parser.profile.util.Markdown;
import com.sysunite.coinsweb.util.FreemarkerUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateModelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author bastbijl, Sysunite 2017
*/
@JacksonXmlRootElement(localName = "query")
public class Query {
private static final Logger log = LoggerFactory.getLogger(Query.class);
@JacksonXmlProperty(localName = "reference", isAttribute = true)
private String reference;
private String description;
@JsonInclude(Include.NON_NULL)
@JacksonXmlCData
private String resultFormat;
@JacksonXmlCData
@JacksonXmlProperty(localName = "sparql")
protected String query;
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
@JsonGetter("description")
public String getDescription() {
return description;
}
public String parseDescription() {
return Markdown.parseLinksToHtml(description);
}
public void setDescription(String description) {
this.description = description;
}
@JsonGetter("resultFormat")
public String getResultFormat() {
return resultFormat;
}
public String parseResultFormat() {
return Markdown.parseLinksToHtml(resultFormat);
}
public void setResultFormat(String resultFormat) {
if(resultFormat != null && !resultFormat.isEmpty()) {
this.resultFormat = IndentedCDATAPrettyPrinter.indentText(resultFormat, 0).trim();
} else {
this.resultFormat = "";
}
}
@JsonIgnore
public List<String> getBindingsOrder() {
List<String> list = new ArrayList<>();
try {
Template template = getFormatTemplate();
if(template != null) {
for(String var : FreemarkerUtil.referenceSet(template)) {
if(!list.contains(var)) {
list.add(var);
}
}
}
} catch (TemplateModelException e) {
log.warn("Failed reading freemarker template variable names");
}
return list;
}
@JsonIgnore
private Template formatTemplate ;
@JsonIgnore
public Template getFormatTemplate() {
if(formatTemplate == null) {
String resultFormat = parseResultFormat();
if(resultFormat == null) {
return null;
}
StringTemplateLoader templateLoader = new StringTemplateLoader();
Configuration cfg = new Configuration();
cfg.setTemplateLoader(templateLoader);
templateLoader.putTemplate("resultFormat", resultFormat);
try {
formatTemplate = cfg.getTemplate("resultFormat");
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new RuntimeException("Something went wrong creating the query result format");
}
}
return formatTemplate;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = IndentedCDATAPrettyPrinter.indentText(query, 0).trim();
}
public Query clone() {
Query clone = new Query();
clone.setReference(this.getReference());
clone.setDescription(this.getDescription());
clone.setQuery(this.getQuery());
clone.setResultFormat(this.getResultFormat());
return clone;
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/graphset/ComposePlan.java
package com.sysunite.coinsweb.graphset;
import org.eclipse.rdf4j.model.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* @author bastbijl, Sysunite 2017
*/
public class ComposePlan {
private static final Logger log = LoggerFactory.getLogger(ComposePlan.class);
private List<Move> list = new ArrayList<>();
private List<Move> unFinished = new ArrayList<>();
private int pointer = 0;
public enum Action { COPY, ADD }
public void addReversed(Action action, GraphVar from, Resource to, boolean onlyUpdate) {
Move move = new Move(action, from, to, onlyUpdate);
list.add(pointer, move);
unFinished.add(move);
}
public void addReversed(Action action, Resource from, Resource to, boolean onlyUpdate) {
Move move = new Move(action, from, to, onlyUpdate);
list.add(pointer, move);
}
public void add(Action action, Resource from, Resource to, boolean onlyUpdate) {
Move move = new Move(action, from, to, onlyUpdate);
list.add(move);
pointer = list.size();
}
public void updateFroms(GraphVar graphVar, Resource context) {
for(int i = 0; i < unFinished.size(); i++) {
Move move = unFinished.get(i);
if(graphVar.equals(move.getFrom())) {
move.setFrom(context);
unFinished.remove(i--);
}
}
}
public String toString() {
String result = "";
for(Move move : list) {
result += "\n" + move.toString();
}
return result;
}
public List<Move> get() {
if(!unFinished.isEmpty()) {
String message = "";
for(Move move : unFinished) {
message += "\n- "+move.toString();
}
throw new RuntimeException("ComposePlan still consists of unFinished Moves:" + message);
}
return list;
}
public class Move {
public final Action action;
public Resource from;
public GraphVar fromPending;
public final Resource to;
public boolean onlyUpdate;
public Move(Action action, Resource from, Resource to, boolean onlyUpdate) {
this.action = action;
this.from = from;
this.to = to;
this.onlyUpdate = onlyUpdate;
}
public Move(Action action, GraphVar fromPending, Resource to, boolean onlyUpdate) {
this.action = action;
this.fromPending = fromPending;
this.to = to;
this.onlyUpdate = onlyUpdate;
}
public GraphVar getFrom() {
return fromPending;
}
public void setFrom(Resource from) {
this.from = from;
this.fromPending = null;
}
public String toString() {
if(action == Action.COPY) {
return "<"+from+"> to <"+to+">";
}
if(action == Action.ADD) {
return "<"+from+"> to <"+to+">";
}
return null;
}
}
}
<file_sep>/src/test/java/com/sysunite/coinsweb/rdfutil/UtilsTest.java
package com.sysunite.coinsweb.rdfutil;
import org.junit.Test;
import java.io.File;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author bastbijl, Sysunite 2017
*/
public class UtilsTest {
@Test
public void testFileFormat() {
assertFalse(Utils.isRdfFile(new File("file.jpg")));
assertFalse(Utils.isRdfFile(new File("file.txt")));
assertTrue(Utils.isRdfFile(new File("file.ttl")));
assertTrue(Utils.isRdfFile(new File("."+File.separator+"path"+File.separator+"file.rdf")));
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/graphset/GraphVar.java
package com.sysunite.coinsweb.graphset;
/**
* @author bastbijl, Sysunite 2017
*/
public interface GraphVar {
}
<file_sep>/src/test/java/application/run/LoadingStrategyTest.java
package application.run;
import com.sysunite.coinsweb.cli.Application;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
/**
* @author bastbijl, Sysunite 2017
*/
public class LoadingStrategyTest extends HostFiles {
Logger log = LoggerFactory.getLogger(LoadingStrategyTest.class);
File file = new File(getClass().getClassLoader().getResource("loading-strategy/config-9.85-virtuoso.yml").getFile());
@Test
public void run() {
log.info("Read "+file.getPath());
System.setProperty("user.dir", file.getParent());
String[] args = {"run",
file.getPath(),
"-l",
"abc.ccr",
"abd.ccr",
};
Application.main(args);
}
}<file_sep>/src/main/java/com/sysunite/coinsweb/graphset/ContainerGraphSetFactory.java
package com.sysunite.coinsweb.graphset;
import com.sysunite.coinsweb.connector.Connector;
import com.sysunite.coinsweb.connector.ConnectorException;
import com.sysunite.coinsweb.filemanager.ContainerFile;
import com.sysunite.coinsweb.filemanager.ContainerFileImpl;
import com.sysunite.coinsweb.filemanager.DescribeFactoryImpl;
import com.sysunite.coinsweb.parser.config.factory.FileFactory;
import com.sysunite.coinsweb.parser.config.pojo.*;
import com.sysunite.coinsweb.parser.profile.factory.ProfileFactory;
import com.sysunite.coinsweb.parser.profile.pojo.ProfileFile;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.DigestInputStream;
import java.util.*;
import static com.sysunite.coinsweb.connector.Rdf4jConnector.asResource;
import static com.sysunite.coinsweb.rdfutil.Utils.containsNamespace;
import static com.sysunite.coinsweb.rdfutil.Utils.withoutHash;
import static java.util.Collections.sort;
/**
* @author bastbijl, Sysunite 2017
*/
public class ContainerGraphSetFactory {
private static final Logger log = LoggerFactory.getLogger(ContainerGraphSetFactory.class);
public static ContainerGraphSet lazyLoad(ContainerFile container, Container containerConfig, Connector connector, Map<String, Set<GraphVar>> inferencePreference) {
log.info("Construct and lazy load graphSet");
ContainerGraphSet graphSet = new ContainerGraphSetImpl(containerConfig.getVariables(), connector);
graphSet.lazyLoad(container, inferencePreference);
Graph main = null;
for(Graph graph : containerConfig.getGraphs()) {
if(graph.getMain() != null && graph.getMain()) {
if(main == null) {
main = graph;
} else {
throw new RuntimeException("No two graphs can be flagged as main");
}
}
}
graphSet.setMain(main);
return graphSet;
}
public static Map<String, Set<GraphVar>> inferencePreference(ProfileFile profileFile) {
HashMap<String, Set<GraphVar>> result = new HashMap<>();
Map<String, Set<String>> stringMap = ProfileFactory.inferencesOverVars(profileFile);
for(String inferenceCode : stringMap.keySet()) {
Set<GraphVar> graphVars = new HashSet<>();
for(String graphVarString : stringMap.get(inferenceCode)) {
graphVars.add(new GraphVarImpl(graphVarString));
}
result.put(inferenceCode, graphVars);
}
return result;
}
/**
* Build load strategy and execute the loading
*
* Returns a map that maps
*
*/
public static ComposePlan load(ContainerGraphSetImpl graphSet, Connector connector, ContainerFile container, Map<String, Set<GraphVar>> inferencePreference) {
Container containerConfig = ((ContainerFileImpl)container).getConfig();
List<Graph> loadList = containerConfig.getGraphs();
// Load all files (φ - graphs)
ArrayList<Graph> phiGraphs = new ArrayList<>();
for (Graph graph : loadList) {
if(Source.ONLINE.equals(graph.getSource().getType()) ||
Source.CONTAINER.equals(graph.getSource().getType()) ||
Source.FILE.equals(graph.getSource().getType())) {
phiGraphs.add(graph);
}
}
HashMap<String, String> changeMap = new HashMap<>();
for(Graph phiGraph : phiGraphs) {
try {
executeLoad(phiGraph.getSource(), connector, container);
} catch (ConnectorException e) {
log.error("Loading this graph to the connector failed: "+phiGraph.getSource().getGraphname(), e);
graphSet.setFailed();
return null;
}
changeMap.put(withoutHash(phiGraph.getSource().getGraphname()), withoutHash(phiGraph.getSource().getStoreContext()));
for(String originalContext : changeMap.keySet()) {
try {
connector.replaceResource(phiGraph.getSource().getStoreContext(), originalContext, changeMap.get(originalContext));
} catch (ConnectorException e) {
log.error("Failed replacing resource", e);
graphSet.setFailed();
}
}
}
// Create all composition graphs (σ - graphs)
Container containerConfig2 = ((ContainerFileImpl) container).getConfig(); // todo check if this is a duplicate
List<Mapping> variables = containerConfig2.getVariables();
ComposePlan composePlan = composeSigmaList(graphSet, connector, variables, loadList, inferencePreference);
executeCompose(graphSet, composePlan, connector, false);
return composePlan;
}
public static void executeCompose(ContainerGraphSetImpl graphSet, ComposePlan composePlan, Connector connector, boolean updateMode) {
List<ComposePlan.Move> list;
try {
list = composePlan.get();
} catch (RuntimeException e) {
log.error(e.getMessage());
graphSet.setFailed();
return;
}
for (ComposePlan.Move move : list) {
// Skip if this operation only needs to be executed when updating
if(!updateMode && move.onlyUpdate) {
continue;
}
try {
if(!updateMode && move.action == ComposePlan.Action.COPY) {
log.info("Execute compose copy " + move.toString());
connector.sparqlCopy(move.from.toString(), move.to.toString());
} else {
log.info("Execute compose add " + move.toString());
connector.sparqlAdd(move.from.toString(), move.to.toString());
}
} catch (ConnectorException e) {
log.error("Failed executing compose copy or add operation", e);
graphSet.setFailed();
return;
}
}
for(Mapping mapping : graphSet.getMappings()) {
try {
connector.storeSigmaGraphExists(mapping.getGraphname(), mapping.getInclusionSet());
} catch (ConnectorException e) {
log.error("Failed saving sigma graph header", e);
graphSet.setFailed();
return;
}
}
}
// Returns true if loading was successful
private static void executeLoad(Source source, Connector connector, ContainerFile container) throws ConnectorException {
String fileName;
String filePath = source.getPath();
if(filePath == null) {
fileName = source.getUri();
} else {
fileName = new File(source.getPath()).getName();
}
String context = generatePhiContext();
ArrayList<String> contexts = new ArrayList<>();
contexts.add(context);
source.setStoreContext(context);
log.info("Upload rdf-file to connector: " + filePath);
DigestInputStream inputStream = FileFactory.toInputStream(source, container);
connector.uploadFile(inputStream, fileName, source.getGraphname(), contexts);
log.info("Uploaded, store phi graph header");
connector.storePhiGraphExists(source, context, fileName, source.getHash());
}
public static String generatePhiContext() {
return QueryFactory.VALIDATOR_HOST + "uploadedFile-" + RandomStringUtils.random(8, true, true);
}
// Extends wildcards and loads the namespace for each file
public static ArrayList<Graph> loadList(List<Graph> originalGraphs, ContainerFile container) {
// Each namespace should be filled from only one source (Graph)
HashMap<String, Graph> namespaceToGraph = new HashMap<>();
ArrayList<Graph> loadList = new ArrayList<>();
// Explicit graphs
for(Graph graph : originalGraphs) {
if(Source.STORE.equals(graph.getSource().getType())) {
loadList.add(graph);
}
else if(Source.FILE.equals(graph.getSource().getType()) ||
Source.ONLINE.equals(graph.getSource().getType())) {
File file = FileFactory.toFile(graph.getSource().asLocator());
try {
ArrayList<String> namespaces = new ArrayList<>();
ArrayList<String> imports = new ArrayList<>();
ArrayList<String> ontologies = new ArrayList<>();
DescribeFactoryImpl.contextsInFile(new FileInputStream(file), file.getName(), namespaces, imports, ontologies, graph.getSource().getGraphname());
for (String graphName : namespaces) {
log.info("Found graph in file/online: " + graphName);
if (containsNamespace(graphName, namespaceToGraph.keySet())) {
throw new RuntimeException("Collision in graphs names, this one can be found in more than one source: " + graphName);
}
Graph clone = graph.clone();
clone.getSource().setGraphname(graphName);
namespaceToGraph.put(graphName, clone);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
else if(Source.CONTAINER.equals(graph.getSource().getType())) {
Source source = graph.getSource();
if(source.isContentFile()) {
ArrayList<Graph> contentGraphs = DescribeFactoryImpl.contentGraphsInContainer(container, graph.getAs(), source.getPath(), source.getGraphname());
for (Graph clone : contentGraphs) {
String graphName = clone.getSource().getGraphname();
log.info("Found graph in content file: " + graphName);
if (containsNamespace(graphName, namespaceToGraph.keySet())) {
throw new RuntimeException("Collision in graphs names, this one can be found in more than one source: " + graphName);
}
namespaceToGraph.put(graphName, clone);
}
} else if(source.isLibraryFile()) {
ArrayList<Graph> libraryGraphs = DescribeFactoryImpl.libraryGraphsInContainer(container, graph.getAs(), source.getPath(), source.getGraphname());
for (Graph clone : libraryGraphs) {
String graphName = clone.getSource().getGraphname();
log.info("Found graph in library file: " + graphName);
if (containsNamespace(graphName, namespaceToGraph.keySet())) {
throw new RuntimeException("Collision in implicit graphs names, this one can be found in more than one source: " + graphName);
}
namespaceToGraph.put(graphName, clone);
}
} else {
throw new RuntimeException("The only location inside a container to address is inside the /bim/ or /bim/repository/ folder");
}
}
else {
throw new RuntimeException("Unsupported graph source type");
}
}
loadList.addAll(namespaceToGraph.values());
return loadList;
}
private static Map<String, Set<String>> reverseSigmaGraphsMap(Map<Set<String>, Set<String>> sigmaGraphs) {
Map<String, Set<String>> map = new HashMap<>();
for(Set<String> sigmaGraph : sigmaGraphs.keySet()) {
String fingerPrint = fingerPrint(sigmaGraphs.get(sigmaGraph), "-");
map.put(fingerPrint, sigmaGraph);
}
return map;
}
public static String fingerPrint(Set<String> items, String delimiter) {
List<String> list = new ArrayList<>();
list.addAll(items);
sort(list);
return "".join(delimiter, list);
}
public static String fingerPrintComposition(String context, Map<Set<String>, Set<String>> sigmaGraphsMap, Map<String, Set<String>> actualInferences, Set<String> cycleDetection) {
if(cycleDetection == null) {
cycleDetection = new HashSet<>();
cycleDetection.add(context);
}
String inferencesFingerPrint = "";
if(actualInferences.containsKey(context)) {
inferencesFingerPrint = "("+fingerPrint(actualInferences.get(context), "&")+")";
}
String subGraphsFingerPrint = "";
String subFingerPrint = "";
for(Set<String> sigmaGraphs : sigmaGraphsMap.keySet()) {
if(sigmaGraphs.contains(context)) {
Set<String> subGraphs = sigmaGraphsMap.get(sigmaGraphs);
subGraphsFingerPrint = fingerPrint(subGraphs, "-");
Set<String> fragments = new HashSet<>();
for(String subContext : subGraphs) {
if(cycleDetection.contains(subContext)) {
throw new RuntimeException("A cycle detected in the sigma graph inclusion");
}
fragments.add(fingerPrintComposition(subContext, sigmaGraphsMap, actualInferences, cycleDetection));
}
subFingerPrint = "["+fingerPrint(fragments, ",")+"]";
break;
}
}
return subGraphsFingerPrint + inferencesFingerPrint + subFingerPrint;
}
// Currently only support for inferencePreference map with one inferenceCode mapping to one graphVar
// and each graphVar only mentioned once in the whole list
private static String inferenceCodeNeedle(GraphVarImpl var, HashMap<GraphVarImpl, List<String>> phiGraphMap, HashMap<GraphVarImpl, List<GraphVarImpl>> graphVarMap, Map<String, Set<GraphVar>> inferencePreference, Map<String, String> contextToHash) {
String needle = null;
for(String inferenceCode : inferencePreference.keySet()) {
if(inferencePreference.get(inferenceCode).contains(var)) {
if(needle != null || inferencePreference.get(inferenceCode).size() > 1) {
return null;
}
HashSet<GraphVarImpl> allVars = new HashSet<>();
allVars.add(var);
int size;
do {
size = allVars.size();
for(GraphVarImpl item : allVars) {
if(graphVarMap.containsKey(item)) {
allVars.addAll(graphVarMap.get(item));
}
}
} while (size < allVars.size());
HashSet<String> phiGraphs = new HashSet<>();
for(GraphVar graphVar : allVars) {
if(phiGraphMap.containsKey(graphVar)) {
phiGraphs.addAll(phiGraphMap.get(graphVar));
}
}
Set<String> hashes = new HashSet<>();
for(String context : phiGraphs) {
hashes.add(contextToHash.get(context));
}
needle = fingerPrint(hashes, "-") +"|"+ inferenceCode ;
}
}
return needle;
}
public static ComposePlan composeSigmaList(ContainerGraphSetImpl graphSet, Connector connector, List<Mapping> variables, List<Graph> originalGraphs, Map<String, Set<GraphVar>> inferencePreference) {
ComposePlan composePlan = new ComposePlan();
HashMap<GraphVar, String> varMap = new HashMap();
for(Mapping mapping : variables) {
varMap.put(mapping.getVariable(), mapping.getGraphname());
}
// Create wish lists
HashSet<GraphVarImpl> allGraphVars = new HashSet<>();
HashMap<GraphVarImpl, List<String>> graphVarIncludesPhiGraphMap = new HashMap<>();
HashMap<GraphVarImpl, List<GraphVarImpl>> graphVarIncludesGraphVarMap = new HashMap<>();
for (Graph graph : originalGraphs) {
if(Source.STORE.equals(graph.getSource().getType())) {
for (GraphVarImpl as : graph.getAs()) {
if(!allGraphVars.contains(as)) {
allGraphVars.add(as);
}
if (!graphVarIncludesGraphVarMap.keySet().contains(as)) {
graphVarIncludesGraphVarMap.put(as, new ArrayList<>());
}
List<GraphVarImpl> inclusions = graphVarIncludesGraphVarMap.get(as);
if (graph.getSource().getGraph() == null) {
throw new RuntimeException("Assuming a source that has one graph if it is not a source of type store");
}
inclusions.add(graph.getSource().getGraph());
}
} else {
for (GraphVarImpl as : graph.getAs()) {
if(!allGraphVars.contains(as)) {
allGraphVars.add(as);
}
if (!graphVarIncludesPhiGraphMap.keySet().contains(as)) {
graphVarIncludesPhiGraphMap.put(as, new ArrayList<>());
}
List<String> inclusions = graphVarIncludesPhiGraphMap.get(as);
if (graph.getSource().getStoreContext() == null || graph.getSource().getStoreContext().isEmpty()) {
throw new RuntimeException("Assuming a source that has no graphs (so it is not a source of type store) should have a store context");
}
inclusions.add(graph.getSource().getStoreContext());
}
}
}
List<Mapping> updatedVarList = new ArrayList<>();
HashMap<Set<String>, List<GraphVarImpl>> fromSetsToFix = new HashMap<>();
// Find a graphVar that is not mapped and is not included by an unmapped graphVar
HashMap<GraphVarImpl, String> mappedGraphVars = new HashMap<>();
GraphVarImpl next = null;
while(mappedGraphVars.size() < allGraphVars.size()) {
for (GraphVarImpl var : allGraphVars) {
if (mappedGraphVars.keySet().contains(var)) {
continue;
}
GraphVar includesThisUnprocessedGraph = null;
for (GraphVar includer : graphVarIncludesGraphVarMap.keySet()) {
if (!mappedGraphVars.keySet().contains(includer) && graphVarIncludesGraphVarMap.get(includer).contains(var)) {
includesThisUnprocessedGraph = includer;
break;
}
}
// Some graph includes this one, try the next
if (includesThisUnprocessedGraph != null) {
continue;
}
next = var;
}
if (next == null) {
throw new RuntimeException("Not able to find the next GraphVar to map");
}
// Now mapping this graphVar
String mappedContext = varMap.get(next);
// Include phi graph
if(graphVarIncludesPhiGraphMap.containsKey(next)) {
List<String> froms = graphVarIncludesPhiGraphMap.get(next);
if (froms.size() > 0) {
for (int i = 0; i < froms.size() - 1; i++) {
composePlan.addReversed(ComposePlan.Action.ADD, asResource(froms.get(i)), asResource(mappedContext), false);
}
composePlan.addReversed(ComposePlan.Action.COPY, asResource(froms.get(froms.size() - 1)), asResource(mappedContext), false);
}
Set<String> fromSet = new HashSet<>();
fromSet.addAll(froms);
Mapping mapping = new Mapping(next, mappedContext, null, null, fromSet, new HashSet());
mapping.setInitialized();
updatedVarList.add(mapping);
}
// Include sigma graph
if (graphVarIncludesGraphVarMap.containsKey(next)) {
List<GraphVarImpl> froms = graphVarIncludesGraphVarMap.get(next);
if (froms.size() > 0) {
for (int i = 0; i < froms.size() - 1; i++) {
composePlan.addReversed(ComposePlan.Action.ADD, froms.get(i), asResource(mappedContext), false);
}
composePlan.addReversed(ComposePlan.Action.COPY, froms.get(froms.size() - 1), asResource(mappedContext), false);
}
Set<String> fromSet = new HashSet<>();
fromSetsToFix.put(fromSet, froms);
Mapping mapping = new Mapping(next, mappedContext, null, null, fromSet, new HashSet());
mapping.setInitialized();
updatedVarList.add(mapping);
}
mappedGraphVars.put(next, mappedContext);
composePlan.updateFroms(next, asResource(mappedContext));
}
for(Set<String> setToFill : fromSetsToFix.keySet()) {
for(GraphVarImpl var : fromSetsToFix.get(setToFill)) {
setToFill.add(mappedGraphVars.get(var));
}
}
graphSet.setVariables(updatedVarList);
return composePlan;
}
}
<file_sep>/src/test/java/com/sysunite/coinsweb/parser/config/ConfigFileTest.java
package com.sysunite.coinsweb.parser.config;
import com.sun.corba.se.impl.orbutil.graph.GraphImpl;
import com.sysunite.coinsweb.connector.ConnectorFactoryImpl;
import com.sysunite.coinsweb.filemanager.DescribeFactoryImpl;
import com.sysunite.coinsweb.parser.config.factory.ConfigFactory;
import com.sysunite.coinsweb.parser.config.pojo.*;
import com.sysunite.coinsweb.steps.StepFactoryImpl;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* @author bastbijl, Sysunite 2017
*/
public class ConfigFileTest {
Logger log = LoggerFactory.getLogger(ConfigFileTest.class);
private boolean visuallyInspect = true;
@BeforeClass
public static void before() {
Store.factory = new ConnectorFactoryImpl();
StepDeserializer.factory = new StepFactoryImpl();
ConfigFactory.setDescribeFactory(new DescribeFactoryImpl());
}
@Test
public void voorbeeldContainer() {
ConfigFile configFile = ConfigFile.parse(new File(getClass().getResource("voorbeeldcontainer-full.yml").getFile()));
ConfigFactory.overrideContainers(configFile, 1, new Path[]{Paths.get("../../../../../voorbeeldcontainer-6.ccr")});
inspect(ConfigFactory.toYml(configFile));
List<Graph> graphs;
Graph graph;
// Before expand
graphs = configFile.getRun().getContainers()[0].getGraphs();
assertEquals(4, graphs.size());
graph = graphs.get(0);
assertEquals("bim/*", graph.getSource().getPath());
assertEquals("*", graph.getSource().getGraphname());
assertEquals("*", graph.getSource().getDefaultFileName());
graph = graphs.get(1);
assertEquals("bim/repository/*", graph.getSource().getPath());
assertEquals("*", graph.getSource().getGraphname());
assertEquals("*", graph.getSource().getDefaultFileName());
DescribeFactoryImpl.expandGraphConfig(configFile);
// After expand
graphs = configFile.getRun().getContainers()[0].getGraphs();
assertEquals(6, graphs.size());
graph = graphs.get(0);
assertEquals(new GraphVarImpl("INSTANCE_UNION_GRAPH"), graph.getSource().getGraph());
assertEquals("file.2.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(1);
assertEquals(new GraphVarImpl("SCHEMA_UNION_GRAPH"), graph.getSource().getGraph());
assertEquals("file.3.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(2);
assertEquals("bim/repository/rws-coins-20-referentiekader-21.ttl", graph.getSource().getPath());
assertEquals("http://otl.rws.nl/coins2/rws-referentiekader.rdf", graph.getSource().getGraphname());
assertEquals("rws-coins-20-referentiekader-21.ttl", graph.getSource().getDefaultFileName());
graph = graphs.get(3);
assertEquals("bim/repository/coins2.0.rdf", graph.getSource().getPath());
assertEquals("http://www.coinsweb.nl/cbim-2.0.rdf", graph.getSource().getGraphname());
assertEquals("coins2.0.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(4);
assertEquals("bim/testdata_211.ttl", graph.getSource().getPath());
assertEquals("http://areaal.rws.nl/S.001032/07032018", graph.getSource().getGraphname());
assertEquals("testdata_211.ttl", graph.getSource().getDefaultFileName());
graph = graphs.get(5);
assertEquals("bim/repository/20180131_otl22_acceptatie_definitief.ttl", graph.getSource().getPath());
assertEquals("http://otl.rws.nl/", graph.getSource().getGraphname());
assertEquals("20180131_otl22_acceptatie_definitief.ttl", graph.getSource().getDefaultFileName());
inspect(ConfigFactory.toYml(configFile));
}
@Test
public void voorbeeldContainerOnlyCbimFile() {
ConfigFile configFile = ConfigFile.parse(new File(getClass().getResource("voorbeeldcontainer-only-cbim-file.yml").getFile()));
ConfigFactory.overrideContainers(configFile, 1, new Path[]{Paths.get("../../../../../voorbeeldcontainer-6.ccr")});
inspect(ConfigFactory.toYml(configFile));
List<Graph> graphs;
Graph graph;
// Before expand
graphs = configFile.getRun().getContainers()[0].getGraphs();
assertEquals(4, graphs.size());
graph = graphs.get(0);
assertEquals("bim/*", graph.getSource().getPath());
assertEquals("*", graph.getSource().getGraphname());
assertEquals("*", graph.getSource().getDefaultFileName());
graph = graphs.get(1);
assertEquals("bim/repository/coins*", graph.getSource().getPath());
assertEquals("*", graph.getSource().getGraphname());
assertEquals("coins*", graph.getSource().getDefaultFileName());
DescribeFactoryImpl.expandGraphConfig(configFile);
// After expand
graphs = configFile.getRun().getContainers()[0].getGraphs();
assertEquals(4, graphs.size());
graph = graphs.get(0);
assertEquals(new GraphVarImpl("INSTANCE_UNION_GRAPH"), graph.getSource().getGraph());
assertEquals("file.2.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(1);
assertEquals(new GraphVarImpl("SCHEMA_UNION_GRAPH"), graph.getSource().getGraph());
assertEquals("file.3.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(2);
assertEquals("bim/repository/coins2.0.rdf", graph.getSource().getPath());
assertEquals("http://www.coinsweb.nl/cbim-2.0.rdf", graph.getSource().getGraphname());
assertEquals("coins2.0.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(3);
assertEquals("bim/testdata_211.ttl", graph.getSource().getPath());
assertEquals("http://areaal.rws.nl/S.001032/07032018", graph.getSource().getGraphname());
assertEquals("testdata_211.ttl", graph.getSource().getDefaultFileName());
inspect(ConfigFactory.toYml(configFile));
}
@Test
public void voorbeeldContainerOnlyCbimNamespace() {
ConfigFile configFile = ConfigFile.parse(new File(getClass().getResource("voorbeeldcontainer-only-cbim-namespace.yml").getFile()));
ConfigFactory.overrideContainers(configFile, 1, new Path[]{Paths.get("../../../../../voorbeeldcontainer-6.ccr")});
inspect(ConfigFactory.toYml(configFile));
List<Graph> graphs;
Graph graph;
// Before expand
graphs = configFile.getRun().getContainers()[0].getGraphs();
assertEquals(4, graphs.size());
graph = graphs.get(0);
assertEquals("bim/*", graph.getSource().getPath());
assertEquals("*", graph.getSource().getGraphname());
assertEquals("*", graph.getSource().getDefaultFileName());
graph = graphs.get(1);
assertEquals("bim/repository/*", graph.getSource().getPath());
assertEquals("http://www.coinsweb.nl/cbim-2.0.rdf", graph.getSource().getGraphname());
assertEquals("*", graph.getSource().getDefaultFileName());
DescribeFactoryImpl.expandGraphConfig(configFile);
// After expand
graphs = configFile.getRun().getContainers()[0].getGraphs();
assertEquals(4, graphs.size());
graph = graphs.get(0);
assertEquals(new GraphVarImpl("INSTANCE_UNION_GRAPH"), graph.getSource().getGraph());
assertEquals("file.2.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(1);
assertEquals(new GraphVarImpl("SCHEMA_UNION_GRAPH"), graph.getSource().getGraph());
assertEquals("file.3.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(2);
assertEquals("bim/repository/coins2.0.rdf", graph.getSource().getPath());
assertEquals("http://www.coinsweb.nl/cbim-2.0.rdf", graph.getSource().getGraphname());
assertEquals("coins2.0.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(3);
assertEquals("bim/testdata_211.ttl", graph.getSource().getPath());
assertEquals("http://areaal.rws.nl/S.001032/07032018", graph.getSource().getGraphname());
assertEquals("testdata_211.ttl", graph.getSource().getDefaultFileName());
inspect(ConfigFactory.toYml(configFile));
}
@Test
public void testVirtual() {
ConfigFile configFile = ConfigFile.parse(new File(getClass().getResource("virtual.yml").getFile()));
inspect(ConfigFactory.toYml(configFile));
List<Graph> graphs;
Graph graph;
// Before expand
graphs = configFile.getRun().getContainers()[0].getGraphs();
assertEquals(2, graphs.size());
graph = graphs.get(0);
assertEquals("nquad.nq", graph.getSource().getPath());
assertEquals("*", graph.getSource().getGraphname());
assertEquals("nquad.nq", graph.getSource().getDefaultFileName());
graph = graphs.get(1);
assertEquals("empty.rdf", graph.getSource().getPath());
assertEquals("*", graph.getSource().getGraphname());
assertEquals("empty.rdf", graph.getSource().getDefaultFileName());
DescribeFactoryImpl.expandGraphConfig(configFile);
// After expand
graphs = configFile.getRun().getContainers()[0].getGraphs();
assertEquals(3, graphs.size());
graph = graphs.get(0);
assertEquals("nquad.nq", graph.getSource().getPath());
assertEquals("http://example.org/graphs/superman", graph.getSource().getGraphname());
assertEquals("nquad.nq", graph.getSource().getDefaultFileName());
graph = graphs.get(1);
assertEquals("empty.rdf", graph.getSource().getPath());
assertEquals("http://www.coinsweb.nl/empty.rdf", graph.getSource().getGraphname());
assertEquals("empty.rdf", graph.getSource().getDefaultFileName());
graph = graphs.get(2);
assertEquals("nquad.nq", graph.getSource().getPath());
assertEquals("http://example.org/graphs/spiderman", graph.getSource().getGraphname());
assertEquals("nquad.nq", graph.getSource().getDefaultFileName());
inspect(ConfigFactory.toYml(configFile));
}
private void inspect(String message) {
if(visuallyInspect) {
System.out.println(message);
}
}
}
<file_sep>/src/test/java/application/run/CreateContainerTest.java
package application.run;
import com.sysunite.coinsweb.cli.Application;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
/**
* @author bastbijl, Sysunite 2017
*/
public class CreateContainerTest extends HostFiles {
Logger log = LoggerFactory.getLogger(CreateContainerTest.class);
File config = new File(getClass().getClassLoader().getResource("create-container/config.yml").getFile());
@Test
public void test() {
log.info("Read "+config.getPath());
System.setProperty("user.dir", config.getParent());
String[] args = {
"run",
config.getPath(),
"-l",
"--yml-to-console"
};
Application.main(args);
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/config/pojo/Graph.java
package com.sysunite.coinsweb.parser.config.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.util.StdConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import static com.sysunite.coinsweb.parser.Parser.isNotNull;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(Include.NON_NULL)
@JsonDeserialize(converter=GraphSanitizer.class)
public class Graph extends ConfigPart {
private static final Logger log = LoggerFactory.getLogger(Graph.class);
private Source source;
private ArrayList<GraphVarImpl> as;
private Boolean main;
public Source getSource() {
return source;
}
public ArrayList<GraphVarImpl> getAs() {
return as;
}
public Boolean getMain() {
return main;
}
public void setSource(Source source) {
this.source = source;
}
public void setAs(ArrayList<GraphVarImpl> as) {
this.as = as;
}
public void setMain(Boolean main) {
this.main = main;
}
@JsonIgnore
public Graph clone() {
Graph clone = new Graph();
clone.setSource(this.getSource().clone());
clone.setAs((ArrayList<GraphVarImpl>) this.getAs().clone());
clone.setMain(this.getMain());
clone.setParent(this.getParent());
return clone;
}
@Override
public void setParent(Object parent) {
super.setParent(parent);
this.source.setParent(this.getParent());
}
}
class GraphSanitizer extends StdConverter<Graph, Graph> {
private static final Logger log = LoggerFactory.getLogger(GraphSanitizer.class);
@Override
public Graph convert(Graph obj) {
isNotNull(obj.getSource());
isNotNull(obj.getAs());
return obj;
}
}
<file_sep>/doc/command.md
# Command line interface
The **coins-validator** can be run in two modes:
* **run** mode to execute the validation proces and create a report
* **describe** mode to generate a part of a configuration file
## Run mode
For a default configuration:
```$ coins-validator run [args] container.ccr```
For explicit configuration (you want to do this):
```$ coins-validator run [args] config.yml [container.ccr ...]```
argument | description
--- | ---
-h | print help message
-l | write a log file
-q | do not ouput anything to the console
[config.yml](https://github.com/sysunite/coins-2-validator/blob/develop/doc/config-yml.md) | the configuration of the validation run
*container.ccr ...* | zero or more containers that override the path in the config.yml
If the command was able to generate a report the **exit code** is ```0```. In all other cases the **exit code** is ```1```. Add the ```-l``` argument and read the log for more information.
Read about the [config.yml](https://github.com/sysunite/coins-2-validator/blob/develop/doc/config-yml.md) for a description what the validator does and how it can be configured.
## Describe mode
```$ coins-validator describe [args] container.ccr ```
argument | description
--- | ---
-a | make absolute paths in generated config
-h | print help message
-l | write a log file
--yml-to-console | print the generated config
-q | do not ouput anything to the console (apart from optional yml)
*container.ccr* | the container file being described
If the command was able to generate a configuration fragment the **exit code** is ```0```. In all other cases the **exit code** is ```1```. Add the ```-l``` argument and read the log for more information.
For a description of the the generated configuration read about the [config.yml](https://github.com/sysunite/coins-2-validator/blob/develop/doc/config-yml.md).
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/config/pojo/Environment.java
package com.sysunite.coinsweb.parser.config.pojo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.util.StdConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.sysunite.coinsweb.parser.Parser.isNotNull;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(converter=EnvironmentSanitizer.class)
public class Environment extends ConfigPart {
private static final Logger log = LoggerFactory.getLogger(Environment.class);
private Store store;
private String tempPath;
private boolean cleanUp = false;
private boolean createRepo = true;
private boolean destroyRepo = false;
private boolean useDisk = true;
public Store getStore() {
return store;
}
public String getTempPath() {
return tempPath;
}
public boolean getCleanUp() {
return cleanUp;
}
public boolean getCreateRepo() {
return createRepo;
}
public boolean getDestroyRepo() {
return destroyRepo;
}
public boolean getUseDisk() {
return useDisk;
}
public void setStore(Store store) {
this.store = store;
this.store.setParent(this.getParent());
}
public void setTempPath(String tempPath) {
this.tempPath = tempPath;
}
public void setCleanUp(boolean cleanUp) {
this.cleanUp = cleanUp;
}
public void setCreateRepo(boolean createRepo) {
this.createRepo = createRepo;
}
public void setDestroyRepo(boolean destroyRepo) {
this.destroyRepo = destroyRepo;
}
public void setUseDisk(boolean useDisk) {
this.useDisk = useDisk;
}
@Override
public void setParent(Object parent) {
super.setParent(parent);
if(this.store != null) {
this.store.setParent(this.getParent());
}
}
}
class EnvironmentSanitizer extends StdConverter<Environment, Environment> {
private static final Logger log = LoggerFactory.getLogger(EnvironmentSanitizer.class);
@Override
public Environment convert(Environment obj) {
isNotNull(obj.getStore());
return obj;
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/steps/ProfileValidation.java
package com.sysunite.coinsweb.steps;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.sysunite.coinsweb.filemanager.ContainerFile;
import com.sysunite.coinsweb.graphset.ContainerGraphSet;
import com.sysunite.coinsweb.graphset.GraphVar;
import com.sysunite.coinsweb.graphset.QueryFactory;
import com.sysunite.coinsweb.parser.config.factory.FileFactory;
import com.sysunite.coinsweb.parser.config.pojo.ConfigPart;
import com.sysunite.coinsweb.parser.config.pojo.Locator;
import com.sysunite.coinsweb.parser.profile.pojo.Bundle;
import com.sysunite.coinsweb.parser.profile.pojo.ProfileFile;
import com.sysunite.coinsweb.steps.profile.ValidationExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ProfileValidation extends ConfigPart implements ValidationStep {
private static final Logger log = LoggerFactory.getLogger(ProfileValidation.class);
public static final String REFERENCE = "ProfileValidation";
// Configuration items
private String type = REFERENCE;
private Locator profile;
private int maxResults = 0;
private int maxInferenceRuns = 50;
private boolean reportInferenceResults = false;
public String getType() {
return type;
}
public Locator getProfile() {
return profile;
}
public int getMaxResults() {
return maxResults;
}
public int getMaxInferenceRuns() {
return maxInferenceRuns;
}
public boolean getReportInferenceResults() {
return reportInferenceResults;
}
public void setType(String type) {
this.type = type;
}
public void setProfile(Locator profile) {
this.profile = profile;
this.profile.setParent(this.getParent());
}
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
public void setMaxInferenceRuns(int maxInferenceRuns) {
this.maxInferenceRuns = maxInferenceRuns;
}
public void setReportInferenceResults(Boolean reportInferenceResults) {
this.reportInferenceResults = reportInferenceResults;
}
@Override
public void setParent(Object parent) {
super.setParent(parent);
if(this.profile != null) {
this.profile.setParent(parent);
}
}
// Result items
private boolean failed = true;
public boolean getFailed() {
return failed;
}
public void setFailed(boolean failed) {
this.failed = failed;
}
private boolean valid = false;
public boolean getValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public void setProfileFile(ProfileFile profileFile) {
this.profileFile = profileFile;
}
@JacksonXmlProperty(localName = "name")
@JacksonXmlElementWrapper(localName="bundleNames")
private List<String> bundleNames = new ArrayList();
public List<String> getBundleNames() {
return bundleNames;
}
public void setBundleNames(List<String> bundleNames) {
this.bundleNames = bundleNames;
}
@JsonSerialize(keyUsing = BundleKeySerializer.class)
private HashMap<String, Bundle> bundles = new HashMap();
public HashMap<String, Bundle> getBundles() {
return bundles;
}
public void setBundles(HashMap<String, Bundle> bundles) {
this.bundles = bundles;
}
public void addBundle(Bundle bundle) {
this.bundleNames.add(bundle.getReference());
this.bundles.put(bundle.getReference(), bundle);
}
public void checkConfig() {
}
@JsonIgnore
private ProfileFile profileFile;
public ProfileFile loadProfileFile() {
if(profileFile == null) {
// Load the profile file
InputStream inputStream = FileFactory.toInputStream(profile);
profileFile = ProfileFile.parse(inputStream);
}
return profileFile;
}
@Override
public void execute(ContainerFile container, ContainerGraphSet graphSet) {
try {
loadProfileFile();
// Check if the vars used in the profile are available
Set<GraphVar> usedVars = QueryFactory.usedVars(profileFile);
for (GraphVar graphVar : usedVars) {
if (!graphSet.hasContext(graphVar)) {
throw new RuntimeException("The specified profile requires " + graphVar + ", please specify it in the config.yml");
}
}
ValidationExecutor executor = new ValidationExecutor(profileFile, graphSet, this);
// Execute the validation
executor.validate();
} catch (RuntimeException e) {
log.warn("Executing failed validationStep of type "+getType());
log.warn(e.getMessage(), e);
failed = true;
}
// Prepare data to transfer to the template
if(getFailed()) {
log.info("\uD83E\uDD49 failed");
} else {
if (getValid()) {
log.info("\uD83E\uDD47 valid");
} else {
log.info("\uD83E\uDD48 invalid");
}
}
}
@JsonIgnore
public ProfileValidation clone() {
ProfileValidation clone = new ProfileValidation();
// Configuration
clone.setType(this.getType());
clone.setProfile(this.getProfile().clone());
clone.setMaxResults(this.getMaxResults());
clone.setMaxInferenceRuns(this.getMaxInferenceRuns());
clone.setReportInferenceResults(this.getReportInferenceResults());
for(String bundleKey : getBundles().keySet()) {
Bundle bundle = getBundles().get(bundleKey);
clone.addBundle(bundle.clone());
}
ArrayList<String> bundleNames = new ArrayList<>();
bundleNames.addAll(this.getBundleNames());
clone.setBundleNames(bundleNames);
clone.setParent(this.getParent());
return clone;
}
}
class BundleKeySerializer extends JsonSerializer<String> {
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeFieldName("bundle");
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/rdfutil/Utils.java
package com.sysunite.coinsweb.rdfutil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* @author bastbijl, Sysunite 2017
*/
public class Utils {
private static final Logger log = LoggerFactory.getLogger(Utils.class);
static List<String> rdf4jFileExtensions = Arrays.asList(
"rdf", "rdfs", "owl", "xml",
"nt",
"ttl",
"n3",
"trix", //"xml",
"trig",
"brf",
"nq",
"jsonld",
"rj"
// "xhtml", "html"
);
static List<String> rdf4jContentTypes = Arrays.asList(
"application/rdf+xml", "application/xml", "text/xml",
"application/n-triples", "text/plain",
"text/turtle", "application/x-turtle",
"text/n3", "text/rdf+n3",
"application/trix",
"application/trig", "application/x-trig",
"application/x-binary-rdf",
"application/n-quads", "text/x-nquads", "text/nquads",
"application/ld+json",
"application/rdf+json"
// "application/xhtml+xml", "application/html", "text/html"
);
public static boolean isRdfFile(File file) {
return isRdfFile(file.getName());
}
public static boolean isRdfFile(String fileName) {
int index = fileName.lastIndexOf('.');
if(index != -1) {
String extension = fileName.substring(index+1);
return rdf4jFileExtensions.contains(extension);
}
return false;
}
public static boolean isRdfContentType(String contentType) {
return rdf4jContentTypes.contains(contentType);
}
public static String withoutHash(String input) {
if(input == null) {
return null;
}
while(input.endsWith("#")) {
input = input.substring(0, input.length()-1);
}
return input;
}
public static String withoutHashOrSlash(String input) {
if(input == null) {
return null;
}
while(input.endsWith("#") || input.endsWith("/")) {
input = input.substring(0, input.length()-1);
}
return input;
}
public static boolean equalNamespace(String ns1, String ns2) {
if(ns1 == null || ns2 == null || ns1.isEmpty() || ns2.isEmpty()) {
return false;
}
return withoutHashOrSlash(ns1).equals(withoutHashOrSlash(ns2));
}
public static boolean containsNamespace(String ns, Iterable<String> set) {
if(ns == null || ns.isEmpty() || set == null) {
return false;
}
ns = withoutHashOrSlash(ns);
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()) {
if(ns.equals(withoutHashOrSlash(iterator.next()))) {
return true;
}
}
return false;
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/config/factory/FileFactory.java
package com.sysunite.coinsweb.parser.config.factory;
import com.sysunite.coinsweb.filemanager.ContainerFile;
import com.sysunite.coinsweb.parser.config.pojo.ConfigFile;
import com.sysunite.coinsweb.parser.config.pojo.Container;
import com.sysunite.coinsweb.parser.config.pojo.Locator;
import com.sysunite.coinsweb.parser.config.pojo.Source;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author bastbijl, Sysunite 2017
*/
public class FileFactory {
private static final Logger log = LoggerFactory.getLogger(ConfigFactory.class);
public static File toFile(Container containerConfig) {
if(containerConfig.isVirtual()) {
try {
return File.createTempFile("container", ".rdf");
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new RuntimeException();
}
} else {
return toFile(containerConfig.getLocation());
}
}
public static File toFile(Locator locator) {
if(Locator.FILE.equals(locator.getType())) {
ConfigFile configFile = locator.getParent();
String path = locator.getPath();
File file = new File(configFile.resolve(path).toString());
return file;
}
if(Locator.ONLINE.equals(locator.getType())) {
throw new RuntimeException("Please don't do this");
// try {
// File file = File.createTempFile(RandomStringUtils.random(8, true, true),".ccr");
// file.deleteOnExit();
// URL url = new URL(locator.getUri());
// URLConnection connection = url.openConnection();
// InputStream input = connection.getInputStream();
// byte[] buffer = new byte[4096];
// int n;
//
// OutputStream output = new FileOutputStream(file);
// while ((n = input.read(buffer)) != -1) {
// output.write(buffer, 0, n);
// }
// output.close();
//
// return file;
// } catch (MalformedURLException e) {
// log.error(e.getMessage(), e);
// } catch (FileNotFoundException e) {
// log.error(e.getMessage(), e);
// } catch (IOException e) {
// log.error(e.getMessage(), e);
// }
}
throw new RuntimeException("The locator could not be transformed to a File");
}
public static InputStream toInputStream(Locator locator) {
String triedReference = "error interpreting locator";
if(Locator.FILE.equals(locator.getType())) {
try {
File file;
if(locator.getParent() != null) {
triedReference = locator.getParent().resolve(locator.getPath()).toString();
file = locator.getParent().resolve(locator.getPath()).toFile();
} else {
triedReference = locator.getPath();
file = new File(locator.getPath());
}
return new FileInputStream(file);
} catch (Exception e) {}
}
if(Locator.ONLINE.equals(locator.getType())) {
try {
URL url = new URL(locator.getUri());
triedReference = url.toString();
return url.openStream();
} catch (Exception e) {}
}
throw new RuntimeException("Locator of type "+locator.getType()+" could not be read as inputStream: "+triedReference);
}
public static DigestInputStream toInputStream(Source source, ContainerFile container) {
String triedReference = "error interpreting source";
if (Source.FILE.equals(source.getType())) {
try {
File file;
if (source.getParent() != null) {
triedReference = source.getParent().resolve(source.getPath()).toString();
file = source.getParent().resolve(source.getPath()).toFile();
} else {
triedReference = source.getPath();
file = new File(source.getPath());
}
return new DigestInputStream(new BufferedInputStream(new FileInputStream(file)), MessageDigest.getInstance("md5"));
} catch (Exception e) {
}
} else if (Source.ONLINE.equals(source.getType())) {
try {
URL url = new URL(source.getUri());
return new DigestInputStream(new BufferedInputStream(url.openStream()), MessageDigest.getInstance("md5"));
} catch (Exception e) {
}
} else if (Source.CONTAINER.equals(source.getType())) {
triedReference = "in container: "+Paths.get(source.getPath());
return container.getFile(Paths.get(source.getPath()));
}
throw new RuntimeException("Source of type "+source.getType()+" could not be read as inputStream: "+triedReference);
}
public static File toFile(Source source) {
String triedReference = "error interpreting source";
if (Source.FILE.equals(source.getType())) {
try {
File file;
if (source.getParent() != null) {
triedReference = source.getParent().resolve(source.getPath()).toString();
file = source.getParent().resolve(source.getPath()).toFile();
} else {
triedReference = source.getPath();
file = new File(source.getPath());
}
return file;
} catch (Exception e) {
throw new RuntimeException("Source of type "+source.getType()+" could not be read as file: "+triedReference);
}
}
throw new RuntimeException("Source of type "+source.getType()+" could not be read as file: "+triedReference);
}
public static void calculateAndSetHash(Source source, ContainerFile container) {
if(source.getHash() != null) {
return;
}
DigestInputStream inputStream = FileFactory.toInputStream(source, container);
try {
while (inputStream.read() != -1);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
String hash = FileFactory.getFileHash(inputStream);
source.setHash(hash);
}
public static String getFileHash(DigestInputStream dis) {
return StringUtils.leftPad(new BigInteger(1, dis.getMessageDigest().digest()).toString(16), 32, '0');
}
public static String getHash(String payload) {
try {
MessageDigest md5 = MessageDigest.getInstance("md5");
DigestInputStream dis = new DigestInputStream(new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8)), md5);
byte buf[] = new byte[8 * 1024];
while (dis.read(buf, 0, buf.length) > 0);
dis.close();
return StringUtils.leftPad(new BigInteger(1, md5.digest()).toString(16), 32, '0');
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);;
throw new RuntimeException("Failed calculating md5 hash", e);
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), e);;
throw new RuntimeException("Failed calculating md5 hash", e);
} catch (IOException e) {
log.error(e.getMessage(), e);;
throw new RuntimeException("Failed calculating md5 hash", e);
}
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/profile/util/Markdown.java
package com.sysunite.coinsweb.parser.profile.util;
/**
* @author bastbijl, Sysunite 2017
*/
public class Markdown {
public static String parseLinksToHtml(String input) {
if(input == null) {
return null;
}
return input.replaceAll("\\[([^\\]]*)\\][\n\t\r ]*\\(http([^)]*)\\)", "<a href=\"http$2\">$1</a>");
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sysunite.coinsweb</groupId>
<artifactId>coins-validator</artifactId>
<version>2.3.0</version>
<!-- Required metadata for Central -->
<name>coins-validator</name>
<description>COINS validator</description>
<url>https://github.com/sysunite/coins-2-validator</url>
<licenses>
<license>
<name>MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
</license>
</licenses>
<scm>
<url>https://github.com/sysunite/coins-2-validator</url>
<connection>scm:git@github.com:sysunite/coins-2-validator.git</connection>
<developerConnection>scm:git@github.com:sysunite/coins-2-validator.git</developerConnection>
</scm>
<developers>
<developer>
<email><EMAIL></email>
<name><NAME></name>
<url>https://github.com/bastbijl</url>
<id>bastbijl</id>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jackson.version>2.9.8</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>com.ontotext.graphdb</groupId>
<artifactId>graphdb-free-runtime</artifactId>
<version>8.8.1</version>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-osgi</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-osgi</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
<exclusion>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources/report-template</directory>
<targetPath>report-template</targetPath>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources/com/sysunite/coinsweb/cli</directory>
<targetPath>com/sysunite/coinsweb/cli</targetPath>
<filtering>true</filtering>
<includes>
<include>coins-validator.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources/com/sysunite/coinsweb/cli</directory>
<targetPath>com/sysunite/coinsweb/cli</targetPath>
<filtering>false</filtering>
<excludes>
<exclude>coins-validator.properties</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<debug>false</debug>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>com.sysunite.coinsweb.cli.Application</Main-Class>
<X-Compile-Source-JDK>1.8</X-Compile-Source-JDK>
<X-Compile-Target-JDK>1.8</X-Compile-Target-JDK>
</manifestEntries>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<file_sep>/doc/connectors.md
## Connectors
Two connectors are build in. The GraphDB connector and an in-mem connector. More connectors can be made by implementing the ```Connector``` interface.
The connector must return Rdf4j objects, so it is required the database being conntected has Rdf4j libraries.
The easiest way is to extend the `Rdf4jConnector` and read the `GraphDB` class as example.
### Registering a custom Connector
In order to make a custom Connector usable in a run these steps are required:
* Register the custom Connector in the `ConnectorFactoryImpl`
```java
public class ConnectorFactoryImpl implements ConnectorFactory {
private static final Logger log = LoggerFactory.getLogger(ConnectorFactoryImpl.class);
private static final Map<String, Class<? extends Connector>> register;
static
{
register = new HashMap();
register.put(GraphDB.REFERENCE, GraphDB.class);
register.put(InMemRdf4j.REFERENCE, InMemRdf4j.class);
```
* Compile the cli with the custom Connector
* Use the name set in `CustomConnector.REFERENCE` in a config.yml
### Connector Inferface
```java
public interface Connector {
void init();
boolean testConnection();
void wipe() throws ConnectorException;
void cleanup(List<String> contexts) throws ConnectorException;
void close();
List<Object> select(String queryString) throws ConnectorException;
List<Object> select(String queryString, long limit) throws ConnectorException;
void update(String queryString) throws ConnectorException;
void sparqlCopy(String fromContext, String toContext) throws ConnectorException;
void sparqlAdd(String fromContext, String toContext) throws ConnectorException;
void replaceResource(String context, String resource, String replace) throws ConnectorException;
void uploadFile(InputStream inputStream, String fileName, String baseUri, ArrayList<String> contexts) throws ConnectorException;
void storePhiGraphExists(Object source, String context, String fileName, String hash) throws ConnectorException;
void storeSigmaGraphExists(String context, Set<String> inclusionSet) throws ConnectorException;
void storeFinishedInferences(String compositionFingerPrint, Set<GraphVar> graphVars, Map<GraphVar, String> contextMap, String inferenceCode) throws ConnectorException;
Map<String, String> exportPhiGraph(String contexts, OutputStream outputStream) throws ConnectorException;
long quadCount(String context);
List<String> getContexts();
List<Object> listPhiGraphs() throws ConnectorException;
Map<String, Set<String>> listPhiContextsPerHash() throws ConnectorException;
Map<Set<String>, Set<String>> listSigmaGraphsWithIncludes() throws ConnectorException;
Map<String, Set<String>> listInferenceCodePerSigmaGraph() throws ConnectorException;
List<Object> listMappings() throws ConnectorException;
void writeContextsToFile(List<String> contexts, OutputStream outputStream, Map<String, String> prefixMap, String mainContext);
void writeContextsToFile(List<String> contexts, OutputStream outputStream, Map<String, String> prefixMap, String mainContext, Function filter);
Map<String, String> getImports(String context) throws ConnectorException;
}
```
<file_sep>/src/main/java/com/sysunite/coinsweb/connector/RdfParseException.java
package com.sysunite.coinsweb.connector;
/**
* @author bastbijl, Sysunite 2017
*/
public class RdfParseException extends Exception {
public RdfParseException(String message) {
super(message);
}
public RdfParseException(Exception original) {
super(original);
}
public RdfParseException(String message, Exception original) {
super(message, original);
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/steps/ValidationStep.java
package com.sysunite.coinsweb.steps;
import com.sysunite.coinsweb.filemanager.ContainerFile;
import com.sysunite.coinsweb.graphset.ContainerGraphSet;
/**
* @author bastbijl, Sysunite 2017
*/
public interface ValidationStep {
// Pojo part
String getType();
void checkConfig();
void setParent(Object configFile);
boolean getValid();
boolean getFailed(); // a fail means the step is invalid and no other steps should be executed
ValidationStep clone();
// Logic part
void execute(ContainerFile container, ContainerGraphSet graphSet);
}
<file_sep>/src/test/java/application/run/Otl210Test.java
package application.run;
import com.sysunite.coinsweb.cli.Application;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
/**
* @author bastbijl, Sysunite 2017
*/
public class Otl210Test extends HostFiles {
Logger log = LoggerFactory.getLogger(Otl210Test.class);
File config = new File(getClass().getClassLoader().getResource("general-9.85.yml").getFile());
@Test
public void test() {
log.info("Read "+config.getPath());
System.setProperty("user.dir", config.getParent() + "/otl-2.1/");
String[] args = {"run", config.getPath(), "--log-trace",
"01_NetwerkRuimteVoorbeeld_OTL21.ccr",
"02_DecompositieWegNetwerk1_OTL21.ccr",
"03_DecompositieWegNetwerk1_OTL21.ccr",
"04_PropertiesWegment_OTL21.ccr",
"05_ConnectedWegmenten_OTL21.ccr",
"06_RealisedWegvak_OTL21.ccr",
"07_WegvakEnum_OTL21.ccr",
"09_ExternalShapeRepresentation_OTL21.ccr",
"10_DocumentReference_OTL21.ccr",
"11_AquaductLifecycle_OTL21.ccr",
"12_LifecycleOTLDocument_OTL21.ccr"
};
Application.main(args);
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/filemanager/ContainerFile.java
package com.sysunite.coinsweb.filemanager;
import java.nio.file.Path;
import java.security.DigestInputStream;
import java.util.ArrayList;
import java.util.Set;
/**
* @author bastbijl, Sysunite 2017
*/
public interface ContainerFile {
boolean isCorruptZip();
boolean hasWrongSlashes();
Set<String> getContentFiles();
Set<String> getInvalidContentFiles();
Set<String> getCorruptContentFiles();
Set<String> getRepositoryFiles();
Set<String> getInvalidRepositoryFiles();
Set<String> getCorruptRepositoryFiles();
Set<String> getWoaFiles();
Set<String> getAttachmentFiles();
Set<String> getOrphanFiles();
DigestInputStream getFile(Path zipPath);
DigestInputStream getContentFile(String filename);
DigestInputStream getInvalidContentFile(String filename);
DigestInputStream getCorruptContentFile(String filename);
DigestInputStream getRepositoryFile(String filename);
DigestInputStream getInvalidRepositoryFile(String filename);
DigestInputStream getCorruptRepositoryFile(String filename);
DigestInputStream getWoaFile(String filename);
DigestInputStream getAttachmentFile(String filename);
DigestInputStream getOrphanFile(String filename);
ArrayList<String> getFileImports(Path zipPath);
ArrayList<String> getContentFileNamespaces(String filename);
ArrayList<String> getRepositoryFileNamespaces(String filename);
Path toPath();
Path getContentFilePath(String filename);
Path getInvalidContentFilePath(String filename);
Path getCorruptContentFilePath(String filename);
Path getRepositoryFilePath(String filename);
Path getInvalidRepositoryFilePath(String filename);
Path getCorruptRepositoryFilePath(String filename);
Path getWoaFilePath(String filename);
Path getAttachmentFilePath(String filename);
Path getOrphanFilePath(String filename);
}
<file_sep>/src/main/java/com/sysunite/coinsweb/filemanager/DeleteOnCloseFileInputStream.java
package com.sysunite.coinsweb.filemanager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* copied from https://stackoverflow.com/questions/4693968/is-there-an-existing-fileinputstream-delete-on-close
*/
public class DeleteOnCloseFileInputStream extends FileInputStream {
static Logger log = LoggerFactory.getLogger(DeleteOnCloseFileInputStream.class);
private File file;
public DeleteOnCloseFileInputStream(String name) throws FileNotFoundException {
this(new File(name));
}
public DeleteOnCloseFileInputStream(File file) throws FileNotFoundException{
super(file);
this.file = file;
}
public void close() throws IOException {
try {
super.close();
} finally {
if(file != null) {
file.delete();
file = null;
}
}
}
public static BufferedInputStream getBuffered(String name) throws FileNotFoundException {
return new BufferedInputStream(new DeleteOnCloseFileInputStream(name));
}
public static BufferedInputStream getBuffered(File file) throws FileNotFoundException {
return new BufferedInputStream(new DeleteOnCloseFileInputStream(file));
}
public static DigestInputStream getBufferedMd5(String name) throws FileNotFoundException {
try {
return new DigestInputStream(new BufferedInputStream(new DeleteOnCloseFileInputStream(name)), MessageDigest.getInstance("md5"));
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), e);;
}
return null;
}
public static DigestInputStream getBufferedMd5(File file) throws FileNotFoundException {
try {
return new DigestInputStream(new BufferedInputStream(new DeleteOnCloseFileInputStream(file)), MessageDigest.getInstance("md5"));
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), e);;
return null;
}
}
}<file_sep>/src/main/java/com/sysunite/coinsweb/parser/config/pojo/Attachment.java
package com.sysunite.coinsweb.parser.config.pojo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.util.StdConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.sysunite.coinsweb.parser.Parser.isNotNull;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(Include.NON_NULL)
@JsonDeserialize(converter=AttachmentSanitizer.class)
public class Attachment extends ConfigPart {
private static final Logger log = LoggerFactory.getLogger(Graph.class);
private Locator location;
private String as;
public Locator getLocation() {
return location;
}
public String getAs() {
return as;
}
public void setLocation(Locator location) {
this.location = location;
}
public void setAs(String as) {
this.as = as;
}
@Override
public void setParent(Object parent) {
super.setParent(parent);
this.location.setParent(this.getParent());
}
}
class AttachmentSanitizer extends StdConverter<Attachment, Attachment> {
private static final Logger log = LoggerFactory.getLogger(GraphSanitizer.class);
@Override
public Attachment convert(Attachment obj) {
isNotNull(obj.getLocation());
isNotNull(obj.getAs());
return obj;
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/connector/inmem/InMemRdf4j.java
package com.sysunite.coinsweb.connector.inmem;
import com.sysunite.coinsweb.connector.Rdf4jConnector;
import com.sysunite.coinsweb.parser.config.pojo.Environment;
import org.apache.commons.io.FileUtils;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
/**
* @author bastbijl, Sysunite 2017
*/
public class InMemRdf4j extends Rdf4jConnector {
private static final Logger log = LoggerFactory.getLogger(InMemRdf4j.class);
public static final String REFERENCE = "rdf4j-sail-memory";
private boolean useDisk;
private File tempFolder;
public InMemRdf4j(Environment config) {
useDisk = config.getUseDisk();
if(useDisk) {
try {
File temp = File.createTempFile("temp-file-name", ".tmp");
tempFolder = temp.getParentFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void init() {
if(initialized) {
return;
}
log.info("Initialize connector ("+REFERENCE+")");
MemoryStore memStore;
if(useDisk) {
memStore = new MemoryStore(tempFolder);
} else {
memStore = new MemoryStore();
}
repository = new SailRepository(memStore);
repository.initialize();
initialized = true;
}
public void close() {
if(!initialized) {
return;
}
repository.shutDown();
if(useDisk) {
try {
FileUtils.deleteDirectory(tempFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/config/pojo/Locator.java
package com.sysunite.coinsweb.parser.config.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.util.StdConverter;
import com.sysunite.coinsweb.parser.config.factory.FileFactory;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static com.sysunite.coinsweb.parser.Parser.isResolvable;
import static com.sysunite.coinsweb.parser.Parser.validate;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(Include.NON_NULL)
@JsonDeserialize(converter=LocatorSanitizer.class)
public class Locator extends ConfigPart {
private static final Logger log = LoggerFactory.getLogger(Locator.class);
public static final String FILE = "file";
public static final String ONLINE = "online";
private String type;
private String path;
private String uri;
public String getType() {
return type;
}
public String getPath() {
if (path == null) {
return null;
}
if(parent != null) {
return parent.relativize(path).toString();
}
return path;
}
public String getUri() {
return uri;
}
public void setType(String type) {
validate(type, FILE, ONLINE);
this.type = type;
}
public void setPath(String path) {
this.path = FilenameUtils.separatorsToSystem(path);
}
public void setUri(String uri) {
this.uri = uri;
}
@JsonIgnore
public String toString() {
if(path != null) {
return path;
}
if(uri != null) {
return uri;
}
return null;
}
@JsonIgnore
public boolean fileExists() {
File file = FileFactory.toFile(this);
return file.exists() && file.isFile();
}
@JsonIgnore
public Locator clone() {
Locator clone = new Locator();
clone.setType(this.type);
clone.setPath(this.path);
clone.setUri(this.uri);
clone.setParent(this.getParent());
return clone;
}
}
class LocatorSanitizer extends StdConverter<Locator, Locator> {
private static final Logger log = LoggerFactory.getLogger(LocatorSanitizer.class);
@Override
public Locator convert(Locator obj) {
if(obj.getType().equals("file")) {
// isFile(obj.getPath());
}
if(obj.getType().equals("online")) {
isResolvable(obj.getUri());
}
return obj;
}
}
<file_sep>/doc/coins-validator.sh
#!/usr/bin/env bash
java -Xms6g -Xmx8g -jar /usr/lib/validator-cli/2.0.8/coins-validator-2.0.8.jar "$@"
<file_sep>/src/test/java/com/sysunite/coinsweb/parser/config/GenerateTest.java
package com.sysunite.coinsweb.parser.config;
import com.sysunite.coinsweb.connector.Connector;
import com.sysunite.coinsweb.parser.config.factory.ConfigFactory;
import com.sysunite.coinsweb.parser.config.pojo.ConfigFile;
import com.sysunite.coinsweb.parser.config.pojo.StepDeserializer;
import com.sysunite.coinsweb.parser.config.pojo.Store;
import com.sysunite.coinsweb.steps.ValidationStep;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
/**
* @author bastbijl, Sysunite 2017
*/
public class GenerateTest {
Logger log = LoggerFactory.getLogger(GenerateTest.class);
@BeforeClass
public static void before() {
Store.factory = new ConnectorFactoryStub();
StepDeserializer.factory = new StepFactoryStub();
}
@Test
public void testMinimalContainer() {
ArrayList<File> containers = new ArrayList();
containers.add(new File(getClass().getClassLoader().getResource("some.ccr").getFile()));
ConfigFile configFile = ConfigFactory.getDefaultConfig(containers);
String yml = ConfigFactory.toYml(configFile);
System.out.println(yml);
}
private static class ConnectorFactoryStub implements com.sysunite.coinsweb.connector.ConnectorFactory {
@Override
public boolean exists(String key) {
return true;
}
@Override
public Class<? extends Connector> get(String key) {
return null;
}
@Override
public Connector build(Object config) {
return null;
}
}
private static class StepFactoryStub implements com.sysunite.coinsweb.steps.StepFactory {
@Override
public boolean exists(String key) {
return true;
}
@Override
public ValidationStep[] getDefaultSteps() {
return null;
}
@Override
public Class<? extends ValidationStep> get(String key) {
return null;
}
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/profile/util/IndentedCDATAPrettyPrinter.java
package com.sysunite.coinsweb.parser.profile.util;
import com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter;
import org.codehaus.stax2.XMLStreamWriter2;
import javax.xml.stream.XMLStreamException;
import java.util.Collections;
/**
* @author bastbijl, Sysunite 2017
*/
public class IndentedCDATAPrettyPrinter extends DefaultXmlPrettyPrinter {
public IndentedCDATAPrettyPrinter() {}
protected IndentedCDATAPrettyPrinter(IndentedCDATAPrettyPrinter base) {
_arrayIndenter = base._arrayIndenter;
_objectIndenter = base._objectIndenter;
_spacesInObjectEntries = base._spacesInObjectEntries;
_nesting = base._nesting;
}
@Override
public DefaultXmlPrettyPrinter createInstance() {
return new IndentedCDATAPrettyPrinter(this);
}
@Override
public void writeLeafElement(XMLStreamWriter2 sw, String nsURI, String localName, String text, boolean isCData) throws XMLStreamException {
if(!this._objectIndenter.isInline()) {
this._objectIndenter.writeIndentation(sw, this._nesting);
}
sw.writeStartElement(nsURI, localName);
if(isCData) {
this._objectIndenter.writeIndentation(sw, this._nesting+1);
String body = indentText(text.trim(), this._nesting+2);
String padding = String.join("", Collections.nCopies(this._nesting+1, INDENT));
sw.writeCData(System.lineSeparator() + body + System.lineSeparator() + padding);
this._objectIndenter.writeIndentation(sw, this._nesting);
} else {
sw.writeCharacters(text);
}
sw.writeEndElement();
this._justHadStartElement = false;
}
public char[] prepend(char[] fragment, char[] with) {
char[] result = new char[with.length + fragment.length];
System.arraycopy(with, 0, result, 0, with.length);
System.arraycopy(fragment, 0, result, with.length, fragment.length);
return result;
}
public static final String INDENT = " ";
public static String indentText(String body, int level) {
String result = "";
String indent = String.join("", Collections.nCopies(level, INDENT));
// Handle both windows and non-windows source
body = body.replaceAll("\\r\\n", "\n");
body = body.replaceAll("\\r", "\n");
String[] lines = body.split("\n");
int cutoff = -1;
boolean skipping = true;
for(String line : lines) {
if(skipping) {
if(line.trim().isEmpty()) {
continue;
} else {
skipping = false;
}
}
int count = line.indexOf(line.trim());
if(cutoff == -1) {
cutoff = count;
}
count = Math.min(count, cutoff);
result += indent + line.substring(count) + System.lineSeparator();
}
return result.substring(0, result.length()-1);
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/steps/DocumentReferenceValidation.java
package com.sysunite.coinsweb.steps;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.sysunite.coinsweb.connector.ConnectorException;
import com.sysunite.coinsweb.filemanager.ContainerFile;
import com.sysunite.coinsweb.graphset.ContainerGraphSet;
import com.sysunite.coinsweb.parser.config.pojo.ConfigPart;
import com.sysunite.coinsweb.parser.config.pojo.GraphVarImpl;
import org.eclipse.rdf4j.query.BindingSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import static com.sysunite.coinsweb.parser.Parser.isNotNull;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(Include.NON_NULL)
public class DocumentReferenceValidation extends ConfigPart implements ValidationStep {
private static final Logger log = LoggerFactory.getLogger(DocumentReferenceValidation.class);
public static final String REFERENCE = "DocumentReferenceValidation";
// Configuration items
private String type = REFERENCE;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private GraphVarImpl lookIn;
public GraphVarImpl getLookIn() {
return lookIn;
}
public void setLookIn(GraphVarImpl lookIn) {
this.lookIn = lookIn;
}
// Result items
private boolean failed = true;
public boolean getFailed() {
return failed;
}
public void setFailed(boolean failed) {
this.failed = failed;
}
private boolean valid = false;
public boolean getValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
@JsonSerialize(using = DocumentReferenceSerializer.class)
private HashMap<String, String> internalDocumentReferences = new HashMap<>();
public HashMap<String, String> getInternalDocumentReferences() {
return internalDocumentReferences;
}
public void setInternalDocumentReferences(HashMap<String, String> internalDocumentReferences) {
this.internalDocumentReferences = internalDocumentReferences;
}
@JsonSerialize(using = DocumentReferenceSerializer.class)
private HashMap<String, String> unmatchedInternalDocumentReferences = new HashMap<>();
public HashMap<String, String> getUnmatchedInternalDocumentReferences() {
return unmatchedInternalDocumentReferences;
}
public void setUnmatchedInternalDocumentReferences(HashMap<String, String> unmatchedInternalDocumentReferences) {
this.unmatchedInternalDocumentReferences = unmatchedInternalDocumentReferences;
}
public void checkConfig() {
isNotNull(lookIn);
}
@Override
public void execute(ContainerFile container, ContainerGraphSet graphSet) {
try {
boolean allReferencesAreSatisfied = true;
if (graphSet.hasContext(getLookIn())) {
String context = graphSet.contextMap().get(getLookIn());
String query =
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX cbim: <http://www.coinsweb.nl/cbim-2.0.rdf#> " +
"SELECT ?document ?filePath ?value " +
"FROM NAMED <" + context + "> " +
"WHERE { graph ?g { " +
" ?document rdf:type cbim:InternalDocumentReference . " +
" ?document cbim:filePath ?filePath . " +
" ?filePath cbim:datatypeValue ?value . " +
"}}";
int logCount = 0;
final int MAX_REPORT_COUNT = 50;
final int MAX_LOG_COUNT = 10;
List<Object> result = graphSet.select(query);
for (Object bindingSet : result) {
String document = ((BindingSet) bindingSet).getBinding("document").getValue().stringValue();
String filePath = ((BindingSet) bindingSet).getBinding("filePath").getValue().stringValue();
String value = ((BindingSet) bindingSet).getBinding("value").getValue().stringValue();
if(++logCount < MAX_LOG_COUNT)
log.info("Found InternalDocumentReference " + document + " to file " + value);
else if(logCount == MAX_LOG_COUNT)
log.info("Found InternalDocumentReference ...");
boolean found = false;
for (String attachment : container.getAttachmentFiles()) {
if (Paths.get(attachment).toFile().getName().equals(value)) {
found = true;
break;
}
}
if(found) {
if(logCount < MAX_REPORT_COUNT)
internalDocumentReferences.put(document, value);
} else {
unmatchedInternalDocumentReferences.put(document, value);
}
allReferencesAreSatisfied &= found;
}
}
valid = allReferencesAreSatisfied;
failed = false;
} catch (RuntimeException e) {
log.warn("Executing failed validationStep of type "+getType());
log.warn(e.getMessage());
failed = true;
} catch (ConnectorException e) {
log.warn("Executing failed validationStep of type "+getType());
log.warn(e.getMessage());
failed = true;
}
// Prepare data to transfer to the template
if(getFailed()) {
log.info("\uD83E\uDD49 failed");
} else {
if (getValid()) {
log.info("\uD83E\uDD47 valid");
} else {
log.info("\uD83E\uDD48 invalid");
}
}
}
@JsonIgnore
public DocumentReferenceValidation clone() {
DocumentReferenceValidation clone = new DocumentReferenceValidation();
// Configuration
clone.setType(this.getType());
clone.setLookIn(this.getLookIn());
clone.setParent(this.getParent());
// Results
// clone.setInternalDocumentReferences(this.getInternalDocumentReferences());
// clone.setValid(this.getValid());
// clone.setFailed(this.getFailed());
return clone;
}
}
class DocumentReferenceSerializer extends StdSerializer<HashMap<String, String>> {
public DocumentReferenceSerializer() {
this(null);
}
public DocumentReferenceSerializer(Class<HashMap<String, String>> t) {
super(t);
}
@Override
public void serialize(HashMap<String, String> map, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartArray();
for (String key : map.keySet()) {
gen.writeStartObject();
gen.writeStringField("uri", key);
gen.writeStringField("fileName", map.get(key));
gen.writeEndObject();
}
gen.writeEndArray();
}
}<file_sep>/src/main/java/com/sysunite/coinsweb/parser/config/pojo/ConfigPart.java
package com.sysunite.coinsweb.parser.config.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* @author bastbijl, Sysunite 2017
*/
public abstract class ConfigPart {
@JsonIgnore
protected ConfigFile parent;
public ConfigFile getParent() {
return parent;
}
public void setParent(Object parent) {
if(parent == null) {
return;
}
if(this.parent != null) {
if(!this.parent.equals(parent)) {
throw new RuntimeException("This ConfigPart was already part of some other ConfigFile, please clone it");
}
}
this.parent = (ConfigFile) parent;
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/config/pojo/Run.java
package com.sysunite.coinsweb.parser.config.pojo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.util.StdConverter;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.sysunite.coinsweb.steps.ValidationStep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.sysunite.coinsweb.parser.Parser.isNotEmpty;
import static com.sysunite.coinsweb.parser.Parser.isNotNull;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonDeserialize(converter=RunSanitizer.class)
public class Run extends ConfigPart {
private static final Logger log = LoggerFactory.getLogger(Run.class);
private Container[] containers;
@JsonDeserialize(using=StepDeserializer.class)
private ValidationStep[] steps;
private Report[] reports;
@JacksonXmlProperty(localName = "container")
@JacksonXmlElementWrapper(localName="containers")
public Container[] getContainers() {
return containers;
}
@JacksonXmlProperty(localName = "step")
@JacksonXmlElementWrapper(localName="steps")
public ValidationStep[] getSteps() {
return steps;
}
@JacksonXmlProperty(localName = "report")
@JacksonXmlElementWrapper(localName="reports")
public Report[] getReports() {
return reports;
}
public void setContainers(Container[] containers) {
this.containers = containers;
// Set pointers to root ConfigFile
for(Container container : this.containers) {
container.setParent(this.getParent());
}
}
public void setSteps(ValidationStep[] steps) {
this.steps = steps;
for(ValidationStep step : this.steps) {
step.setParent(this.getParent());
}
}
public void setReports(Report[] reports) {
this.reports = reports;
for(Report report : this.reports) {
report.setParent(this.getParent());
}
}
@Override
public void setParent(Object parent) {
super.setParent(parent);
for(Container container : this.containers) {
container.setParent(this.getParent());
}
for(ValidationStep step : this.steps) {
step.setParent(this.getParent());
}
for(Report report : this.reports) {
report.setParent(this.getParent());
}
}
}
class RunSanitizer extends StdConverter<Run, Run> {
private static final Logger log = LoggerFactory.getLogger(RunSanitizer.class);
@Override
public Run convert(Run obj) {
isNotEmpty(obj.getContainers());
isNotNull(obj.getSteps());
return obj;
}
}
<file_sep>/src/test/java/com/sysunite/coinsweb/connector/OutlineModelTest.java
package com.sysunite.coinsweb.connector;
import org.eclipse.rdf4j.model.Namespace;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Set;
/**
* @author bastbijl, Sysunite 2017
*/
public class OutlineModelTest {
Logger log = LoggerFactory.getLogger(OutlineModelTest.class);
@Test
public void test() throws IOException {
File a = new File(getClass().getResource("a.ttl").getFile());
File b = new File(getClass().getResource("b.ttl").getFile());
File c = new File(getClass().getResource("c.ttl").getFile());
File d = new File(getClass().getResource("d.ttl").getFile());
File e = new File(getClass().getResource("e.ttl").getFile());
File f = new File(getClass().getResource("f.ttl").getFile());
File schema = new File(getClass().getResource("schema.ttl").getFile());
File shacl = new File(getClass().getResource("shacl.ttl").getFile());
File sparql = new File(getClass().getResource("sparql.ttl").getFile());
File voiv = new File(getClass().getResource("void.ttl").getFile());
File otl = new File(getClass().getClassLoader().getResource("otl-2.1/otl-2.1.ttl").getFile());
File nquad = new File(getClass().getResource("nquad.nq").getFile());
File content = new File(getClass().getResource("content.rdf").getFile());
read(a);
read(b);
read(c);
read(d);
read(e);
read(f);
read(schema);
read(shacl);
read(sparql);
read(voiv);
read(otl);
read(nquad);
read(content);
}
public void read(File file) throws IOException {
String backupNameSpace = "http://example.com/backup";
RDFFormat format = Rdf4jUtil.interpretFormat(file);
if(format == null) {
throw new RuntimeException("Not able to determine format of file: " + file);
}
OutlineModel model = new OutlineModel();
RDFParser rdfParser = Rio.createParser(format);
rdfParser.setRDFHandler(new StatementCollector(model));
rdfParser.parse(new BufferedInputStream(new FileInputStream(file)), backupNameSpace);
Set<String> imports = model.getImports();
Set<Resource> contexts = model.getContexts();
Set<Resource> ontologies = model.getOntologies();
Set<Namespace> namespaces = model.getNamespaces();
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/parser/config/pojo/ConfigFile.java
package com.sysunite.coinsweb.parser.config.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.util.StdConverter;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.sysunite.coinsweb.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.sysunite.coinsweb.parser.Parser.isNotNull;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(Include.NON_NULL)
@JsonDeserialize(converter=ConfigFileSanitizer.class)
public class ConfigFile {
private static final Logger log = LoggerFactory.getLogger(ConfigFile.class);
private Environment environment;
private Run run;
private String version;
@JsonIgnore
private Path localizeTo;
public ConfigFile() {
}
public ConfigFile(Path localizeTo) {
this.localizeTo = localizeTo;
}
public static ConfigFile parse(File file) {
return parse(file, Paths.get(file.getParent()));
}
public static ConfigFile parse(File file, Path basePath) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
String message = "";
try {
ConfigFile configFile = mapper.readValue(file, ConfigFile.class);
if(basePath != null) {
configFile.localizeTo(basePath);
}
return configFile;
} catch (Exception e) {
message = e.getMessage();
}
throw new RuntimeException("Was not able to parse config file: "+message);
}
public static ConfigFile parse(InputStream inputStream) {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
String message = "";
try {
return mapper.readValue(inputStream, ConfigFile.class);
} catch (Exception e) {
message = e.getMessage();
}
throw new RuntimeException("Was not able to parse config file: "+message);
}
public Run getRun() {
return run;
}
public Environment getEnvironment() {
return environment;
}
public String getVersion() {
return version;
}
public void setRun(Run run) {
this.run = run;
this.run.setParent(this);
}
public void setEnvironment(Environment environment) {
this.environment = environment;
this.environment.setParent(this);
}
public void setVersion(String version) {
this.version = version;
}
public void localizeTo(Path path) {
this.localizeTo = path;
}
public Path resolve(String path) {
if(this.localizeTo == null) {
return Paths.get(path);
} else {
return this.localizeTo.resolve(Paths.get(path));
}
}
public Path relativize(String path) {
if(this.localizeTo == null) {
return Paths.get(path);
} else {
try {
return this.localizeTo.relativize(Paths.get(path));
} catch(IllegalArgumentException e) {
return Paths.get(path);
}
}
}
}
class ConfigFileSanitizer extends StdConverter<ConfigFile, ConfigFile> {
private static final Logger log = LoggerFactory.getLogger(ConfigFileSanitizer.class);
@Override
public ConfigFile convert(ConfigFile obj) {
isNotNull(obj.getEnvironment());
isNotNull(obj.getRun());
isNotNull(obj.getVersion());
if(!Version.VERSION.equals(obj.getVersion())) {
throw new RuntimeException("The config yml is not suitable for this version of the coins-validator");
}
return obj;
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/connector/RDFXMLBasePrettyWriter.java
package com.sysunite.coinsweb.connector;
import org.eclipse.rdf4j.common.xml.XMLUtil;
import org.eclipse.rdf4j.model.*;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.util.Literals;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.model.vocabulary.RDFS;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.helpers.XMLWriterSettings;
import org.eclipse.rdf4j.rio.rdfxml.RDFXMLWriter;
import java.io.*;
import java.util.Map;
import java.util.Stack;
/**
* @author bastbijl, Sysunite 2017
*/
public class RDFXMLBasePrettyWriter extends RDFXMLWriter implements Closeable, Flushable {
/*-----------*
* Variables *
*-----------*/
private String base;
/*
* We implement striped syntax by using two stacks, one for predicates and one for subjects/objects.
*/
/**
* Stack for remembering the nodes (subjects/objects) of statements at each level.
*/
private final Stack<RDFXMLBasePrettyWriter.Node> nodeStack = new Stack<>();
/**
* Stack for remembering the predicate of statements at each level.
*/
private final Stack<IRI> predicateStack = new Stack<IRI>();
/*--------------*
* Constructors *
*--------------*/
/**
* Creates a new RDFXMLPrintWriter that will write to the supplied OutputStream.
*
* @param out
* The OutputStream to write the RDF/XML document to.
*/
public RDFXMLBasePrettyWriter(OutputStream out) {
super(out);
}
/**
* Creates a new RDFXMLPrintWriter that will write to the supplied Writer.
*
* @param out
* The Writer to write the RDF/XML document to.
*/
public RDFXMLBasePrettyWriter(Writer out) {
super(out);
}
/*---------*
* Methods *
*---------*/
public void setBase(String base) {
this.base = base;
}
private String applyBase(String uri) {
if(base != null && uri.toString().startsWith(base)) {
return uri.toString().substring(base.length());
}
return uri;
}
@Override
protected void writeHeader()
throws IOException
{
// This export format needs the RDF Schema namespace to be defined:
setNamespace(RDFS.PREFIX, RDFS.NAMESPACE);
try {
// This export format needs the RDF namespace to be defined, add a
// prefix for it if there isn't one yet.
setNamespace(RDF.PREFIX, RDF.NAMESPACE);
if (getWriterConfig().get(XMLWriterSettings.INCLUDE_XML_PI)) {
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
}
if (getWriterConfig().get(XMLWriterSettings.INCLUDE_ROOT_RDF_TAG)) {
writeStartOfStartTag(RDF.NAMESPACE, "RDF");
if (defaultNamespace != null) {
writeNewLine();
writeIndents(1);
writer.write("xmlns=\"");
writer.write(XMLUtil.escapeDoubleQuotedAttValue(defaultNamespace));
writer.write("\"");
}
for (Map.Entry<String, String> entry : namespaceTable.entrySet()) {
String name = entry.getKey();
String prefix = entry.getValue();
writeNewLine();
writeIndents(1);
writer.write("xmlns:");
writer.write(prefix);
writer.write("=\"");
writer.write(XMLUtil.escapeDoubleQuotedAttValue(name));
writer.write("\"");
}
if (base != null) {
writeNewLine();
writeIndent();
writer.write("xml:base");
writer.write("=\"");
writer.write(base);
writer.write("\"");
}
writeEndOfStartTag();
}
writeNewLine();
}
finally {
headerWritten = true;
}
}
@Override
protected void writeIndent()
throws IOException
{
writer.write(" ");
}
@Override
public void flush()
throws IOException
{
if (writingStarted) {
if (!headerWritten) {
writeHeader();
}
try {
flushPendingStatements();
}
catch (RDFHandlerException e) {
if (e.getCause() != null && e.getCause() instanceof IOException) {
throw (IOException)e.getCause();
}
else {
throw new IOException(e);
}
}
writer.flush();
}
}
@Override
public void close()
throws IOException
{
try {
if (writingStarted) {
endRDF();
}
}
catch (RDFHandlerException e) {
if (e.getCause() != null && e.getCause() instanceof IOException) {
throw (IOException)e.getCause();
}
else {
throw new IOException(e);
}
}
finally {
nodeStack.clear();
predicateStack.clear();
writer.close();
}
}
@Override
public void endRDF()
throws RDFHandlerException
{
if (!writingStarted) {
throw new RDFHandlerException("Document writing has not yet started");
}
try {
if (!headerWritten) {
writeHeader();
}
flushPendingStatements();
if (getWriterConfig().get(XMLWriterSettings.INCLUDE_ROOT_RDF_TAG)) {
writeEndTag(RDF.NAMESPACE, "RDF");
}
writer.flush();
}
catch (IOException e) {
throw new RDFHandlerException(e);
}
finally {
writingStarted = false;
headerWritten = false;
}
}
@Override
protected void flushPendingStatements()
throws IOException, RDFHandlerException
{
if (!nodeStack.isEmpty()) {
popStacks(null);
}
}
/**
* Write out the stacks until we find subject. If subject == null, write out the entire stack
* @throws IOException
*/
private void popStacks(Resource newSubject)
throws IOException, RDFHandlerException
{
// Write start tags for the part of the stacks that are not yet
// written
for (int i = 0; i < nodeStack.size() - 1; i++) {
RDFXMLBasePrettyWriter.Node node = nodeStack.get(i);
if (!node.isWritten()) {
if (i > 0) {
writeIndents(i * 2 - 1);
IRI predicate = predicateStack.get(i - 1);
writeStartTag(predicate.getNamespace(), predicate.getLocalName());
writeNewLine();
}
writeIndents(i * 2);
writeNodeStartTag(node);
node.setIsWritten(true);
}
}
// Write tags for the top subject
RDFXMLBasePrettyWriter.Node topNode = nodeStack.pop();
if (predicateStack.isEmpty()) {
// write out an empty subject
writeIndents(nodeStack.size() * 2);
writeNodeEmptyTag(topNode);
writeNewLine();
}
else {
IRI topPredicate = predicateStack.pop();
if (!topNode.hasType()) {
// we can use an abbreviated predicate
writeIndents(nodeStack.size() * 2 - 1);
writeAbbreviatedPredicate(topPredicate, topNode.getValue());
}
else {
// we cannot use an abbreviated predicate because the type needs to
// written out as well
writeIndents(nodeStack.size() * 2 - 1);
writeStartTag(topPredicate.getNamespace(), topPredicate.getLocalName());
writeNewLine();
// write out an empty subject
writeIndents(nodeStack.size() * 2);
writeNodeEmptyTag(topNode);
writeNewLine();
writeIndents(nodeStack.size() * 2 - 1);
writeEndTag(topPredicate.getNamespace(), topPredicate.getLocalName());
writeNewLine();
}
}
// Write out the end tags until we find the subject
while (!nodeStack.isEmpty()) {
RDFXMLBasePrettyWriter.Node nextElement = nodeStack.peek();
if (nextElement.getValue().equals(newSubject)) {
break;
}
else {
nodeStack.pop();
// We have already written out the subject/object,
// but we still need to close the tag
writeIndents(predicateStack.size() + nodeStack.size());
writeNodeEndTag(nextElement);
if (predicateStack.size() > 0) {
IRI nextPredicate = predicateStack.pop();
writeIndents(predicateStack.size() + nodeStack.size());
writeEndTag(nextPredicate.getNamespace(), nextPredicate.getLocalName());
writeNewLine();
}
}
}
}
@Override
public void handleStatement(Statement st)
throws RDFHandlerException
{
if (!writingStarted) {
throw new RDFHandlerException("Document writing has not yet been started");
}
Resource subj = st.getSubject();
IRI pred = st.getPredicate();
Value obj = st.getObject();
try {
if (!headerWritten) {
writeHeader();
}
if (!nodeStack.isEmpty() && !subj.equals(nodeStack.peek().getValue())) {
// Different subject than we had before, empty the stack
// until we find it
popStacks(subj);
}
// Stack is either empty or contains the same subject at top
if (nodeStack.isEmpty()) {
// Push subject
nodeStack.push(new RDFXMLBasePrettyWriter.Node(subj));
}
// Stack now contains at least one element
RDFXMLBasePrettyWriter.Node topSubject = nodeStack.peek();
// Check if current statement is a type statement and use a typed node
// element is possible
// FIXME: verify that an XML namespace-qualified name can be created
// for the type URI
if (pred.equals(RDF.TYPE) && obj instanceof IRI && !topSubject.hasType()
&& !topSubject.isWritten())
{
// Use typed node element
topSubject.setType((IRI)obj);
}
else {
if (!nodeStack.isEmpty() && pred.equals(nodeStack.peek().nextLi())) {
pred = RDF.LI;
nodeStack.peek().incrementNextLi();
}
// Push predicate and object
predicateStack.push(pred);
nodeStack.push(new RDFXMLBasePrettyWriter.Node(obj));
}
}
catch (IOException e) {
throw new RDFHandlerException(e);
}
}
/**
* Write out the opening tag of the subject or object of a statement up to (but not including) the end of
* the tag. Used both in writeStartSubject and writeEmptySubject.
*/
private void writeNodeStartOfStartTag(RDFXMLBasePrettyWriter.Node node)
throws IOException, RDFHandlerException
{
Value value = node.getValue();
if (node.hasType()) {
// We can use abbreviated syntax
writeStartOfStartTag(node.getType().getNamespace(), node.getType().getLocalName());
}
else {
// We cannot use abbreviated syntax
writeStartOfStartTag(RDF.NAMESPACE, "Description");
}
if (value instanceof IRI) {
IRI uri = (IRI)value;
writeAttribute(RDF.NAMESPACE, "about", applyBase(uri.toString()));
}
else {
BNode bNode = (BNode)value;
writeAttribute(RDF.NAMESPACE, "nodeID", getValidNodeId(bNode));
}
}
/**
* Write out the opening tag of the subject or object of a statement.
*/
private void writeNodeStartTag(RDFXMLBasePrettyWriter.Node node)
throws IOException, RDFHandlerException
{
writeNodeStartOfStartTag(node);
writeEndOfStartTag();
writeNewLine();
}
/**
* Write out the closing tag for the subject or object of a statement.
*/
private void writeNodeEndTag(RDFXMLBasePrettyWriter.Node node)
throws IOException
{
if (node.getType() != null) {
writeEndTag(node.getType().getNamespace(), node.getType().getLocalName());
}
else {
writeEndTag(RDF.NAMESPACE, "Description");
}
writeNewLine();
}
/**
* Write out an empty tag for the subject or object of a statement.
*/
private void writeNodeEmptyTag(RDFXMLBasePrettyWriter.Node node)
throws IOException, RDFHandlerException
{
writeNodeStartOfStartTag(node);
writeEndOfEmptyTag();
}
/**
* Write out an empty property element.
*/
private void writeAbbreviatedPredicate(IRI pred, Value obj)
throws IOException, RDFHandlerException
{
writeStartOfStartTag(pred.getNamespace(), pred.getLocalName());
if (obj instanceof Resource) {
Resource objRes = (Resource)obj;
if (objRes instanceof IRI) {
IRI uri = (IRI)objRes;
writeAttribute(RDF.NAMESPACE, "resource", applyBase(uri.toString()));
}
else {
BNode bNode = (BNode)objRes;
writeAttribute(RDF.NAMESPACE, "nodeID", getValidNodeId(bNode));
}
writeEndOfEmptyTag();
}
else if (obj instanceof Literal) {
Literal objLit = (Literal)obj;
// datatype attribute
IRI datatype = objLit.getDatatype();
// Check if datatype is rdf:XMLLiteral
boolean isXmlLiteral = datatype.equals(RDF.XMLLITERAL);
// language attribute
if (Literals.isLanguageLiteral(objLit)) {
writeAttribute("xml:lang", objLit.getLanguage().get());
}
else {
if (isXmlLiteral) {
writeAttribute(RDF.NAMESPACE, "parseType", "Literal");
}
else {
writeAttribute(RDF.NAMESPACE, "datatype", applyBase(datatype.toString()));
}
}
writeEndOfStartTag();
// label
if (isXmlLiteral) {
// Write XML literal as plain XML
writer.write(objLit.getLabel());
}
else {
writeCharacterData(objLit.getLabel());
}
writeEndTag(pred.getNamespace(), pred.getLocalName());
}
writeNewLine();
}
protected void writeStartTag(String namespace, String localName)
throws IOException
{
writeStartOfStartTag(namespace, localName);
writeEndOfStartTag();
}
/**
* Writes <tt>n</tt> indents.
*/
protected void writeIndents(int n)
throws IOException
{
n++;
for (int i = 0; i < n; i++) {
writeIndent();
}
}
/*------------------*
* Inner class Node *
*------------------*/
private static class Node {
private int nextLiIndex = 1;
private Resource nextLi;
private Value value;
// type == null means that we use <rdf:Description>
private IRI type = null;
private boolean isWritten = false;
/**
* Creates a new Node for the supplied Value.
*/
public Node(Value value) {
this.value = value;
}
Resource nextLi() {
if (nextLi == null) {
nextLi = SimpleValueFactory.getInstance().createIRI(RDF.NAMESPACE + "_" + nextLiIndex);
}
return nextLi;
}
public void incrementNextLi() {
nextLiIndex++;
nextLi = null;
}
public Value getValue() {
return value;
}
public void setType(IRI type) {
this.type = type;
}
public IRI getType() {
return type;
}
public boolean hasType() {
return type != null;
}
public void setIsWritten(boolean isWritten) {
this.isWritten = isWritten;
}
public boolean isWritten() {
return isWritten;
}
}
}
<file_sep>/src/main/java/com/sysunite/coinsweb/steps/ContainerFileWriter.java
package com.sysunite.coinsweb.steps;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.sysunite.coinsweb.filemanager.ContainerFile;
import com.sysunite.coinsweb.graphset.ContainerGraphSet;
import com.sysunite.coinsweb.parser.config.pojo.ConfigPart;
import com.sysunite.coinsweb.parser.config.pojo.GraphVarImpl;
import com.sysunite.coinsweb.parser.config.pojo.Locator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author bastbijl, Sysunite 2017
*/
@JsonInclude(JsonInclude.Include.NON_NULL) // todo wrong this line?
public class ContainerFileWriter extends ConfigPart implements ValidationStep {
private static final Logger log = LoggerFactory.getLogger(ContainerFileWriter.class);
public static final String REFERENCE = "ContainerFileWriter";
// Configuration items
private String type = REFERENCE;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private Locator location;
public Locator getLocation() {
return location;
}
public void setLocation(Locator location) {
this.location = location;
}
@Override
public void setParent(Object parent) {
super.setParent(parent);
if(this.location != null) {
this.location.setParent(parent);
}
}
// Result items
private boolean failed = true;
public boolean getFailed() {
return failed;
}
public void setFailed(boolean failed) {
this.failed = failed;
}
private boolean valid = false;
public boolean getValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public void checkConfig() {
}
@Override
public void execute(ContainerFile container, ContainerGraphSet graphSet) {
try {
if(graphSet.getMain() == null) {
throw new RuntimeException("No main context (graphname) is set");
}
GraphVarImpl main = (GraphVarImpl) graphSet.getMain();
// try {
// log.info("Dump graphSet contexts to temp files:");
// for(GraphVar graphVar : graphSet.contextMap().keySet()) {
// File rdfFile = File.createTempFile(RandomStringUtils.random(8, true, true), ".rdf");
// OutputStream outputStream = new FileOutputStream(rdfFile);
// String context = graphSet.contextMap().get(graphVar);
// ArrayList<String> contexts = new ArrayList<>();
// contexts.add(context);
// graphSet.writeContextToFile(contexts, outputStream);
// outputStream.close();
// log.info("Compare "+context+" to "+main);
// for(Graph graph : ((ContainerFileImpl)container).getConfig().getGraphs()) {
// if(graph.getAs().contains(graphVar)) {
// if(graph.getMain() != null && graph.getMain()) {
// log.info("- "+graphVar+" to "+rdfFile.getName()+" (is main)");
// ((ContainerFileImpl)container).addContentFile(rdfFile, graph.getSource().getGraphname());
// } else {
// log.info("- "+graphVar+" to "+rdfFile.getName());
// ((ContainerFileImpl)container).addLibraryFile(rdfFile, graph.getSource().getGraphname());
// }
// }
// }
//
// }
//
// log.info("Register the configured files as attachments:");
// for(Attachment attachment : ((ContainerFileImpl)container).getConfig().getAttachments()) {
// ((ContainerFileImpl)container).addAttachmentFile(FileFactory.toFile(attachment.getLocation()));
// }
// } catch (FileNotFoundException e) {
// log.error(e.getMessage(), e);
// } catch (IOException e) {
// log.error(e.getMessage(), e);
// }
// File ccrFile;
// if (location.getParent() != null) {
// ccrFile = location.getParent().resolve(location.getPath()).toFile();
// } else {
// ccrFile = new File(location.getPath());
// }
//
// log.info("Save the container file to: "+ccrFile.getPath());
// ((ContainerFileImpl)container).writeZip(ccrFile.toPath());
valid = true;
failed = false;
} catch (RuntimeException e) {
log.warn("Executing failed validationStep of type "+getType());
log.warn(e.getMessage(), e);
failed = true;
}
}
@JsonIgnore
public ContainerFileWriter clone() {
ContainerFileWriter clone = new ContainerFileWriter();
// Configuration
clone.setType(this.getType());
clone.setLocation(this.getLocation().clone());
clone.setParent(this.getParent());
// Results
clone.setValid(this.getValid());
clone.setFailed(this.getFailed());
return clone;
}
}
<file_sep>/README.md
# COINS 2.0 Validator

Get a validation report of a coins container.
### Use command line interface (cross platform)
* download fat jar [(latest)](https://github.com/sysunite/coins-2-validator/releases/download/v2.3.0/coins-validator-2.3.0.jar) from https://github.com/sysunite/coins-2-validator/releases
* run the command:
```$ java -Xms6g -Xmx8g -jar validator-cli-2.3.0.jar [args]```
* or use a [.bat](https://github.com/sysunite/coins-2-validator/blob/develop/doc/coins-validator.bat) or [.sh](https://github.com/sysunite/coins-2-validator/blob/develop/doc/coins-validator.sh) script to wrap this java command with the name coins-validator:
```$ coins-validator [args]```

Read [HOWTO use the CLI](https://github.com/sysunite/coins-2-validator/blob/develop/doc/command.md) for a desrcription how to use the command line interface.
Read the [Code reference](https://github.com/sysunite/coins-2-validator/blob/develop/doc/reference.md) for an explanation of the Java code.
| d30bc0ad2ce5af786be4b0f293142f9b96c770dd | [
"Markdown",
"Maven POM",
"Java",
"Dockerfile",
"Shell"
] | 47 | Markdown | cckmit/coins-2-validator | 0ca4d944198ab82332658770563b54230907592c | 12b4e83a2a3f0ad62de82e2e00b3712ca222a01c |
refs/heads/master | <repo_name>BaltimoreBirds/art_gallery<file_sep>/spec/factories/artworks.rb
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :artwork do
artist_id 1
creation_date "2013-09-15"
sale_date "2013-09-15"
price 1
art_genre "MyString"
availability false
end
end
<file_sep>/app/models/collection.rb
class Collection < ActiveRecord::Base
has_many :artworks,
through: :art_collections
has_many :art_collections
has_many :customers,
through: :customer_collections
has_many :customer_collections
validates_presence_of :genre
end
<file_sep>/app/models/artwork.rb
class Artwork < ActiveRecord::Base
has_many :collections,
through: :art_collections
has_many :art_collections
belongs_to :customer
validates_presence_of :art_genre
validates_presence_of :creation_date
validates_presence_of :artist_id
end
<file_sep>/db/migrate/20130915215213_remove_artist_id.rb
class RemoveArtistId < ActiveRecord::Migration
def up
remove_column :collections, :artist_id, :integer
end
def down
add_column :collections, :artist_id, :integer
end
end
<file_sep>/spec/models/artwork_spec.rb
require 'spec_helper'
describe Artwork do
manet=FactoryGirl.create(:artwork)
it{should belong_to(:customer)}
it{should have_valid(:artist_id).when(manet.artist_id)}
it{should_not have_valid(:artist_id).when(nil, "")}
it{should have_valid(:creation_date).when(manet.creation_date)}
it{should_not have_valid(:creation_date).when(nil, "")}
it{should have_valid(:art_genre).when(manet.art_genre)}
it{should_not have_valid(:art_genre).when(nil, "")}
it{should have_valid(:availability).when(manet.availability)}
it{should have_valid(:sale_date).when(manet.sale_date)}
it{should have_valid(:price).when(manet.price)}
end
<file_sep>/db/migrate/20130916003536_add_customer_id_to_artwork.rb
class AddCustomerIdToArtwork < ActiveRecord::Migration
def up
add_column :artworks, :customer_id, :integer
end
def down
remove_column :artworks, :customer_id
end
end
<file_sep>/app/models/customer_collection.rb
class CustomerCollection < ActiveRecord::Base
belongs_to :customer
belongs_to :collection
validates_presence_of :customer
validates_presence_of :collection
end
<file_sep>/db/migrate/20130915195737_create_artworks.rb
class CreateArtworks < ActiveRecord::Migration
def change
create_table :artworks do |t|
t.integer :artist_id
t.date :creation_date
t.date :sale_date
t.integer :price
t.string :art_genre
t.boolean :availability
t.timestamps
end
end
end
<file_sep>/spec/models/artist_spec.rb
require 'spec_helper'
describe Artist do
manet=FactoryGirl.create(:artist)
it{should have_valid(:first_name).when(manet.first_name)}
it{should_not have_valid(:first_name).when(nil, "")}
it{should have_valid(:last_name).when(manet.last_name)}
it{should_not have_valid(:last_name).when(nil, "")}
it{should have_valid(:birthplace).when(manet.birthplace)}
it{should_not have_valid(:birthplace).when(nil, "")}
it{should have_valid(:style).when(manet.style)}
it{should_not have_valid(:style).when(nil, "")}
end
<file_sep>/spec/models/customer_spec.rb
require 'spec_helper'
describe Customer do
manet=FactoryGirl.create(:customer)
it{should have_many(:artworks)}
it{should have_valid(:first_name).when(manet.first_name)}
it{should_not have_valid(:first_name).when(nil, "")}
it{should have_valid(:last_name).when(manet.last_name)}
it{should_not have_valid(:last_name).when(nil, "")}
it{should have_valid(:email_address).when(manet.email_address)}
it{should_not have_valid(:email_address).when(nil, "")}
it{should have_valid(:money_spent).when(manet.money_spent)}
end
<file_sep>/app/models/artist.rb
class Artist < ActiveRecord::Base
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :birthplace
validates_presence_of :style
end
<file_sep>/spec/models/customer_collection_spec.rb
require 'spec_helper'
describe CustomerCollection do
it {should belong_to :customer}
it {should belong_to :collection}
it{should have_valid(:collection).when(Collection.new)}
it{should_not have_valid(:collection).when(nil)}
it{should have_valid(:customer).when(Customer.new)}
it{should_not have_valid(:customer).when(nil)}
end
<file_sep>/spec/models/art_collection_spec.rb
require 'spec_helper'
describe ArtCollection do
it {should belong_to :artwork}
it {should belong_to :collection}
it {should have_valid(:artwork).when(Artwork.new)}
it {should_not have_valid(:artwork).when(nil)}
it {should have_valid(:collection).when(Collection.new)}
it {should_not have_valid(:collection).when(nil)}
end
<file_sep>/app/models/customer.rb
class Customer < ActiveRecord::Base
has_many :collections,
through: :customer_collections
has_many :collections
has_many :artworks
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :email_address
end
<file_sep>/spec/models/collection_spec.rb
require 'spec_helper'
describe Collection do
monet=FactoryGirl.create(:collection)
it {should have_valid(:genre).when(monet.genre)}
it {should_not have_valid(:genre).when(nil, " ")}
end
<file_sep>/db/migrate/20130916005833_remove_unneccessary_table_columns.rb
class RemoveUnneccessaryTableColumns < ActiveRecord::Migration
def up
remove_column :collections, :artwork_id
remove_column :customers, :artwork_id
remove_column :customers, :collection
end
def down
add_column :collections, :artwork_id, :integer
add_column :customers, :artwork_id, :integer
add_column :customers, :collection, :integer
end
end
<file_sep>/app/models/art_collection.rb
class ArtCollection < ActiveRecord::Base
belongs_to :artwork
belongs_to :collection
validates_presence_of :artwork
validates_presence_of :collection
end
<file_sep>/spec/factories/artists.rb
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :artist do
first_name "MyString"
last_name "MyString"
email "MyString"
birthplace "MyString"
style "MyString"
end
end
| 0e6293c72ce205b8ee174a534e40b48fee28607b | [
"Ruby"
] | 18 | Ruby | BaltimoreBirds/art_gallery | 828613f673482b6dac31bfc79d0f696402331f19 | 9615778eb0a883809da8e8ddd893da9aba5b64f4 |
refs/heads/master | <file_sep>/*
Connectors enable external applications and scripts to provide information
for GoHome. Based on the backend used they may also register services and/or
call them. For detailed information about the different connector types please
refer to the respective documentation.
*/
package connector
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 rules
import (
"github.com/moraes/config"
"github.com/robertkrimen/otto"
"github.com/sirupsen/logrus"
"home/core"
"home/core/eventbus"
"home/core/service"
"fmt"
)
func apiLog(call otto.FunctionCall) otto.Value {
logrus.Infof("[Plugins/rules] JavaScript-Log: %s", call.Argument(0).String())
return otto.Value{}
}
func apiServiceCall(call otto.FunctionCall) otto.Value {
svc := call.Argument(0).String()
interfaceValue, err := call.Argument(1).Export()
if err != nil {
logrus.Errorf("Plugins: rules: javascript supplied invalid parameters")
return otto.UndefinedValue()
}
params := interfaceValue.(map[string]interface{})
future := service.CallService(svc, params)
result := <-future.Result
var res otto.Value
if _, ok := result.(error); ok {
res, err = otto.ToValue(result.(error).Error())
} else {
res, err = otto.ToValue(result)
}
if err != nil {
logrus.Errorf("Plugins: rules: failed to convert service result to javascript")
return otto.UndefinedValue()
}
return res
}
func apiSubscribe(call otto.FunctionCall) otto.Value {
topic := call.Argument(0).String()
func_name := call.Argument(1).String()
logrus.Infof("[Plugins/rules] javascript vm subscibed to %s", topic, func_name)
eventbus.EventBus.Subscribe(topic, func(event eventbus.Event) {
data, _ := config.RenderJson(event)
jsCmd := fmt.Sprintf("(%s.bind(Home))(%s)", func_name, data)
result, err := call.Otto.Run(jsCmd)
if err != nil {
logrus.Warnf("JavaScript-Error: %s error=%s", result, err)
}
})
return otto.Value{}
}
func apiGetState(call otto.FunctionCall) otto.Value {
state := call.Argument(0).String()
value := core.StateTracker.Get(state)
result, _ := call.Otto.ToValue(value)
return result
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 main
import (
"fmt"
"os"
"os/signal"
"runtime"
"github.com/sirupsen/logrus"
"home/core"
"home/core/backend"
"home/core/eventbus"
"home/core/service"
_ "home/backends"
_ "home/plugins"
)
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
func shutdownHome(param service.Arguments) interface{} {
eventbus.EventBus.Publish(eventbus.Event{
Topic: eventbus.HOME_SHUTDOWN,
Origin: "home",
})
return fmt.Sprintln("Shutting down home")
}
func main() {
config, err := core.ParseConfig("./config.yaml")
if err != nil {
logrus.Errorf("Failed to parse configuration: %s", err)
return
}
switch core.Global.Logging {
case "debug":
logrus.SetLevel(logrus.DebugLevel)
case "info":
logrus.SetLevel(logrus.InfoLevel)
case "warn":
logrus.SetLevel(logrus.WarnLevel)
case "error":
logrus.SetLevel(logrus.ErrorLevel)
default:
logrus.SetLevel(logrus.InfoLevel)
logrus.Warnf("Home: invalid log level supplied: '%s'", core.Global.Logging)
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
_ = sig
eventbus.EventBus.Publish(eventbus.Event{
Topic: eventbus.HOME_SHUTDOWN,
Origin: "home",
})
}
}()
logrus.Infof("[Home] Geo-Location set to: Lat=%f Long=%f", core.Global.Latitude, core.Global.Longitude)
service.ServiceRegistry.Register(&backend.Component{
Name: "core",
}, "shutdown_home", "Shutdown home", shutdownHome, map[string]string{}, map[string]string{})
eventbus.EventBus.Start()
backendConfig, _ := config.List("backends")
backend.DefaultManager.StartBackendsByConfig(backendConfig)
eventbus.EventBus.Subscribe(eventbus.HOME_SHUTDOWN, func(event eventbus.Event) {
backend.DefaultManager.StopBackends()
})
core.PluginManager.Start(config)
core.StateTracker.Start()
service.ServiceRegistry.Start()
eventbus.EventBus.Publish(eventbus.Event{
Topic: eventbus.HOME_STARTED,
Origin: "home",
})
eventbus.EventBus.Wait()
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 eventbus
import (
"sync"
"time"
"github.com/sirupsen/logrus"
)
// Subscriber is a function accepting a single `eventbus.Event` parameter
// and is called whenever a matching event is published on the event bus
type Subscriber func(Event)
// SubscriberEntry represents the actual subscription of a Subscriber
// function and is returned after the subscription has been successful
type SubscriberEntry struct {
call Subscriber
constraint int
}
// Once can be called on a SubscriberEntry to force the event bus to
// remove the subscription after the next notification
func (sub *SubscriberEntry) Once() *SubscriberEntry {
sub.constraint = CONSTRAINT_ONCE
return sub
}
// Once can be called on a SubscriberEntry to force the event bus to
// remove the subscription after the next notification
func (sub *SubscriberEntry) Delete() *SubscriberEntry {
sub.constraint = CONSTRAINT_DELETED
return sub
}
type eventBus struct {
subscriber map[string][]*SubscriberEntry
events chan Event
wg sync.WaitGroup
subscriberLock sync.Mutex
}
// Publish can be used to publish a new message on the event bus
// All Subscribers matching the event.Topic will be notified
func (bus *eventBus) Publish(event Event) {
bus.events <- event
}
func (bus *eventBus) handle() {
defer bus.wg.Done()
for {
select {
case event := <-bus.events:
logrus.Debugf("EventBus: %s published '%s'", event.Origin, event.Topic)
bus.subscriberLock.Lock()
newSub := make([]*SubscriberEntry, 0)
for _, sub := range bus.subscriber[event.Topic] {
if sub.constraint != CONSTRAINT_DELETED {
go sub.call(event)
newSub = append(newSub, sub)
if sub.constraint == CONSTRAINT_ONCE {
sub.constraint = CONSTRAINT_DELETED
}
}
}
bus.subscriber[event.Topic] = newSub
bus.subscriberLock.Unlock()
if event.Topic == HOME_SHUTDOWN {
logrus.Infof("EventBus: shutting down due to HOME_SHUTDOWN")
return
}
case <-time.After(15 * time.Second):
logrus.Debugf("EventBus: idle since 5 seconds")
}
}
}
func (bus *eventBus) Subscribe(topic string, call Subscriber) *SubscriberEntry {
bus.subscriberLock.Lock()
defer bus.subscriberLock.Unlock()
sub := &SubscriberEntry{
call: call,
constraint: 0,
}
logrus.Debugf("EventBus: new subscription for: %s", topic)
bus.subscriber[topic] = append(bus.subscriber[topic], sub)
return sub
}
// Start prepares and starts the eventbus
func (bus *eventBus) Start() {
bus.wg.Add(1)
go bus.handle()
}
// Wait until the eventbus has finished processing by receiving a
// HOME_SHUTDOWN event, otherwise this function will block forever
func (bus *eventBus) Wait() {
bus.wg.Wait()
}
// newEventBus returns a new eventbus instance
func newEventBus() *eventBus {
bus := &eventBus{
events: make(chan Event),
subscriber: make(map[string][]*SubscriberEntry, 100),
}
return bus
}
// Eventbus singelton instance
var EventBus *eventBus
func init() {
EventBus = newEventBus()
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 plugins
import (
"fmt"
"log"
"math/rand"
"time"
"github.com/StephanDollberg/go-json-rest-middleware-jwt"
"github.com/ant0ine/go-json-rest/rest"
"github.com/braintree/manners"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
"net/http"
"home/core"
"home/core/backend"
"home/core/service"
"home/utils"
)
// HTTPAPIServer represent the http rest api server plugin
type HTTPAPIServer struct{}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
func randomString(l int) string {
bytes := make([]byte, l)
for i := 0; i < l; i++ {
bytes[i] = byte(randInt(65, 90))
}
return string(bytes)
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
// Start start the http rest api plugin
func (cli *HTTPAPIServer) Start(config map[string]interface{}) error {
wwwroot, _ := utils.GetString("static", config, "")
addr, _ := utils.GetString("listen", config, ":8080")
secret, ok := utils.GetString("secret", config, randomString(128))
if !ok {
logrus.Warnf("Plugins: httpapi: generated new secret: %s", secret)
}
jwt_middleware := &jwt.JWTMiddleware{
Key: []byte(secret),
Realm: "jwt auth",
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
Authenticator: func(userId string, password string) bool {
return userId == "admin" && password == "<PASSWORD>"
}}
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
api.Use(&rest.IfMiddleware{
Condition: func(request *rest.Request) bool {
return request.URL.Path != "/login"
},
IfTrue: jwt_middleware,
})
router, err := rest.MakeRouter(
rest.Post("/login", jwt_middleware.LoginHandler),
rest.Get("/refresh_token", jwt_middleware.RefreshHandler),
rest.Get("/", getApiVersion),
rest.Get("/sensors", getAllSensors),
rest.Get("/sensors/:backend.:sensor", getSensor),
rest.Get("/services", getAllServices),
rest.Get("/services/:backend.:service", getService),
rest.Post("/services/:backend.:service", callService),
)
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
http.Handle("/v1/", http.StripPrefix("/v1", api.MakeHandler()))
if wwwroot != "" {
logrus.Infof("Plugin: httpapi: service static content from %s", wwwroot)
http.Handle("/ui/", http.StripPrefix("/ui", http.FileServer(http.Dir(wwwroot))))
}
go func() {
logrus.Infof("Plugin: httpapi: starting on %s", addr)
manners.ListenAndServe(addr, http.DefaultServeMux)
}()
return nil
}
// Stop stops the http server api
func (cli *HTTPAPIServer) Stop() {
logrus.Infof("Plugin: httpapi: requesting shutdown")
manners.Close()
}
// Name returns the name of the http server api
func (cli *HTTPAPIServer) Name() string {
return "httpapi"
}
func init() {
core.PluginManager.Register(&HTTPAPIServer{})
}
func getSensor(w rest.ResponseWriter, r *rest.Request) {
sensor := r.PathParam("backend") + "." + r.PathParam("sensor")
w.WriteJson(core.StateTracker.Get(sensor))
}
func getService(w rest.ResponseWriter, r *rest.Request) {
service := r.PathParam("backend") + "." + r.PathParam("service")
w.WriteJson(fmt.Sprintf("Not yet implemented: %s", service))
}
func callService(w rest.ResponseWriter, r *rest.Request) {
svc := r.PathParam("backend") + "." + r.PathParam("service")
var params interface{}
r.DecodeJsonPayload(¶ms)
if _, ok := params.(map[string]interface{}); !ok {
w.WriteJson(map[string]string{"Error": "Call parameters must be a JSON object"})
return
}
future := service.CallService(svc, params.(map[string]interface{}))
result := <-future.Result
switch r := result.(type) {
case error:
rest.Error(
w,
r.Error(),
http.StatusInternalServerError,
)
default:
w.WriteJson(r)
}
}
func getApiVersion(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(
map[string]string{
"version": "1",
},
)
}
func getAllSensors(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(backend.DefaultManager.Describe())
}
func getAllServices(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(service.ServiceRegistry.Describe())
}
<file_sep>package utils
import "sync"
type TryableLock struct {
lock sync.Mutex
locked bool
}
func (t *TryableLock) Lock() bool {
t.lock.Lock()
defer t.lock.Unlock()
if t.locked {
return false
}
t.locked = true
return true
}
func (t *TryableLock) Unlock() bool {
t.lock.Lock()
defer t.lock.Unlock()
if !t.locked {
return false
}
t.locked = false
return true
}
<file_sep>package utils
import (
"testing"
)
func TestTryableLog(test *testing.T) {
t := TryableLock{}
if !t.Lock() {
test.Errorf("failed to lock mutex")
}
if t.Lock() {
test.Errorf("succeeded to lock mutex")
}
if !t.Unlock() {
test.Errorf("failed to unlock mutex")
}
if t.Unlock() {
test.Errorf("succeeded to unlock mutex")
}
}
func TestSaveConfigGetString(t *testing.T) {
config := map[string]interface{}{
"str": "string_value",
"int": 1,
"float": 3.12,
"abr": map[string]string{"test": "test"},
}
res, ok := GetString("str", config, "def")
if res != "string_value" || !ok {
t.Errorf("GetString: %#v %#v ", res, ok)
}
res, ok = GetString("", config, "def")
if res != "def" || ok {
t.Errorf("GetString: %#v %#v ", res, ok)
}
res, ok = GetString("int", config, "def")
if res != "1" || !ok {
t.Errorf("GetString: %#v %#v ", res, ok)
}
res, ok = GetString("float", config, "def")
if res != "3.120000" || !ok {
t.Errorf("GetString: %#v %#v ", res, ok)
}
res, ok = GetString("abr", config, "def")
if res != "def" || ok {
t.Errorf("GetString: %#v %#v ", res, ok)
}
res, ok = GetString("abr", nil, "def")
if res != "def" || ok {
t.Errorf("GetString: %#v %#v ", res, ok)
}
// int
resInt, ok := GetInt("str", config, 123)
if resInt != 123 || ok {
t.Errorf("GetInt: %#v %#v ", resInt, ok)
}
resInt, ok = GetInt("", config, 123)
if resInt != 123 || ok {
t.Errorf("GetInt: %#v %#v ", resInt, ok)
}
resInt, ok = GetInt("int", config, 123)
if resInt != 1 || !ok {
t.Errorf("GetInt: %#v %#v ", resInt, ok)
}
resInt, ok = GetInt("float", config, 123)
if resInt != 3 || !ok {
t.Errorf("GetInt: %#v %#v ", resInt, ok)
}
resInt, ok = GetInt("abr", config, 123)
if resInt != 123 || ok {
t.Errorf("GetInt: %#v %#v ", resInt, ok)
}
resInt, ok = GetInt("abr", nil, 123)
if resInt != 123 || ok {
t.Errorf("GetInt: %#v %#v ", resInt, ok)
}
// float
resFloat, ok := GetFloat64("str", config, 1.00123)
if resFloat != 1.00123 || ok {
t.Errorf("GetFloat64: %#v %#v ", resFloat, ok)
}
resFloat, ok = GetFloat64("", config, 1.00123)
if resFloat != 1.00123 || ok {
t.Errorf("GetFloat64: %#v %#v ", resFloat, ok)
}
resFloat, ok = GetFloat64("int", config, 1.00123)
if resFloat != 1 || !ok {
t.Errorf("GetFloat64: %#v %#v ", resFloat, ok)
}
resFloat, ok = GetFloat64("float", config, 1.00123)
if resFloat != 3.12 || !ok {
t.Errorf("GetFloat64: %#v %#v ", resFloat, ok)
}
resFloat, ok = GetFloat64("abr", config, 1.00123)
if resFloat != 1.00123 || ok {
t.Errorf("GetFloat64: %#v %#v ", resFloat, ok)
}
resFloat, ok = GetFloat64("abr", nil, 1.00123)
if resFloat != 1.00123 || ok {
t.Errorf("GetFloat64: %#v %#v ", resFloat, ok)
}
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 plugins
import (
"encoding/json"
"fmt"
"home/core"
"home/core/eventbus"
"home/core/service"
"io/ioutil"
"time"
"github.com/robertkrimen/otto"
"github.com/sirupsen/logrus"
)
type RuleVM struct {
otto *otto.Otto
Name string
exit chan bool
Event chan eventbus.Event
}
func NewRuleVM(name string) *RuleVM {
res := &RuleVM{
otto: otto.New(),
Name: name,
exit: make(chan bool),
Event: make(chan eventbus.Event),
}
return res
}
func (vm *RuleVM) PrepareEnv() error {
Service := func(call otto.FunctionCall) otto.Value {
svc := call.Argument(0).String()
interfaceValue, err := call.Argument(1).Export()
if err != nil {
logrus.Errorf("Plugins: rules: javascript supplied invalid parameters")
return otto.UndefinedValue()
}
params := interfaceValue.(map[string]interface{})
future := service.CallService(svc, params)
result := <-future.Result
var res otto.Value
if _, ok := result.(error); ok {
res, err = otto.ToValue(result.(error).Error())
} else {
res, err = otto.ToValue(result)
}
if err != nil {
logrus.Errorf("Plugins: rules: failed to convert service result to javascript")
return otto.UndefinedValue()
}
return res
}
Log := func(call otto.FunctionCall) otto.Value {
logrus.Infof("Plugins: jsrule: %s Log: %s", vm.Name, call.Argument(0).String())
return otto.Value{}
}
err := vm.otto.Set("Service", Service)
if err != nil {
return err
}
err = vm.otto.Set("Log", Log)
if err != nil {
return err
}
return nil
}
func (vm *RuleVM) Run() {
// Verify that a Rule variable exists
r, err := vm.otto.Get("Rule")
if err != nil {
logrus.Warnf("rule %s: no rule definition found", vm.Name)
return
}
vm.otto.Run("Rule.init()")
name, err := r.Object().Get("name")
if err == nil {
vm.Name = name.String()
}
// Subscribe for all state changes
eventbus.EventBus.Subscribe(eventbus.STATE_CHANGED, func(e eventbus.Event) {
vm.Event <- e
})
for {
select {
case <-vm.exit:
return
case event, ok := <-vm.Event:
if !ok {
logrus.Warnf("rule %s: event channel closed", vm.Name)
return
}
// This is a dirty hack. find something better ....
jsData, err := json.Marshal(event)
if err != nil {
logrus.Warnf("rule %s: failed to marshal event: %s", vm.Name, err)
continue
}
res, err := vm.otto.Run(fmt.Sprintf("Rule.onEvent(%s)", jsData))
if err != nil {
logrus.Warnf("rule %s: JS error occured: %s (%s)", vm.Name, err, res)
}
case <-time.After(1 * time.Second):
res, err := vm.otto.Run("Rule.update()")
if err != nil {
logrus.Warnf("rule %s: returned error %s with result %s", vm.Name, err, res)
}
}
}
}
type RuleManager struct {
activeVMs []RuleVM
}
func (handler *RuleManager) Name() string {
return "jsrule"
}
func (handler *RuleManager) Start(options map[string]interface{}) error {
var list []interface{}
switch a := options["files"].(type) {
case []interface{}:
list = a
default:
return fmt.Errorf("invalid configuration: %#v", options)
}
for _, file := range list {
rule := NewRuleVM(file.(string))
rule.PrepareEnv()
data, err := ioutil.ReadFile(file.(string))
if err != nil {
return err
}
logrus.Debugf("initializing new JS virtual machine: %s, %s", file, rule.Name)
rule.otto.Run(string(data))
go rule.Run()
}
return nil
}
func (handler *RuleManager) Stop() {
for _, r := range handler.activeVMs {
select {
case r.exit <- true:
default:
// Do not block if one of our VMs got stuck in some loop
}
}
}
func init() {
core.PluginManager.Register(&RuleManager{})
}
<file_sep>package service
import (
"home/core/eventbus"
"code.google.com/p/go-uuid/uuid"
"github.com/sirupsen/logrus"
)
type Future struct {
uuid string
Result chan interface{}
}
func (f *Future) callback(event eventbus.Event) {
logrus.Debugf("Future: %s has been set to %#v", f.uuid, event.Data)
f.Result <- event.Data
}
func (f *Future) Get() interface{} {
return <-f.Result
}
func NewFuture() *Future {
f := &Future{
uuid: uuid.NewUUID().String(),
Result: make(chan interface{}),
}
eventbus.EventBus.Subscribe(f.uuid, f.callback).Once()
logrus.Debugf("Future: %s new future created", f.uuid)
return f
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 devicetracker
import (
"fmt"
"home/core/backend"
"home/utils"
"time"
"github.com/moraes/config"
"github.com/nethack42/go-netgear"
"github.com/sirupsen/logrus"
)
type netgearComponent struct {
name string
router *netgear.Netgear
last string
isUpdating bool
knownDevices map[string]string
trackOnlyKnown bool
}
/*
This backend provides a device tracker by querying Netgear routers via the
proprietary Genie protocol (see github.com/nethack42/go-netgear).
Note that only newer Netgear routers are supported. There might be ways
to query this information on older models too, but this is currently not
supported.
In order to use this backend within your GoHome domain add something like the
following to your configuration file:
backends:
- type: netgear
name: MyRouter1
host: 192.168.0.1
username: admin
password: <PASSWORD>
track_only_known: y
devices:
"00:00:00:00:00:11": "Bob"
"11:22:33:44:55:66": "Alice"
Note that none of those fields are required to be set. If obmitted, `host`
defaults to "routerlogin.net", `username` to "admin" and `password` to "".
If `track_only_known` is not set it defaults to "n" and thus all devices
connected to the router will be returned. If `track_only_known` is set to "y"
only devices with their MAC address configured in `devices` will be tracked.
Data in state changes published by this backend have the following format:
[
[TO_BE_DONE]
]
*/
func NetgearDeviceTrackerBackend(config map[string]interface{}, back *backend.Backend) error {
deviceList := make(map[string]string)
host, _ := utils.GetString("host", config, "routerlogin.net")
username, _ := utils.GetString("username", config, "admin")
password, _ := utils.GetString("password", config, "")
trackS, _ := utils.GetString("only_known_devices", config, "y")
track := true
// Re do this more elegant
for _, str := range []string{"n", "no", "0", "false"} {
if str == trackS {
track = false
}
}
if config["devices"] != nil {
devs := config["devices"].(map[string]interface{})
for mac, name := range devs {
deviceList[mac] = name.(string)
}
}
component := &backend.Component{
StateSink: make(chan interface{}),
Polling: updateNetgear,
Name: "devices",
Type: backend.DeviceTracker,
Internal: &netgearComponent{
router: netgear.NewRouter(host, username, password),
knownDevices: deviceList,
trackOnlyKnown: track,
},
}
back.RegisterComponent <- component
return nil
}
func updateNetgear(comp *backend.Component) error {
net := comp.Internal.(*netgearComponent)
start := time.Now()
if net.isUpdating {
logrus.Infof("Component: %s ignoring polling request. update still running", comp.URN())
return nil
}
net.isUpdating = true
defer func() {
net.isUpdating = false
}()
logrus.Debugf("Component: %s Updating attached devices", comp.URN())
res, err := net.router.Login()
if err != nil {
return err
}
if res {
device, err := net.router.GetAttachedDevices()
var preparedDevices []netgear.AttachedDevice
if err != nil {
return err
}
for i, dev := range device {
if net.knownDevices[dev.Mac] != "" {
if net.trackOnlyKnown {
dev.Name = net.knownDevices[dev.Mac]
preparedDevices = append(preparedDevices, dev)
} else {
device[i].Name = net.knownDevices[dev.Mac]
}
}
}
if net.trackOnlyKnown {
device = preparedDevices
}
str, err := config.RenderJson(device)
if err != nil {
return err
}
net.last = str
comp.StateSink <- device
} else {
return fmt.Errorf("Failed to login")
}
logrus.Debugf("Component: %s updated connected devices in %s", comp.URN(), time.Now().Sub(start))
return nil
}
func init() {
backend.Register("netgear", NetgearDeviceTrackerBackend)
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 external
import (
"fmt"
"home/core/backend"
"home/core/service"
"os/exec"
"github.com/sirupsen/logrus"
)
type command struct {
result string
command string
}
/*
LocalScriptBackend provides the possibility to execute local scripts while
publishing their results on the internal eventbus. Scripts can either be
registered as components/sensors or as services. In the first case scripts are
polled in a regular interval. The latter one enables the script to be called
vie Service Call requests.
In order to use this backend add something like the following to your
configuration:
backends:
- type: script
scripts:
- exec: /path/to/script
name: MyPrettyName
#type: sensor (default)
- exec: /path/to/other/script
name: my_pretty_name_2
type: service
Service scripts can latter be called by sending a Service Call request to
`script.MyPrettyName`. Note that `script` may differ if a `name` field is
specified within the backend configuration.
The result of script executions is published as a string within state_changed
events.
*/
func LocalScriptBackend(config map[string]interface{}, back *backend.Backend) error {
var scripts []interface{}
services := make(map[string]command)
switch a := config["scripts"].(type) {
case []interface{}:
scripts = a
default:
logrus.Warnf("Backend: %s invalid configuration: %#v", back.Name(), config)
return nil // CHANGE ME
}
for _, s := range scripts {
script, ok := s.(map[string]interface{})
if !ok {
logrus.Warnf("Backend: %s script with invalid configuration: %#v", back.Name(), script)
continue
}
exec, ok := script["exec"].(string)
if !ok {
logrus.Warnf("Backend: %s script configuration without `exec`: %s", back.Name(), script)
continue
}
name, ok := script["name"].(string)
if !ok {
name = exec
}
execType, ok := script["type"].(string)
if !ok {
execType = "sensor"
}
cmd := command{
command: exec,
}
comp := &backend.Component{
StateSink: make(chan interface{}),
Name: name,
Polling: updateScriptResult,
Internal: cmd,
}
switch execType {
case "sensor":
back.RegisterComponent <- comp
case "service":
service.ServiceRegistry.Register(back, comp.Name, "Call local script",
cmd.execute, map[string]string{}, map[string]string{})
}
}
back.Internal = services
return nil
}
func (cmd *command) execute(param service.Arguments) interface{} {
data, _ := cmd.callScript()
return data
}
func (cmd *command) callScript() (string, bool) {
changed := false
res, err := exec.Command("/bin/sh", "-c", cmd.command).Output()
if err != nil {
return err.Error(), true
}
if string(res) != cmd.result {
cmd.result = string(res)
changed = true
}
return string(res), changed
}
func updateScriptResult(comp *backend.Component) error {
cmd, ok := comp.Internal.(command)
if !ok {
return fmt.Errorf("invalid component internal: %#v", comp.Internal)
}
res, ok := cmd.callScript()
if ok {
comp.StateSink <- res
}
return nil
}
func init() {
backend.Register("script", LocalScriptBackend)
}
<file_sep>/*
Package suntracker contains backends which can track sun-rise and sun-set.
This information is useful to determine if it is dark outside or not.
*/
package suntracker
<file_sep>package backend
import (
"fmt"
"home/core/eventbus"
"sync"
"time"
)
import "testing"
import "github.com/stretchr/testify/assert"
func TestComponentDescribe(t *testing.T) {
c := &Component{
Name: "test_component",
backend: &Backend{
name: "test_backend",
},
Type: "test_type",
}
assert.EqualValues(t, map[string]string{
"type": "test_type",
"name": "test_component",
"urn": "test_backend.test_component",
}, c.Describe())
assert.Equal(t, "test_backend.test_component", c.String())
}
func TestComponentStateChangesAndPollingCalls(t *testing.T) {
b := &Backend{
name: "backend",
}
c := &Component{
StateSink: make(chan interface{}),
Name: "comp",
backend: b,
Type: "type",
Internal: false,
}
eventbus.EventBus.Start()
go c.handlePollingAndStateChanges()
// Test polling calls
c.Polling = func(c *Component) error {
c.Internal = true
return nil
}
old := PollingTimeout
PollingTimeout = 10 * time.Microsecond
time.Sleep(PollingTimeout * 5)
PollingTimeout = old
assert.Equal(t, true, c.Internal.(bool))
var wg sync.WaitGroup
wg.Add(1)
// Test state changes
sub := eventbus.EventBus.Subscribe(eventbus.STATE_CHANGED, func(event eventbus.Event) {
assert.EqualValues(t, eventbus.Event{
Origin: "backend.comp",
Topic: eventbus.STATE_CHANGED,
Data: "event-data",
}, event)
wg.Done()
})
sub.Once()
c.StateSink <- "event-data"
wg.Wait()
wg.Add(1)
// Test state changes
sub = eventbus.EventBus.Subscribe(eventbus.STATE_CHANGED, func(event eventbus.Event) {
assert.EqualValues(t, eventbus.Event{
Origin: "backend.comp",
Topic: eventbus.STATE_CHANGED,
Error: fmt.Errorf("event-data"),
}, event)
wg.Done()
})
sub.Once()
c.StateSink <- fmt.Errorf("event-data")
wg.Wait()
}
func TestComponentPolling(t *testing.T) {
b := &Backend{
name: "backend",
OnComponentError: func(c *Component, e error) error {
assert.Equal(t, "backend.comp", c.String())
assert.Equal(t, "example", e.Error())
c.Internal = true
return fmt.Errorf("error: %s", e)
},
}
c := &Component{
Name: "comp1",
backend: b,
Type: "type",
Internal: false,
}
c.update()
// Nothing should happen as Polling is nill
c.Name = "comp"
c.Polling = func(c *Component) error {
assert.Equal(t, "backend.comp", c.String())
return fmt.Errorf("example")
}
c.update()
// Now backend.OnComponentError should be called and set Internal to true
assert.Equal(t, true, c.Internal.(bool))
}
<file_sep>/** In this file, we create a React component which incorporates components provided by material-ui */
const React = require('react');
const ReactDOM = require('react-dom')
// Cards
const Card = require('material-ui/lib/card/card');
const CardHeader = require('material-ui/lib/card/card-header');
const CardActions = require('material-ui/lib/card/card-actions');
const CardExpandable = require('material-ui/lib/card/card-expandable');
const CardMedia = require('material-ui/lib/card/card-media');
const CardTitle = require('material-ui/lib/card/card-title');
const CardText = require('material-ui/lib/card/card-text');
const List = require('material-ui/lib/lists/list');
const ListItem = require('material-ui/lib/lists/list-item');
// Avatar
const Avatar = require('material-ui/lib/avatar');
// Theme management
const ThemeManager = require('material-ui/lib/styles/theme-manager'); const LightRawTheme = require('material-ui/lib/styles/raw-themes/light-raw-theme');
const Colors = require('material-ui/lib/styles/colors');
const DeviceTracker = React.createClass({
childContextTypes: {
muiTheme: React.PropTypes.object
},
getInitialState () {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
};
},
getChildContext() {
return {
muiTheme: this.state.muiTheme,
};
},
componentDidMount() {
this.update();
window.setInterval(this.update, 5000);
},
update() {
let sensor_urn = this.props.sensor.urn;
window.HomeAPI.Sensor(sensor_urn, function(data) {
if (!this.isMounted()) {
return;
}
this.setState({"devices": data});
}.bind(this));
},
componentWillMount() {
let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, {
accent1Color: Colors.deepOrange500
});
this.setState({muiTheme: newMuiTheme});
},
render() {
let sensor = this.props.sensor;
let backend = this.props.backend;
let devices = this.state.devices;
let avatars = [];
if (devices === undefined || devices === null) {
devices = [];
}
let count = devices.length;
let namesAtHome = "";
for (var i in devices) {
var device = devices[i];
if (device.name == "--") {
continue;
}
namesAtHome = namesAtHome + " | " + device.name;
var firstLetter = device.name[0];
avatars.push(
<ListItem
key={device.name}
leftAvatar={<Avatar style={{marginLeft: "10px"}}>{firstLetter}</Avatar>}
primaryText={device.name}
secondaryText={
<p>Current IP: <span style={{color: Colors.darkBlack}}>{device.ip}</span> ({device.mac})</p>
}
secondaryTextLines={1} />
)
}
let shouldExpand = (window.innerWidth > 1000);
return (
<Card initiallyExpanded={shouldExpand} style={{marginTop: "20px"}}>
<CardHeader
title={count + " devices are at home"}
subtitle={backend.name + ": " + namesAtHome}
avatar={<Avatar style={{'backgroundColor': '#e5e5e5'}} src='imgs/wireless.png'></Avatar>}
actAsExpander={true}
showExpandableButton={true}>
</CardHeader>
<CardText expandable={true}>
<List>
{avatars}
</List>
</CardText>
</Card>
);
},
});
module.exports = DeviceTracker;
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 eventbus
import (
"fmt"
)
// Event represents a message published on the eventbus and passed to all
// subscribers
type Event struct {
// Origin represents the name of the originating component
Origin string
// Error is set to the last component error if any
Error error
// Data contains additional information. The format is defined by the
// origin, as long as it can be marshalled as JSON
Data interface{}
// Topic represents a kind of routing key to identify subscribers
Topic string
}
// String returns the string representation of an event
func (e Event) String() string {
return fmt.Sprintf("origin=%s svc=%s data=%s", e.Origin, e.Topic, e.Data)
}
<file_sep>/** In this file, we create a React component which incorporates components provided by material-ui */
const React = require('react');
const ReactDOM = require('react-dom')
// Cards
const Card = require('material-ui/lib/card/card');
const CardHeader = require('material-ui/lib/card/card-header');
const CardActions = require('material-ui/lib/card/card-actions');
const CardExpandable = require('material-ui/lib/card/card-expandable');
const CardMedia = require('material-ui/lib/card/card-media');
const CardTitle = require('material-ui/lib/card/card-title');
const CardText = require('material-ui/lib/card/card-text');
const List = require('material-ui/lib/lists/list');
const ListItem = require('material-ui/lib/lists/list-item');
const ClearFix = require('material-ui/lib/clearfix');
// Avatar
const Avatar = require('material-ui/lib/avatar');
// Theme management
const ThemeManager = require('material-ui/lib/styles/theme-manager'); const LightRawTheme = require('material-ui/lib/styles/raw-themes/light-raw-theme');
const Colors = require('material-ui/lib/styles/colors');
function timeToGo(s) {
// Utility to add leading zero
function z(n) {
return (n < 10? '0' : '') + n;
}
// Convert string to date object
var d = new Date(s);
var diff = d - new Date();
// Allow for previous times
var sign = diff < 0? '-' : '';
diff = Math.abs(diff);
// Get time components
var hours = diff/3.6e6 | 0;
var mins = diff%3.6e6 / 6e4 | 0;
// Return formatted string
return sign + z(hours) + 'h ' + z(mins) + 'min';
}
const Weather = React.createClass({
childContextTypes: {
muiTheme: React.PropTypes.object
},
getInitialState () {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
};
},
getChildContext() {
return {
muiTheme: this.state.muiTheme,
};
},
componentDidMount() {
this.update();
window.setInterval(this.update, 5000);
},
update() {
let sensor_urn = this.props.sensor.urn;
window.HomeAPI.Sensor(sensor_urn, function(data) {
if (!this.isMounted()) {
return;
}
this.setState({"sensor" : data});
}.bind(this));
},
componentWillMount() {
let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, {
accent1Color: Colors.deepOrange500
});
this.setState({muiTheme: newMuiTheme});
},
render() {
let sensor = this.props.sensor;
let backend = this.props.backend;
let sensor_data = this.state.sensor;
if (sensor_data === undefined) {
return (
<Card initiallyExpanded={false} style={{marginTop: "20px"}}>
<CardHeader
title="Loading"
avatar={<Avatar src='imgs/weather.png'></Avatar>}>
</CardHeader>
</Card>
);
}
let temperature = sensor_data.main.temp;
let descr = sensor_data.weather[0].description;
let icon = "http://openweathermap.org/img/w/" + sensor_data.weather[0].icon + ".png";
let name = sensor_data.name;
let pressure = sensor_data.main.pressure;
let humidity = sensor_data.main.humidity;
let wind = sensor_data.wind.speed + "m/s at " + sensor_data.wind.deg + "°";
let unit = "K";
if (sensor_data.Unit == "metric") {
unit = "°C";
}
let shouldExpand = (window.innerWidth > 1000);
console.log(shouldExpand);
return (
<Card initiallyExpanded={shouldExpand} style={{marginTop: "20px"}}>
<CardHeader
title={descr + " at " + temperature + unit}
subtitle={"in " + name}
avatar={<Avatar src={icon}></Avatar>}
actAsExpander={true}
showExpandableButton={true}>
</CardHeader>
<CardText expandable={true}>
<List>
<ListItem
leftAvatar={<Avatar src={icon} style={{float: 'left'}} />}
primaryText={temperature + unit + " at " + descr} >
</ListItem>
</List>
<ClearFix style={{float: 'left', width: '49%'}}>
<List>
<ListItem
leftAvatar={<Avatar src='imgs/pressure.png'></Avatar>}
primaryText={<span><span style={{color:"gray"}}>Pressure: </span>{pressure}</span>} >
</ListItem>
<ListItem
leftAvatar={<Avatar src='imgs/humidity.png'></Avatar>}
primaryText={<span><span style={{color:"gray"}}>Humidity: </span>{humidity}</span>} >
</ListItem>
</List>
</ClearFix>
<ClearFix style={{float: 'right', width: '49%'}}>
<List>
<ListItem
leftAvatar={<Avatar src='imgs/wind.png'></Avatar>}
primaryText={<span><span style={{color:"gray"}}>Wind: </span>{wind}</span>} >
</ListItem>
</List>
</ClearFix>
</CardText>
</Card>
);
},
});
module.exports = Weather;
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 weather
import (
owm "github.com/nethack42/openweathermap"
"home/core"
"home/core/backend"
"home/utils"
"github.com/moraes/config"
"github.com/sirupsen/logrus"
"time"
)
type weatherTracker struct {
current *owm.CurrentWeatherData
lastCheck time.Time
lastJSON string
unit string
delay int
}
func updateWeather(component *backend.Component) error {
weather := component.Internal.(*weatherTracker)
nextCheck := weather.lastCheck.Add(time.Duration(weather.delay) * time.Minute)
if time.Now().Before(nextCheck) {
logrus.Debugf("Component: %s skipping update. Next check at %s", component.URN(), nextCheck.Local())
return nil
}
coord := owm.Coordinates{
Longitude: core.Global.Longitude,
Latitude: core.Global.Latitude,
}
if err := weather.current.CurrentByCoordinates(&coord); err != nil {
logrus.Warnf("Component: %s failed to update current weather conditions: %s", component.URN(), err)
return err
}
json, err := config.RenderJson(weather.current)
if err != nil {
logrus.Warnf("Component: %s failed to update current weather conditions: %s", component.URN(), err)
return err
}
if json != weather.lastJSON {
weather.lastJSON = json
component.StateSink <- weather.current
}
weather.lastCheck = time.Now()
return nil
}
func initOpenWeatherMapBackend(config map[string]interface{}, back *backend.Backend) error {
apiKey, ok := utils.GetString("api_key", config, "")
if !ok {
logrus.Warnf("Backend: %s configuration option missing: 'apiKey'", back.Name())
return nil // CHANGE
}
weather := weatherTracker{}
weather.unit, _ = utils.GetString("unit", config, "C")
language, _ := utils.GetString("language", config, "DE")
weather.delay, _ = utils.GetInt("delay", config, 60)
w, err := owm.NewCurrent(weather.unit, language, apiKey)
if err != nil {
logrus.Warnf("Backend: %s failed to update state", back.Name())
}
weather.current = w
back.RegisterComponent <- &backend.Component{
Internal: &weather,
Name: "weather",
Polling: updateWeather,
Type: backend.WeatherTracker,
StateSink: make(chan interface{}),
}
return nil
}
func init() {
backend.Register("weather", initOpenWeatherMapBackend)
}
<file_sep>package backend
import (
"sync"
"time"
"github.com/sirupsen/logrus"
)
var PollingTimeout = 5 * time.Second
type Backend struct {
// name of the backend, specified by `name` key
name string
// RegisterComponent channel can be used to regsiter new components
// within GoHome
RegisterComponent chan *Component
// used to identify the backend via `type` key
// should be set by the `Initialize` function
identifier string
// OnShutdown is called when the backend should perform a shutdown.
// This value can be nil if not required
OnShutdown func(*Backend) error
// OnComponentError is called when a registered component returns an error
// during startup, polling or via state changes.
// This value can be nil if not required
OnComponentError func(*Component, error) error
// Internal can be used by each backend to store backend-local information
Internal interface{}
lock sync.Mutex
components []*Component
componentsLock sync.Mutex
}
func (backend *Backend) Lock() {
backend.lock.Lock()
}
func (backend *Backend) Unlock() {
backend.lock.Unlock()
}
// Name returns the name of the backend as specified within the
// configuration
func (backend *Backend) Name() string {
return backend.name
}
func (backend *Backend) handleComponentError(c *Component, err error) error {
logrus.Warnf("Backend: %s raised an error: '%s'", c.URN(), err)
ret := err
backend.Lock()
defer backend.Unlock()
if backend.OnComponentError != nil {
ret = backend.OnComponentError(c, err)
}
return ret
}
func (backend *Backend) shutdown() error {
backend.Lock()
defer backend.Unlock()
if backend.OnShutdown != nil {
if err := backend.OnShutdown(backend); err != nil {
return err
}
}
return nil
}
func (backend *Backend) handleComponentRegistration() {
for {
select {
case c, ok := <-backend.RegisterComponent:
if !ok {
logrus.Warnf("Backend: %s closed component registration channel", backend.Name())
return
}
backend.registerComponent(c)
}
}
}
func (backend *Backend) registerComponent(c *Component) {
c.backend = backend
go c.handlePollingAndStateChanges()
backend.componentsLock.Lock()
defer backend.componentsLock.Unlock()
backend.components = append(backend.components, c)
logrus.Infof("Backend: %s registered component: %s", backend.Name(), c.URN())
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file mpdcept 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 mpdpress or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
package mediaplayer
import (
"fmt"
"home/core/backend"
"home/core/service"
"home/utils"
gompd "github.com/fhs/gompd/mpd"
"github.com/moraes/config"
"github.com/sirupsen/logrus"
)
/*
This backend let GoHome connect to an MPD server and retrieve information about
it's current status as well as perform some basic operations like play/pause.
In order to use this backend add something like the following to your configuration:
backends:
- type: mpd
endpoint: 192.168.0.10:6600
Data within state changes published on the eventbus will have the following
format:
{
"TOBEDONE": "TOBEDONE"
}
In addition, the following service calls are exported
<mpd-name>.play()
<mpd-nam>.pause()
*/
func MediaPlayerDaemonBackend(config map[string]interface{}, back *backend.Backend) error {
url, ok := utils.GetString("endpoint", config, "localhost:6600")
if !ok {
logrus.Warn("Backend: %s missing configuration option 'endpoint'. assuming 'localhost:6600'", back.Name())
}
intern := mpdClientComponent{
url: url,
connected: false,
}
comp := &backend.Component{
Name: "mpd",
Internal: &intern,
StateSink: make(chan interface{}),
Polling: updateMPD,
}
back.RegisterComponent <- comp
service.ServiceRegistry.Register(comp, "pause", "Pause MPD playback", intern.pause,
map[string]string{}, map[string]string{})
service.ServiceRegistry.Register(comp, "play", "Resume MPD playback", intern.play,
map[string]string{}, map[string]string{})
go (&intern).connect()
return nil
}
// mpdClientComponent represents a connection to a music player daemon (MPD)
// endpoint
type mpdClientComponent struct {
client *gompd.Client
lastJSONString string
url string
connected bool
}
func (mpd *mpdClientComponent) pause(param service.Arguments) interface{} {
if !mpd.connected {
return fmt.Errorf("mpd endpoint not connected")
}
mpd.client.Pause(true)
return nil
}
func (mpd *mpdClientComponent) play(param service.Arguments) interface{} {
if !mpd.connected {
return fmt.Errorf("mpd endpoint not connected")
}
mpd.client.Pause(false)
return nil
}
func updateMPD(comp *backend.Component) error {
mpd := comp.Internal.(*mpdClientComponent)
if !mpd.connected {
defer mpd.connect()
return nil
}
status, err := mpd.client.Status()
if err != nil {
mpd.connected = false
return err
}
song, err := mpd.client.CurrentSong()
if err != nil {
mpd.connected = false
return err
}
res := map[string]interface{}{
"song": song,
"status": status,
}
json, err := config.RenderJson(res)
if err != nil {
return err
}
if json != mpd.lastJSONString {
mpd.lastJSONString = json
comp.StateSink <- res
}
return nil
}
func (mpd *mpdClientComponent) connect() error {
var err error
mpd.client, err = gompd.Dial("tcp", mpd.url)
if err != nil {
mpd.connected = false
return err
}
mpd.connected = true
return nil
}
func init() {
backend.Register("mpd", MediaPlayerDaemonBackend)
}
<file_sep>package backend
const (
// Sensor should return {"state": "<some-thing>"}
Sensor = "sensor"
// Switch should return {"state": "<on/off>"}
Switch = "switch"
// DeviceTracker should return [ Device{Name: "", Mac: "", Known: <0/1>, Availbale: <0/1>}, ...]
DeviceTracker = "device_tracker"
// SunTracker should return { "state": "<below_horizon/above_horizon>", "next-rise": "...", "next-set": "..."}
SunTracker = "sun_tracker"
// WeatherTracker should return ... TODO
WeatherTracker = "weather_tracker"
)
<file_sep>package rules
import (
"home/core/eventbus"
"github.com/moraes/config"
"github.com/robertkrimen/otto"
"github.com/sirupsen/logrus"
)
type JsRule struct {
Name string
VM *otto.Otto
result string
}
func apiRule(call otto.FunctionCall) otto.Value {
obj := call.Argument(0).Object()
nameValue, err := obj.Get("name")
if err != nil {
logrus.Errorf("Error: %v", err)
return otto.Value{}
}
name := nameValue.String()
rule := &JsRule{
Name: name,
VM: call.Otto,
}
obj.Call("init")
call.Otto.Set(rule.Name, obj)
logrus.Infof("Registered javascript: %#v", rule)
eventbus.EventBus.Subscribe(eventbus.STATE_CHANGED, func(event eventbus.Event) {
data, _ := config.RenderJson(event)
o, err := call.Otto.Object(rule.Name)
if err != nil {
logrus.Warnf("JavaScript-Error: %s: %s error=%s", rule.Name, o, err)
}
val, err := call.Otto.Object("(" + data + ")")
if err != nil {
logrus.Warnf("JavaScript-Error: %s: %s error=%s", rule.Name, val, err)
}
resultValue, err := o.Call("onChange", val)
if err != nil {
logrus.Warnf("JavaScript-Error: %s: %s error=%s", rule.Name, resultValue, err)
}
result := resultValue.String()
if rule.result != result {
logrus.Infof("Sending update %s -> %s (old: %s)", rule.Name, result, rule.result)
event := eventbus.Event{
Topic: eventbus.STATE_CHANGED,
Origin: "rule." + rule.Name,
Error: nil,
Data: result,
}
eventbus.EventBus.Publish(event)
rule.result = result
}
})
return otto.Value{}
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 core
import (
"github.com/moraes/config"
"github.com/sirupsen/logrus"
"home/core/eventbus"
"home/utils"
)
type Plugin interface {
Name() string
Start(map[string]interface{}) error
Stop()
}
type pluginManager struct {
known_plugins map[string]Plugin
plugins map[string]Plugin
}
func (mgr *pluginManager) Register(plugin Plugin) {
mgr.known_plugins[plugin.Name()] = plugin
logrus.Infof("Plugins: registered plugin: '%s'", plugin.Name())
}
func (mgr *pluginManager) Start(options *config.Config) error {
plugins, err := options.List("plugins")
if err != nil {
logrus.Warnf("Plugins: No configuration section found")
return err
}
for _, plug := range plugins {
plugin_conf := plug.(map[string]interface{})
pluginType, ok := utils.GetString("type", plugin_conf, "")
if !ok {
logrus.Warnf("Plugins: failed to get type for '%s'", plugin_conf)
continue
}
plugin := mgr.known_plugins[pluginType]
if plugin != nil {
err = plugin.Start(plugin_conf)
if err != nil {
logrus.Warnf("Plugins: failed to start plugin: '%s' error: '%s'", plugin.Name(), err)
continue
}
mgr.plugins[plugin.Name()] = plugin
logrus.Infof("Plugins: plugin started successfully: '%s'", plugin.Name())
} else {
logrus.Warnf("Plugins: plugin does not exists: '%s'", pluginType)
}
}
eventbus.EventBus.Subscribe(eventbus.HOME_SHUTDOWN, mgr.Stop)
return nil
}
func (mgr *pluginManager) Stop(event eventbus.Event) {
for name, plugin := range mgr.plugins {
logrus.Infof("Plugins: stopping plugin: '%s'", name)
plugin.Stop()
}
}
var PluginManager *pluginManager
func init() {
PluginManager = &pluginManager{
known_plugins: make(map[string]Plugin),
plugins: make(map[string]Plugin),
}
}
<file_sep>package service
// Arguments represents parameters passed to a service call
type Arguments struct {
arguments map[string]interface{}
}
// Value represents the actual parameter returned when parsing arguments
type Value struct {
value interface{}
ok bool
}
// Arg returns the parameter `Value` with name 'name'
func (arg Arguments) Arg(name string) Value {
if val, ok := arg.arguments[name]; ok {
return Value{
value: val,
ok: true,
}
}
return Value{
value: nil,
ok: false,
}
}
// String returns Value as string
func (v Value) String() (str string, ok bool) {
if !v.ok {
return "", false
}
str, ok = v.value.(string)
return
}
// DefaultString returns Value as string or a default if not set
func (v Value) DefaultString(def string) string {
value, ok := v.String()
if !ok {
return def
}
return value
}
// Int returns Value as an integer
func (v Value) Int() (i int, ok bool) {
if !v.ok {
return 0, false
}
i, ok = v.value.(int)
return
}
// DefaultInt returns Value as an integer or a default value on error
func (v Value) DefaultInt(def int) int {
value, ok := v.Int()
if !ok {
return def
}
return value
}
// Float64 returns Value as float64
func (v Value) Float64() (i float64, ok bool) {
if !v.ok {
return 0, false
}
i, ok = v.value.(float64)
return
}
// DefaultFloat64 returns Value as float64 or a default value on error
func (v Value) DefaultFloat64(def float64) float64 {
value, ok := v.Float64()
if !ok {
return def
}
return value
}
// List returns Value as a list
func (v Value) List() (l []interface{}, ok bool) {
if !v.ok {
return nil, false
}
l, ok = v.value.([]interface{})
return
}
// DefaultList returns Value as list or a default value on error
func (v Value) DefaultList(def []interface{}) []interface{} {
value, ok := v.List()
if !ok {
return def
}
return value
}
// Map returns Value as a map
func (v Value) Map() (m map[interface{}]interface{}, ok bool) {
if !v.ok {
return nil, false
}
m, ok = v.value.(map[interface{}]interface{})
return
}
// DefaultMap returns value as a map or a default value on error
func (v Value) DefaultMap(def map[interface{}]interface{}) map[interface{}]interface{} {
value, ok := v.Map()
if !ok {
return def
}
return value
}
// Interface returns Value as an interface
func (v Value) Interface() (interface{}, bool) {
if !v.ok {
return nil, false
}
return v.value, true
}
<file_sep>package eventbus
import "testing"
import "github.com/stretchr/testify/assert"
func TestSubscriberConstraint(t *testing.T) {
sub := SubscriberEntry{}
sub.Once()
assert.EqualValues(t, sub.constraint, CONSTRAINT_ONCE)
sub.Delete()
assert.EqualValues(t, sub.constraint, CONSTRAINT_DELETED)
}
func TestEventString(t *testing.T) {
assert.Equal(t, "origin=Origin svc=Topic data=Data", Event{
Origin: "Origin",
Topic: "Topic",
Data: "Data",
}.String())
}
func TestEventBus(t *testing.T) {
bus := newEventBus()
assert.NotNil(t, bus)
bus.Start()
// Test subsubscription
original := Event{
Origin: "1",
Topic: "test",
Data: "some value",
}
sub := bus.Subscribe("test", func(event Event) {
assert.EqualValues(t, original, event)
// Now set the the subscription to once
})
sub2 := bus.Subscribe("constraint", func(event Event) {
assert.Equal(t, "1", event.Origin)
bus.Publish(Event{Topic: HOME_SHUTDOWN})
})
sub2.Once()
assert.NotNil(t, sub)
bus.Publish(original)
bus.Publish(Event{Topic: "constraint", Origin: "1"})
bus.Publish(Event{Topic: "constraint", Origin: "2"})
bus.Wait()
}
<file_sep>/** In this file, we create a React component which incorporates components provided by material-ui */
const React = require('react');
const ReactDOM = require('react-dom');
const Inspector = require('react-json-inspector');
// Theme management
const ThemeManager = require('material-ui/lib/styles/theme-manager'); const LightRawTheme = require('material-ui/lib/styles/raw-themes/light-raw-theme');
const Colors = require('material-ui/lib/styles/colors');
const DropDownMenu = require('material-ui/lib/drop-down-menu');
const Tabs = require('material-ui/lib/tabs/tabs');
const Tab = require('material-ui/lib/tabs/tab');
const MediaQuery = require('react-responsive');
const SensorInspector = React.createClass({
childContextTypes: {
muiTheme: React.PropTypes.object
},
getInitialState () {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
activeView: "Raw",
};
},
getChildContext() {
return {
muiTheme: this.state.muiTheme,
};
},
componentDidMount() {
window.HomeAPI.getSensors(function(data) {
if (!this.isMounted()) {
return;
}
this.setState({"backends": data});
}.bind(this));
},
componentWillMount() {
let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, {
accent1Color: Colors.deepOrange500
});
this.setState({muiTheme: newMuiTheme});
},
_onTabChange(value, e, tab) {
let name = tab.props.label;
this.setState({"activeView": name});
},
_onSensorChange(event, selected, menuItem) {
window.HomeAPI.Sensor(menuItem.payload, function(data) {
if (!this.isMounted()) {
return;
}
this.setState({"data": data});
}.bind(this));
},
render() {
let menus = [
{ payload: 'none', text: 'Select sensor' },
];
var backends = this.state.backends;
if (backends === undefined) {
backends = {};
}
for(var name in backends) {
let backend = backends[name];
let components = backend.components;
for (var i in components) {
let c = components[i];
menus.push({payload: c.urn, text: c.urn});
}
}
let component;
if (this.state.activeView == "Raw") {
let data = this.state.data;
if (data === undefined) {
data = {};
}
component = <Inspector data={data} isExpanded={function(k, i){ return true; }}/>;
}
return (
<div style={{marginTop: "10px"}}>
<MediaQuery minDeviceWidth={1224} values={{deviceWidth: 1600}}>
<DropDownMenu menuItems={menus} style={{left: 0, position: 'absolute'}}
labelStyle={{color: 'white'}}
onChange={this._onSensorChange}/>
</MediaQuery>
<MediaQuery maxDeviceWidth={1224}>
<DropDownMenu menuItems={menus} width="100%"
style={{width: "100%"}}
onChange={this._onSensorChange}/>
</MediaQuery>
<Tabs onChange={this._onTabChange} >
<Tab label="Raw" style={{backgroundColor: 'gray'}}></Tab>
<Tab label="Widget" style={{backgroundColor: 'gray'}}></Tab>
</Tabs>
<br />
{component}
</div>
);
},
});
module.exports = SensorInspector;
<file_sep>const jQuery = require('jquery')
class HomeAPI {
constructor(url) {
this.url = url;
this.token = "";
}
login(user, password, success, error) {
console.log("Login");
jQuery.ajax(
{
type: "POST",
url: this.apiURL() + "login",
contentType: "application/json",
data: JSON.stringify({"username": user, "password": <PASSWORD>}),
success: function(data) {
window.HomeAPI.token = data.token
success(data);
},
error: error,
}
)
}
GET(url, success, error) {
jQuery.ajax(
{
type: "GET",
beforeSend: function(r) {
r.setRequestHeader("Authorization", "Bearer " + window.HomeAPI.token)
},
url: url,
success: success,
error: error,
}
)
}
POST(url, data, success, error) {
jQuery.ajax(
{
type: "POST",
beforeSend: function(r) {
r.setRequestHeader("Authorization", "Bearer " + window.HomeAPI.token)
},
url: url,
data: JSON.stringify(data),
contentType: "application/json",
success: success,
error: error,
}
)
}
ping(callback) {
jQuery.getJSON(this.url, callback);
}
apiURL() {
return this.url + "v1/";
}
sensorURL() {
return this.apiURL() + "sensors";
}
serviceURL() {
return this.apiURL() + "services";
}
getSensors(callback) {
this.GET(this.sensorURL(), callback);
}
getServices(callback) {
this.GET(this.serviceURL(), callback);
}
Sensor(sensor_name, callback) {
this.GET(this.sensorURL() + "/" + sensor_name, callback);
}
Service(service_name, data, success, error) {
this.POST(this.serviceURL() + "/" + service_name, data, success, error);
}
}
module.exports = HomeAPI;
<file_sep>/*
Package mediaplyer contains various backends for querying and controlling
media players like MPD, PlexMediaServer, or UPNP clients.
*/
package mediaplayer
<file_sep>/*
Package notify contains backends which can be used to send notifications
about certain events within GoHome. Please refer the each backend documentation
about how to integrate them within your GoHome domain.
*/
package notify
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 connector
import "fmt"
import "sync"
import "net/http"
import (
"home/core/backend"
"home/core/service"
)
import "home/utils"
import "github.com/sirupsen/logrus"
import "github.com/gorilla/websocket"
/*
Backend providing a JSON based component connector via Websockets.
Configuration
In order to use this websocket based connector add something like the following
to your configuration file:
backends:
- type: websocket
listen: httpapi
Description
The `listen` parameter may specifiy an endpoint the websocket server should
be bound to (e.g. localhost:8080, 0.0.0.0:6600, :9000). As a special case,
"httpapi" can be specified. If so, the websocket connector backend attaches it
self the the HTTP API plugin and will therefore share it's HTTP server. In the
latter case the access URI will be "/devices" instead of "/".
API Description
First a Websocket connection must be established. During this HTTP request,
the device name and type must be provided. Consider the following Websocket URL:
ws://example.com/device?name=<YourDeviceName>&type=<YourDeviceType>
If this module is not used in conjunction with the HTTP API plugin the request
URL should look like:
ws://example.com/?name=<YourDeviceName>&type=<YourDeviceType>
If both parameters are provided a websocket connection can be initialized.
Now the client can start providing data by sending JSON messages following this
format:
{
"topic": "state_changed",
"state": <YourStateOfWhatsOEver>
}
Everything provided in `state` will be published on the internal eventbus and
thus be available for all subscribers.
Note that a WebSocket component can only send state updates and register service
calles. It is prohibited to execute other services or send other topics then
"state_changed" and "register_service".
Invalid messages will be logged and the respective connection will be closed.
In order to register new service calles within GoHome a Websocket component could
send a service registration request with the following format:
{
"topic": "register_service",
"name": "<NameOfYourService>",
"required": {
"param1": "This is the first and only parameter required"
},
"optional" {
"param2": "This is an optional parameter which defaults to: some-value"
}
}
The `name`, `required` and `optional` fields are required to be set during
service registration. However, `required` and `optional` may be an empty
map/object.
Whenever a service should be executed GoHome send the following request via the
Websocket connection:
{
"topic": "service_call",
"method": "<NameOfYourService>",
"params": [<ListOfParameters]
}
BUG: Currently it is NOT possible for Websocket components to return a response
to the caller! All service call will immediately return nil.
*/
func WebsocketConnectorBackend(config map[string]interface{}, back *backend.Backend) error {
logrus.Infof("Started backend %s with name %s", config["type"].(string), back.Name())
listen, _ := utils.GetString("listen", config, "httpapi")
back.OnShutdown = shutdownWebsockets
back.Internal = &websocketServer{
clients: make(map[string]peer),
name: back.Name(),
back: back,
}
if listen == "httpapi" {
logrus.Infof("Backend: %s: attaching to default HTTP server (httpapi) on URI /device", back.Name())
http.Handle("/device", back.Internal.(*websocketServer))
} else {
logrus.Infof("Backend: %s: listening on %s", back.Name(), listen)
go http.ListenAndServe(listen, back.Internal.(*websocketServer))
}
return nil
}
func shutdownWebsockets(back *backend.Backend) error {
logrus.Infof("Shutting down backend %s", back.Name())
// Currently we cannot gracefully shutdown the HTTP server ...
return nil
}
type serviceCall struct {
name string
peer peer
}
func (s *serviceCall) call(params service.Arguments) interface{} {
s.peer.conn.WriteJSON(map[string]interface{}{
"topic": "service_call",
"method": s.name,
"params": params,
})
logrus.Infof("Component: %s sent RPC request for: %s", s.peer.component.URN(), s.name)
return nil
}
type peer struct {
component *backend.Component
remote string
conn *websocket.Conn
isRunning sync.WaitGroup
services []serviceCall
}
func (p peer) handleServiceRegistration(msg map[string]interface{}) error {
name, ok := msg["name"].(string)
if !ok {
return fmt.Errorf("name not defined")
}
requiredI, ok := msg["required"].(map[string]interface{})
if !ok {
return fmt.Errorf("required parameter field is invalid: %#v", msg["required"])
}
optionalI, ok := msg["optional"].(map[string]interface{})
if !ok {
return fmt.Errorf("optional parameter field is invalid: %#v", msg["optional"])
}
required := make(map[string]string)
for k, v := range requiredI {
desc, ok := v.(string)
if !ok {
return fmt.Errorf("invalid description of parameter: %s", k)
}
required[k] = desc
}
optional := make(map[string]string)
for k, v := range optionalI {
desc, ok := v.(string)
if !ok {
return fmt.Errorf("invalid description of parameter: %s", k)
}
optional[k] = desc
}
logrus.Infof("Component: %s tries to register a service call: name=%s required=%s optional=%s", p.component.URN(), name, required, optional)
svc := serviceCall{
name: name,
peer: p,
}
service.ServiceRegistry.Register(p.component, name, "", svc.call, required, optional)
p.services = append(p.services, svc)
return nil
}
func (p peer) handleIncoming() {
defer p.isRunning.Done()
for {
var msg map[string]interface{}
err := p.conn.ReadJSON(&msg)
if err != nil {
logrus.Warnf("%s|%s (%s) disconnected: %s", p.remote, p.component.Name, p.component.Type, err)
p.conn.Close()
p.component.StateSink <- fmt.Errorf("Connection lost")
return
}
logrus.Infof("%s|%s (%s) sent: %s", p.remote, p.component.Name, p.component.Type, msg)
switch msg["topic"] {
case "state_changed":
p.component.StateSink <- msg["state"]
case "register_service":
err = p.handleServiceRegistration(msg)
if err != nil {
logrus.Warnf("Component: %s failed to register a service call: %s", p.component.URN(), err)
}
default:
logrus.Warnf("%s|%s (%s) sent bogus topic: %s", p.remote, p.component.Name, p.component.Type, msg["topic"])
}
}
}
type websocketServer struct {
clients map[string]peer
name string
back *backend.Backend
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
func (ws *websocketServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
typ := r.URL.Query().Get("type")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logrus.Warnf("Backend: %s: failed to upgrade connection: %s", ws.name, err)
return
}
if name == "" {
conn.WriteJSON(map[string]string{"error": "parameter name is required"})
conn.Close()
return
}
if typ == "" {
conn.WriteJSON(map[string]string{"error": "parameter type is required"})
conn.Close()
return
}
logrus.Infof("Backend: %s: %s connected successfully as %s (type=%s)", ws.name, r.RemoteAddr, name, typ)
comp := &backend.Component{
StateSink: make(chan interface{}),
Name: name,
Type: typ,
}
p := peer{
remote: r.RemoteAddr,
conn: conn,
component: comp,
}
ws.clients[p.component.Name] = p
comp.Internal = p
p.isRunning.Add(1)
go p.handleIncoming()
ws.back.RegisterComponent <- comp
}
func init() {
backend.Register("websocket", WebsocketConnectorBackend)
}
<file_sep>/*
Package external contains backends which executes external programs
(local or remote).
*/
package external
<file_sep>var Rule = {
name: "StartStopMPD",
origin: "",
init: function() {
this.mpd_playing = false;
this.stopped_mpd = false;
},
update: function() {
},
onEvent: function(event) {
if (event.Origin != "mpd.mpd" && event.Origin != "rule.AwayMode") {
return;
}
if (event.Origin == "mpd.mpd") {
this.mpd_playing = (event.Data.status.state != "pause");
}
if (event.Origin == "rule.AwayMode" && event.Data == "away") {
this.stopped_mpd = this.mpd_playing;
if (this.mpd_playing) {
Service("mpd.pause", {});
}
}
if (event.Origin == "rule.AwayMode" && event.Data == "home" && this.stopped_mpd) {
// Someone arrived at home and we stopped MPD before. so start playback again
this.stopped_mpd = false
Service("mpd.play", {});
}
Log(JSON.stringify(event));
},
};
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 core
import (
"github.com/sirupsen/logrus"
"fmt"
"home/core/eventbus"
"sync"
)
type stateTracker struct {
lock sync.Mutex
states map[string]interface{}
}
func (state *stateTracker) Update(event eventbus.Event) {
state.lock.Lock()
defer state.lock.Unlock()
if event.Error != nil {
event.Data = fmt.Sprintf("%s", event.Error)
}
logrus.Infof("States: updating state for component '%s'", event.Origin)
state.states[event.Origin] = event.Data
}
func (state *stateTracker) Start() {
eventbus.EventBus.Subscribe(eventbus.STATE_CHANGED, state.Update)
}
func (state *stateTracker) Get(name string) interface{} {
state.lock.Lock()
defer state.lock.Unlock()
return state.states[name]
}
var StateTracker *stateTracker
func init() {
StateTracker = &stateTracker{
states: make(map[string]interface{}),
}
}
<file_sep>/*
Package weather contains backens capable to tracking weather conditions
and provide forcast information.
*/
package weather
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 plugins
import (
"home/core"
"home/core/eventbus"
"home/plugins/rules"
"github.com/sirupsen/logrus"
)
type RuleHandler struct {
vms []*rules.JavascriptVM
}
func (handler *RuleHandler) Name() string {
return "rules"
}
func (handler *RuleHandler) Start(options map[string]interface{}) error {
var list []interface{}
switch a := options["files"].(type) {
case []interface{}:
list = a
default:
logrus.Warnf("[Plugin/rules] invalid configuration: %#v", options)
return nil // CHANGE ME
}
for _, file := range list {
vm := &rules.JavascriptVM{
Name: file.(string),
File: file.(string),
}
_ = vm.PrepareVM()
handler.vms = append(handler.vms, vm)
}
eventbus.EventBus.Subscribe(eventbus.HOME_STARTED, func(event eventbus.Event) {
for _, vm := range handler.vms {
vm.LoadContentFromFile(vm.File)
logrus.Infof("[Plugins/rules] started javascript VM: %s", vm.File)
}
})
return nil
}
func (handler *RuleHandler) Stop() {
}
func init() {
core.PluginManager.Register(&RuleHandler{})
}
<file_sep>Log("test log");
var Rule = {
name: "Example Rule",
init: function() {
},
update: function(any) {
if (this.count === undefined) {
this.count = 0;
}
this.count = this.count + 1;
//Log("called: " + this.count);
},
onEvent: function(event) {
//Log("Event " + event.Origin + " " + JSON.stringify(event));
}
}
<file_sep>/*
Devicetracker components are used to track devices nearby your GoHome
domain. This might be achieved in various ways (connected to a Wireless Router,
Bluetooth devices nearby, aso...).
*/
package devicetracker
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 eventbus
const (
// STATE_CHANGED describes an event type topic which is fired whenever a
// component publishes a state change
STATE_CHANGED = "status_changed"
// HOME_STARTED event is fired when GoHome started up successfully
HOME_STARTED = "home_started"
// HOME_SHUTDOWN event is fired when GoHome should shutdown. Components
// which need to perform clean up actions should subscribe for HOME_SHUTDOWN
HOME_SHUTDOWN = "home_shutdown"
// SERVICE_CALL represents a service call event. The service registry will
// then execute the call
SERVICE_CALL = "service_call"
// CONSTRAINT_ONCE is used to limit a eventbus subscription to be notified
// only once
CONSTRAINT_ONCE = 1
// CONSTRAINT_DELETED is used when a subscription should not be notified
// again and should be deleted immediately
CONSTRAINT_DELETED = 2
)
<file_sep>/*
Example package contains various examples on how backends,
components and service might be implemented.
*/
package example
<file_sep>package backend
import (
"home/core/eventbus"
"home/utils"
"time"
"github.com/sirupsen/logrus"
)
import "fmt"
// Component represents an internal sensor which pusblishes state changes to a
// self defined channel. See below for further information about components
type Component struct {
// StateSink is used to publish state changes on the event bus
StateSink chan interface{}
// Name is the name of the component
Name string
// Polling will be called on a regular interval to update the state of the
// component. If polling is not required this value should be nil
Polling func(*Component) error
// Internal can be used by components to keep track of changes and other stuff
Internal interface{}
backend *Backend
// Type is used to describe the type of the component. This is later used within
// the user interface to determine how to display component data
// see component_types.go for a list of pre-defined component type values
Type string
updateLock utils.TryableLock
}
// Init initalizes a new component (all required values for operation)
func (component *Component) Init(name string, createStateChannel bool) {
component.Name = name
if createStateChannel {
component.StateSink = make(chan interface{})
}
}
// Describe returns a map containing basic information about the component
// Expect name, type and urn keys to be set
func (component *Component) Describe() map[string]string {
result := make(map[string]string)
result["type"] = component.Type
result["name"] = component.Name
result["urn"] = component.URN()
return result
}
// URN return a unique resource name used
func (component *Component) URN() string {
if component.backend == nil {
return component.Name
}
return fmt.Sprintf("%s.%s", component.backend.Name(), component.Name)
}
// String is a wrapper about URN()
func (component *Component) String() string {
return component.URN()
}
func (component *Component) update() {
if !component.updateLock.Lock() {
logrus.Infof("Component: %s update still running. skipping schedule", component.URN())
return
}
defer component.updateLock.Unlock()
if component.Polling != nil {
logrus.Debugf("Component: %s polling for updates", component.URN())
err := component.Polling(component)
if err != nil {
component.backend.handleComponentError(component, err)
}
}
}
func (component *Component) handlePollingAndStateChanges() {
backend := component.backend
go component.update()
if component.StateSink == nil {
logrus.Warnf("Component: %s does not provide a state sink channel", component.URN())
return
}
for {
select {
case state, ok := <-component.StateSink:
if !ok {
logrus.Warnf("Component: %s closed state sink channel", component.URN())
return
}
switch c := state.(type) {
case error:
logrus.Warnf("Component: %s published error '%s'", component.URN(), c)
backend.handleComponentError(component, c)
event := eventbus.Event{
Topic: eventbus.STATE_CHANGED,
Origin: component.URN(),
Error: c,
Data: nil,
}
eventbus.EventBus.Publish(event)
default:
logrus.Debugf("Component: %s published state '%s'", component.URN(), state)
event := eventbus.Event{
Topic: eventbus.STATE_CHANGED,
Origin: component.URN(),
Error: nil,
Data: c,
}
eventbus.EventBus.Publish(event)
}
case <-time.After(PollingTimeout):
logrus.Debugf("Component: %s scheduling update", component.URN())
go component.update()
}
}
}
<file_sep>/** In this file, we create a React component which incorporates components provided by material-ui */
const React = require('react');
const ReactDOM = require('react-dom');
const jQuery = require('jquery');
// Standard inputs
const RaisedButton = require('material-ui/lib/raised-button');
// Dialog
const Dialog = require('material-ui/lib/dialog');
// Grids
const GridList = require('material-ui/lib/grid-list/grid-list');
const GridTile = require('material-ui/lib/grid-list/grid-tile');
const Toggle = require('material-ui/lib/toggle');
// Theme management
const ThemeManager = require('material-ui/lib/styles/theme-manager'); const LightRawTheme = require('material-ui/lib/styles/raw-themes/light-raw-theme');
const Colors = require('material-ui/lib/styles/colors');
// Cards
const Card = require('material-ui/lib/card/card');
const CardHeader = require('material-ui/lib/card/card-header');
const CardActions = require('material-ui/lib/card/card-actions');
const CardExpandable = require('material-ui/lib/card/card-expandable');
const CardMedia = require('material-ui/lib/card/card-media');
const CardTitle = require('material-ui/lib/card/card-title');
const CardText = require('material-ui/lib/card/card-text');
const ClearFix = require('material-ui/lib/clearfix');
// Avatar
const Avatar = require('material-ui/lib/avatar');
// components
const SunTracker = require('./sun_tracker.jsx');
const Weather = require('./weather.jsx');
const DeviceTracker = require('./device_tracker.jsx');
var MediaQuery = require('react-responsive');
const Dashboard = React.createClass({
childContextTypes: {
muiTheme: React.PropTypes.object
},
getInitialState () {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
};
},
getChildContext() {
return {
muiTheme: this.state.muiTheme,
};
},
componentWillMount() {
let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, {
accent1Color: Colors.deepOrange500
});
this.setState({muiTheme: newMuiTheme});
},
componentDidMount() {
window.HomeAPI.getSensors(function(data) {
if (!this.isMounted()) {
return;
}
this.setState({"backends": data});
}.bind(this));
},
render() {
console.log("Dashboard: rendering ....");
let containerStyle = {
textAlign: 'center',
};
let menuStyle = {
textAlign: 'left'
}
let standardActions = [
{ text: 'Okay' }
];
var widgets = [];
var backends = this.state.backends;
if (backends === undefined) {
backends = {};
}
for(var name in backends) {
let backend = backends[name];
let components = backend.components;
for (var i in components) {
let c = components[i];
if (c.type == "sun_tracker") {
widgets.push(<SunTracker key={c.urn} backend={backend} sensor={c} />);
} else
if (c.type == "weather_tracker") {
widgets.push(<Weather key={c.urn} backend={backend} sensor={c} />);
}
if (c.type == "device_tracker") {
widgets.push(<DeviceTracker key={c.urn} backend={backend} sensor={c} />);
}
}
}
let widgets_left = [];
let widgets_right = [];
var i;
for (i = 0; i < widgets.length/2; i++) {
let w = widgets[i];
widgets_left.push(w);
}
for(; i < widgets.length; i++) {
let w = widgets[i];
widgets_right.push(w);
}
return (
<div>
<MediaQuery minWidth={1224}>
<div style={{marginLeft: '10%', width: '80%'}}>
<ClearFix style={{float: 'left', width: "45%", marginRight: "5%"}}>
{widgets_left}
</ClearFix>
<ClearFix style={{float: 'left', width: "45%"}}>
{widgets_right}
</ClearFix>
</div>
</MediaQuery>
<MediaQuery maxWidth={1224}>
<div>
{widgets}
</div>
</MediaQuery>
</div>
)
/* return (
<div>
<MediaQuery minDeviceWidth={1224} values={{deviceWidth: 1600}}>
<GridList style={{maxWidth: "80%", marginLeft: "auto", marginRight: "auto", paddingTop: "20px"}}>
<Card initiallyExpanded={true}>
<CardHeader
title="Lights"
subtitle="Vienna"
avatar={<Avatar style={{color:'white', backgroundColor: 'orange'}}>L</Avatar>}
actAsExpander={true}
showExpandableButton={true}>
</CardHeader>
<CardActions style={{textAlign: 'center'}} expandable={true} initiallyExpanded={false} >
<RaisedButton label="On"/>
<RaisedButton label="Off"/>
</CardActions>
<CardText expandable={true}>
<Toggle label="Livingroom"/>
</CardText>
</Card>
<Card initiallyExpanded={true}>
<CardHeader
title="Devices"
subtitle="Power Switch"
avatar={<Avatar style={{color:'white', backgroundColor: "blue"}}>S</Avatar>}
actAsExpander={true}
showExpandableButton={true}>
</CardHeader>
<CardActions style={{textAlign: 'center'}} expandable={true} initiallyExpanded={false} >
<RaisedButton label="On"/>
<RaisedButton label="Off"/>
</CardActions>
<CardText expandable={true}>
<Toggle style={{padding: 10}} label={<b>Coffee-Maker</b>}/>
<hr />
<Toggle style={{padding: 10}} label={<b>PC: Centauri</b>}/>
<Toggle style={{padding: 10}} label={<b>PC: Clara</b>}/>
<Toggle style={{padding: 10}} label={<b>PC: Home</b>}/>
</CardText>
</Card>
</GridList>
</MediaQuery>
<MediaQuery maxDeviceWidth={1224}>
<Card initiallyExpanded={true}>
<CardHeader
title="Lights"
subtitle="Vienna"
avatar={<Avatar style={{color:'white', backgroundColor: 'orange'}}>L</Avatar>}
actAsExpander={true}
showExpandableButton={true}>
</CardHeader>
<CardActions style={{textAlign: 'center'}} expandable={true} initiallyExpanded={false} >
<RaisedButton label="On"/>
<RaisedButton label="Off"/>
</CardActions>
<CardText expandable={true}>
<Toggle label="Livingroom"/>
</CardText>
</Card>
<Card initiallyExpanded={true}>
<CardHeader
title="Devices"
subtitle="Power Switch"
avatar={<Avatar style={{color:'white', backgroundColor: "blue"}}>S</Avatar>}
actAsExpander={true}
showExpandableButton={true}>
</CardHeader>
<CardActions style={{textAlign: 'center'}} expandable={true} initiallyExpanded={false} >
<RaisedButton label="On"/>
<RaisedButton label="Off"/>
</CardActions>
<CardText expandable={true}>
<Toggle style={{padding: 10}} label={<b>Coffee-Maker</b>}/>
<hr />
<Toggle style={{padding: 10}} label={<b>PC: Centauri</b>}/>
<Toggle style={{padding: 10}} label={<b>PC: Clara</b>}/>
<Toggle style={{padding: 10}} label={<b>PC: Home</b>}/>
</CardText>
</Card>
</MediaQuery>
</div>
);*/
},
});
var A = React.createClass({
render: function(){
return (
<div>
<div>Device Test!</div>
<MediaQuery minDeviceWidth={1224} values={{deviceWidth: 1600}}>
<div>You are a desktop or laptop</div>
<MediaQuery minDeviceWidth={1824}>
<div>You also have a huge screen</div>
</MediaQuery>
<MediaQuery maxWidth={1224}>
<div>You are sized like a tablet or mobile phone though</div>
</MediaQuery>
</MediaQuery>
<MediaQuery maxDeviceWidth={1224}>
<div>You are a tablet or mobile phone</div>
</MediaQuery>
<MediaQuery orientation='portrait'>
<div>You are portrait</div>
</MediaQuery>
<MediaQuery orientation='landscape'>
<div>You are landscape</div>
</MediaQuery>
<MediaQuery minResolution='2dppx'>
<div>You are retina</div>
</MediaQuery>
</div>
);
}
});
module.exports = Dashboard;
<file_sep>package backend
import (
"fmt"
"home/core/eventbus"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBackend(t *testing.T) {
eventbus.EventBus.Start()
var wg sync.WaitGroup
shutdown_complete := false
var valid_event eventbus.Event
var component_error error
b := &Backend{
name: "test",
identifier: "test",
RegisterComponent: make(chan *Component),
OnShutdown: func(b *Backend) error {
shutdown_complete = true
return fmt.Errorf("shutdown error")
},
OnComponentError: func(c *Component, e error) error {
component_error = e
return e
},
}
wg.Add(1)
go b.handleComponentRegistration()
c := &Component{
StateSink: make(chan interface{}),
Name: "comp",
}
eventbus.EventBus.Subscribe(eventbus.STATE_CHANGED, func(e eventbus.Event) {
if e.Error != nil || e.Origin != "test.comp" {
return
}
defer wg.Done()
valid_event = e
})
b.RegisterComponent <- c
c.StateSink <- fmt.Errorf("example error")
c.StateSink <- "some data"
wg.Wait()
assert.EqualValues(t, fmt.Errorf("example error"), component_error)
assert.Equal(t, "some data", valid_event.Data)
close(b.RegisterComponent)
err := b.shutdown()
assert.Equal(t, true, shutdown_complete)
assert.Equal(t, fmt.Errorf("shutdown error"), err)
eventbus.EventBus.Publish(eventbus.Event{Topic: eventbus.HOME_SHUTDOWN})
}
<file_sep>PROJECT MOVED, UPSTREAM DEVELOPMENT IS DONE HERE: [https://git.ppacher.at/paz/go-home](https://git.ppacher.at/paz/go-home)
This one is an old copy and will be removed/archived soon!
<file_sep>/*
GoHome aims to provide a code base for DIY "smart-homes". How "smart" it is
depends on your creativity (and programming skills ;)). However, a lot of
modules and plugins are already available so you might be able to start right
away.
Currently the following features (incomplete) are supported:
- control everything via a Web User-Interface (mainly based on react and modern-ui)
- control a MPD server like mpd itself or mopidy
- execute and watch on local command Output
- extend by connecting to a JSON websocket
- track devices within your WLAN (currently only Netgear routers are supported)
- send notification to your Android Phone via Notify-My-Android
- track weather conditions and sun state
- write rules to control all of that in JavaScript ;)
Note: GoHome is still under development and has not been released yet. Therefore
any API may change at any moment.
Installation
In order to install and build GoHome the following instructions are required:
git clone https://github.com/nethack42/go-home
cd go-home
export GOPATH=$(pwd)
go build home
Then copy config.yaml.example to config.yaml and change it to your linking.
Aftwards you are safe to start GoHome.
./home
For more information on how to configure the various backends and plugins please
refer to their documentation (which should also be available within the
respective source file.)
*/
package main
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 notify
import (
"fmt"
"home/core/backend"
"home/core/service"
"home/utils"
"github.com/dustin/go-nma"
"github.com/sirupsen/logrus"
)
type notifyMyAndroid struct {
nma *nma.NMA
backend *backend.Backend
}
func NotifyMyAndroidBackend(config map[string]interface{}, back *backend.Backend) error {
apiKey, ok := utils.GetString("api_key", config, "")
if !ok {
return fmt.Errorf("Backend: %s missing configuration option 'api_key'", back.Name())
}
comp := ¬ifyMyAndroid{
nma: nma.New(apiKey),
backend: back,
}
back.Internal = comp
service.ServiceRegistry.Register(back, "notify", "Send a notification via Notify-My-Android",
comp.Notify, map[string]string{
"subject": "Subject of the notification",
"message": "Message part of the notification",
},
map[string]string{
"priority": "Priority of the notification. Defaults to 0",
})
return nil
}
func (notify *notifyMyAndroid) Notify(param service.Arguments) interface{} {
if notify.nma == nil {
return fmt.Errorf("Backend is not initialized")
}
subject, ok := param.Arg("subject").String()
if !ok {
return service.InvalidParameterType{Parameter: "subject", RequiredType: "string"}
}
message := param.Arg("message").DefaultString("")
priority := param.Arg("priority").DefaultInt(0)
e := nma.Notification{
Application: "Home",
Event: subject,
Description: message,
Priority: nma.PriorityLevel(priority),
}
if err := notify.nma.Notify(&e); err != nil {
return service.InternalError{Err: err}
}
logrus.Infof("Backend: %s sent notification with pritority: %d", notify.backend.Name(), e.Priority)
return fmt.Sprintf("%s sent notification with pritority: %d", notify.backend.Name(), e.Priority)
}
// init is called when the file is initialized and registers the nma
// platform within the home core
func init() {
backend.Register("nma", NotifyMyAndroidBackend)
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 utils
import (
"fmt"
"strconv"
)
// GetString returns the value of the config key as string or a default on error
func GetString(key string, config map[string]interface{}, def string) (string, bool) {
var res string
value, ok := config[key]
if !ok {
return def, false
}
switch v := value.(type) {
case string:
res = v
case int:
res = strconv.Itoa(v)
case float64:
res = fmt.Sprintf("%f", value)
default:
return def, false
}
return res, true
}
// GetInt returns the value of the config key as interget or a default on error
func GetInt(key string, config map[string]interface{}, def int) (int, bool) {
var res int
var err error
value := config[key]
if value == nil {
return def, false
}
switch v := value.(type) {
case int:
res = v
case string:
res, err = strconv.Atoi(v)
if err != nil {
return def, false
}
case float64:
res = int(v)
default:
return def, false
}
return res, true
}
// GetFloat64 returns the value of the config key as float64 or a default on error
func GetFloat64(key string, config map[string]interface{}, def float64) (float64, bool) {
value := config[key]
if value == nil {
return def, false
}
switch n := value.(type) {
case float64:
return n, true
case int:
return float64(n), true
case string:
res, err := strconv.ParseFloat(n, 64)
if err != nil {
return def, false
}
return res, true
}
return def, false
}
<file_sep>package service
import (
"home/core/eventbus"
"testing"
)
func TestFuture(t *testing.T) {
eventbus.EventBus.Start()
f := NewFuture()
_ = f
}
<file_sep>package backend
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
var shutdown bool = false
var onerror bool = false
func initTestBackend(config map[string]interface{}, b *Backend) error {
b.OnShutdown = func(b *Backend) error {
shutdown = true
return nil
}
b.OnComponentError = func(c *Component, e error) error {
onerror = true
return e
}
return nil
}
func TestManager(t *testing.T) {
mgr := NewManager()
// Must work
assert.Equal(t, nil, mgr.Register("test", initTestBackend))
assert.Equal(t, nil, Register("test", initTestBackend))
// This one must fail since the backend identifier (test) is already
// used
assert.Equal(t,
fmt.Errorf("Backend: test name already registered"),
mgr.Register("test", initTestBackend))
// Check if Describe works (0 backends started with 0 components)
assert.EqualValues(t,
map[string]map[string]interface{}{},
mgr.Describe())
// Start backend instance
assert.Nil(t, mgr.StartBackendsByConfig([]interface{}{
map[string]interface{}{
"type": "test",
},
}))
// Check Describe (1 backend, 0 components)
assert.EqualValues(t,
map[string]map[string]interface{}{
"test": map[string]interface{}{
"name": "test",
"type": "test",
"components": []map[string]string(nil),
},
},
mgr.Describe())
// Start backend instance (must fail due to same name)
assert.Error(t, mgr.StartBackendsByConfig([]interface{}{
map[string]interface{}{
"type": "test",
},
}))
// Start backend instance (must work)
assert.Nil(t, mgr.StartBackendsByConfig([]interface{}{
map[string]interface{}{
"type": "test",
"name": "test2",
},
}))
// Start backend instance (must fail due to missing type)
assert.Error(t, mgr.StartBackendsByConfig([]interface{}{
map[string]interface{}{
"type": "",
},
}))
// Start backend instance (must fail due to missing type)
assert.Error(t, mgr.StartBackendsByConfig([]interface{}{
map[string]interface{}{
"name": "test",
},
}))
// Start backend instance (must fail due to invalid type)
assert.Error(t, mgr.StartBackendsByConfig([]interface{}{
"test",
}))
mgr.StopBackends()
assert.Equal(t, true, shutdown)
assert.Equal(t, false, onerror)
}
<file_sep>const Home = require('./home.jsx');
window.HomeAPI = new Home('/');
(function() {
let React = require('react');
let ReactDOM = require('react-dom');
let injectTapEventPlugin = require('react-tap-event-plugin');
let Main = require('./components/main.jsx');
window.React = React;
injectTapEventPlugin();
window.HomeAPI.login("admin", "admin", function(data) {
ReactDOM.render(<Main />, document.getElementById("app"));
}, function(data) {
console.log(data);
});
})();
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 rules
import (
"home/core"
)
var HomeJSCoreAPI map[string]interface{}
func init() {
HomeJSCoreAPI = make(map[string]interface{})
HomeJSCoreAPI["Subscribe"] = apiSubscribe
HomeJSCoreAPI["Log"] = apiLog
HomeJSCoreAPI["State"] = apiGetState
HomeJSCoreAPI["Service"] = apiServiceCall
HomeJSCoreAPI["Config"] = core.Global
HomeJSCoreAPI["Rule"] = apiRule
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 example
import "home/core/backend"
import "github.com/sirupsen/logrus"
func initExampleBackend(config map[string]interface{}, back *backend.Backend) error {
// config represents the backend configuration passed to GoHome. Thus,
// the `name` (if set) and `typ` fields are still present within the map.
logrus.Infof("Started backend %s with name %s", config["type"].(string), back.Name())
// Manipulate the backend structure as you like
back.OnShutdown = shutdownExampleBackend
// use the component registration channel to register new components
// here a simple boolen "sensor" is created which value will toggle every
// few seconds
comp := &backend.Component{
StateSink: make(chan interface{}),
Name: "example",
Polling: updateExampleComponent,
Internal: true,
}
back.RegisterComponent <- comp
return nil
}
func updateExampleComponent(comp *backend.Component) error {
if comp.Internal.(bool) {
comp.Internal = false
} else {
comp.Internal = true
}
comp.StateSink <- comp.Internal
return nil
}
func shutdownExampleBackend(back *backend.Backend) error {
logrus.Infof("Shutting down backend %s", back.Name())
return nil
}
func init() {
backend.Register("example", initExampleBackend)
// Equal to
// backend.DefaultManager.Register("example", initExampleBackend)
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 service
import (
"fmt"
"home/core/backend"
"home/core/eventbus"
"sync"
"github.com/sirupsen/logrus"
)
type Call struct {
Name string
Parameter map[string]interface{}
FutureTopic string
}
func (c Call) String() string {
return fmt.Sprintf("%s(%#v)", c.Name, c.Parameter)
}
type Service func(param Arguments) interface{}
type callEntry struct {
Call Service
Owner interface{}
RequiredArguments map[string]string
OptionalArguments map[string]string
}
type serviceRegistry struct {
calls map[string]callEntry
callLock sync.Mutex
}
func (svc *serviceRegistry) Register(owner interface{}, name, descr string, call Service, required, optional map[string]string) {
svc.callLock.Lock()
defer svc.callLock.Unlock()
ownerString, _ := getOwnerName(owner)
name = fmt.Sprintf("%s.%s", ownerString, name)
svc.calls[name] = callEntry{
Call: call,
Owner: owner,
RequiredArguments: required,
OptionalArguments: optional,
}
logrus.Infof("Services: %s registered", name)
}
func getOwnerName(ownerInterface interface{}) (owner string, bType string) {
switch o := ownerInterface.(type) {
case *backend.Backend:
owner = o.Name()
bType = "backend"
case *backend.Component:
owner = o.Name
bType = "component"
default:
owner = fmt.Sprintf("%#v", owner)
bType = "unkown"
}
return
}
func (svc *serviceRegistry) OnEvent(event eventbus.Event) {
logrus.Debugf("Services: received event from eventbus")
call := event.Data.(Call)
svc.callLock.Lock()
defer svc.callLock.Unlock()
func_call := svc.calls[call.Name].Call
owner, bType := getOwnerName(svc.calls[call.Name].Owner)
if func_call != nil {
// Verify that all required parameters are given
for name, _ := range svc.calls[call.Name].RequiredArguments {
if _, ok := call.Parameter[name]; !ok {
eventbus.EventBus.Publish(eventbus.Event{
Topic: call.FutureTopic,
Data: MissingParameter{Parameter: name},
})
logrus.Warnf("Services: %s service %s called. owner is %s, parameters '%s' is missing", bType, call.Name, owner, name)
return
}
}
logrus.Infof("Services: %s service %s called. owner is %s, parameters are %#v", bType, call.Name, owner, call.Parameter)
go func() {
res := func_call(Arguments{arguments: call.Parameter})
eventbus.EventBus.Publish(eventbus.Event{
Topic: call.FutureTopic,
Data: res,
})
}()
} else {
logrus.Warnf("Services: %s does not exist", call.Name)
eventbus.EventBus.Publish(eventbus.Event{
Topic: call.FutureTopic,
Data: fmt.Errorf("Service %s does not exist", call.Name),
Error: fmt.Errorf("Service %s does not exist", call.Name),
})
}
}
func (svc *serviceRegistry) Start() {
eventbus.EventBus.Subscribe(eventbus.SERVICE_CALL, svc.OnEvent)
}
func (svc *serviceRegistry) Describe() map[string]map[string]map[string]string {
svc.callLock.Lock()
defer svc.callLock.Unlock()
result := make(map[string]map[string]map[string]string)
for name := range svc.calls {
result[name] = make(map[string]map[string]string)
result[name]["required"] = svc.calls[name].RequiredArguments
result[name]["optional"] = svc.calls[name].OptionalArguments
}
return result
}
var ServiceRegistry *serviceRegistry
func init() {
ServiceRegistry = &serviceRegistry{
calls: make(map[string]callEntry),
}
}
func CallService(name string, param map[string]interface{}) *Future {
future := NewFuture()
event := eventbus.Event{
Origin: "ServiceCall",
Topic: eventbus.SERVICE_CALL,
Data: Call{
Name: name,
Parameter: param,
FutureTopic: future.uuid,
},
}
eventbus.EventBus.Publish(event)
return future
}
<file_sep>// Away-Mode Implementation
//
var Rule = {
name: "AwayMode",
origin: "R6300.devices",
init: function() {
this.state = "away";
this.count = 0;
this.Away = function(event) {
if (event.Data == null || event.Data == undefined) {
return;
}
if (event.Data.length > 0) {
Service("nma.notify", {
subject: "AwayMode",
message: "Deactivated",
});
Log("Deactivating Away Mode");
this.state = "home";
}
};
this.Home = function(event) {
if (event.Data == null || event.Data == undefined || event.Data.length == 0) {
this.count = this.count + 1;
if (this.count > 10) {
Service("nma.notify", {
subject: "AwayMode",
message: "Activated",
});
this.count = 0;
this.state = "away";
Log("Activating Away Mode");
}
return;
}
this.count = 0;
};
this.handler = {
"away": this.Away,
"home": this.Home,
};
},
onEvent: function(event) {
if (event.Origin != "R6300.devices") {
return this.state;
}
this.handler[this.state].bind(this)(event)
return this.state;
},
update: function() {
},
};
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 middleware
import "home/core/backend"
/*
Middleware implementation to detect the absence of people within a GoHome domain
Absence is detected by querying configured input sources for changes. If no
presence-indicator matches within a predefined timeframe an empty house is
assumed. As soon as a presence indicator is detected, the state is changed to
"someone-home".
Usage
In order to use the PresenceDetection middleware add something like the following
to your configuration file:
backends:
- type: presence_middleware
inputs:
- urn: netgear.devices
match_home: "return len(data) > 0"
match_away: "return (data == null||data == undefined||len(data) == 0)"
- urn: tinkerforge.motion_detection
match_home: "return (data == true)"
Description
For each input configured there may be one (or both) of match_home and match_away.
Each of them is used to match the specific value for the input respectively. If
one of the is missing, a negative result of the given one will result in a state
change. The match_* parameters should contain a JavaScript expression returning
either true or false. The data of the input source the changed is available via
the `data` variable.
For example, imagine your match_home rule in <match_home>, the called JavaScript
would look like this:
var func = function(data) {
<match_home>;
}
return func(data);
Thus, one can also write multi line/expressions for evaluation.
Error handling
In case a match_* expression fails, the result is ignored and the current state
is kept.
*/
func PresenceDetectionMiddleware(config map[string]interface{}, back *backend.Backend) error {
p := &presenceIndicator{}
p.Init("presence", true) // Init is inherited from backend.Component
p.Polling = p.update
back.RegisterComponent <- &p.Component // Shadow member backend.Component
return nil
}
type presenceIndicator struct {
backend.Component
}
func (p *presenceIndicator) update(comp *backend.Component) error {
return nil
}
func init() {
backend.Register("presence_middleware", PresenceDetectionMiddleware)
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 core
import (
"github.com/moraes/config"
"github.com/sirupsen/logrus"
)
type globalConfig struct {
// Latitude where GoHome is located
Latitude float64
// Longitude where GoHome is located
Longitude float64
// Name of this GoHome instance ()
Name string
// Logging level
Logging string
}
// Global configuration important across plugins, backends, components and the
// core itself
var Global globalConfig
// ParseConfig reads a YAML configuration file, prepares the global config and
// return the configuration for further usage
func ParseConfig(filename string) (*config.Config, error) {
cfg, err := config.ParseYamlFile(filename)
if err == nil {
var err error
Global.Latitude, err = cfg.Float64("global.latitude")
if err != nil {
logrus.Warnf("Global option 'Latitude' not set")
}
Global.Longitude, err = cfg.Float64("global.longitude")
if err != nil {
logrus.Warnf("Global option 'Longitude' not set")
}
Global.Name, err = cfg.String("global.name")
if err != nil {
logrus.Warnf("Global option 'name' not set. Using. '%s'", "Home")
Global.Name = "Home"
}
Global.Logging, err = cfg.String("global.logging")
if err != nil {
logrus.Warnf("Global option 'logging' not set. Using. '%s'", "info")
Global.Logging = "info"
}
}
return cfg, err
}
<file_sep>package service
import "fmt"
type InvalidParameterType struct {
Parameter string
RequiredType string
}
func (e InvalidParameterType) Error() string {
return fmt.Sprintf("InvalidParameterType: %s is not %s", e.Parameter, e.RequiredType)
}
type MissingParameter struct {
Parameter string
}
func (e MissingParameter) Error() string {
return fmt.Sprintf("MissingParameter: %s", e.Parameter)
}
type InternalError struct {
Err error
}
func (e InternalError) Error() string {
return fmt.Sprintf("InternalError: %s", e.Err.Error())
}
<file_sep>package suntracker
import (
"fmt"
"io/ioutil"
"net/http"
"time"
"home/core"
"home/core/backend"
"home/utils"
"github.com/moraes/config"
"github.com/sirupsen/logrus"
)
type sunTracker struct {
nextRise time.Time
nextSet time.Time
currentState string
lng float64
lat float64
lastUpdate time.Time
}
func initSunTrackerBackend(config map[string]interface{}, back *backend.Backend) error {
lat, _ := utils.GetFloat64("latitude", config, core.Global.Latitude)
lng, _ := utils.GetFloat64("longitude", config, core.Global.Longitude)
comp := &backend.Component{
StateSink: make(chan interface{}),
Name: "sun_tracker",
Polling: updateSunTracker,
Type: backend.SunTracker,
Internal: &sunTracker{
lng: lng,
lat: lat,
},
}
back.RegisterComponent <- comp
return nil
}
func updateSunTracker(component *backend.Component) error {
sun := component.Internal.(*sunTracker)
if sun.lastUpdate.Add(1 * time.Hour).After(time.Now()) {
logrus.Debugf("Component: %s skipping update", component.URN())
return nil
}
sun.lastUpdate = time.Now()
url := fmt.Sprintf("http://api.sunrise-sunset.org/json?lat=%f&lng=%f&formatted=0", sun.lat, sun.lng)
timeRise, timeSet, err := sun.getSunState(url)
if err != nil {
return err
}
// We are 'below_horizon' and need to get the information for the next day
if time.Now().After(timeSet) {
url = fmt.Sprintf("http://api.sunrise-sunset.org/json?lat=%f&lng=%f&formatted=0&date=tomorrow", core.Global.Latitude, core.Global.Longitude)
timeRise, timeSet, err = sun.getSunState(url)
if err != nil {
return err
}
sun.currentState = "below_horizon"
} else
// Its before sunset of today
if time.Now().Before(timeRise) {
sun.currentState = "below_horizon"
} else {
sun.currentState = "above_horizon"
}
sun.nextSet = timeSet.Local()
sun.nextRise = timeRise.Local()
return updateState(component)
}
func updateState(component *backend.Component) error {
sun := component.Internal.(*sunTracker)
newState := map[string]interface{}{
"state": sun.currentState,
"sun-rise": sun.nextRise,
"sun-set": sun.nextSet,
}
component.StateSink <- newState
return nil
}
func (sun *sunTracker) getSunState(url string) (time.Time, time.Time, error) {
res, err := http.Get(url)
if err != nil {
return time.Now(), time.Now(), err
}
content, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return time.Now(), time.Now(), err
}
resp, err := config.ParseJson(string(content))
if err != nil {
return time.Now(), time.Now(), err
}
nextRise, err := resp.String("results.sunrise")
if err != nil {
return time.Now(), time.Now(), err
}
nextSet, err := resp.String("results.sunset")
if err != nil {
return time.Now(), time.Now(), err
}
timeRise, err := time.Parse(time.RFC3339, nextRise)
if err != nil {
return time.Now(), time.Now(), err
}
timeSet, err := time.Parse(time.RFC3339, nextSet)
if err != nil {
return time.Now(), time.Now(), err
}
return timeRise, timeSet, nil
}
func init() {
backend.Register("sun", initSunTrackerBackend)
}
<file_sep>package backend
import "github.com/sirupsen/logrus"
import "fmt"
// InitBackendFunction is required when a new backend is registered at startup
// This function is called when the backend has been selected by the configuration
// and will be supplied with the backend config itself as well as a pre-initialized
// Backend structure. Overwrite required fields as neccessary but have a look at
// the documentation to ensure which fields should not be altered!
type InitBackendFunction func(map[string]interface{}, *Backend) error
// Manager is respobsible for handling backends and their components
type Manager struct {
backendInitializers map[string]InitBackendFunction
backend map[string]*Backend
}
// Register a new backend initialization function within the backend manager
// The init function is registered with a backend identifier
func (mgr *Manager) Register(name string, init InitBackendFunction) error {
if mgr.backendInitializers[name] != nil {
return fmt.Errorf("Backend: %s name already registered", name)
}
mgr.backendInitializers[name] = init
logrus.Debugf("Backend: %s registered as a backend provider", name)
return nil
}
// Describe returns a map containing registered backends and their components
func (mgr *Manager) Describe() map[string]map[string]interface{} {
result := make(map[string]map[string]interface{})
for name, backend := range mgr.backend {
var components []map[string]string
backend.componentsLock.Lock()
for _, comp := range backend.components {
components = append(components, comp.Describe())
}
backend.componentsLock.Unlock()
result[name] = make(map[string]interface{})
result[name]["name"] = name
result[name]["type"] = backend.identifier
result[name]["components"] = components
}
return result
}
// StartBackend starts the backend specified by `typ` with the `name`.
// `config` is passed to the backend initialization method for further configuration
func (mgr *Manager) StartBackend(name, typ string, config map[string]interface{}) (*Backend, error) {
be := &Backend{
name: name,
identifier: typ,
RegisterComponent: make(chan *Component),
}
go be.handleComponentRegistration()
initFunc := mgr.backendInitializers[typ]
if initFunc != nil {
if err := initFunc(config, be); err != nil {
return nil, err
}
return be, nil
}
return nil, fmt.Errorf("Backend: %s (name=%s) backend provider is not registered", typ, name)
}
// StartBackendsByConfig initializes and starts all backends defined within
// the given list of backend configuration. Each list entry is required to
// contain a `type` and a optional `name` key. `type` specifies the backend
// to use and name will be used for the backend after initialization in order
// to support re-use of backends.
func (mgr *Manager) StartBackendsByConfig(config []interface{}) error {
var last_error error
for _, rawConfig := range config {
if backendConfig, ok := rawConfig.(map[string]interface{}); ok {
if typ, ok := backendConfig["type"].(string); ok {
name := typ
if tmp, ok := backendConfig["name"].(string); !ok {
logrus.Warnf("Backend: %s configuration without 'name' defaulting to type (%s)", typ, typ)
} else {
name = tmp
}
if mgr.backend[name] != nil {
logrus.Errorf("Backend: %s (type=%s) already registered as name", name, typ)
last_error = fmt.Errorf("Backend: %s (type=%s) already registered as name", name, typ)
continue
}
backend, err := mgr.StartBackend(name, typ, backendConfig)
if err != nil {
logrus.Errorf("Backend: %s (type=%s) failed to start: %#v", name, typ, err)
last_error = fmt.Errorf("Backend: %s (type=%s) failed to start: %#v", name, typ, err)
continue
}
mgr.backend[name] = backend
logrus.Debugf("Backend: %s started", backend.Name())
} else {
logrus.Errorf("Backend: 'type' not specified or of invalid type: %#v", backendConfig)
last_error = fmt.Errorf("Backend: 'type' not specified or of invalid type: %#v", backendConfig)
}
} else {
logrus.Errorf("Backend: Exptected string map as configuration. got: %#v", rawConfig)
last_error = fmt.Errorf("Backend: Exptected string map as configuration. got: %#v", rawConfig)
}
}
return last_error
}
// StopBackends stops all registered backends (as long as OnShutdown has been set)
func (mgr *Manager) StopBackends() error {
for _, backend := range mgr.backend {
backend.shutdown()
}
return nil
}
// DefaultManager is a backend manager 'instance' which can be safely used accross
// different packages
var DefaultManager *Manager
// NewManager returns a fully initializes backend manager
func NewManager() *Manager {
return &Manager{
backend: make(map[string]*Backend),
backendInitializers: make(map[string]InitBackendFunction),
}
}
// Register a new backend within the DefaultManager.
// See Manager.Register() for more information
func Register(name string, init InitBackendFunction) error {
if DefaultManager != nil {
return DefaultManager.Register(name, init)
}
return fmt.Errorf("DefaultManager has not been initialized!!!")
}
func init() {
DefaultManager = NewManager()
}
<file_sep>/*
This package contains available backends which can be used if compiled into
GoHome.
Overview
Backends are an essential part as they provide data via components/
sensors and services which can later be called. For more information about
backends and components please refer to the documentaiton of the `backend`
package. More information on service can be found in the `service` package
documentation.
Configuration
The configuration of backends should be placed in the global configuration file
of GoHome under the `backends` section. Consider the following example:
global:
name: My Home Somewhere
latitude: 17.43
longitude: 48.87
backends:
- type: sun_tracker
- name: AustriaSunState
This would automatically enable and configure a backend called sun_tracker if
registered (thus being available and configured in stub.go during compile-time).
*/
package backends
<file_sep>/*
The core package contains all packages required to operate GoHome.
*/
package core
<file_sep>package service
import "testing"
func TestValue(t *testing.T) {
}
<file_sep>// go-home: home automation controller
//
// website: https://github.com/nethack42/go-home
// author: <NAME> <<EMAIL>>
//
// Copyright 2015 <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 rules
import (
"sync"
"github.com/robertkrimen/otto"
_ "github.com/robertkrimen/otto/underscore"
"io/ioutil"
"github.com/sirupsen/logrus"
)
type JavascriptVM struct {
VM *otto.Otto
Name string
File string
lock sync.Mutex
}
func (js *JavascriptVM) PrepareVM() error {
js.lock.Lock()
defer js.lock.Unlock()
// create javascript VM
js.VM = otto.New()
// Expose go functions
js.prepareEnvironment()
return nil
}
func (js *JavascriptVM) prepareEnvironment() {
logrus.Debugf("Plugin: rules: initializing javascript environment for %s", js.Name)
// Set JavaScript Home core API object
js.VM.Set("Home", HomeJSCoreAPI)
}
func (js *JavascriptVM) LoadContent(content string) error {
js.lock.Lock()
defer js.lock.Unlock()
result, err := js.VM.Run(content)
if err != nil {
logrus.Warnf("JavaScript-Error: %s error=%s", result, err)
}
return nil
}
func (js *JavascriptVM) LoadContentFromFile(file string) error {
js.lock.Lock()
defer js.lock.Unlock()
data, err := ioutil.ReadFile(file)
if err != nil {
return err
}
result, err := js.VM.Run(string(data))
logrus.Debugf("JS-Result: %s error=%s", result, err)
return nil
}
| 8a7b96f842a0cd439857291368286bda9512b300 | [
"JavaScript",
"Go",
"Markdown"
] | 61 | Go | nethack42/go-home | d7b6c3fe3a2bd23964b85c7fb1fa40b89266206d | 2cdb813e37bbd4a989654f8c720292c4a7cc6703 |
refs/heads/master | <file_sep>class Student
# Remember, you can access your database connection anywhere in this class
# with DB[:conn]
include Helper
def initialize(*args, **hash)
vars = %w(name grade id)
super(vars, args, hash)
end
def self.create_table
sql_input = <<-SQL
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
grade TEXT
)
SQL
DB[:conn].execute(sql_input)
end
def self.drop_table
sql_command = <<-SQL
DROP TABLE
students
SQL
DB[:conn].execute(sql_command)
end
def save
sql_command = <<-SQL
INSERT INTO
students (
name,
grade
) VALUES (
?, ?
)
SQL
DB[:conn].execute(sql_command, self.name, self.grade)
@id = DB[:conn].execute(
"SELECT LAST_INSERT_ROWID() FROM students"
)[0][0]
self
end
def self.create(**args)
self.new(**args).save
end
end
| fcaa8b2683af1f253a99dcc4a6e8e611cda4027e | [
"Ruby"
] | 1 | Ruby | AlisherZakir/orm-mapping-to-table-lab-london-web-051319 | 082c911ec964d638184223f8e787dbaa7542094b | af751eee03b404efbcb38091cb9589b9b1d430dc |
refs/heads/master | <file_sep>require('./styles/usage/app.scss');
// var common = require('./scripts/utils/util.common.js');
//
// var html = require('./scripts/tpls/index.html')
//
// common.render(html);
//
// require('./scripts/views/index.js');
var layout = require('./scripts/tpls/layout.html');
var common = require('./scripts/utils/util.common.js');
common.render(layout);
//conponents
import index from "./scripts/components/index.vue";
import home from "./scripts/components/home.vue";
//router
const routes = [
{
path:'/',
component: index,
children: [{
path: '/',
component:home
}]
}
]
const router = new VueRouter({
routes // (缩写)相当于 routes: routes
});
const app = new Vue({
router
}).$mount('#app');
<file_sep>//var Vue = require('../lib/vue.js');
//var $ = require('../lib/zepto.js');
//var IScroll = require('../lib/iscroll-probe.js');
//var Swiper = require('../lib/swiper.js');
var common = require('../utils/util.common.js');
new Vue({
el:'#m-index',
data:{
swiper:null,
navIndex:0,
nav:['足球现场','足球现场','足球现场'],
list:[]
},
methods:{
changeTab:function(index){
//console.log(0);
//console.log(this.swiper);
this.swiper.slideTo(index);
this.navIndex = index;
}
},
mounted:function(){
/*setTimeout(function(){
this.nav[0].title="abc"
}.bind(this),3000)*/
fetch('/api/list').then(response => response.json())
.then(res =>{
//console.log(res)
var that = this;
that.list = res;
that.swiper = new Swiper('#index-swiper',{
loop:false,
onSlideChangeStart: function(swiper){
//alert(swiper.activeIndex);
that.navIndex = swiper.activeIndex;
}
});
common.isAllLoaded('#index-scroll ul',function(){
console.log('all loaded')
})
common.scroll(that);
})
.catch(e => console.log("Oops, error", e));
//console.log(IScroll)
}
});
| 495216c8446f8ccda86352a55331687a5fb900e0 | [
"JavaScript"
] | 2 | JavaScript | lijiawang66/vuejs | a93c905b56fd78caef1f2bfa41604365f1a3d79b | 8d2a017a5e81e07759a38c607c73d3b96fbe6fcf |
refs/heads/master | <file_sep>from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('DOC', views.docSearch, name='docSearch'),
path('SLOT', views.slot_search, name='slotSearch'),
path('fill_slot/id<int:slot_id>/', views.fill_slot, name='fill_slot'),
]
<file_sep>from django.shortcuts import render
from django.http import HttpResponse
from requests.auth import HTTPBasicAuth
from django import forms
import requests
import json
import datetime
import fhirclient.models.bundle as bund
from django.shortcuts import redirect
class DatePickerForm(forms.Form):
day = forms.DateField(initial=datetime.date.today)
# Create your views here.
def index(request):
#GET https://team02-rof.interopland.com/new-hope-services/fhir/Patient?name=Ben&_pretty=true
BASE_URL = 'https://team02-rof.interopland.com/new-hope-services/fhir/Patient'
msg = ""
if request.method == 'POST':
params = {
'name': request.POST['name'],
'phone': request.POST['phone'],
#'phone': request.POST['phone'],
'_pretty': 'true'}
print(f"request.POST = {request.POST}")
response = requests.get(BASE_URL, params = params,
auth=('mihin_hapi_fhir', '<KEY>'))
print(f"response = {response}")
print(f"response.content = {response.text}")
try:
msg = json.dumps(response.json(), indent=4, sort_keys=True)
except:
msg = response.text
return render(request, 'patient_search.html', {
'msg': msg
})
#return HttpResponse("Hello, world. You're at the polls index.")
def fill_slot(request, slot_id):
ROOT_URL = 'https://team02-rof.interopland.com/new-hope-services/fhir/Slot/'
resp = requests.get(
ROOT_URL + str(slot_id),
auth=('mihin_hapi_fhir', '<KEY>')
)
resp_text = resp.text
resp_text = resp_text.replace("free", "busy")
print(f"resp = {resp_text}")
resp2 = requests.put(
ROOT_URL + str(slot_id),
data=resp_text,
auth=('mihin_hapi_fhir', '<KEY>')
)
print(f"resp2 = {resp2}")
response = redirect('slotSearch')
return response
def slot_search(request):
#GET https://team02-rof.interopland.com/new-hope-services/fhir/Patient?name=Ben&_pretty=true
BASE_URL = 'https://team02-rof.interopland.com/new-hope-services/fhir/Slot'
ROOT_URL = 'https://team02-rof.interopland.com/new-hope-services/fhir/'
msg = ""
slots = []
sched = {}
provs = {}
locs = {}
ui_slots = []
if request.method == 'POST':
form = DatePickerForm(request.POST)
if form.is_valid():
#Do Query
#print(f"request.POST = {request.POST}")
start_date = datetime.datetime.strptime(request.POST['day'], '%Y-%m-%d')
#print(f"start_date = {start_date}")
tomorrow_date = start_date + datetime.timedelta(days=1)
params = {
'status': 'free',
'start':[
f'ge{start_date.replace(microsecond=0).isoformat()}',
f'le{tomorrow_date.replace(microsecond=0).isoformat()}'
]}
print(f"tomorrow_date = {tomorrow_date}")
response = requests.get(BASE_URL, params = params,
auth=('mihin_hapi_fhir', '<KEY>'))
#print(f"response = {response}")
#print(f"response.content = {response.text}")
bundle = bund.Bundle(response.json())
#print(f"bund = {bundle}")
#print(f"bund_dict = {bundle.__dict__}")
entries = bundle.entry
for entry in entries:
print(f"entry = {entry.resource.__dict__}")
sdate = entry.resource.start.date
sched_ref = entry.resource.schedule.reference
print(f"sdate = {sdate}, sched_ref = {sched_ref}")
slots.append((
entry.resource.start.date,
entry.resource.end.date,
entry.resource.schedule.reference,
entry.resource.id
))
if sched_ref not in sched:
resp = requests.get(
ROOT_URL + sched_ref,
auth=('mihin_hapi_fhir', '<KEY>')
)
print(f"resp = {resp.text}")
try:
sched[sched_ref] = resp.json()
except:
sched[sched_ref] = resp.text
for sched_key, sched_val in sched.items():
actors = sched_val['actor']
prac_ref = None
loc_ref = None
for actor in actors:
print(f"actor = {actor}")
if actor['reference'].startswith('Location'):
loc_ref = actor['reference']
elif actor['reference'].startswith('Practitioner'):
prac_ref = actor['reference']
else:
print(f"Unknown actor reference: {actor.reference}")
print(f"loc_ref = {loc_ref}, prac_ref = {prac_ref}")
sched[sched_key] = (loc_ref, prac_ref)
if loc_ref not in locs:
resp = requests.get(
ROOT_URL + loc_ref,
auth=('mihin_hapi_fhir', '<KEY>')
)
print(f"resp = {resp.text}")
try:
locs[loc_ref] = resp.json()
except:
locs[loc_ref] = resp.text
if prac_ref not in provs:
resp = requests.get(
ROOT_URL + prac_ref,
auth=('mihin_hapi_fhir', 'cLQgfFT<KEY>')
)
print(f"resp = {resp.text}")
try:
provs[prac_ref] = resp.json()
except:
provs[prac_ref] = resp.text
#print(f"entry = {entry.resource.__dict__}")
#print(f"date = {entry.resource.start.date}")
#reference
#print(f"sched = {entry.resource.schedule.__dict__}")
print(f"sched = {sched}")
print(f"locs = {locs}")
print(f"provs = {provs}")
for slot in slots:
print(f"slot[2] = {slot[2]}")
print(f"sched = {sched}")
s = sched[slot[2]]
print(f"s = {s}")
l = locs[s[0]]['name']
p = provs[s[1]]['name'][0]
print(f"l = {l}, p = {p}")
p_name = f"{p['family']}, {p['given'][0]}"
print(f"p_name = {p_name}")
#print(f"loc = {locs[s[0]]}\nprac = {provs[s[1]]}")
ui_slots.append([
slot[0], slot[1],
l, p_name,
slot[3]
])
#msg += f"\n{slot[0]}-{slot[1]}:{locs[
try:
msg = json.dumps(response.json(), indent=4, sort_keys=True)
except:
msg = response.text
else:
form = DatePickerForm()
print(f"ui_slots = {ui_slots}")
return render(request, 'slot_search.html', {
'form': form,
'ui_slots': ui_slots,
'msg': msg
})
#{locs[sched[0]]}
# Create your views here.
def docSearch(request):
#GET https://team02-rof.interopland.com/new-hope-services/fhir/Patient?name=Ben&_pretty=true
#twzddba28GjsiSq!
BASE_URL = 'https://team02-rof.interopland.com/new-hope-services/fhir/Patient'
msg = ""
if request.method == 'POST':
params = {
'name': request.POST['name'],
'family': request.POST['email'],
'phone': request.POST['phone'],
'_pretty': 'true'
}
print(f"request.POST = {request.POST}")
response = requests.get(BASE_URL, params = params,
auth=('mihin_hapi_fhir', '<KEY>'))
print(f"response = {response}")
print(f"response.content = {response.text}")
try:
msg = json.dumps(response.json(), indent=4, sort_keys=True)
except json.JSONDecodeError:
msg = response.text
return render(request, 'patient_search.html', {
'msg': msg
})
#return HttpResponse("Hello, world. You're at the polls index.")
| a75d19a0a45d4efdfc0f6aaf2260a2ed0060dc3d | [
"Python"
] | 2 | Python | mwhavens/docapt | 8525aca5830d6b9d6aa615cbb866e9811b6e9611 | 398fc1711cabb26b3ceb3bbe07188c0d285f099a |
refs/heads/master | <repo_name>obviousrebel/pybreak<file_sep>/pybreak_turtle.py
import turtle
wn = turtle.Screen()
wn.title('PyBreak')
wn.bgcolor('black')
wn.setup(width=800, height=600)
wn.tracer(0)
paddle = turtle.Turtle()
paddle.speed(0)
paddle.shape('square')
paddle.shapesize(1, 5, 1)
paddle.color('blue')
paddle.penup()
paddle.goto(0, -250)
ball = turtle.Turtle()
ball.speed(0)
ball.shape('square')
ball.color('white')
ball.penup()
ball.goto(0, 0)
def paddle_right():
if(paddle.xcor() < 325):
paddle.setx(paddle.xcor() + 40)
def paddle_left():
if(paddle.xcor() > -325):
paddle.setx(paddle.xcor() - 40)
wn.listen()
wn.onkeypress(paddle_right, 'Right')
wn.onkeypress(paddle_left, 'Left')
while True:
wn.update()
| 3f3aa2389185da721e411936524cda453edd1c92 | [
"Python"
] | 1 | Python | obviousrebel/pybreak | 14808bf5ed0f867a0f9a4ee03489a4f383e4f227 | 6f8e3d38b78ba6273a9c3c3cae187a5ffd175f53 |
refs/heads/master | <repo_name>danjokeny/FinalExam810<file_sep>/README.md
FinalExam810
final exam for class 810
<NAME>
<file_sep>/client/src/model.js
var ValidTodo = ['High', 'Meium', 'Low'];
var ToDoSchema = new ToDoSchema({
todo: {type: String},
priotity: { type: String, enum: ValidTodo },
done: {type: Boolean, default: false}
});
module.exports = Mongoose.model('ToDo', ToDoSchema); | 0e662e4bf3745d5b4d800163600a2fd6cc883b39 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | danjokeny/FinalExam810 | 229c4ee25f6c77d2b0049ec70615590bcb85b607 | 4bcba3db29adb09e27b0302166a92ec3cc920334 |
refs/heads/master | <file_sep>#!/bin/bash --
#
# MAC adress changer
# http://lihars.tk
#author:<NAME>
#grep yahan HWaddr ko search karta hai aur address deta hai
#change interface and new mac accordingly
echo "enter interface";
read inter;
echo "Old mac adress: ";
ifconfig -a | grep HWaddr | grep $inter;
echo "\nenter new mac id"
read new_mac;
sudo ifconfig $inter down
sudo ifconfig $inter hw ether $new_mac
sudo ifconfig $inter up
echo "New mac adress: $new_mac"
#mac ko dekh ke daliyo
| 583cf005a51560491af6de3d707f94ed695cb6cf | [
"Shell"
] | 1 | Shell | rs91092/simple-bash-macchanger-for-linux | 141f36d635f0c707e8821bceeef2d475f5cf5a90 | 8c978c22bdf8b235cabe39f1f59c6a08ee4e83fb |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace ShowLog
{
class StaticTarget
{
public static ObservableCollection<string> StaticLogMessages { get; set; } = new ObservableCollection<string>();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ShowLog
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
MainWindowViewModel viewModel = new MainWindowViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = viewModel;
object obj = new object();
BindingOperations.EnableCollectionSynchronization(viewModel.LogMessages, obj);
object obj2 = new object();
BindingOperations.EnableCollectionSynchronization(StaticTarget.StaticLogMessages, obj2);
}
private async void AddLog_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
try
{
viewModel.LogMessages.Add(viewModel.LogMessage);
StaticTarget.StaticLogMessages.Add(viewModel.LogMessage);
viewModel.LogMessage = null;
}
catch (Exception ex)
{
}
});
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
namespace ShowLog
{
public class MainWindowViewModel : INotifyPropertyChanged
{
public ObservableCollection<String> LogMessages { get; set; } = new ObservableCollection<string>();
private string logMessage;
public string LogMessage
{
get { return logMessage; }
set
{
logMessage = value;
OnPropertyChanged();
}
}
public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| 8ef966e68262799c77e051540f238d2812affe5a | [
"C#"
] | 3 | C# | kdziewit/ShowLog | 1d1a40af6d04df2df71b67e5ff64c297d9167142 | acc8a3b55b5131afc608023e193a80157a0876b5 |
refs/heads/master | <file_sep>package com.itea.java.basic.l10.enums.game;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
public class MyLogFormatter extends SimpleFormatter {
@Override
public synchronized String format(LogRecord record) {
return record.getMessage() + "\n";
}
}
<file_sep>package com.itea.java.basic.l10.practice;
public enum SomeEnum {
SOME_VALUE,
ANOTHER_VALUE
}
<file_sep>package com.itea.java.basic.l10.enums;
public class EnumSwitchExample {
public static void main(String[] args) {
}
private String plan(DayOfWeek dayOfWeek) {
switch (dayOfWeek) {
case MONDAY: return "ITEA lesson";
case TUESDAY: return "ITEA homework";
case WEDNESDAY: return "ITEA lesson";
case THURSDAY: return "Workout";
case FRIDAY: return "Party hard";
case SATURDAY: return "Eat and sleep";
case SUNDAY: return "Getting ready...";
default: return "Actually, it is not possible";
}
}
}
<file_sep>package com.itea.java.basic.l10.enums.game;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class FileLoggerFactory {
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd-HH-mm-ss";
public static Logger getLogger() {
try {
Logger logger = Logger.getLogger("my-logger");
FileHandler fileHandler = new FileHandler(generateLogFilename());
SimpleFormatter simpleFormatter = new SimpleFormatter();
logger.addHandler(fileHandler);
for (Handler handler : logger.getHandlers()) {
handler.setFormatter(simpleFormatter);
}
return logger;
} catch (IOException e) {
e.getStackTrace();
return null;
}
}
private static String generateLogFilename() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
String dateTimeString = LocalDateTime.now().format(formatter);
return "log " + dateTimeString + ".txt";
}
}<file_sep>package com.itea.java.basic.l10.practice.cards;
public class LinkedCardStack implements CardStack {
private LinkedCardStackElement top;
public void push(Card card) {
if (top == null) {
LinkedCardStackElement element = new LinkedCardStackElement(card, null);
top = element;
} else {
LinkedCardStackElement element = new LinkedCardStackElement(card, top);
top = element;
}
}
public Card pop() {
Card result = top.getCard();
top = top.getPrev();
return result;
}
public boolean empty() {
return top == null;
}
public int length() {
LinkedCardStackElement tmp = top;
if (empty()) {
return 0;
}
int size = 0;
while (tmp.getPrev() != null) {
size ++;
tmp = tmp.getPrev();
}
return size;
}
}
<file_sep>package com.itea.java.basic.l10.practice;
public final class SomeEnum1 {
public static final SomeEnum1 SOME_VALUE = new SomeEnum1();
public static final SomeEnum1 ANOTHER_VALUE = new SomeEnum1();
private SomeEnum1() {
}
}
<file_sep>package com.itea.java.basic.l10.enums.game;
public enum Result {
WIN("You win!"),
LOOSE("You loose!"),
DRAW("It is draw");
Result(String message) {
this.message = message;
}
private String message;
@Override
public String toString() {
return message;
}
}
<file_sep>package com.itea.java.basic.l10.practice;
import java.io.InputStreamReader;
import static com.itea.java.basic.l10.practice.Month.*;
//import static com.itea.java.basic.l10.practice.Month.getMonth;
import static java.lang.Math.PI;
public class MonthExample {
public static void main(String[] args) {
System.out.println(getMonth(5));
System.out.println(getMonth(new InputStreamReader(System.in)));
System.out.println(JANUARY);
double d = PI;
Class monthClass = Month.class;
}
private static int getNumberOfDays(int monthNumber) {
for (Month month : Month.values()) {
if (month.ordinal() == (monthNumber - 1)) {
return month.getNumberOfDays();
}
}
return 0;
}
}
<file_sep>package com.itea.java.basic.l10.practice.cards;
public enum Mast {
PIK,
CHERV,
KREST,
BUBN,
rgdgsefsefse,
}
<file_sep>package com.itea.java.basic.l10.trycatch;
import java.util.Scanner;
public class TryCatchExample {
public TryCatchExample() throws Exception {
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
if (i == 0) {
throw new RuntimeException("0 is not allowed");
}
}
}
| 5caba1205d2c4cc33eafd8f4131dbd0399cef27e | [
"Java"
] | 10 | Java | anton1113/l10-practice | 6c062fe60de450e098d66d2647faf59347c6e6bd | deff48b89b547d6cd54c48fbb5861a694c25d7dd |
refs/heads/master | <repo_name>optimusprime94/algoritmer-laboration-1<file_sep>/C-algoritmer1/twothreeTree.c
#include "genlib.h"
#include "twothreeTree.h"
typedef struct nodeT {
int element1;
int element2;
struct nodeT *previous;
struct nodeT *nextL;
struct nodeT *nextM;
struct nodeT *nextR;
} nodeT;
struct twotreeCDT {
nodeT *node;
};
/* Funktioner */
twotreeADT NewTree(void) {
twotreeADT ttTree;
ttTree = New(twotreeADT);
ttTree->node = NULL;
return (ttTree);
}
void FreeTree(twotreeADT tree)
{
/*
twotreeADT *cp, *nextp;
// *nextL;
//*nextM;
// *nextR;
cp = tree->node;
while (cp != NULL) {
}
*/
}
void TreeInsert(twotreeADT tree, int newValue) {
} //treeADT tree, element
void TreePrint(twotreeADT ttTree) {
printf("%d\n", ttTree->node);
/*
printf("%d\n", ttTree->node->element1);
printf("%d\n", ttTree->node->element1);
printf("%d\n", ttTree->node->element1);
*/
}
bool TreeIsEmpty(twotreeADT tree)
{
return (tree->node == NULL);
}<file_sep>/C-algoritmer1/twothreeTree.h
/*
* File: twothreeTree.h
* Version: 1.0
* Authors: <NAME>, <NAME>, <NAME> och <NAME>.
* -----------------------------------------------------
* This file contains basic functions for implementing a
* two-three tree datastructure.
*
*
*/
#ifndef _twothreeTree_h
#define _twothreeTree_h
typedef int elementT;
typedef struct twotreeCDT *twotreeADT;
/*
* Function: NewTree
* Usage: NewTree();
* ----------------------
*
*
*/
twotreeADT NewTree(void);
/*
* Function: FreeTree
* Usage: FreeTree(tree);
* ----------------------
*
*
*/
void FreeTree(twotreeADT tree);
/*
* Function: FreeBlock
* Usage: TreeInsert(tree, newValue);
* ----------------------
*
*
*/
void TreeInsert(twotreeADT tree, int newValue);
/*
* Function: TreePrint
* Usage: TreePrint(tree);
* ----------------------
*
*
*/
void TreePrint(twotreeADT tree);
/*
* Function: TreeIsEmpty
* Usage: TreeIsEmpty(twotreeADT tree);
* ----------------------
*
*
*/
bool TreeIsEmpty(twotreeADT tree);
#endif // !_2-3treeADT.h_
<file_sep>/README.md
# algoritmer-laboration-1<file_sep>/C-algoritmer1/main.c
#include "genlib.h"
main() {
printf("Hello nick");
} | f135c65fd0ce9a204688e67341f65129be7bb4ea | [
"Markdown",
"C"
] | 4 | C | optimusprime94/algoritmer-laboration-1 | 45329ecb20416ab5e38bf89808ab3e2a41a68039 | 84791e0d7f0f4be25f234b5b63cf83bf421b7a45 |
refs/heads/main | <repo_name>neerajbardia/dh-key-exchange<file_sep>/README.md
# dh-key-exchange
Diffie Helann Key Exchange algorithm, used for secure transfer of the key over the communication lines
This technique is mostly used for key exchange and not actual data trasmission, coupled with RSA algorithm it can form a very secure communication/data transfer.
<file_sep>/dh_key_exchange.py
#diffie hellman key exchange
#this is a single file with the sender and the reciever functions, this file can be split into two separate files and made to communicate through socket programming to enable
#transfer of data. Socket programming and diffie hellman key exchange algorithm together can be very helpful to undestand the use of diffie hellman. Also there can be a
#middle-man too who can alter the messages and hence check if the algorithm is actually working or not.
import random
import sys
from math import sqrt
sys.setrecursionlimit(10**6)
prime_no=int(input("Enter the prime no:"))
private_s=47 #input of two private keys s stands for sender, r stands for reciever
private_r=53
def isPrime( n): #checking if a no is prime or not
if (n <= 1):
return False
if (n <= 3):
return True
if (n % 2 == 0 or n % 3 == 0):
return False
i = 5
while(i * i <= n):
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def power( x, y, p):
res = 1
x = x % p
while (y > 0):
if (y & 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
def findPrimefactors(s, n) :
while (n % 2 == 0) :
s.add(2)
n = n // 2
for i in range(3, int(sqrt(n)), 2):
while (n % i == 0) :
s.add(i)
n = n // i
if (n > 2) :
s.add(n)
def findPrimitive( n) :
s = set()
if (isPrime(n) == False):
return -1
phi = n - 1
findPrimefactors(s, phi)
for r in range(2, phi + 1):
flag = False
for it in s:
if (power(r, phi // it, n) == 1):
flag = True
break
if (flag == False):
return r
return -1
primitive_root= findPrimitive(prime_no)
print("Primitive Root:",primitive_root)
public_r=(primitive_root**private_r)%prime_no
public_s=(primitive_root**private_s)%prime_no
print("Public key of Reciever:",public_r)
print("Public key of Sender:",public_s)
key_s=(public_s**private_r)%prime_no
key_r=(public_r**private_s)%prime_no
if key_r==key_s:
print("Success! key shared successfully")
print("Shared Key:",key_r)
else:
print("Failed")
| 2920457be9c9131267729fa9824e5db72966e091 | [
"Markdown",
"Python"
] | 2 | Markdown | neerajbardia/dh-key-exchange | e58f471fb2020c2f99aefcfcc80ccd8135779dfb | 355f3299cb8de47f70a95fe6f373bdea331de094 |
refs/heads/master | <file_sep>require 'rails_helper'
feature 'commenting' do
before do
user = User.create email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>'
login_as user
visit '/photos'
click_link 'Add a photo'
expect(current_path).to eq '/photos/new'
attach_file 'Image', 'spec/testimages/cat.png'
fill_in 'Caption', with: 'TestCap'
click_button 'Create Photo'
end
scenario 'allows users to leave a comment using a form' do
visit '/photos'
click_link 'Add a comment'
fill_in "Thoughts", with: "So Cute!"
click_button 'Leave Comment'
expect(page).to have_content("So Cute!")
end
end
<file_sep>require 'rails_helper'
feature 'photos' do
context 'no photos have been added' do
scenario 'should display a prompt to add a photo' do
visit '/photos'
expect(page).to have_content 'No photos yet'
expect(page).to have_link 'Add a photo'
end
end
context 'adding photos' do
before do
user = User.create email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>'
login_as user
end
scenario 'by a user who has signed in' do
visit '/photos'
click_link 'Add a photo'
expect(current_path).to eq '/photos/new'
attach_file 'Image', 'spec/testimages/cat.png'
fill_in 'Caption', with: 'Kitty'
click_button 'Create Photo'
expect(page).to have_css('img[src*="cat.png"]')
expect(page).not_to have_content 'No pictures yet'
end
end
end
| 4856fb5c49ff36718eafb31a9cf9f3748fe1d5e2 | [
"Ruby"
] | 2 | Ruby | duskyshelf/instagram-challenge | 11ecc2a7066744f372e63b5e5062383f3f56b455 | f3f4e07c2d0a96f3c9f8ede952a6b4f53baecd3d |
refs/heads/master | <repo_name>AlistairBall/3DUnity<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/WeaponShoot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponShoot : MonoBehaviour {
public Rigidbody projectilePrefab;
public Transform projectileSpawnPoint;
public float projectileForce;
int ammo;
// Use this for initialization
void Start () {
ammo = 20;
projectileForce = 10.0f;
}
// Update is called once per frame
public void Shoot()
{
if(ammo > 0)
{
Rigidbody temp = Instantiate(projectilePrefab,
projectileSpawnPoint.position, projectileSpawnPoint.rotation);
temp.AddRelativeForce(projectileSpawnPoint.forward * projectileForce,
ForceMode.Impulse);
ammo--;
}
}
public void GrenadeLaunch()
{
Rigidbody temp = Instantiate(projectilePrefab,
projectileSpawnPoint.position, projectileSpawnPoint.rotation);
temp.AddRelativeForce(projectileSpawnPoint.forward * projectileForce,
ForceMode.Impulse);
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Supplies.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Supplies
{
// Var
public float ammo;
public float bandages;
public float weight;
public Supplies(int size)
{
bandages = size;
ammo = size * 5;
weight = bandages * 0.2f + ammo * 0.8f;
}
public static Supplies operator +(Supplies lhs, Supplies rhs)
{
Supplies s = new Supplies(0);
s.bandages = lhs.bandages + rhs.bandages;
s.ammo = lhs.ammo + rhs.ammo;
s.weight = lhs.ammo + rhs.ammo;
return s;
}
public static bool operator <(Supplies lhs, Supplies rhs)
{
return lhs.weight < rhs.weight;
}
public static bool operator >(Supplies lhs, Supplies rhs)
{
return lhs.weight > rhs.weight;
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Camera.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour {
private float rotationSpeed;
private Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start () {
rotationSpeed = 6;
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.Escape)) { Screen.lockCursor = false; }
else
{
Screen.lockCursor = true;
// mouse position on the x axis
transform.Rotate(-Input.GetAxis("Mouse Y") * rotationSpeed, 0, 0);
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/ChangeSceneTo.cs
// BasicFPSController
// <NAME>
// Changes scene to given index.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeSceneTo : MonoBehaviour
{
public void SwitchTo(int index)
{
SceneManager.LoadScene(index);
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Shotgun.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shotgun : MonoBehaviour {
public Transform player;
public Rigidbody pelletPrefab;
public Rigidbody pellet;
float BulletSpread = 8.0f;
float pelletSpeed = 70f;
int pelletCount = 8;
float fireRate = 0.5f;
float nextFire = 0.0f;
public Transform ProjectileSpawn;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0) && Time.time > nextFire && player.GetComponent<PlayerControler>().shotgunAmmo >= 0)
{
player.GetComponent<PlayerControler>().shotgunAmmo--;
player.GetComponent<PlayerControler>().AmmoText.text = "Ammo: " + player.GetComponent<PlayerControler>().shotgunAmmo.ToString();
for (var i = 0; i < pelletCount; i++)
{
var pelletRot = transform.rotation;
pelletRot.x = Random.Range(-BulletSpread, BulletSpread);
pelletRot.y = Random.Range(-BulletSpread, BulletSpread);
pellet = Instantiate(pelletPrefab, ProjectileSpawn.position, pelletRot);
pellet.velocity = transform.forward * pelletSpeed;
}
nextFire = Time.time + fireRate;
}
}
void OnCollisionEnter()
{
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/ESCPauseMenu.cs
// BasicFPSController
// <NAME>
// ESC brings up hidden Canvas and pauses game clock.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ESCPauseMenu : MonoBehaviour
{
// Varribles
public Canvas GUI;
public Canvas UI;
public bool Paused = false;
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
// Lock Cursor to center of the screen unless ESC
// Also switch canvas's, Freeze time and Freeze Controls
if (Input.GetKey(KeyCode.Escape))
{
// Switch pasued
Paused = !Paused;
if(Paused)
{
UI.enabled = (true);
GUI.enabled = (false);
Time.timeScale = 0;
}
else if(!Paused)
{
Time.timeScale = 1;
GUI.enabled = (true);
UI.enabled = (false);
}
}
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Gun.cs
// BasicFPSController
// <NAME>
// Gun Parent Class.
using UnityEngine;
public class Gun : MonoBehaviour
{
public float damage;
public float range;
public float impactForce;
public float fireRate;
private float nextTimeToFire = 0.0f;
public ParticleSystem mf;
public GameObject fpsCam;
public GameObject impact;
void Awake()
{
fpsCam = GameObject.Find("MainCamera");
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButton(0) && Time.time >= nextTimeToFire)
{
Fire();
nextTimeToFire = Time.time + 1f/fireRate;
}
}
void Fire()
{
mf.Play();
RaycastHit hit;
if( Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range) )
{
//Debug.Log(hit.transform.name);
Health target = hit.transform.GetComponent<Health>();
if(target != null)
{
if(hit.transform.tag != "Player"){target.TakeDamage(damage);}
}
if(hit.rigidbody !=null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject impactGo = Instantiate(impact, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGo, 2.0f);
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Damage.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Damage : MonoBehaviour {
public int basicHealth;
public int specialHealth;
public GameObject Spawner;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision c)
{
//Destroy(c.gameObject);
if (c.gameObject.tag == "Projectile" || c.gameObject.tag == "Pellet" && gameObject.tag == "basicEnemy")
{
basicHealth--;
}
else if (basicHealth == 0)
{
Instantiate(Spawner, transform.position, Quaternion.identity);
Spawner.SetActive(true);
Destroy(gameObject);
}
if (c.gameObject.tag == "Projectile" || c.gameObject.tag == "Pellet" && gameObject.tag == "specialEnemy")
{
specialHealth--;
}
else if (gameObject.tag == "specialEnemy" && specialHealth == 0)
{
Instantiate(Spawner, c.transform.position, Quaternion.identity);
Spawner.SetActive(true);
Destroy(gameObject);
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/FollowUntil.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowUntil : MonoBehaviour
{
//Var
public bool active;
public GameObject target;
public float speed;
public float veiwDistance;
private RaycastHit cast;
// Use this for initialization
void Start ()
{
// Sets defaults for varribles
if(target == null){target = GameObject.FindWithTag("Player");}
if(speed == 0){speed = 0.1f;}
if(veiwDistance == 0){veiwDistance = 10.0f;}
}
// Update is called once per frame
void Update ()
{
if(CheckTargetDistance())
{
active = true;
if(AskPermission())
{
transform.position = Vector3.MoveTowards(transform.position, target.transform.position , speed);
}
}
else {active = false;}
}
bool CheckTargetDistance()
{
// Draw the same Raycast for Debuging [ **Not accurate to the other ray in game **]
//Debug.DrawRay(transform.position, target.transform.position * veiwDistance, Color.cyan);
// If target in range follow other wise, When target too far away stop following
if (Physics.Raycast(transform.position,( target.transform.position - transform.position) , out cast, veiwDistance) && cast.collider.tag.Equals("Player"))
{
//Debug.Log("Player Spotted");
return true;
}
else {return false;}
}
bool AskPermission()
{
if ( this.GetComponent<Enemy>().currentAction == "FollowUntil")
{
return true;
//Debug.Log( "Action Allowed" + this.name);
}
else
{
return false;
//Debug.log("Action Overridden" + this.name);
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Spawn.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawn : MonoBehaviour
{
// Var
public Transform SpawnBase;
public GameObject HealthPrefab;
public GameObject RiflePrefab;
public GameObject ShotgunPrefab;
private int ranInt;
public string SpawnOption;
public bool spawn;
// Use this for initialization
void Start ()
{
spawn = false;
}
// Update is called once per frame
void Update ()
{
if (SpawnOption == "Random" && !spawn) {RandomSpawn(); spawn = true;}
else if (SpawnOption == "Health"&& !spawn) {SpawnHealth(); spawn = true;}
else if (SpawnOption == "Rifle"&& !spawn) { SpawnRifle(); spawn = true;}
else if (SpawnOption == "Shotgun" && !spawn) { SpawnShotgun(); spawn = true; }
}
void OnDestroy()
{
}
void RandomSpawn()
{
Random.seed = System.DateTime.Now.Millisecond;
ranInt = Random.Range( 1 , 4);
if(ranInt == 1)
{
Instantiate(HealthPrefab, new Vector3( SpawnBase.transform.position.x, SpawnBase.transform.position.y +1 , SpawnBase.transform.position.z ), Quaternion.identity);
}
else if(ranInt == 2)
{
Instantiate(RiflePrefab, new Vector3( SpawnBase.transform.position.x, SpawnBase.transform.position.y +1 , SpawnBase.transform.position.z), Quaternion.identity);
}
else if (ranInt == 3)
{
Instantiate(ShotgunPrefab, new Vector3(SpawnBase.transform.position.x, SpawnBase.transform.position.y + 1, SpawnBase.transform.position.z), Quaternion.identity);
}
}
void SpawnHealth()
{
Instantiate(HealthPrefab, new Vector3( SpawnBase.transform.position.x, SpawnBase.transform.position.y +1, SpawnBase.transform.position.z ), Quaternion.identity);
}
void SpawnRifle()
{
Instantiate(RiflePrefab, new Vector3( SpawnBase.transform.position.x, SpawnBase.transform.position.y +1, SpawnBase.transform.position.z ), Quaternion.identity);
}
void SpawnShotgun()
{
Instantiate(ShotgunPrefab, new Vector3(SpawnBase.transform.position.x, SpawnBase.transform.position.y + 1, SpawnBase.transform.position.z), Quaternion.identity);
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/ExitToDesktop.cs
// BasicFPSController
// <NAME>
// Exit To Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExitToDesktop : MonoBehaviour
{
public void ExitProgram()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
Debug.Log("Program Terminated");
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/ADS.cs
// BasicFPSController
// <NAME>
// On right click aim down sights
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ADS : MonoBehaviour
{
public GameObject fpsCam;
public float zoom;
private Camera cam;
private float normal;
void Start()
{
//normal = cam.fieldOfView;
zoom = 20;
}
void Awake()
{
cam = GameObject.Find("MainCamera").GetComponent<Camera>();
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButton(1))
{
//cam.fieldOfView = zoom;
}
else
{
//cam.fieldOfView = normal;
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/PlayerDamage.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerDamage : MonoBehaviour {
public Image healthBar;
public int health = 200;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision c)
{
if (c.gameObject.tag == "Projectile" || c.gameObject.tag == "Pellet")
{
health -= 20;
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/PlayerControler.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
[RequireComponent(typeof(CharacterController))]
public class PlayerControler : MonoBehaviour
{
// Var
private float speed;
private float rotationSpeed;
private float jumpHeight;
private float gravity;
private float MaxStamina;
private float CurrStamina;
public Image healthBar;
public GameObject shovelIcon;
public GameObject goldKeyIcon;
public GameObject silverKeyIcon;
public Text AmmoText;
public Text Notification;
private bool isSprinting = false;
private Vector3 moveDirection = Vector3.zero;
private bool sMoveType;
private CharacterController cc;
public bool inBush;
private bool hasGoldKey = false;
private bool hasShovel = false;
private bool hasSilverKey = false;
public bool hasRifle;
public bool hasShotgun;
public int health;
public int pistolAmmo;
public int rifleAmmo;
public int shotgunAmmo;
public Stack Weapons;
// public Projectile projectilePrefab;
// public Transform projectileSpawnPoint;
public GameObject AK47;
public GameObject Handgun;
public GameObject Shotgun;
public GameObject shovelWaypoint;
public GameObject goldKeyWaypoint;
public GameObject silverKeyWaypoint;
public GameObject[] Enemies;
public GameObject enemyGameObject;
// Initialization ( On Create )
void Start ()
{
MaxStamina = 75;
CurrStamina = MaxStamina;
speed = 8;
rotationSpeed = 6;
jumpHeight = 15;
gravity = 9.8f;
Weapons = new Stack();
inBush = false;
silverKeyWaypoint.SetActive(false);
goldKeyWaypoint.SetActive(false);
shovelWaypoint.SetActive(false);
hasRifle = false;
hasShotgun = false;
if (Enemies == null)
{
Enemies = GameObject.FindGameObjectsWithTag("basicEnemy");
}
cc = GetComponent<CharacterController>();
if (!cc) gameObject.AddComponent<CharacterController>();
}
// Update is called once per frame
void Update ()
{
if (isSprinting == false)
{
try
{
StartCoroutine("GainStamina");
}
catch(Exception e)
{
Debug.LogWarning(e);
}
}
// hit ESC to unlock mouse and use cursor
if (Input.GetKey(KeyCode.Escape)) {Screen.lockCursor = false;}
else
{
Screen.lockCursor = true;
// mouse position on the x axis
transform.Rotate(0, Input.GetAxis("Mouse X") * rotationSpeed, 0);
}
RaycastHit hit;
// Debug.DrawRay(transform.position, transform.forward * 5.0f, Color.red);
// if (Physics.Raycast(transform.position, transform.forward, out hit, 5.0f))
//{
// Debug.Log(hit.collider.name);
//}
//----------------------------Controls--------------------------------------------------------------
// Debug.Log(projectileSpawnPoint.position);
if (Input.GetKeyDown(KeyCode.Q))
{
SceneManager.LoadScene("StartMenu", 0);
Cursor.visible = true;
Screen.lockCursor = false;
}
if (Input.GetKeyDown(KeyCode.Alpha1))
{
Handgun.SetActive(true);
AmmoText.text = "Ammo: Infinite";
AK47.SetActive(false);
Shotgun.SetActive(false);
}
if (Input.GetKeyDown(KeyCode.Alpha2) && hasRifle == true)
{
Handgun.SetActive(false);
AK47.SetActive(true);
AmmoText.text = "Ammo :" + rifleAmmo.ToString();
Shotgun.SetActive(false);
}
if (Input.GetKeyDown(KeyCode.Alpha3) && hasShotgun == true)
{
Handgun.SetActive(false);
AK47.SetActive(false);
Shotgun.SetActive(true);
AmmoText.text = "Ammo :" + shotgunAmmo.ToString();
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
try
{
speed = 15;
isSprinting = true;
StartCoroutine("Stamina");
}
catch (Exception e)
{
Debug.LogWarning(e);
}
}
if(health<= 0)
{
Notification.text = "GAME OVER";
Screen.lockCursor = false;
Cursor.visible = true;
SceneManager.LoadScene("StartMenu", 0);
}
//---------------COntrole END-------------------------------
if (CurrStamina < 0)
{
CurrStamina = 0;
}
float curSpeed = Input.GetAxis("Vertical") * speed;
cc.SimpleMove(transform.forward * curSpeed);
curSpeed = Input.GetAxis("Horizontal") * speed * 2;
cc.SimpleMove(transform.right * curSpeed);
// Jump
if (cc.isGrounded)
{
moveDirection = new Vector3(0, 0, Input.GetAxis("Vertical"));
//float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
//float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
// target.transform.Rotate(vertical, horizontal, 0);
if (Screen.lockCursor)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * rotationSpeed, 0);
}
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButtonDown("Jump"))
moveDirection.y = jumpHeight;
}
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
cc.Move(moveDirection * Time.deltaTime);
//update end
}
public void QuitGame()
{
// quite game in editor
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
IEnumerator Stamina()
{
for (float f = CurrStamina; f <= MaxStamina && f >= 1; f--)
{
if (Input.GetKeyUp(KeyCode.LeftShift)){
f = CurrStamina;
isSprinting = false;
break;
}
else
{
CurrStamina--;
// Debug.Log(CurrStamina + "/" + MaxStamina);
yield return new WaitForSeconds(.1f);
}
}
speed = 8;
isSprinting = false;
}
IEnumerator GainStamina()
{
for (float g = CurrStamina; g < MaxStamina && g >= 0; g++)
{
CurrStamina++;
// Debug.Log(CurrStamina + "/" + MaxStamina);
if (CurrStamina > MaxStamina)
{
CurrStamina = MaxStamina;
break;
}
yield return new WaitForSeconds(.5f);
}
}
void OnTriggerEnter (Collider other)
{
if( gameObject.tag == "Player" && other.gameObject.tag == "PickUpHP" )
{
if (health == 200)
{
healthBar.fillAmount = 1.0f;
}
else if (health >= 150)
{
health = 200;
healthBar.fillAmount = 1.0f;
Destroy(other.gameObject);
}
else
{
//Debug.Log(other.gameObject.name);
health += 50;
healthBar.fillAmount = healthBar.fillAmount + 0.25f;
Destroy(other.gameObject);
}
}
if (gameObject.tag == "Player" && other.gameObject.tag == "ShovelPickup")
{
//Debug.Log(other.gameObject.name);
hasShovel = true;
shovelIcon.SetActive(true);
shovelWaypoint.SetActive(true);
Destroy(other.gameObject);
Notification.text = "Go to the West Wall and dig to Escape!";
Invoke("ClearNotificationtext", 6);
}
if (gameObject.tag == "Player" && other.gameObject.tag == "GoldKeyPickup")
{
//Debug.Log(other.gameObject.name);
hasGoldKey = true;
goldKeyIcon.SetActive(true);
goldKeyWaypoint.SetActive(true);
Destroy(other.gameObject);
Notification.text = "Get to the North Gate to Escape!";
Invoke("ClearNotificationtext", 6);
}
if (gameObject.tag == "Player" && other.gameObject.tag == "SilverKeyPickup")
{
//Debug.Log(other.gameObject.name);
hasSilverKey = true;
silverKeyIcon.SetActive(true);
silverKeyWaypoint.SetActive(true);
Destroy(other.gameObject);
Notification.text = "Go to the Docks and get on a Boat to Escape!!";
Invoke("ClearNotificationtext", 6);
}
if(other.gameObject.tag == "PickUpRifle" && gameObject.tag == "Player")
{
if(hasRifle == false)
{
hasRifle = true;
Handgun.SetActive(false);
AK47.SetActive(true);
Shotgun.SetActive(false);
rifleAmmo = 150;
AmmoText.text = "Ammo: " + rifleAmmo.ToString();
AddRifleAmmoText();
Destroy(other.gameObject);
}
else
rifleAmmo += 50;
Destroy(other.gameObject);
}
if (other.gameObject.tag == "PickUpShotgun" && gameObject.tag == "Player")
{
if (hasShotgun == false)
{
hasShotgun = true;
Handgun.SetActive(false);
AK47.SetActive(false);
Shotgun.SetActive(true);
shotgunAmmo = 20;
AmmoText.text = "Ammo: " + shotgunAmmo.ToString();
AddShotgunAmmoText();
Destroy(other.gameObject);
}
else
shotgunAmmo += 10;
Destroy(other.gameObject);
}
if (other.gameObject.tag == "Hide")
{
// Enemy enemyScript = enemyGameObject.GetComponent<Enemy>();
// enemyScript.Getem = true;
inBush = true;
}
if (other.gameObject.tag == "EndGameShovel" && hasShovel == true )
{
Notification.text = "Congratulations! You escaped!";
Invoke("QuitGame", 5);
}
else if(other.gameObject.tag == "EndGameShovel" && hasShovel == false)
{
Notification.text = "Comeback when you have something to dig under this hole with!";
Invoke("ClearNotificationtext", 6);
}
if (other.gameObject.tag == "EndGameSilverKey" && hasSilverKey == true)
{
Notification.text = "Congratulations! You escaped!";
Invoke("QuitGame", 5);
}
else if (other.gameObject.tag == "EndGameSilverKey" && hasSilverKey == false)
{
Notification.text = "Comeback when you have a silver key to sail away!";
Invoke("ClearNotificationtext", 6);
}
if (other.gameObject.tag == "EndGameGoldKey" && hasGoldKey == true)
{
Notification.text = "Congratulations! You escaped!";
Invoke("QuitGame", 5);
}
else if (other.gameObject.tag == "EndGameGoldKey" && hasGoldKey == false)
{
Notification.text = "Comeback when you have a gold key to unlock this gate!";
Invoke("ClearNotificationtext", 6);
}
}
void OnTriggerExit( Collider other)
{
if(other.gameObject.tag == "Hide")
{
inBush = false;
}
}
void OnCollisionEnter(Collision c)
{
if (c.gameObject.tag == "Projectile" || c.gameObject.tag == "Pellet")
{
health -= 10;
healthBar.fillAmount = healthBar.fillAmount - 0.05f;
}
}
void AddRifleAmmoText()
{
AmmoText.text = "Ammo: " + rifleAmmo.ToString();
}
void AddShotgunAmmoText()
{
AmmoText.text = "Ammo: " + shotgunAmmo.ToString();
}
void ClearNotificationtext()
{
Notification.text = "";
}
}<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/OverloadedOperators.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OverloadedOperators : MonoBehaviour
{
// Var
Supplies a;
Supplies b;
Supplies abCombo;
// Initialization ( On Create )
void Start ()
{
a = new Supplies(4);
b = new Supplies(6);
abCombo = a + b;
Debug.Log(abCombo.weight);
}
// Update is called once per frame
void Update ()
{
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/AnimController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimController : MonoBehaviour {
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.C))
{
anim.SetTrigger("Shooting 1 hand");
anim.SetBool("IsRunning", false);
}
if (Input.GetKeyDown(KeyCode.X))
{
anim.SetTrigger("Shooting 2 hands");
anim.SetBool("IsRunning", false);
}
if (Input.GetKeyDown(KeyCode.W))
{
anim.SetBool("IsRunning", true);
}
else if (Input.GetKeyUp(KeyCode.W))
{
anim.SetBool("IsRunning", false);
}
if (Input.GetKeyDown(KeyCode.F))
{
anim.SetTrigger("Spell");
anim.SetBool("IsRunning", false);
}
if (Input.GetKeyDown(KeyCode.Space))
{
anim.SetTrigger("Jump");
anim.SetBool("IsRunning", false);
}
if (Input.GetKeyDown(KeyCode.R))
{
anim.SetTrigger("Dead");
anim.SetBool("IsRunning", false);
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Rifle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rifle : MonoBehaviour {
public Transform player;
public Projectile projectilePrefab;
public Transform projectileSpawnPoint;
float nextFire = 0.0f;
float fireRate = 0.1f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 SpawnPoint = new Vector3(projectileSpawnPoint.position.x, projectileSpawnPoint.position.y, projectileSpawnPoint.position.z);
if (Input.GetMouseButton(0) && Time.time > nextFire && player.GetComponent<PlayerControler>().rifleAmmo >= 0)
{
Projectile temp = Instantiate(projectilePrefab,
SpawnPoint, projectileSpawnPoint.rotation);
player.GetComponent<PlayerControler>().rifleAmmo--;
player.GetComponent<PlayerControler>().AmmoText.text = "Ammo: " + player.GetComponent<PlayerControler>().rifleAmmo.ToString();
nextFire = Time.time + fireRate;
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
// Currently doesnt do much but later will be the brain in every enemy that decideing
// what action <-[Script] has most priority for the entity todo.
// Var
public GameObject Player;
public string currentAction;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if ( this.GetComponent<FollowUntil>().active ){currentAction = "FollowUntil";}
// By default just do normal patrol
else {currentAction = "TwoPointPatrol";}
// Print Current action
//Debug.Log( "Current Action Is: " + currentAction);
}
}<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/AI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AI : MonoBehaviour {
public Transform Enemy;
public GameObject[] Path;
public Transform player;
public Image basicHealthBar;
public Image specialHealthBar;
public float rotationDamping = 2f;
public Projectile projectilePrefab;
public Transform projectileSpawnPoint;
public int basicHealth;
public int specialHealth;
public GameObject Spawner;
int rotationSpeed = 80;
private float speed = 0.2f;
int currentWaypoint = 0;
float accuracyWaypoint = 4.0f;
public float shotInterval = 1f;
private float shotTime = 0;
private
bool Getem = false;
bool stop = false;
bool isDead = false;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
Vector3 direction = player.position - this.transform.position;
float angle = Vector3.Angle(direction, Enemy.up);
Debug.Log(basicHealth + "/" + specialHealth);
if (Getem == false)
{
direction = Path[currentWaypoint].transform.position - transform.position;
this.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
this.transform.Translate(0, 0, Time.deltaTime * speed);
anim.SetInteger("State", 1);
transform.position = Vector3.MoveTowards(transform.position, Path[currentWaypoint].transform.position, 0.2f);
}
//
if (Getem == true && (Time.time - shotTime) > shotInterval)
{
anim.SetInteger("State", 2);
//transform.LookAt(player);
LookAtTarget();
shotTime = Time.time;
Vector3 offset = new Vector3(0.0f, 0.7f, 0.0f);
Instantiate(projectilePrefab, transform.position + (player.position - transform.position).normalized + offset, Quaternion.LookRotation(player.position - transform.position));
}
if (gameObject.tag == "basicEnemy" && basicHealth == 0)
{
anim.SetInteger("State", 3);
shotInterval = 100;
Destroy(gameObject, 2);
speed = 0;
Invoke("DropSpawner", 1.999999999f);
}
if (gameObject.tag == "specialEnemy" && specialHealth == 0)
{
anim.SetInteger("State", 3);
shotInterval = 100;
Destroy(gameObject, 2);
speed = 0;
Invoke("DropSpawner", 1.9999f);
}
if (Vector3.Distance(Path[currentWaypoint].transform.position, transform.position) < accuracyWaypoint)
{
currentWaypoint = Random.Range(0, Path.Length);
//currentWaypoint++;
//if(currentWaypoint >= Path.Length )
//{
// currentWaypoint = 0;
//}
}
}
void OnCollisionEnter(Collision c)
{
//Destroy(c.gameObject);
if (c.gameObject.tag == "Projectile" || c.gameObject.tag == "Pellet" && gameObject.tag == "basicEnemy" && basicHealth > 0)
{
basicHealth--;
basicHealthBar.fillAmount = basicHealthBar.fillAmount - 0.333f;
if (Getem == true)
{
anim.SetInteger("State", 4);
}
else
{
anim.SetInteger("State", 5);
}
}
if (gameObject.tag == "specialEnemy" && c.gameObject.tag == "Projectile" || c.gameObject.tag == "Pellet" && specialHealth > 0)
{
specialHealth--;
specialHealthBar.fillAmount = specialHealthBar.fillAmount - 0.2f;
if (Getem == true)
{
anim.SetInteger("State", 4);
}
else
{
anim.SetInteger("State", 5);
}
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
anim.SetInteger("State", 2);
Getem = true;
}
if (other.gameObject.tag == "Hide")
{
Getem = false;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
anim.SetInteger("State", 1);
Getem = false;
}
}
void DropSpawner()
{
Instantiate(Spawner, transform.position, Quaternion.identity);
Spawner.SetActive(true);
}
void LookAtTarget()
{
// transform.LookAt(player.position);
Vector3 dir = player.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed).eulerAngles;
transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Handgun.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Handgun : MonoBehaviour {
public Projectile projectilePrefab;
public Transform projectileSpawnPoint;
public Transform player;
// Use this for initialization
void Start () {
if (!projectilePrefab)
Debug.LogError("Projectile Prefab not set.");
if (!projectileSpawnPoint)
Debug.LogError("ProjectileSpawnPoint not set.");
}
// Update is called once per frame
void Update () {
Vector3 SpawnPoint = new Vector3(projectileSpawnPoint.position.x, projectileSpawnPoint.position.y, projectileSpawnPoint.position.z);
if (Input.GetMouseButtonDown(0))
{
Projectile temp = Instantiate(projectilePrefab,
SpawnPoint, projectileSpawnPoint.rotation);
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Enemy2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy2 : MonoBehaviour
{
public Transform PlayerPos;
public Transform Home;
private bool Getem = false;
private
bool stop = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Getem == true && stop == false)
{
transform.position = Vector3.MoveTowards(transform.position, PlayerPos.transform.position, 0.5f);
}
else if (Getem == false && stop == false)
{
transform.position = Vector3.MoveTowards(transform.position, Home.transform.position, 0.7f);
}
Debug.Log(Getem);
}
void OnDestroy()
{
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
Getem = true;
}
if(other.gameObject.tag == "Hide")
{
Getem = false;
}
//if (other.gameObject.tag == "Stop")
//{
// stop = true;
//}
//else
//{
// stop = false;
//}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
Getem = false;
}
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/Health.cs
// BasicFPSController
// <NAME>
// Just Basic Health componet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Health : MonoBehaviour
{
public float MaxHP;
public float currentHP;
public bool dead;
void Start ()
{
currentHP = MaxHP;
}
public void TakeDamage(float change)
{
if (currentHP <= change)
{
Die();
}
else
{
currentHP = currentHP - change;
}
}
public void Die()
{
Debug.Log(gameObject + ": Has Died.");
Destroy(gameObject);
}
}
<file_sep>/GameDev1-FinalProject-AlistairBall/Assets/Scripts/WeaponPickerUpper.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponPickerUpper : MonoBehaviour
{
GameObject weapon;
GameObject weapon2;
GameObject weaponAttach;
// Use this for initialization
void Start()
{
if (!weaponAttach)
{
weaponAttach = GameObject.Find("WeaponAttachPoint");
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.T) && weapon)
{
weaponAttach.transform.DetachChildren();
Physics.IgnoreCollision(transform.GetComponent<Collider>(),
weapon.GetComponent<Collider>(), false);
weapon.GetComponent<Rigidbody>().isKinematic = true;
weapon.GetComponent<Rigidbody>().AddRelativeForce(
weaponAttach.transform.forward * 10, ForceMode.Impulse);
weapon = null;
}
if(Input.GetKeyDown(KeyCode.T) && weapon2)
{
weaponAttach.transform.DetachChildren();
Physics.IgnoreCollision(transform.GetComponent<Collider>(),
weapon2.GetComponent<Collider>(), false);
weapon2.GetComponent<Rigidbody>().isKinematic = true;
weapon2.GetComponent<Rigidbody>().AddRelativeForce(
weaponAttach.transform.forward * 10, ForceMode.Impulse);
weapon2 = null;
}
if (Input.GetButtonDown("Fire1"))
{
if (weapon)
{
WeaponShoot w = weapon.GetComponent<WeaponShoot>();
if (w)
{
w.Shoot();
}
}
else if (weapon2)
{
WeaponShoot w = weapon2.GetComponent<WeaponShoot>();
if (w)
{
w.GrenadeLaunch();
}
}
}
}
void OnControllerColliderHit(ControllerColliderHit c)
{
if (c.gameObject.tag == "Weapon")
{
weapon = c.gameObject;
//turn off physics for gun
weapon.GetComponent<Rigidbody>().isKinematic = true;
//
weapon.transform.SetPositionAndRotation(weaponAttach.transform.position,
weaponAttach.transform.localRotation);
weapon.transform.SetParent(weaponAttach.transform);
weapon.transform.localRotation =
weaponAttach.transform.localRotation;
//ignore collisions between the character and the weapon
Physics.IgnoreCollision(transform.GetComponent<Collider>(),
weapon.GetComponent<Collider>());
}
else if (c.gameObject.tag == "GrenadeWeapon")
{
weapon2 = c.gameObject;
//turn off physics for gun
weapon2.GetComponent<Rigidbody>().isKinematic = true;
//
weapon2.transform.SetPositionAndRotation(weaponAttach.transform.position,
weaponAttach.transform.localRotation);
weapon2.transform.SetParent(weaponAttach.transform);
weapon2.transform.localRotation =
weaponAttach.transform.localRotation;
//ignore collisions between the character and the weapon
Physics.IgnoreCollision(transform.GetComponent<Collider>(),
weapon2.GetComponent<Collider>());
}
}
}
| 14f86609b5151bc5ebf83ff836facc199a164c85 | [
"C#"
] | 23 | C# | AlistairBall/3DUnity | 49c7eec97d4be0f0030dc7306926ba24b2bb99ca | 368c982835bb094b53ce052e2f8f928c0b89292e |
refs/heads/master | <repo_name>zbb1211/myvuedemo<file_sep>/src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
/* eslint-disable */
// eslint-disable-next-line
import Vue from 'vue';
import App from './App';
import VueRouter from 'vue-router';
import axios from 'axios';
import seller from './components/seller/seller';
import goods from './components/goods/goods';
import ratings from './components/ratings/ratings';
Vue.prototype.$http = axios;
Vue.config.productionTip = false;
Vue.use(VueRouter);
const routes = [
{path: '/goods',component:goods},
{path: '/ratings',component:ratings},
{path: '/seller',component:seller},
{path:'/',component:goods}
];
const router = new VueRouter({
mode: 'history',
routes
});
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
}).$mount('#app');
| 91839e8e8f2e5a8deb69b2e74dcad3d363c74f62 | [
"JavaScript"
] | 1 | JavaScript | zbb1211/myvuedemo | a4d25f6b02be4de6803a63a91735d48e708b4b4c | d60dcd8fee61703132016035feba0fad5aa8e5a6 |
refs/heads/master | <repo_name>Tipster74743/QCard<file_sep>/src/pages/signup/signup.component.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { OAuthService } from 'angular-oauth2-oidc';
import { UserService } from "../../services/userService";
import { LoginPage } from "../login/login.component";
import { OktaService } from "../../services/oktaService";
import { HomePage } from "../home/home";
@Component({
selector: 'signup',
templateUrl: 'signup.component.html'
})
export class SignUpPage {
private user = {
firstName: '',
lastName: '',
phone: '',
email: '',
password: ''
};
constructor(private navCtrl: NavController,
private oktaService: OktaService,
private userService: UserService) {
}
register(): void {
this.oktaService.register(this.user)
.then(user => {
this.userService.setProfile(user);
this.navCtrl.push(HomePage);
})
.catch(error => {
console.log(error);
});
}
login() {
this.navCtrl.push(LoginPage);
}
}
<file_sep>/src/services/oktaService.ts
import { Injectable } from "@angular/core";
import { Http, Headers, RequestOptions } from "@angular/http";
@Injectable()
export class OktaService {
private loginUrl: string = 'https://dev-582651.oktapreview.com/api/v1/users';
private api_token: string = '<KEY>';
constructor(private http: Http) {}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
register(userData) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Authorization', `SSWS ${this.api_token}`);
let body = {
"profile": {
"firstName": userData.firstName,
"lastName": userData.lastName,
"email": userData.email,
"login": userData.email,
"mobilePhone": userData.phone
},
"credentials": {
"<PASSWORD>": {
"value": <PASSWORD>
}
}
};
let options = new RequestOptions({ headers: headers });
return this.http.post(this.loginUrl, body, options)
.toPromise()
.then(response => response.json().profile)
.catch(this.handleError)
}
}
<file_sep>/src/services/userService.ts
import { Injectable } from "@angular/core";
@Injectable()
export class UserService {
private _user = {};
constructor() {
}
public setProfile(profile) {
this._user = {
email: profile.login,
name: `${profile.firstName} ${profile.lastName}`,
timeZone: profile.timeZone
}
}
get user() {
return this._user;
}
}
<file_sep>/src/pages/home/home.ts
import { Component } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { NavController } from "ionic-angular";
import { LoginPage } from "../login/login.component";
import { UserService } from "../../services/userService";
@Component({
selector: 'home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,
public userService: UserService,
public oauthService: OAuthService) {
}
logout() {
this.oauthService.logOut();
this.navCtrl.setRoot(LoginPage);
this.navCtrl.popToRoot();
}
get user() {
return this.userService.user;
}
}
<file_sep>/README.md
*Substitute ios for android if not on a Mac.*
# Temp
This project was generated with [Ionic](https://ionicframework.com/getting-started/)
## Setting up
After cloning the repository Run
`npm install`
You may also need to run
`npm install -g ionic`
## Development server
Run `ionic serve` for a dev server. Navigate to `http://localhost:8100`. The app will automatically reload if you change any of the source files.
## Build
Run
```
ionic cordova run android --prod --release
```
# or
```
ionic cordova build android --prod --release
```
## Running on Mobile
Run a production build of your app with `ionic cordova build ios --prod`
Open the .xcodeproj file in platforms/ios/ in Xcode
Connect your phone via USB and select it as the run target
Click the play button in Xcode to try to run your app
| c90bb14ca4a37943d294e00200d23c2a345af383 | [
"Markdown",
"TypeScript"
] | 5 | TypeScript | Tipster74743/QCard | 68a774ee3bf0049a2525bd7ab23ae0f19adac075 | fc6d65c081615aa709300b7383666d4f23124f0b |
refs/heads/master | <file_sep>"use strict";
//----- Класс сохранения и открытия файлов
class AJAXStorage {
constructor(varName, updList, disBtns, enBtns) {
let self = this;
self.varName = varName;
self.storage = {};
self.updList = updList;
self.disBtns = disBtns;
self.enBtns = enBtns;
function restoreInfo() {
$.ajax(
{
url : ajaxHandlerScript, type : 'POST', cache : false, dataType:'json',
data : { f : 'READ', n : varName },
success : readReady, error : errorHandler, complete: updList
}
);
}
function readReady(callresult) {
if ( callresult.error!=undefined )
console.log(callresult.error);
else if ( callresult.result!="" ) {
self.storage = JSON.parse(callresult.result);
}
}
restoreInfo();
}
addValue(key, value) {
let self = this;
if (key in self.storage) {
repeatName = true;
}
self.storage[key] = value;
function storeInfo() {
updatePassword=<PASSWORD>();
$.ajax( {
url : ajaxHandlerScript, type : 'POST', cache : false, dataType:'json',
data : { f : 'LOCKGET', n : self.varName, p : updatePassword },
success : lockGetReady, error : errorHandler, complete: self.updList
}
);
}
function lockGetReady(callresult) {
if ( callresult.error != undefined )
console.log(callresult.error);
else {
let storage = self.storage;
$.ajax( {
url : ajaxHandlerScript, type : 'POST', cache : false, dataType:'json',
data : { f : 'UPDATE', n : self.varName, v : JSON.stringify(storage), p : updatePassword },
success : updateReady, error : errorHandler
}
);
}
}
function updateReady(callresult) {
if ( callresult.error != undefined )
console.log(callresult.error);
}
storeInfo();
}
getValue(key) {
if (key in this.storage) {
return this.storage[key];
} else {
return undefined;
}
}
deleteValue(key) {
let self = this;
if (key in self.storage) {
delete self.storage[key];
function storeInfo() {
updatePassword = <PASSWORD>();
$.ajax( {
url : ajaxHandlerScript, type : 'POST', cache : false, dataType:'json',
data : { f : 'LOCKGET', n : self.varName, p : updatePassword },
success : lockGetReady, error : errorHandler,
beforeSend : self.disBtns, complete : self.enBtns
}
);
}
function lockGetReady(callresult) {
if ( callresult.error != undefined )
console.log(callresult.error);
else {
let storage = self.storage;
$.ajax( {
url : ajaxHandlerScript, type : 'POST', cache : false, dataType:'json',
data : { f : 'UPDATE', n : self.varName, v : JSON.stringify(storage), p : updatePassword },
success : updateReady, error : errorHandler,
}
);
}
}
function updateReady(callresult) {
if ( callresult.error != undefined )
console.log(callresult.error);
}
storeInfo();
return true;
} else {
return false;
}
}
getKeys() {
return Object.keys(this.storage);
}
}<file_sep># Simple-SVG-editor | 20154e904cbc6b45016d8b1732f1e360384b9816 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | SergeiDragun/Simple-SVG-editor | 732c5c53716c30aa1c27987438087f02b2dd677e | 2a71b06acc2bf5f6ee60e699c0c3c2220cb02276 |
refs/heads/master | <repo_name>gjmolter/ivetravelled-world<file_sep>/components/Combobox.js
import { useState, useEffect } from "react";
import {
Combobox,
ComboboxInput,
ComboboxPopover,
ComboboxList,
ComboboxOption,
} from "@reach/combobox";
import "@reach/combobox/styles.css";
import { worldJSON } from "../utils/mapData";
const ComboBox = ({ selectedCountry, selectedList = [] }) => {
const [term, setTerm] = useState("");
const [results, setResults] = useState(worldJSON);
useEffect(() => {
var tempCountries = worldJSON.filter((country) => {
return (
country.name.toLowerCase().includes(term.trim().toLowerCase()) &&
!selectedList.includes(country.id.toLowerCase())
);
});
setResults(tempCountries);
}, [term]);
return (
<Combobox
onSelect={(item) => {
selectedCountry(item);
setTerm("");
}}
className="comboInputWrapper"
>
<ComboboxInput
value={term}
onChange={(e) => setTerm(e.target.value)}
selectOnClick
className="addCountryInput"
placeholder="Add Country..."
/>
{results && (
<ComboboxPopover className="comboPopOver">
{results.length > 0 ? (
<ComboboxList>
{results.map((country, index) => (
<ComboboxOption
key={index}
value={country.name}
className="comboOption"
>
<span style={{ marginRight: "8px" }}>{country.flag}</span>
{country.name}
</ComboboxOption>
))}
</ComboboxList>
) : (
<span style={{ display: "block", margin: 8 }}>
No results found
</span>
)}
</ComboboxPopover>
)}
<style jsx global>{`
.addCountryInput {
width: 240px;
margin: 10px;
border: none;
background: none;
color: white;
font-size: 18px;
padding: 5px;
}
.addCountryInput:focus {
outline: none;
}
.comboPopOver {
margin-top: 14px;
margin-left: -5px;
z-index: 10;
background: #2d2d2d;
color: white;
max-height: 200px;
overflow: scroll;
-ms-overflow-style: none;
scrollbar-width: none;
}
.comboPopOver::-webkit-scrollbar {
display: none; /* Safari and Chrome */
}
.comboOption:hover,
[data-reach-combobox-option][aria-selected="true"] {
background: #46e992;
color: #2d2d2d;
font-weight: bold;
}
.comboBox:focus {
outline: none;
}
@media only screen and (max-width: 768px) {
.addCountryInput,
.comboInputWrapper {
width: 90%;
font-size: 14px;
text-align: center;
}
}
`}</style>
</Combobox>
);
};
export default ComboBox;
<file_sep>/components/YouveTravelled.js
import { useEffect, useState } from "react";
import {
monarchies,
getCountryById,
worldLand,
europeanUnion,
sevenWondersNew,
sevenWondersOld,
} from "../utils/mapData";
const YouveTravelled = ({ countries }) => {
const [currentDisplay, setCurrentDisplay] = useState("land");
const [displayPercentage, setDisplayPercentage] = useState(0);
useEffect(() => {
switch (currentDisplay) {
case "land":
var landPercentage = 0;
countries.forEach((country) => {
landPercentage += getCountryById(country).land;
});
setDisplayPercentage(landPercentage / worldLand);
break;
case "monarchies":
var monCount = 0;
countries.forEach((country) => {
if (monarchies.includes(country)) monCount++;
});
setDisplayPercentage((monCount / monarchies.length) * 100);
break;
case "eu":
var euCount = 0;
countries.forEach((country) => {
if (europeanUnion.includes(country)) euCount++;
});
setDisplayPercentage((euCount / europeanUnion.length) * 100);
break;
case "7old":
var wonderCount = 0;
countries.forEach((country) => {
if (sevenWondersOld.includes(country)) wonderCount++;
});
setDisplayPercentage((wonderCount / sevenWondersOld.length) * 100);
break;
case "7new":
var wonderCount = 0;
countries.forEach((country) => {
if (sevenWondersNew.includes(country)) wonderCount++;
});
setDisplayPercentage((wonderCount / sevenWondersNew.length) * 100);
break;
default:
setDisplayPercentage(0);
break;
}
}, [countries, currentDisplay]);
function handleSelectChange(event) {
setCurrentDisplay(event.target.value);
}
return (
<>
<div className="panels percentage">
<p>
You've travelled{" "}
<strong>
{displayPercentage > 0 ? displayPercentage.toFixed(1) : 0}%
</strong>{" "}
of the{" "}
<select
value={currentDisplay}
onChange={handleSelectChange}
className="selectDisplay"
>
<option value="land">World Land</option>
<option value="eu">European Union</option>
<option value="7old">Ancient 7 Wonders</option>
<option value="7new">New 7 Wonders</option>
<option value="monarchies">World Monarchies</option>
</select>
</p>
</div>
<style jsx>{`
.selectDisplay {
border: 1px solid #46e992;
border-radius: 5px;
background: no-repeat;
color: white;
font-size: 17px;
appearance: none;
padding: 3px 7px;
margin-left: 2px;
}
.selectDisplay:focus {
outline: none;
}
.selectDisplay option {
background: #2d2d2d;
color: white;
}
.percentage {
right: -1px;
width: 400px;
top: 119px;
border-radius: 0 0 0 20px;
height: 50px;
align-items: center;
}
.percentage p {
margin: 0;
}
.percentage strong {
color: #46e992;
}
@media only screen and (max-width: 768px) {
.percentage {
width: 100% !important;
right: 0 !important;
border-radius: 0 !important;
}
.percentage > p,
.percentage select {
font-size: 13px;
}
}
`}</style>
</>
);
};
export default YouveTravelled;
<file_sep>/README.md
This is a little side-project I have created, and there is a very simple explanation to why it exists:
### I ❤ Geography!
If you think it could be improved in any way, go ahead and make a Pull Request!
<file_sep>/components/Tooltip.js
import { useState, useEffect } from "react";
const Tooltip = ({ text = "", offsetX = 0, offsetY = 0, children }) => {
const [xPos, setXPos] = useState(0);
const [yPos, setYPos] = useState(0);
function getTooltipPosition({ clientX: xPosition, clientY: yPosition }) {
setXPos(xPosition);
setYPos(yPosition);
}
useEffect(() => {
if (text !== "") {
window.addEventListener("mousemove", getTooltipPosition);
} else {
window.removeEventListener("mousemove", getTooltipPosition);
}
return () => {
if (text !== "") {
window.removeEventListener("mousemove", getTooltipPosition);
}
};
}, [text]);
return (
<div
style={{
display: text !== "" ? "block" : "none",
position: "fixed",
top: yPos + offsetY,
left: xPos + offsetX,
zIndex: 10,
pointerEvents: "none",
whiteSpace: "nowrap",
}}
>
<span className="tooltip">{text}</span>
<style jsx>{`
.tooltip {
background: #363533bb;
padding: 4px 7px;
border-radius: 5px;
color: #46e992;
font-size: 12px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
`}</style>
</div>
);
};
export default Tooltip;
<file_sep>/components/Toast.js
const Toast = ({ text }) => {
return (
<div
style={{
position: "absolute",
bottom: text !== "" ? "50px" : "-40px",
right: "calc(50vw - 100px)",
width: "200px",
textAlign: "center",
padding: "6px",
background: "#373534d6",
fontSize: "15px",
borderRadius: "10px",
color: "#46e992",
transition: "bottom 200ms ease",
zIndex: "1",
}}
>
{text}
</div>
);
};
export default Toast;
| a743d2260306be6fc3d5b6e3f8ed8661dc6b6baa | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | gjmolter/ivetravelled-world | e5c637784d9f90950bf16f5199953661d082a128 | a850135eff841323c1906f36dea0dc50f0d0f2c9 |
refs/heads/master | <file_sep>asgiref==3.2.3
beautifulsoup4==4.8.2
certifi==2019.11.28
chardet==3.0.4
dj-database-url==0.5.0
Django==3.0.3
django-heroku==0.3.1
django-webpack-loader==0.6.0
gunicorn==20.0.4
idna==2.8
numpy==1.18.1
pandas==0.25.3
psycopg2==2.7.5
psycopg2-binary==2.8.4
python-dateutil==2.8.1
pytz==2019.3
requests==2.22.0
six==1.14.0
soupsieve==1.9.5
sqlparse==0.3.0
urllib3==1.25.8
whitenoise==5.0.1
<file_sep>from django.shortcuts import render
from django.http import Http404
from .models import Channel
def index(request):
msg = 'My Message'
return render(request, 'index.html', {'message': msg})
def rank(request):
channels = Channel.objects.filter(published_at__isnull=False).filter().order_by('-published_at')
return render(request, 'rank.html', {'channels': channels})
def category_rank(request, category):
channels = Channel.objects.filter(published_at__isnull=False).order_by('-published_at')
return render(request, 'rank.html', {'channels': channels, 'category': category})
def community(request):
return render(request, 'community.html')
def error(request):
raise Http404("Not Found")
<file_sep>from django.contrib import admin
from .models import Channel
from .models import CommonCode
admin.site.register(Channel)
admin.site.register(CommonCode)<file_sep># MukGo: 먹방에 대한 고찰
## 개발 환경 설정
### 1. PC 설치 항목
#### a. 파이썬 3.7.6 설치
<https://www.python.org/downloads/release/python-376/>
#### b. Git 설치
<https://git-scm.com/>
#### c. PyCharm 설치
<https://www.jetbrains.com/pycharm/>
### 2. 계정 생성 항목
#### a. Github 계정 생성
www.github.com
### 3. Python 가상 환경 설정
#### a. Python Virtual Environmnet 생성
<http://pythonstudy.xyz/python/article/302-%EA%B0%80%EC%83%81-%ED%99%98%EA%B2%BD>
파이썬 설치한 경로에서 실행
Mac OS
pyvenv ~/venv1
python3.7 -m venv ~/venv2
Windows OS
C:\Python35> python Tools\scripts\pyvenv.py C:\PyEnv\venv1
C:\>c:\Python35\python -m venv c:\path\to\venv1
#### b. Activate Virtual Environment
파이썬 설치한 경로에서 실행
Mac OS
. ~/venv1/bin/activate
Windows OS
C:\PyEnv\venv1> Scripts\activate.bat
#### c. 가상 환경에 Django 설치
<http://pythonstudy.xyz/python/article/303-Django-%EC%84%A4%EC%B9%98>
pip install django
### 4. 로컬 개발환경 설정
#### a. Gihub 개인 계정에서 https://github.com/chungkang/mukgo 프로젝트 fork
#### b. fork한 프로젝트 로컬로 clone
git clone 'fork한 프로젝트 URL'
ex) git clone https://github.com/MukGo/mukgo.git
#### c. 프로젝트에서 필요한 라이브러리 설치
가상환경에서 해당 프로젝트 root 디렉토리 진입
pip install -r requirements.txt
#### d. 로컬 서버 가동
프로젝트 root 디렉토리 진입
./manage.py runserver
### 5. Github를 사용한 협업 방법
Git의 사용법에 대해서는 '누구나 쉽게 이해할 수 있는 Git 입문' 참고
<https://backlog.com/git-tutorial/kr/>
#### a. branch 생성
자신의 브랜치 확인
git branch
개발 일감에 맞는 브랜치 생성
git branch <branchname>
브랜치 전환
git checkout <branchname>
#### b. 로컬에서 commit 하고 원격 저장소로 push하기
PyCharm을 사용해서 개발
git staging 확인
git status
개발한 내용 add
git add 작업파일명
(전체를 add 할 경우) git add .
개발한 내용 commit
git commit -m "설명을 추가"
#### c. 자신의 원격 저장소에 push
해당 브랜치 자신의 원격 저장소로 push
git push --set-upstream origin 브랜치명
** git push 전에 github 계정 로그인
자신의 깃허브 해당 원격 저장소에서 Compare&pull request 클릭하여 upstream 저장소로 전송
## 참고 자료
Django 프로젝트 이해
http://pythonstudy.xyz/python/article/301-Django-%EC%86%8C%EA%B0%9C
https://wikidocs.net/6600
웹에 대한 이해
https://opentutorials.org/course/1688/9334
https://opentutorials.org/course/1688/9408
Python pip 패키지 관리자
http://pythonstudy.xyz/python/article/504-pip-%ED%8C%A8%ED%82%A4%EC%A7%80-%EA%B4%80%EB%A6%AC%EC%9E%90
Git 이란
https://opentutorials.org/course/307/2475
Github
https://github.com/
Github 사용법
https://backlog.com/git-tutorial/kr/intro/intro2_4.html
<file_sep>from django.db import models
from django.utils import timezone
class Channel(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
url = models.CharField(max_length=100)
crawling_url = models.CharField(max_length=100)
gender = models.CharField(max_length=10)
subscribers = models.IntegerField()
genre = models.CharField(max_length=200)
thumbnail = models.CharField(max_length=4000, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_at = timezone.now()
self.save()
def __str__(self):
return self.title
class CommonCode(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
code_group = models.CharField(max_length=100)
code = models.CharField(max_length=100)
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_at = timezone.now()
self.save()
def __str__(self):
return self.name | 2557c615434d65a62148cb06e2eebd2fc923786c | [
"Markdown",
"Python",
"Text"
] | 5 | Text | chungkang/mukgo | 6d351f2b25ea1f4c3b61d70f304121923d39f426 | f8684494e63820fff9dd55562a539435b1d39629 |
refs/heads/master | <file_sep>//Main redux action file that imports all other action files and exports them for use with reducers
import * as matchActions from './match';
export {
matchActions
};
<file_sep>import React from 'react';
import Avatar from 'material-ui/Avatar';
import person1 from '../../../content/ma-long.jpg';
import person2 from '../../../content/fan-zhendong.jpg';
class PlayerInfo extends React.Component {
render() {
var {player, playerInformation} = this.props;
var classNames = "player-information ";
classNames += player == 1 ? "player1" : "player2"
return (
<div className={classNames}>
<div className="player-identity">
<Avatar
src={player == 1 ? person1 : person2}
style={{
width: '100%',
height: '100%'
}}
/>
<h2 className="player-name">{playerInformation.name}</h2>
</div>
</div>
);
}
};
export default PlayerInfo;
<file_sep>export var matchReducer = (state = {}, action) => {
switch(action.type) {
case "START_MATCH":
return {
playerInformation: action.playerInformation,
scores: [{
player: 1,
gameScores: [0],
matchScore: 0
},
{
player: 2,
gameScores: [0],
matchScore: 0
}],
questionAnswers: [{
game: 1,
points: [[]]
}]
}
case "ADD_POINT":
var scores = state.scores;
var questionAnswers = state.questionAnswers;
questionAnswers[action.gameInMatch].points.push([]);
scores[action.winner].gameScores[action.gameInMatch]++;
return {
playerInformation: state.playerInformation,
questionAnswers: state.questionAnswers,
scores: scores
}
case "ADD_GAME":
var scores = state.scores;
var questionAnswers = state.questionAnswers;
scores[action.winner].matchScore++;
scores[action.winner].gameScores.push(0);
if(action.winner == 0) {
scores[action.winner+1].gameScores.push(0);
} else {
scores[action.winner-1].gameScores.push(0);
}
questionAnswers.push({
game: action.gameInMatch,
points: [[]]
})
return {
playerInformation: state.playerInformation,
questionAnswers: questionAnswers,
scores: scores
}
case "ADD_ANSWER":
var questionAnswers = state.questionAnswers;
// console.log(questionAnswers, action.gameInMatch)
questionAnswers[action.gameInMatch].points[action.pointInGame].push("");
questionAnswers[action.gameInMatch].points[action.pointInGame][action.question] = action.answer;
return {
playerInformation: state.playerInformation,
scores: state.scores,
questionAnswers: questionAnswers
}
default:
return state
}
};
<file_sep>import React from 'react';
import {Link} from 'react-router-dom';
import Match from '../Match/Match';
import RaisedButton from 'material-ui/RaisedButton';
class LandingPage extends React.Component {
render() {
return (
<div className="landing-page-container">
<Link to={"/match"}>
<RaisedButton label="Start New Match" primary={true} />
</Link>
</div>
);
}
};
export default LandingPage;
<file_sep>import React from 'react';
import PlayerInfo from './PlayerInfo';
import Scores from './Scores';
class MatchInformation extends React.Component {
render() {
var {server, scores, playerInformation} = this.props;
return (
<div className="match-information">
<PlayerInfo player={1} playerInformation={playerInformation[0]} />
<Scores server={server} scores={scores} playerInformation={playerInformation} />
<PlayerInfo player={2} playerInformation={playerInformation[1]} />
</div>
);
}
};
export default MatchInformation;
<file_sep>//Main redux reducer file that imports all other reducer files and exports them for use with redux store
import {matchReducer} from './match';
export {
matchReducer
};
<file_sep>import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import Dialog from 'material-ui/Dialog';
import SelectField from 'material-ui/SelectField';
import {Link} from 'react-router-dom';
class Navigation extends React.Component {
constructor(props) {
super(props);
this.state = {
gameSettingsOpen: false,
resetMatchDialog: false,
endMatchDialog: false
}
this.toggleGameSettings = this.toggleGameSettings.bind(this);
this.toggleResetMatchDialog = this.toggleResetMatchDialog.bind(this);
this.toggleEndMatchDialog = this.toggleEndMatchDialog.bind(this);
this.handleQuestionComplexityChange = this.handleQuestionComplexityChange.bind(this);
this.changeGamesToWin = this.changeGamesToWin.bind(this);
this.resetMatch = this.resetMatch.bind(this);
}
toggleGameSettings() {
this.setState({
gameSettingsOpen: !this.state.gameSettingsOpen
})
}
toggleResetMatchDialog() {
this.setState({
resetMatchDialog: !this.state.resetMatchDialog
})
}
toggleEndMatchDialog() {
this.setState({
endMatchDialog: !this.state.endMatchDialog
})
}
handleQuestionComplexityChange(event, index, value) {
this.props.changeQuestionComplexity(value);
}
changeGamesToWin(event, index, value) {
this.props.changeGamesToWin(value);
}
resetMatch() {
this.props.resetMatch();
this.setState({
resetMatchDialog: false
})
}
render() {
var {gameSettingsOpen, resetMatchDialog, endMatchDialog} = this.state;
var {questionComplexity, gamesToWin} = this.props;
const gameSettingsActions = [
<FlatButton
label="Close"
primary={true}
onTouchTap={this.toggleGameSettings}
/>
]
const resetMatchActions = [
<FlatButton
label="Submit"
primary={true}
onTouchTap={this.resetMatch}
/>,
<FlatButton
label="Cancel"
secondary={true}
onTouchTap={this.toggleResetMatchDialog}
/>
]
const endMatchActions = [
<Link to={"/"}>
<FlatButton
label="Submit"
primary={true}
/>
</Link>,
<FlatButton
label="Cancel"
secondary={true}
onTouchTap={this.toggleEndMatchDialog}
/>
]
return (
<div className="navigation">
<IconMenu
iconButtonElement={<IconButton style={{width: '100%'}}><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
style={{width: '100%'}}
>
<MenuItem primaryText="Game Settings" onClick={this.toggleGameSettings} />
<MenuItem primaryText="Restart Match" onClick={this.toggleResetMatchDialog} />
<MenuItem primaryText="End Match" onClick={this.toggleEndMatchDialog} />
</IconMenu>
<Dialog
title="Game Settings"
actions={gameSettingsActions}
open={gameSettingsOpen}
onRequestClose={this.toggleGameSettings}
>
<SelectField
floatingLabelText="Question Complexity"
value={questionComplexity}
onChange={this.handleQuestionComplexityChange}
>
<MenuItem value={1} primaryText="All Questions" />
<MenuItem value={2} primaryText="Simple Analysis" />
<MenuItem value={3} primaryText="No Analysis" />
</SelectField>
<SelectField
floatingLabelText="Games Per Match"
value={gamesToWin}
onChange={this.changeGamesToWin}
>
<MenuItem value={3} primaryText="Best of 5" />
<MenuItem value={4} primaryText="Best of 7" />
</SelectField>
</Dialog>
<Dialog
title="Reset Match?"
actions={resetMatchActions}
open={resetMatchDialog}
onRequestClose={this.toggleResetMatchDialog}
>
</Dialog>
<Dialog
title="End Match?"
actions={endMatchActions}
open={endMatchDialog}
onRequestClose={this.toggleEndMatchDialog}
>
</Dialog>
</div>
);
}
};
export default Navigation;
<file_sep>import React from 'react';
import {connect} from 'react-redux';
import {matchActions} from 'actions';
import RaisedButton from 'material-ui/RaisedButton';
import FontIcon from 'material-ui/FontIcon';
import Slider from 'material-ui/Slider';
import Snackbar from 'material-ui/Snackbar';
import questions from '../../api/questions';
class Questions extends React.Component {
constructor(props) {
super(props);
this.state = {
step: 0,
questions: questions,
sliderValue: 0.5,
sliderDescription: "Balanced",
selectedStarNumber: 0,
pointWinner: 1,
gamePoint: 0,
nextPointIndication: false
}
this.incrementStep = this.incrementStep.bind(this);
this.incrementStepSimple = this.incrementStepSimple.bind(this);
this.incrementStepBasic = this.incrementStepBasic.bind(this);
this.handleSliderValue = this.handleSliderValue.bind(this);
}
componentWillReceiveProps(nextProps) {
if(nextProps.resetPoint && nextProps.resetPoint != this.props.resetPoint) {
this.setState({
step: 0
})
}
}
incrementStep(questionAnswer) {
var step = this.state.step;
var gamePoint = this.state.gamePoint;
if(step === 8 || step === 9) {
this.setState({
selectedStarNumber: questionAnswer+1
})
setTimeout(() => {
this.setState({
step: ++step,
selectedStarNumber: 0
})
}, 300)
} else if (step === 10) {
this.props.nextPoint(this.state.pointWinner, ++this.state.gamePoint);
this.setState({
nextPointIndication: true
})
setTimeout(() => {
this.setState({
step: 0,
gamePoint: ++gamePoint,
nextPointIndication: false
})
}, 300)
} else if (step == 0) {
this.setState({
step: ++step,
pointWinner: questionAnswer
})
} else {
this.setState({
step: ++step
})
}
}
incrementStepSimple(questionAnswer) {
var step = this.state.step;
var gamePoint = this.state.gamePoint;
if (step === 6) {
this.props.nextPoint(this.state.pointWinner, ++this.state.gamePoint);
this.setState({
nextPointIndication: true
})
setTimeout(() => {
this.setState({
step: 0,
gamePoint: ++gamePoint,
nextPointIndication: false
})
}, 300)
} else if (step == 0) {
this.setState({
step: ++step,
pointWinner: questionAnswer
})
} else {
this.setState({
step: ++step
})
}
}
incrementStepBasic(questionAnswer) {
var step = this.state.step;
var gamePoint = this.state.gamePoint;
this.props.nextPoint(questionAnswer, ++this.state.gamePoint);
this.setState({
gamePoint: ++gamePoint
})
}
handleSliderValue(event, value) {
var sliderDescription = "";
if(value === 0) {
sliderDescription = "Shutdown";
} else if (value === 0.25) {
sliderDescription = "Understimulated";
} else if (value === 0.5) {
sliderDescription = "Balanced";
} else if (value === 0.75) {
sliderDescription = "Overstimulated";
} else if (value === 1.0) {
sliderDescription = "Overwhelmed"
}
this.setState({
sliderValue: value,
sliderDescription: sliderDescription
});
}
render() {
var {questions, step, sliderValue, sliderDescription, selectedStarNumber, nextPointIndication} = this.state;
var {questionComplexity, gameInMatch, pointInGame} = this.props;
const renderQuestions = () => {
return (
<h2 className="question-title">{questions[step].question}</h2>
)
}
const renderComplexAnswers = () => {
var finalJSX = [];
if(step >= 0 && step <=7) {
questions[step].answers.forEach((answer, i) => {
finalJSX.push(<RaisedButton label={answer} labelStyle={{fontSize: '2vw', width: '100%', padding: '0'}} onClick={() => {
if(step == 0) {
this.props.dispatch(matchActions.addAnswer(pointInGame-1, gameInMatch-1, step, i))
this.incrementStep(answer == "Me" ? 1 : 2);
} else {
this.props.dispatch(matchActions.addAnswer(pointInGame-1, gameInMatch-1, step, i))
this.incrementStep();
}
}} key={answer} className="question-answer"/>)
})
} else if (step == 8 || step == 9) {
for(let i = 0; i<selectedStarNumber; i++) {
finalJSX.push(<FontIcon key={i} className="material-icons" style={{fontSize: '6rem', marginLeft: '5%'}}>star</FontIcon>)
}
for(let i = selectedStarNumber; i<5; i++) {
finalJSX.push(<FontIcon key={i} onClick={() => {
this.props.dispatch(matchActions.addAnswer(pointInGame-1, gameInMatch-1, step, i))
this.incrementStep(i)
}} className="material-icons" style={{fontSize: '6rem', marginLeft: '5%'}}>star_border</FontIcon>)
}
} else if (step == 10) {
finalJSX.push(
<div className="slider-container">
<Slider step={0.25} value={sliderValue} onChange={this.handleSliderValue} style={{width: '80%', marginLeft: '10%'}}/>
<p className="slider-description">{sliderDescription}</p>
<RaisedButton className="next-question-button" label="Next Point" primary={true} onClick={() => {
this.props.dispatch(matchActions.addAnswer(pointInGame-1, gameInMatch-1, step, sliderValue))
this.incrementStep()
}} />
<Snackbar
open={true}
message="Add notes for point before clicking next point!"
autoHideDuration={3000}
/>
</div>
)
}
return finalJSX;
}
const renderSimpleAnswers = () => {
var finalJSX = [];
questions[step].answers.forEach((answer, i) => {
finalJSX.push(<RaisedButton label={answer} labelStyle={{fontSize: '2vw', width: '100%', padding: '0'}} onClick={() => {
if(step == 0) {
this.props.dispatch(matchActions.addAnswer(pointInGame-1, gameInMatch-1, step, i))
this.incrementStepSimple(answer == "Me" ? 1 : 2);
} else {
this.props.dispatch(matchActions.addAnswer(pointInGame-1, gameInMatch-1, step, i))
this.incrementStepSimple();
}
}} key={answer} className="question-answer"/>)
})
return finalJSX;
}
const renderBasicAnswer = () => {
var finalJSX = [];
questions[step].answers.forEach((answer, i) => {
finalJSX.push(<RaisedButton label={answer} labelStyle={{fontSize: '2vw', width: '100%', padding: '0'}} onClick={() => {
if(step == 0) {
this.props.dispatch(matchActions.addAnswer(pointInGame-1, gameInMatch-1, step, i))
this.incrementStepBasic(answer == "Me" ? 1 : 2);
} else {
this.props.dispatch(matchActions.addAnswer(pointInGame-1, gameInMatch-1, step, i))
this.incrementStepBasic();
}
}} key={answer} className="question-answer"/>)
})
return finalJSX;
}
const renderCorrectQuestionSet = () => {
if(questionComplexity == 1) {
return (
<div>
{renderQuestions()}
{renderComplexAnswers()}
</div>
)
} else if (questionComplexity == 2) {
return (
<div>
{renderQuestions()}
{renderSimpleAnswers()}
</div>
)
} else if (questionComplexity == 3) {
return (
<div>
{renderQuestions()}
{renderBasicAnswer()}
</div>
)
}
}
const renderNextPointIndication = () => {
return (
<h2 className="next-point-indication">Next Point</h2>
)
}
const renderCorrectScreen = () => {
var finalJSX = [];
if(nextPointIndication) {
finalJSX.push(<div>{renderNextPointIndication()}</div>)
} else {
finalJSX.push(<div>{renderCorrectQuestionSet()}</div>)
}
return finalJSX;
}
return (
<div className="questions">
{renderCorrectScreen()}
</div>
);
}
};
export default connect(
(state) => {
return state;
}
)(Questions);
<file_sep>module.exports = {
playerInformation: [{
player: 1,
name: "<NAME>",
rating: 2000,
record: "1-0"
},
{
player: 2,
name: "<NAME>",
rating: 1950,
record: "2-1"
}],
questionAnswers: [{
game: 1,
answers: []
}]
}
<file_sep>//Configures Redux store used to manage react component state
//Exports configuration function, which allows Root component to configure the store
var redux = require('redux');
var thunk = require('redux-thunk').default;
var {matchReducer} = require('../reducers/index');
//Configuration function exported and used by Root component
export var configure = (initialState = {}) => {
//Creates main reducer using the various reducer files
var reducer = redux.combineReducers({
match: matchReducer
});
//Creates the redux store using the main reducer and applies thunk and websocket middleware
var store = redux.createStore(reducer, initialState, redux.compose(
redux.applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
));
return store;
};
<file_sep>Table Tennis progressive web application for creating tournaments and matches with websocket viewing and match analysis
<file_sep>//Redux actions for current User including calls to api file
import {userAPI} from '../api/api';
export var startMatch = (playerInformation) => {
return {
type: "START_MATCH",
playerInformation
}
}
export var addPoint = (winner, gameInMatch) => {
return {
type: "ADD_POINT",
winner,
gameInMatch
}
}
export var addGame = (winner, gameInMatch) => {
return {
type: "ADD_GAME",
winner,
gameInMatch
}
}
export var addAnswer = (pointInGame, gameInMatch, question, answer) => {
return {
type: "ADD_ANSWER",
pointInGame,
gameInMatch,
question,
answer
}
}
<file_sep>import React from 'react';
import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';
import Checkbox from 'material-ui/Checkbox';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton';
import FileFileDownload from 'material-ui/svg-icons/file/file-download';
import CoinFlip from './CoinFlip';
class PreMatch extends React.Component {
constructor(props) {
super(props);
this.state = {
matchType: 1,
playerInformation: [{
player: 1,
name: "",
rating: "",
record: ""
},
{
player: 2,
name: "",
rating: "",
record: ""
}],
attemptedSubmit: false,
server: 1,
coinFlip: false,
proMenuPlayer: false,
proMenuOpponent: false
}
this.handleMatchTypeChange = this.handleMatchTypeChange.bind(this);
this.handlePlayerInformation = this.handlePlayerInformation.bind(this);
this.startMatch = this.startMatch.bind(this);
this.setServer = this.setServer.bind(this);
this.setServerCoin = this.setServerCoin.bind(this);
this.toggleCoinFlip = this.toggleCoinFlip.bind(this);
this.quickStart = this.quickStart.bind(this);
this.handleOpenProMenuPlayer = this.handleOpenProMenuPlayer.bind(this);
this.handlePlayerProChange = this.handlePlayerProChange.bind(this);
this.handleOpenProMenuOpponent = this.handleOpenProMenuOpponent.bind(this);
this.handleOpponentProChange = this.handleOpponentProChange.bind(this);
this.addProPlayer = this.addProPlayer.bind(this);
}
handleMatchTypeChange(event, index, value) {
this.setState({
matchType: value
})
}
handlePlayerInformation(event, field) {
var playerInformation = this.state.playerInformation;
if(field == 1) {
playerInformation[0].name = event.target.value;
} else if (field == 2) {
playerInformation[0].rating = event.target.value;
} else if (field == 3) {
playerInformation[0].record = event.target.value;
} else if (field == 4) {
playerInformation[1].name = event.target.value;
} else if (field == 5) {
playerInformation[1].rating = event.target.value;
} else if (field == 6) {
playerInformation[1].record = event.target.value;
}
this.setState({
playerInformation: playerInformation
})
}
startMatch() {
var playerInformation = this.state.playerInformation;
var server = this.state.server;
if(playerInformation[0].name && playerInformation[0].rating && playerInformation[0].record && playerInformation[1].name && playerInformation[1].rating && playerInformation[1].record && (server == 1 || server == 2)) {
this.props.startMatch(playerInformation, server)
} else {
this.setState({
attemptedSubmit: true
})
}
}
setServer(event, isInputChecked, player) {
if(isInputChecked) {
this.setState({
server: player
})
} else {
this.setState({
server: 0
})
}
}
setServerCoin(player) {
this.setState({
server: player
})
}
toggleCoinFlip() {
this.setState({
coinFlip: !this.state.coinFlip
})
}
quickStart() {
var playerInformation = this.state.playerInformation;
var server = this.state.server;
playerInformation[0].name = "Guest Player";
playerInformation[0].rating = "Unrated";
playerInformation[0].record = "0-0";
playerInformation[1].name = "Opponent";
playerInformation[1].rating = "Unrated";
playerInformation[1].record = "0-0";
this.setState({
playerInformation: playerInformation
})
setTimeout(() => {
this.props.startMatch(playerInformation, server);
}, 500)
}
handleOpenProMenuPlayer() {
this.setState({
proMenuPlayer: true
})
}
handlePlayerProChange(value) {
this.setState({
proMenuPlayer: value
})
}
handleOpenProMenuOpponent() {
this.setState({
proMenuOpponent: true
})
}
handleOpponentProChange(value) {
this.setState({
proMenuOpponent: value
})
}
addProPlayer(player, pro) {
var playerInformation = this.state.playerInformation;
if(pro == 1) {
playerInformation[player-1].name = "<NAME>";
playerInformation[player-1].rating = "3437";
playerInformation[player-1].record = "7-player (Jun)";
} else if (pro == 2) {
playerInformation[player-1].name = "<NAME>";
playerInformation[player-1].rating = "3346";
playerInformation[player-1].record = "6-1 (Jun)";
} else if (pro == 3) {
playerInformation[player-1].name = "<NAME>";
playerInformation[player-1].rating = "3129";
playerInformation[player-1].record = "5-1 (Jun)";
} else if (pro == 4) {
playerInformation[player-1].name = "<NAME>";
playerInformation[player-1].rating = "2953";
playerInformation[player-1].record = "2-1 (Jun)";
}
this.setState({
playerInformation: playerInformation
})
}
render() {
var {matchType, playerInformation, attemptedSubmit, server, coinFlip, proMenuPlayer, proMenuOpponent} = this.state;
const coinFlipActions = [
<FlatButton
label="Close"
primary={true}
onTouchTap={this.toggleCoinFlip}
/>
]
return (
<div className="pre-match">
<div className="pre-match-information">
<h2>Match Settings</h2>
<SelectField
floatingLabelText="Match Type"
value={matchType}
onChange={this.handleMatchTypeChange}
>
<MenuItem value={1} primaryText="Singles" />
<MenuItem value={2} primaryText="Doubles - Coming Soon" disabled={true} />
</SelectField>
<RaisedButton label="Quick Start" onTouchTap={this.quickStart} primary={true} className="quick-start-button" />
</div>
<hr />
<div className="pre-match-players-information">
<div className="pre-match-player-information">
<h2 className="pre-match-player-information-header">Player Information</h2>
<TextField
floatingLabelText="Name"
errorText={attemptedSubmit && !playerInformation[0].name ? "This field is required" : ""}
onChange={(event) => this.handlePlayerInformation(event, 1)}
value={playerInformation[0].name ? playerInformation[0].name : ""}
/>
<br/>
<TextField
floatingLabelText="Rating"
errorText={attemptedSubmit && !playerInformation[0].rating ? "This field is required" : ""}
onChange={(event) => this.handlePlayerInformation(event, 2)}
value={playerInformation[0].rating ? playerInformation[0].rating : ""}
/>
<br/>
<TextField
floatingLabelText="Record"
errorText={attemptedSubmit && !playerInformation[0].record ? "This field is required" : ""}
onChange={(event) => this.handlePlayerInformation(event, 3)}
value={playerInformation[0].record ? playerInformation[0].record : ""}
/>
<Checkbox
label="Initial Server"
onCheck={(event, isInputChecked) => this.setServer(event, isInputChecked, 1)}
disabled={server == 2 ? true : false}
checked={server == 1 ? true : false}
/>
<RaisedButton label="Flip A Coin" onTouchTap={this.toggleCoinFlip} primary={true} className="flip-for-server" />
<IconMenu
iconButtonElement={<RaisedButton onTouchTap={this.handleOpenProMenuPlayer} label="Play As a Pro" />}
open={proMenuPlayer}
onRequestChange={this.handlePlayerProChange}
>
<MenuItem value="1" primaryText="<NAME>" onClick={() => this.addProPlayer(1, 1)} />
<MenuItem value="2" primaryText="<NAME>" onClick={() => this.addProPlayer(1, 2)} />
<MenuItem value="3" primaryText="<NAME>" onClick={() => this.addProPlayer(1, 3)} />
<MenuItem value="4" primaryText="<NAME>" onClick={() => this.addProPlayer(1, 4)} />
</IconMenu>
</div>
<div className="pre-match-opponent-information">
<h2 className="pre-match-opponent-information-header">Opponent Information</h2>
<TextField
floatingLabelText="Name"
errorText={attemptedSubmit && !playerInformation[1].name ? "This field is required" : ""}
onChange={(event) => this.handlePlayerInformation(event, 4)}
value={playerInformation[1].name ? playerInformation[1].name : ""}
/>
<br/>
<TextField
floatingLabelText="Rating"
errorText={attemptedSubmit && !playerInformation[1].rating ? "This field is required" : ""}
onChange={(event) => this.handlePlayerInformation(event, 5)}
value={playerInformation[1].rating ? playerInformation[1].rating : ""}
/>
<br/>
<TextField
floatingLabelText="Record"
errorText={attemptedSubmit && !playerInformation[1].record ? "This field is required" : ""}
onChange={(event) => this.handlePlayerInformation(event, 6)}
value={playerInformation[1].record ? playerInformation[1].record : ""}
/>
<Checkbox
label="Initial Server"
onCheck={(event, isInputChecked) => this.setServer(event, isInputChecked, 2)}
disabled={server == 1 ? true : false}
checked={server == 2 ? true : false}
/>
<IconMenu
iconButtonElement={<RaisedButton onTouchTap={this.handleOpenProMenuOpponent} label="Play Against a Pro" />}
open={proMenuOpponent}
onRequestChange={this.handleOpponentProChange}
>
<MenuItem value="1" primaryText="<NAME>" onClick={() => this.addProPlayer(2, 1)} />
<MenuItem value="2" primaryText="<NAME>" onClick={() => this.addProPlayer(2, 2)} />
<MenuItem value="3" primaryText="<NAME>" onClick={() => this.addProPlayer(2, 3)} />
<MenuItem value="4" primaryText="<NAME>" onClick={() => this.addProPlayer(2, 4)} />
</IconMenu>
</div>
</div>
<RaisedButton className="start-match" label="Start Match" fullWidth={true} primary={true} onClick={this.startMatch}/>
<Dialog
actions={coinFlipActions}
open={coinFlip}
onRequestClose={this.toggleCoinFlip}
style={{height: '30%'}}
>
<CoinFlip server={server} setServer={this.setServerCoin} />
</Dialog>
</div>
);
}
};
export default PreMatch;
<file_sep>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import coin_heads from '../../../content/coin-heads.jpg';
import coin_tails from '../../../content/coin-tails.jpg';
class CoinFlip extends React.Component {
constructor(props) {
super(props);
this.state = {
server: this.props.server,
flipping: false
}
this.flipCoin = this.flipCoin.bind(this);
}
flipCoin() {
var server = Math.floor(Math.random() * 2) + 1;
this.setState({
flipping: true
})
setTimeout(() => {
this.props.setServer(server)
this.setState({
server: server,
flipping: false
})
}, 1000)
}
render() {
var {server, flipping} = this.state;
const renderFlipIndicator = () => {
if(flipping) {
return (
<p className="flip-indicator">Flipping...</p>
)
}
}
return (
<div className="coin">
<div className="flipper">
<div className="coin-front" style={server == 2 ? {display: 'none'} : {}}>
<img src={coin_heads} className="coin-heads" style={flipping ? {transition: 'translate 1s', translate: 'rotate(360deg)'} : {}} />
</div>
<div className="coin-back" style={(server == 1 || server == 0) ? {display: 'none'} : {}}>
<img src={coin_tails} className="coin-tails" style={flipping ? {transition: 'translate 1s', translate: 'rotate(360deg)'} : {}} />
</div>
<RaisedButton label="Flip Coin" primary={true} onClick={this.flipCoin} className="flip-coin-button" style={{display: 'inline-block'}} />
{renderFlipIndicator()}
</div>
</div>
);
}
};
export default CoinFlip;
| 4e0626dd1f90c210edbe02b37a943fac956f5416 | [
"JavaScript",
"Markdown"
] | 14 | JavaScript | tttimmusgrove/ttworld | 1da4b846023c97469ab480717e21332441d12e09 | 79d58acd55b914a03ee2f711437bce8fdcaffcd3 |
refs/heads/master | <file_sep>declare module 'mui-icons'
declare module 'mui-icons/cmdi/*'
<file_sep>FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . /usr/src/app
ADD src /usr/src/app/src
RUN yarn
RUN yarn build
CMD ["yarn", "start"]
<file_sep>import { connect, createStore } from 'babydux'
type Store = {
distribution: number
measure: '15_miles' | '20_miles' | '30_miles'
standard: 'time_distance' | 'time' | 'distance'
}
export let store = createStore<Store>({
distribution: 0.5,
measure: '15_miles',
standard: 'time_distance'
}, true)
export let withStore = connect(store)
<file_sep># bayes-mvp [![Build Status][build]](https://circleci.com/gh/bcherny/bayes-mvp) [![apache2]](https://www.apache.org/licenses/LICENSE-2.0)
[build]: https://img.shields.io/circleci/project/bcherny/bayes-mvp.svg?branch=master&style=flat-square
[apache2]: https://img.shields.io/npm/l/bayes-mvp.svg?style=flat-square
> Network adequacy tool for [Bayes Impact](https://github.com/bayesimpact)
## Install
1. Install [NVM](https://github.com/creationix/nvm#installation)
2. Install Node 8: `nvm install v8.1.3`
3. Install [Yarn](https://yarnpkg.com/en/docs/install)
4. Clone this repo: `git clone <EMAIL>:bcherny/bayes-mvp.git`
## Environment
Create a file called ".env" in the root of this repo and define `MAPBOX_TOKEN` in it. For example:
```sh
# contents of .env:
MAPBOX_TOKEN=abcdefg
```
## Run
```sh
cd bayes-mvp/client
yarn
yarn build
yarn start
```
Then, open *https://localhost:9000* in your browser.
## Editor
I suggest editing this project using [VSCode](https://code.visualstudio.com/).
## License
Apache2
| ebdb1899496bf440efff9e57012e8ec590cf9fc7 | [
"Markdown",
"TypeScript",
"Dockerfile"
] | 4 | TypeScript | bcherny/tds-frontend | 3c2fa215b86fb999db340541d1955348eea37053 | 6f161a79f616272eddef4be5079c8c29801158c6 |
refs/heads/master | <repo_name>MarckRDA/primeira-aula<file_sep>/README.md
# Projeto Entra21
### Escrevendo e lendo do console:
//Escrevendo:
Console.WriteLine(texto);
//Lendo:
Console.ReadLine();
### Declarando variáveis e constantes
var text = "meu texto";
string text = "meu texto";
const string text = "meu texto";
### Tipos básicos:
// Tipo numérico
var number = 1;
//Tipo texto/string
var text = "meu texto";
//Tipo booleano/bool
var boolean = true;
//Tipo numérico com ponto flutuante/double:
var price = 4.099;
//Tipo Data/DateTime
var currentDate = DateTime.Now;
### Parsers/ Transformadores
// Transformar um texto/string em um número/int:
var userAge = Int32.Parse(result);
### Operadores de matemática:
// Somar:
1 + 1;
// Subtrair:
1 - 1;
// Dividir:
2 / 1;
// Multiplicar:
1 * 2;
// Resto:
1 % 2;
// vai retornar 1
## Operadores de comparação
### (toda comparação retorna um booleano/bool)
// É igual?
1 == 1;
// Vai retornar true
// É diferente?
1 != 1;
// Vai retornar false
// É diferente?
!(1 == 1)
// Vai retornar false
// Booleano da esquerda é true e o da direita também?
true && true;
// vai retornar true
// Booleano da esquerda é true ou o da direita também?
true || true
// vai retornar true
### Operadores de comparação para números/matemática:
// É maior?
1 > 1;
// Vai retornar false
// É menor?
1 < 1;
// Vai retornar false
// É maior OU igual?
1 >= 1;
// Vai retornar true
// É menor OU igual?
1 <= 1;
// Vai retornar true
### Bloco condicionais:
// Escrevendo olá SOMENTE quando 1 > 0:
if(1 > 0)
{
Console.WriteLine("Olá");
}
// Caso 1 NÃO for maior que 0, e 2 > 1, escreva Boa tarde!
else if (2 > 1)
{
Console.WriteLine("Boa tarde");
}
// Caso NENHUMA das condições anteriores forem verdadeiras, escreva xau!
else
{
Console.WriteLine("Xau");
}
### Comandos do editor Visual Studio Code
Selecionando o texto...
Segurar a tecla shift e utilizar as setas
Comando para comentar:
CTRL + K + C
Comando para desfazer:
CTRL + Z
Comando para refazer:
CTRL + Y
Comando para descomentar:
CTRL + U
Comando para abrir o terminal:
CTRL + '
Comando para entrantrar arquivos:
CTRL + T
### Depurando a aplicação
1. Clicar no ícone da baratinha e depois no botão de engrenagem:
2. Selecionar o texto '.Net Core'.
3. Alterar a opção "console" para "integratedTerminal".
4. Adicionar quantos breakpoint quiser (clicar na esquerda do número da linha).
5. Clicar na baratinha e depois no botão Start(verdinho).
6. Selecionar o terminal (Sair na tab "Debug Console").
7. F10 vai para a próxima linha.
8. F5 para o próxima breakpoint.
9. Shift + F5 para "saltar" a aplicação
10. CTRL + Shift + F5 para reiniciar o debug.
<file_sep>/Program.cs
using System;
namespace primeira_aula
{
class Program
{
static void NumerosCrescentes(string[] args)
{
var count = 1;
while (count >= 10){
System.Console.WriteLine(count);
count++;
}
}
static void NumerosDecrescentes(string[] args)
{
var count = 10;
while (count > 0){
System.Console.WriteLine(count);
count--;
}
}
static void NumerosCrescentesPares(string[] args)
{
var count = 1;
while (count <= 10){
if(count % 2 == 0){
System.Console.WriteLine(count);
}
count++;
}
}
static void SomaDe1a100(string[] args)
{
var count = 1;
int n = 0;
while (count <= 100){
n +=count;
System.Console.WriteLine(n);
count++;
}
}
static void ImparesMenosresQue200(string[] args)
{
int count = 1;
while (count < 200){
if(count % 2 != 0){
System.Console.WriteLine(count);
}
count++;
}
}
static void MediaIdade(string[] args)
{
double sum = 0.0;
double count = 0.0;
while (true)
{
System.Console.WriteLine("Digite uma idade");
var idade = Int32.Parse(System.Console.ReadLine());
if(idade == 0){
break;
}
sum += idade;
count++;
}
System.Console.WriteLine($"A média de idades da turma é" + String.Format("(0:0.00)", sum/count));
}
static void IdadesPercentagemMulheres(string[] args)
{
var age = 0.0;
var womenNames = "";
var count = 0.0;
while (count < 5)
{
System.Console.WriteLine("Digit woman's name: ");
womenNames = System.Console.ReadLine();
System.Console.WriteLine("Digit woman's age: ");
int n = Int32.Parse(System.Console.ReadLine());
if(n >= 18 && n <= 35 ){
age++;
}
count++;
}
System.Console.WriteLine($"A porcentagem de mulher com idades entre 18 e 35 é: {(age/count)*100} ");
}
static void Main(string[] args)
{
var candidates = new string[2];
var option = 0;
var candidate1Vote = 0;
var candidate2Vote = 0;
var counterInputCandidates = 0;
while(true){
System.Console.WriteLine("Selecione o modo de operação da urna:");
System.Console.WriteLine(" 1) Cadastrar candidato/ 2) Votação / 3) Apuração de votos");
option = Int32.Parse(System.Console.ReadLine());
if(option == 1){
System.Console.WriteLine("Por favor, insira a senha: ");
var password = System.Console.ReadLine();
if(password == "<PASSWORD>"){
while(counterInputCandidates < 2){
var intermediateCandidates = System.Console.ReadLine();
candidates[counterInputCandidates] = intermediateCandidates;
counterInputCandidates++;
}
}else{
System.Console.WriteLine("Senha errada!!");
continue;
}
}else if(option == 2){
if(candidates.Length == 0){
System.Console.WriteLine("Por favor, insira os candidados primeiro");
continue;
}
var optionVoteOrExit = 0;
System.Console.WriteLine($"Aperte 1 para o candidato {candidates[0]} ou 2 para o {candidates[1]}. Pressione 0 para encerrar a votação");
while(optionVoteOrExit != 0){
//ToDoAtHome
if(optionVoteOrExit == 1){
}
}
}
}
}
}
}
}
| 0a496e4107b1a63873cfc12c077de5dd813f8d76 | [
"Markdown",
"C#"
] | 2 | Markdown | MarckRDA/primeira-aula | bbba1bcd6a5b39efcb42508c2f9268900ca44261 | fb03e39894cd6aac70916b98c09b7a26a8720388 |
refs/heads/master | <repo_name>makungaj1/e-commerce<file_sep>/middleware/isAdmin.js
module.exports = function(req, res, next) {
// 401 Unauthorized
// 403 Forbidden
const { isAdmin } = req.employee;
if (!isAdmin) return res.status(403).json('Access denied');
next();
};
<file_sep>/models/customer.js
const config = require('config');
const Joi = require('joi');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const customerSchema = new mongoose.Schema({
firstName: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
lastName: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
sex: {
type: String,
required: true,
minlength: 1,
maxlength: 10
},
email: {
type: String,
required: true,
unique: true
},
phoneNumber1: {
type: Number,
required: true,
minlength: 10,
maxlength: 15
},
phoneNumber2: {
type: Number,
required: false,
minlength: 10,
maxlength: 15
},
address1: {
street: {
type: String,
require: true,
minlength: 2
},
city: {
type: String,
require: true,
minlength: 2
},
county: {
type: String,
require: true,
minlength: 2
},
state: {
type: String,
require: true,
minlength: 2
},
zipcode: {
type: Number,
require: true,
minlength: 4
},
country: {
type: String,
minlength: 2,
default: 'United States'
},
primary: {
type: Boolean,
require: true,
default: true
}
},
address2: {
street: {
type: String,
require: false,
minlength: 2
},
city: {
type: String,
require: false,
minlength: 2
},
county: {
type: String,
require: false,
minlength: 2
},
state: {
type: String,
require: false,
minlength: 2
},
zipcode: {
type: Number,
require: false,
minlength: 4
},
country: {
type: String,
require: false,
minlength: 2,
default: 'United States'
},
primary: {
type: Boolean,
require: false,
default: false
}
},
birth: {
month: {
type: String,
minlength: 2,
require: true
},
day: {
type: Number,
minlength: 2,
require: true
},
year: {
type: Number,
minlength: 2,
require: true
}
},
password: {
type: String,
require: true
},
date: {
type: Date,
default: Date.now
},
payment: {
creditCardNumber: {
type: Number,
require: true,
minlength: 14
},
cardType: {
type: String,
require: true,
minlength: 2
},
cardExpiration: {
month: {
type: Number,
require: true,
minlength: 2
},
year: {
type: Number,
require: true,
minlength: 4
}
}
},
billingAddress: {
street: {
type: String,
require: true,
minlength: 2
},
city: {
type: String,
require: true,
minlength: 2
},
county: {
type: String,
require: true,
minlength: 2
},
state: {
type: String,
require: true,
minlength: 2
},
zipcode: {
type: Number,
require: true,
minlength: 4
},
country: {
type: String,
minlength: 2,
default: 'United States'
}
},
shippingAddress: {
street: {
type: String,
require: false,
minlength: 2
},
city: {
type: String,
require: false,
minlength: 2
},
county: {
type: String,
require: false,
minlength: 2
},
state: {
type: String,
require: false,
minlength: 2
},
zipcode: {
type: Number,
require: false,
minlength: 4
},
country: {
type: String,
require: false,
minlength: 2,
default: 'United States'
}
},
isEmployee: {
type: Boolean,
default: false
},
isCustomer: {
type: Boolean,
default: true
}
});
customerSchema.methods.generateAuthToken = function() {
// const paylod = { id: this._id, name: this.name }; the token will have id and name
const paylod = { id: this._id, isCustomer: this.isCustomer, isEmployee: this.isEmployee };
const token = jwt.sign(paylod, config.get('jwtPrivateKey'));
return token;
};
const Customer = mongoose.model('Customers', customerSchema);
function validatecustomer(customer) {
const schema = {
firstName: Joi.string().min(5).max(255).required(),
lastName: Joi.string().min(5).max(255).required(),
sex: Joi.string().required(),
email: Joi.string().min(5).max(255).required().email(),
phoneNumber1: Joi.number().min(10).required(),
phoneNumber2: Joi.number().min(10),
password: Joi.string().min(5).max(255).required(),
address1: Joi.object({
street: Joi.string().min(5).max(255).required(),
city: Joi.string().min(5).max(255).required(),
zipcode: Joi.number().min(4).required(),
county: Joi.string().min(2).max(255).required(),
state: Joi.string().min(2).max(255).required(),
country: Joi.string().min(2).max(255),
primary: Joi.boolean()
}).required(),
address2: Joi.object({
street: Joi.string().min(5).max(255).required(),
city: Joi.string().min(5).max(255).required(),
zipcode: Joi.number().min(4).required(),
county: Joi.string().min(2).max(255).required(),
state: Joi.string().min(2).max(255).required(),
country: Joi.string().min(2).max(255).required(),
primary: Joi.boolean().required()
}),
birth: Joi.object({
month: Joi.string().min(2).max(255).required(),
day: Joi.number().min(1).max(255).required(),
year: Joi.number().min(4).required(),
place: Joi.object({
city: Joi.string().min(2).max(255),
country: Joi.string().min(2).max(255)
}).required()
}).required(),
payment: Joi.object({
creditCardNumber: Joi.number().required().min(14),
cardType: Joi.string().required().min(2),
cardExpiration: Joi.object({
month: Joi.number().required().min(2),
year: Joi.number().required().min(4)
}).required()
}).required(),
billingAddress: Joi.object({
street: Joi.string().min(5).max(255).required(),
city: Joi.string().min(5).max(255).required(),
zipcode: Joi.number().min(4).required(),
county: Joi.string().min(2).max(255).required(),
state: Joi.string().min(2).max(255).required(),
country: Joi.string().min(2).max(255),
primary: Joi.boolean()
}).required(),
shippingAddress: Joi.object({
street: Joi.string().min(5).max(255).required(),
city: Joi.string().min(5).max(255).required(),
zipcode: Joi.number().min(4).required(),
county: Joi.string().min(2).max(255).required(),
state: Joi.string().min(2).max(255).required(),
country: Joi.string().min(2).max(255),
primary: Joi.boolean()
}).required(),
isCustomer: Joi.boolean(),
isEmployee: Joi.boolean()
};
return Joi.validate(customer, schema);
}
function validateAuth(customer) {
const schema = {
email: Joi.string().min(5).max(255).required().email(),
password: Joi.string().min(5).max(255).required()
};
return Joi.validate(customer, schema);
}
exports.Customer = Customer;
exports.validate = validatecustomer;
exports.validateAuth = validateAuth;
<file_sep>/routes/customers.js
const express = require('express');
const bcrypt = require('bcrypt');
const router = express.Router();
const _ = require('lodash');
const auth = require('../middleware/auth');
const { Customer, validate } = require('../models/customer');
// @Get the information about the logged in customer. Private route
router.get('/me', auth, async (req, res) => {
try {
const { id, isCustomer } = req.employee;
if (!isCustomer) return res.status(401).json({ msg: 'Access denied' });
const customer = await Customer.findById(id).select('firstName lastName sex phoneNumber1 phoneNumber2');
res.json(customer);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
// @Register a customer
router.post('/', async (req, res) => {
try {
// Check for error
const { error } = validate(req.body);
if (error) return res.status(400).json({ msg: error.details[0].message });
// Check if customer already exist
let customer = await Customer.findOne({ email: req.body.email });
if (customer) return res.status(400).json({ msg: 'customer already exists.' });
customer = new Customer(
_.pick(req.body, [
'firstName',
'lastName',
'sex',
'email',
'phoneNumber1',
'phoneNumber2',
'address1',
'address2',
'birth',
'password',
'payment',
'billingAddress',
'shippingAddress'
])
);
// Hash password
const salt = await bcrypt.genSalt(10);
customer.password = await bcrypt.hash(customer.password, salt);
//Save customer to the database
await customer.save();
const token = customer.generateAuthToken();
res.header('x-auth-token', token).json({ token });
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
module.exports = router;
<file_sep>/routes/products.js
const express = require('express');
const router = express.Router();
const _ = require('lodash');
const auth = require('../middleware/auth');
const isAdmin = require('../middleware/isAdmin');
const { Product, validate } = require('../models/product');
const { Item } = require('../models/itemsDeleted');
// @Get Products
// @Get all product
// @Access Public
router.get('/', async (req, res) => {
try {
const products = await Product.find().sort();
if (products.length === 0) return res.json({ msg: 'No Products' });
res.json(products);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
// @Get Product with a given id
// @Get one product
// @Access Public
router.get('/:id', async (req, res) => {
try {
const product = await Product.findById(req.params.id);
if (!product) return res.status(400).json({ msg: 'Product not found.' });
res.json(product);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
// @Add Products
// @Add one product
// @Access Private, employee admin only
router.post('/', auth, async (req, res) => {
try {
const { id, isEmployee } = req.employee;
// res.json(req.employee);
if (!isEmployee) return res.status(401).json({ msg: 'Access denied' });
// Check for error
const { error } = validate(req.body);
if (error) return res.status(400).json({ msg: error.details[0].message });
// Check if the product already exist
let product = await Product.findOne({ name: req.body.name });
if (product) return res.status(400).json({ msg: 'Product always exists' });
product = new Product(
_.pick(req.body, [
'name',
'category',
'discount',
'weight',
'availableDiscount',
'pictureUrl',
'note',
'price',
'quantityPerUnit'
])
);
product.addedBy.id = id;
//Save product to the database
await product.save();
res.send(product);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
// @Delete Product with a given id
// @delete one product
// @Access Private employee admin only
router.delete('/:id', [ auth, isAdmin ], async (req, res) => {
try {
const { id, isEmployee } = req.employee;
// res.json(req.employee);
if (!isEmployee) return res.status(401).json({ msg: 'Access denied' });
// Check if the product already exist
let product = await Product.findById(req.params.id);
if (!product) return res.status(400).json({ msg: 'Product not found' });
// Find and delete
await Product.findByIdAndRemove(req.params.id);
res.json({ msg: 'Product deleted' });
// Get record
const record = new Item({
itemId: req.params.id,
deletedBy: id
});
await record.save();
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
// @Put Product with a given id
// @Update one product
// @Access Private employee admin only
router.put('/:id', auth, async (req, res) => {
try {
const { id, isEmployee } = req.employee;
// res.json(req.employee);
if (!isEmployee) return res.status(401).json({ msg: 'Access denied' });
// Find the product
let product = await Product.findById(req.params.id);
if (!product) returnres.status(400).json({ msg: 'Product not found' });
const { name, category, weight, availableDiscount, note, quantityPerUnit } = req.body;
// Build product object
let productObject = {};
if (name) productObject.name = name;
if (weight) productObject.weight = weight;
if (availableDiscount) productObject.availableDiscount = availableDiscount;
if (note) productObject.note = note;
if (quantityPerUnit) productObject.quantityPerUnit = quantityPerUnit;
productObject.category = category;
if (category.name) productObject.category.name = category.name;
if (category.description) productObject.category.description = category.description;
if (category.pictureUrl) productObject.category.pictureUrl = category.pictureUrl;
if (category.isAvailable) productObject.category.isAvailable = category.isAvailable;
// res.json(category.name);
productObject.editedBy = product.editedBy;
productObject.editedBy.id = id;
// Find and update
product = await Product.findByIdAndUpdate(req.params.id, { $set: productObject }, { new: true });
res.json(product);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
module.exports = router;
<file_sep>/index.js
const express = require('express');
const app = express();
const error = require('./middleware/error');
app.use(express.json());
require('./config/db')();
app.use('/api/employees', require('./routes/employees'));
app.use('/api/customers', require('./routes/customers'));
app.use('/api/products', require('./routes/products'));
app.use('/api/inventories', require('./routes/inventories'));
app.use('/api/auth', require('./routes/auth'));
// error handeling
// app.use(error);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
<file_sep>/README.md
# e-commerce
Building my first full stack E-Commerce app with Javascript/Node.js and React
<file_sep>/models/itemsDeleted.js
const mongoose = require('mongoose');
const itemsDeletedSchema = new mongoose.Schema({
itemId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'id'
},
deletedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'id'
},
date: {
type: Date,
default: Date.now()
}
});
const Item = mongoose.model('ItemsDeleted', itemsDeletedSchema);
exports.Item = Item;
<file_sep>/routes/auth.js
const express = require('express');
const bcrypt = require('bcrypt');
const router = express.Router();
const _ = require('lodash');
const { validateAuth, Customer } = require('../models/customer');
const { Employee } = require('../models/employee');
// @Auth
router.post('/', async (req, res) => {
// Check for error
const { error } = validateAuth(req.body);
if (error) return res.status(400).json({ msg: error.details[0].message });
// Check if employee or customer exists
const employee = await Employee.findOne({ email: req.body.email });
const customer = await Customer.findOne({ email: req.body.email });
if (!customer && !employee) return res.status(400).json({ msg: 'Invalid email or password' });
const isboth = employee && customer ? true : false;
const validPassword = await <PASSWORD>.compare(req.body.password, <PASSWORD>);
const validCustomerPassword = await bcrypt.compare(req.body.password, <PASSWORD>);
if (!validPassword && !validCustomerPassword) return res.status(400).json({ msg: 'Invalid email or password' });
const token = isboth && validPassword ? employee.generateAuthToken() : customer.generateAuthToken();
res.header('x-auth-token', token).json({ token });
});
module.exports = router;
<file_sep>/models/inventory.js
const Joi = require('joi');
const mongoose = require('mongoose');
const inventorySchema = new mongoose.Schema({
productID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'products._id'
},
employeeID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'employees._id'
},
availableQuantity: {
type: Number,
required: true,
default: 0
},
note: {
type: String,
required: true,
minlength: 5
},
reorderLevel: {
type: Number,
default: 0
},
date: {
type: Date,
default: Date.now()
}
});
const Inventory = mongoose.model('Inventory', inventorySchema);
function validateInventory(inventory) {
const schema = {
availableQuantity: Joi.number().default(0),
note: Joi.string().required(),
reorderLevel: Joi.number().required()
};
return Joi.validate(inventory, schema);
}
exports.Inventory = Inventory;
exports.validate = validateInventory;
<file_sep>/routes/employees.js
const express = require('express');
const bcrypt = require('bcrypt');
const router = express.Router();
const auth = require('../middleware/auth');
const _ = require('lodash');
const { Employee, validate } = require('../models/employee');
// @Get information about the logged in employee. Private route
router.get('/me', auth, async (req, res) => {
try {
const { id, isEmployee } = req.employee;
if (!isEmployee) return res.status(401).json({ msg: 'Access denied' });
const employee = await Employee.findById(id).select('firstName lastName sex phoneNumber1 phoneNumber2');
res.json(employee);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
// @Register a employee
router.post('/', async (req, res) => {
try {
// Check for error
const { error } = validate(req.body);
if (error) return res.status(400).json({ msg: error.details[0].message });
// Check if employee already exist
let employee = await Employee.findOne({ email: req.body.email });
if (employee) return res.status(400).json({ msg: 'employee already exists.' });
employee = new Employee(
_.pick(req.body, [ 'firstName', 'lastName', 'sex', 'email', 'phoneNumber', 'address', 'birth', 'password' ])
);
// Hash password
const salt = await bcrypt.genSalt(10);
employee.password = await bcrypt.hash(employee.password, salt);
//Save employee to the database
await employee.save();
const token = employee.generateAuthToken();
res.header('x-auth-token', token).json({ token });
// res.json({ token });
// res.send(employee);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
module.exports = router;
| 7606fef35a30acdbfdb3b989410bd7787145309a | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | makungaj1/e-commerce | 1d87f060597caae96313d18dcfadc18aea08a2a7 | 14a717be9ff07fed813738bc34bf8b21a8cfb005 |
refs/heads/main | <repo_name>WatchDog773/webSite-YourCourses<file_sep>/backend-webSite-YourCourses/routes/api.js
const express = require("express");
const router = express.Router();
const securityConfig = require("../config/security");
const apiAuth = require("./api/api_auth");
const apiCourses = require("./api/api_courses");
router.use("/auth", apiAuth);
router.use("/courses", apiCourses);
const heartBeat = (req, res) => {
res.status(200).json({ ok: true });
};
router.get("/heartbeat", securityConfig.verifyUser, heartBeat);
module.exports = router;
<file_sep>/frontend-website-yourcourses_/src/utilities/Axios.js
import axios from "axios";
const publicaxios = axios.create();
publicaxios.defaults.headers.common["cache-control"] = "no-cache";
publicaxios.defaults.headers.post["Content-Type"] = "no-cache";
publicaxios.defaults.headers.put["Content-Type"] = "no-cache";
const privateaxios = axios.create();
privateaxios.defaults.headers.common["cache-control"] = "no-cache";
privateaxios.defaults.headers.post["Content-Type"] = "no-cache";
privateaxios.defaults.headers.put["Content-Type"] = "no-cache";
export const setJWT = (jwt) => {
privateaxios.defaults.headers.common["Authorization"] = `Bearer ${jwt}`;
};
export const setUnAuthInterceptor = (logoutHandler) => {
privateaxios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
console.log(error);
if (error.response) {
switch (error.response.status) {
case 401:
logoutHandler();
break;
default:
console.log(error);
}
} else {
console.log(error);
}
return Promise.reject(error);
}
);
};
export const naxios = publicaxios;
export const paxios = privateaxios;
<file_sep>/frontend-website-yourcourses_/src/components/common/ButtonExit.js
import { Button } from "react-bootstrap";
import { useStateContext } from "../../utilities/Context";
import { LOGOUT } from "../../utilities/store/reducers/auth.reducer";
import { useState } from "react";
import { Redirect } from "react-router-dom";
//import axios from "axios";
const Exit = ({ contenido }) => {
const [, dispath] = useStateContext();
const ruta = "/";
const [redirect, setRedirect] = useState("");
if (redirect !== "") {
return <Redirect to={redirect}></Redirect>;
}
const onLogin = (e) => {
dispath({ type: LOGOUT });
setRedirect(`${ruta}`);
window.location.reload();
};
return (
<Button onClick={onLogin} className="btn solid">
{contenido}
</Button>
);
};
export default Exit;
<file_sep>/frontend-website-yourcourses_/src/components/common/ButtonGeneral.js
import { useState } from "react";
import { Redirect } from "react-router-dom";
import { Button } from "react-bootstrap";
const ButtonGeneralBo = ({ ruta, contenido }) => {
const [redirect, setRedirect] = useState("");
if (redirect !== "") {
return <Redirect to={redirect}></Redirect>;
}
return (
<div>
<Button
onClick={(e) => {
setRedirect(`${ruta}`);
}}
>
{contenido}
</Button>
</div>
);
};
export default ButtonGeneralBo;
<file_sep>/frontend-website-yourcourses_/src/components/private/OneCourse.js
import { useEffect, useState } from "react";
import { useStateContext } from "../../utilities/Context";
import { paxios } from "../../utilities/Axios";
import { useHistory } from "react-router-dom";
import { Container, Card } from "react-bootstrap";
import Footer from "../common/Footer";
import Navbar from "../common/Navbar";
import {
LESSONS_ERROR,
LESSONS_LOADED,
LESSONS_RESET,
LESSONS_LOADING,
} from "../../utilities/store/reducers/lessons.reducer";
import ButtonGeneral from "../common/ButtonGeneral";
// import Page from '../common/Page';
// import Field from '../cmns/Field';
// import { SecondaryButton, PrimaryButton } from '../cmns/Buttons';
const OneCourse = () => {
const [{ lessons, courses }, dispath] = useStateContext();
const [form, setForm] = useState({
name: "",
description: "",
});
const history = useHistory();
console.log("Este console log", lessons);
useEffect(() => {
//console.log(lessons);
dispath({ type: LESSONS_LOADING });
const _id = courses.currentId;
paxios
.get(`/api/courses/lessons/${_id}`)
.then(({ data }) => {
//console.log("Dataaaa", data);
dispath({ type: LESSONS_LOADED, payload: data });
//setForm(data);
})
.catch((ex) => {
console.log(ex);
dispath({ type: LESSONS_ERROR });
alert("Algo salio mal.");
history.push("/courses");
});
}, []);
//console.log("foorm", form);
//console.log("lecioneeeeees", lessons);
let ListElements = [];
ListElements = lessons.lessons.map((o) => {
return (
<div>
<h2>{o.name}</h2>
</div>
);
});
return (
// <div>
// <Container>
// <Card className="m-3">
// <h1>{form.name}</h1>
// </Card>
// </Container>
// </div>
<div>
<Navbar />
<ButtonGeneral ruta="/courses" contenido="Atras" />
<Container>{ListElements}</Container>
<Footer />
</div>
);
};
export default OneCourse;
<file_sep>/frontend-website-yourcourses_/src/utilities/store/reducers/courses.reducer.js
// import { StateContext } from "../../Context";
const initialState = {
hasMore: true,
courses: [],
total: 0,
currentPage: 1,
pageLimit: 5,
fetching: false,
error: "",
currentId: null,
searchfilter: "",
};
export const COURSES_LOADING = "COURSES_LOADING";
export const COURSES_LOADED = "COURSES_LOADED";
export const COURSES_RESET = "COURSES_RESET";
export const COURSES_ERROR = "COURSES_ERROR";
export const COURSES_SET_CURRENT = "COURSES_SET_CURRENT";
const coursesReducer = (state = initialState, action = {}) => {
switch (action.type) {
case COURSES_LOADING:
return { ...state, fetching: true };
case COURSES_LOADED:
return {
...state,
courses: [...state.courses, ...action.payload],
fetching: false,
};
case COURSES_RESET:
if (action.payload) {
return { ...initialState, searchfilter: action.payload.searchfilter };
} else {
let { searchfilter } = state;
return { ...initialState, searchfilter: searchfilter };
}
case COURSES_ERROR:
return { ...state, fetching: false };
case COURSES_SET_CURRENT:
console.log(action);
return { ...state, currentId: action.payload._id };
default:
return state;
}
};
export default coursesReducer;
<file_sep>/frontend-website-yourcourses_/src/components/common/Mystyle.js
import styled from "styled-components";
const Mystyles = styled.div`
.navbar {
background: #4caf50;
}
`;
export default Mystyles;
<file_sep>/frontend-website-yourcourses_/src/components/common/Carousel.js
import {Carousel} from 'react-bootstrap'
import {useState} from 'react'
function ControlledCarousel() {
const [index, setIndex] = useState(0);
const handleSelect = (selectedIndex, e) => {
setIndex(selectedIndex);
};
return (
<div>
<Carousel activeIndex={index} onSelect={handleSelect}>
<Carousel.Item>
<img
className="d-block w-100"
src="assets/slider1.png"
alt="First slide"
/>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="assets/slider2.png"
alt="Second slide"
/>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="assets/slider3.png"
alt="Third slide"
/>
</Carousel.Item>
</Carousel>
</div>
);
}
export default ControlledCarousel;
<file_sep>/frontend-website-yourcourses_/src/utilities/store/reducers/lessons.reducer.js
// import { StateContext } from "../../Context";
const initialState = {
hasMore: true,
lessons: [],
total: 0,
currentPage: 1,
pageLimit: 5,
fetching: false,
error: "",
currentId: null,
searchfilter: "",
};
export const LESSONS_LOADING = "LESSONS_LOADING";
export const LESSONS_LOADED = "LESSONS_LOADED";
export const LESSONS_RESET = "LESSONS_RESET";
export const LESSONS_ERROR = "LESSONS_ERROR";
export const LESSONS_SET_CURRENT = "LESSONS_SET_CURRENT";
const lessonsReducer = (state = initialState, action = {}) => {
switch (action.type) {
case LESSONS_LOADING:
return { ...state, fetching: true };
case LESSONS_LOADED:
return {
...state,
lessons: [...state.lessons, ...action.payload],
fetching: false,
};
case LESSONS_RESET:
if (action.payload) {
return { ...initialState, searchfilter: action.payload.searchfilter };
} else {
let { searchfilter } = state;
return { ...initialState, searchfilter: searchfilter };
}
case LESSONS_ERROR:
return { ...state, fetching: false };
case LESSONS_SET_CURRENT:
console.log(action);
return { ...state, currentId: action.payload._id };
default:
return state;
}
};
export default lessonsReducer;
<file_sep>/frontend-website-yourcourses_/src/components/public/NotFound.js
import { useState } from "react";
import { Redirect } from "react-router-dom";
import { Container, Row, Button } from "react-bootstrap";
import Navbar from "../common/Navbar";
import Footer from "../common/Footer";
import imgNotFound from "./notFound.png";
const NotFound = () => {
let [redirect, setRedirect] = useState("");
if (redirect !== "") {
return <Redirect to={redirect}></Redirect>;
}
return (
<div>
<Navbar />
<Container>
<Row >
<h1 className="mx-auto mt-5">Oops!</h1>
</Row>
<Row xs={50} md={50} sm={4} className="justify-content-md-center" >
<img style={{ "max-width": "100%" }} src={imgNotFound} rounded/>
</Row>
<Row>
<h2 className="mx-auto">No lo pudimos encontrar</h2>
</Row>
<Row>
<div className="mx-auto">
<Button
onClick={(e) => {
setRedirect("/");
}}
>
Volver
</Button>
</div>
</Row>
</Container>
<Footer />
</div>
);
};
export default NotFound;
<file_sep>/backend-webSite-YourCourses/config/db.js
// Cliente de mongodb
const MongoClient = require("mongodb").MongoClient;
let db = null;
module.exports = class MongoDataModel {
static async getDb() {
if (!db) {
try {
const connection = await MongoClient.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
});
db = connection.db(process.env.MONGO_DB);
return db;
} catch (error) {
console.log(error);
throw error;
}
} else {
return db;
}
}
};
<file_sep>/frontend-website-yourcourses_/src/components/common/Section.js
import {Container, Row, Col, Image} from 'react-bootstrap'
import React from 'react';
import img from './developer_activity_bv83.svg'
const Section = () =>{
return(
<div style={{background:"#bfe0ff"}}>
<Container style={{paddingTop: '9%', paddingBottom: '9%'}}>
<Row>
<Col md>
<Image src = {img} fluid ></Image>
</Col>
<Col md>
<h1 style={{textAlign:"center"}}><strong>¿Por qué es importante aprender a programar?</strong> </h1>
<h4 style={{textAlign:"justify"}}>La programación es una herramienta fundamental
en el mundo en el que vivimos, convirtiéndose en
una salida laboral importante. Además, su aprendizaje
constituye una oportunidad al mejorar el razonamiento
lógico formal.</h4>
</Col>
</Row>
</Container>
</div>
);
}
export default Section;<file_sep>/frontend-website-yourcourses_/src/components/common/Footer.js
import {Card} from 'react-bootstrap'
import React from 'react';
import CardGroup from 'react-bootstrap/CardGroup'
const Footer = () => {
return(
<div>
<p></p>
<Card collapseOnSelect bg="dark" expand="lg" variant="dark" className="text-center">
<Card.Title className="text-white" >Your Courses</Card.Title>
</Card>
<CardGroup>
<Card collapseOnSelect bg="dark" expand="lg" variant="dark" className="text-center">
<Card.Body>
<Card.Title className="text-white">Explorar</Card.Title>
<Card.Text >
<ul class = "box" className="text-dark">
<li><a href="#home">Cursos</a></li>
<li><a href="#home">Acceder</a></li>
<li><a href="#home">Registrarse</a></li>
<li><a href="#home">Acerca de</a></li>
</ul>
</Card.Text>
</Card.Body>
</Card>
<Card collapseOnSelect bg="dark" expand="lg" variant="dark" className="text-center">
<Card.Body>
<Card.Title className="text-white">¿Necesitas Ayuda?</Card.Title>
<Card.Text>
<ul class="box h-box" className="text-dark">
<li><a href="#home">Blog</a></li>
<li><a href="#home">Precios</a></li>
<li><a href="#home">Cursos</a></li>
<li><a href="#home">Certificaciónes</a></li>
<li><a href="#home">Servicio al cliente</a></li>
</ul>
</Card.Text>
</Card.Body>
</Card>
<Card collapseOnSelect bg="dark" expand="lg" variant="dark" className="text-center">
<Card.Body>
<Card.Title className="text-white">Legal</Card.Title>
<Card.Text>
<ul class="box" className="text-dark">
<li><a href="#home">Políticas de Privacidad</a></li>
<li><a href="#home">Términos de uso</a></li>
<li><a href="#home">Contáctanos</a></li>
</ul>
</Card.Text>
</Card.Body>
</Card>
</CardGroup>
<Card collapseOnSelect bg="dark" expand="lg" variant="dark" className="text-center">
<Card.Footer className="text-muted" className="text-white">©2020 Your Courses Todos los derechos reservados</Card.Footer>
</Card>
</div>
);
}
export default Footer;<file_sep>/frontend-website-yourcourses_/src/components/public/Home.js
import Navbar from "../common/Navbar";
import Carousel from '../common/Carousel';
import Footer from "../common/Footer";
import CardView from '../common/CardView';
import Section from '../common/Section'
function Home() {
return (
<div>
<Navbar />
<Carousel/>
<Section/>
<CardView/>
<Footer/>
</div>
);
}
export default Home;
<file_sep>/frontend-website-yourcourses_/src/components/common/Navbar.js
import { useState } from "react";
import { Link } from "react-router-dom";
import { useStateContext } from "../../utilities/Context";
import BackToLogin from "../common/ButtonBackLogin";
import ButtonExit from "../common/ButtonExit";
import { Navbar, Nav, Button } from "react-bootstrap";
//import Mystyles from "./Mystyle";
const NavBar = () => {
const [{ auth }] = useStateContext();
const navButtonsNoUser = (
<Navbar collapseOnSelect bg="light" expand="lg" variant="dark">
<Navbar.Brand href="/">Your Courses</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto"></Nav>
<Nav className="ml-auto">
<Nav.Item>
<BackToLogin />
</Nav.Item>
</Nav>
</Navbar.Collapse>
</Navbar>
);
const navButtonsUser = (
<Navbar collapseOnSelect bg="light" expand="lg" variant="dark">
<Navbar.Brand href="/">Your Courses</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="/startit">Cursos</Nav.Link>
<Nav.Link href="/new">Agregar un curso</Nav.Link>
<Nav.Link href="/myInscriptions">Mis inscripciones</Nav.Link>
<Nav.Link href="/myCourses">Mis cursos</Nav.Link>
</Nav>
<Nav className="ml-auto">
<Nav.Item>
<ButtonExit contenido="Salir" />
</Nav.Item>
</Nav>
</Navbar.Collapse>
</Navbar>
);
if (auth.logged) {
return navButtonsUser;
} else {
return navButtonsNoUser;
}
};
export default NavBar;
<file_sep>/frontend-website-yourcourses_/src/components/private/MyInscriptions.js
// /inscription/:userId
import { useStateContext } from "../../utilities/Context";
import { paxios } from "../../utilities/Axios";
import { useEffect } from "react";
import { useHistory } from "react-router-dom";
import CardDeck from "react-bootstrap/CardDeck";
// import { Card, Container, Button, Form } from "react-bootstrap";
import { Card, Container, Button, Row } from "react-bootstrap";
import ButtonGeneral from "../common/ButtonGeneral";
import imgLessons from "./Lessons.png";
import axios from "axios";
import Footer from "../common/Footer";
import Navbar from "../common/Navbar";
import {
COURSES_LOADING,
COURSES_LOADED,
COURSES_RESET,
COURSES_ERROR,
COURSES_SET_CURRENT,
} from "../../utilities/store/reducers/courses.reducer";
const ListCourses = () => {
const [{ auth, courses }, dispatch] = useStateContext();
const history = useHistory();
let ListElements = [];
ListElements = courses.courses.map((o) => {
if (auth.user.email != o.author) {
return (
<div className="col-md-4 mt-5 shadow-lg p-3 mb-5 bg-white rounded">
<CardDeck>
<Card className="text-center mt-2">
<Card.Footer></Card.Footer>
<Card.Body>
<Card.Title>{o.name}</Card.Title>
<Card.Text>{o.author}</Card.Text>
<Card.Text>{o.description}</Card.Text>
<Card.Text>{o.information}</Card.Text>
</Card.Body>
<Card.Footer>
<small className="text-muted">$ {o.price}</small>
</Card.Footer>
<Card.Body>
<Button
onClick={() => {
dispatch({
type: COURSES_SET_CURRENT,
payload: { _id: o._id },
});
history.push("/courses/one");
}}
>
Ver más
</Button>
</Card.Body>
</Card>
</CardDeck>
</div>
);
} else {
return (
<div className="col-md-4">
<CardDeck>
<Card className="text-center mt-2">
<Card.Footer></Card.Footer>
<Card.Body>
<Card.Title>{o.name}</Card.Title>
<Card.Text>{o.author}</Card.Text>
<Card.Text>{o.description}</Card.Text>
<Card.Text>{o.information}</Card.Text>
</Card.Body>
<Card.Footer>
<small className="text-muted">$ {o.price}</small>
</Card.Footer>
<Card.Body>
<Button
onClick={() => {
dispatch({
type: COURSES_SET_CURRENT,
payload: { _id: o._id },
});
history.push("/courses/one");
}}
>
Ver lecciones
</Button>
<Button
onClick={() => {
dispatch({
type: COURSES_SET_CURRENT,
payload: { _id: o._id },
});
history.push("/newLesson");
}}
>
Agregar lecciones
</Button>
<Button>Eliminar</Button>
</Card.Body>
</Card>
</CardDeck>
</div>
);
}
});
console.log("El largo de la lista: ", ListElements.length);
useEffect(() => {
dispatch({ type: COURSES_RESET });
dispatch({ type: COURSES_LOADING });
paxios
.get(`/api/courses/inscription/${auth.user._id}`)
.then(({ data }) => {
dispatch({ type: COURSES_LOADED, payload: data });
console.log(data);
})
.catch((ex) => {
dispatch({ type: COURSES_ERROR });
}); //end paxios
}, []);
if (ListElements.length == 0) {
return (
<div>
<Navbar />
<Container>
<Row>
<h1 className="mx-auto mt-5">
No te has inscrito a un curso todavía
</h1>
</Row>
<Row xs={80} md={80} sm={4} className="justify-content-md-center">
<img style={{ "max-width": "100%" }} src={imgLessons} rounded />
</Row>
<Row>
<h2 className="mx-auto">¡Inscribirte ya!</h2>
</Row>
<Row>
<div className="mx-auto">
<ButtonGeneral ruta="/startit" contenido="Ir a cursos" />
</div>
</Row>
</Container>
<Footer />
</div>
);
} else {
return (
<div>
<Navbar />
<div className="container">
<div className="row">{ListElements}</div>
</div>
<Footer />
</div>
);
}
};
export default ListCourses;
<file_sep>/frontend-website-yourcourses_/src/utilities/store/reducers/auth.reducer.js
// 1. El estado inicial
const emptyAuth = {
logged: false,
jwt: "",
user: {},
isFetching: false,
error: "",
signin: false,
redirect: false,
searchFilter: "",
};
// 1.2 El estado inicial
let initialState = {
...emptyAuth,
...JSON.parse(localStorage.getItem("store_auth")),
};
// 2. Acciones o eventos
// Para el login
export const LOGIN_FETCHING = "LOGIN_FETCHING";
export const LOGIN_FETCHING_FAILED = "LOGIN_FETCHING_FAILED";
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const JWT_INVALID = "JWT_INVALID";
// Para el logout
export const LOGOUT = "LOGOUT";
// Para signup
export const SIGNIN_FETCHING = "SIGNIN_FETCHING";
export const SIGNIN_FETCHING_FAILED = "SIGNIN_FETCHING_FAILED";
export const SIGNIN_SUCCES = "SIGNIN_SUCCES";
export const SIGNIN_END = "SIGNIN_END";
// 3.
const authReducer = (state = initialState, action = {}) => {
switch (action.type) {
case LOGIN_FETCHING: {
return { ...state, isFetching: true };
}
case LOGIN_FETCHING_FAILED: {
return { ...state, isFetching: false };
}
case LOGIN_SUCCESS: {
const newState = {
...state,
...action.payload,
isFetching: false,
logged: true,
};
localStorage.setItem("store_auth", JSON.stringify(newState));
return { ...newState };
}
case JWT_INVALID: {
return {
...emptyAuth,
redirect: action.payload.to,
};
}
case SIGNIN_FETCHING: {
return { ...state, isFetching: true };
}
// https://www.youtube.com/watch?v=Xa7ECigMWRs
case LOGOUT: {
localStorage.removeItem("store_auth");
return { logged: false };
}
case SIGNIN_SUCCES:
if (action.payload) {
return { ...initialState, searchFilter: action.payload.searchFilter };
} else {
let { searchFilter } = state;
return { ...initialState, searchFilter: searchFilter };
}
default: {
return state;
}
}
};
export default authReducer;
// const emptyAuth = {
// logged: false,
// jwt: "",
// user: {},
// isFetching: false,
// error: "",
// signing: false,
// redirect: false,
// };
// let initialState = {
// ...emptyAuth,
// ...JSON.parse(localStorage.getItem("store_auth")),
// };
// export const LOGIN_FETCHING = "LOGIN_FETCHING";
// export const LOGIN_FETCHING_FAILED = "LOGIN_FETCHING_FAILED";
// export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
// export const LOGOUT = "LOGOUT";
// export const JWT_INVALID = "JWT_INVALID";
// export const SIGNIN_FETCHING = "SIGNIN_FETCHING";
// export const SIGNIN_FETCHING_FAILED = "SIGNIN_FETCHING_FAILED";
// export const SIGNIN_SUCCESS = "SIGNIN_SUCCESS";
// export const SIGNIN_END = "SIGNIN_END";
// const authReducer = (state = initialState, action = {}) => {
// switch (action.type) {
// case LOGIN_FETCHING:
// return { ...state, isFetching: true };
// case LOGIN_FETCHING_FAILED:
// return { ...state, isFetching: false };
// case LOGIN_SUCCESS:
// const newState = {
// ...state,
// ...action.payload,
// isFetching: false,
// logged: true,
// };
// localStorage.setItem("store_auth", JSON.stringify(newState));
// return { ...newState };
// case LOGOUT:
// return { ...state };
// case JWT_INVALID:
// return { ...emptyAuth, redirect: action.payload.to };
// case SIGNIN_FETCHING:
// return { ...state };
// case SIGNIN_FETCHING_FAILED:
// return { ...state };
// case SIGNIN_SUCCESS:
// return { ...state };
// case SIGNIN_END:
// return { ...state };
// default:
// return state;
// }
// };
// export default authReducer;
<file_sep>/frontend-website-yourcourses_/src/components/public/LogIn.js
import { useState } from "react";
import { useHistory, useLocation } from "react-router-dom";
/*import { faArrowLeft } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; */
import { Button, Nav } from "react-bootstrap";
import { naxios as axios, setJWT } from "../../utilities/Axios";
import imgLogin from "./login.svg";
import "./Login&signUp.css";
import { useStateContext } from "../../utilities/Context";
import {
LOGIN_FETCHING,
LOGIN_FETCHING_FAILED,
LOGIN_SUCCESS,
} from "../../utilities/store/reducers/auth.reducer";
import ButtonGeneral from "../common/ButtonGeneral";
//import axios from "axios";
const LogIn = () => {
/*let [redirect, setRedirect] = useState("");
if (redirect !== "") {
return <Redirect to={redirect}></Redirect>;
}*/
const [form, setForm] = useState({
email: "",
password: "",
});
const [, dispath] = useStateContext();
const routeHistory = useHistory();
const location = useLocation();
const onChange = (e) => {
const { name, value } = e.target;
setForm({
...form, //spread Operator
[name]: value,
});
};
// La accion del boton
let { from } = location.state || { from: { pathname: "/startit" } };
const onLogin = (e) => {
const { email, password } = form;
//console.log(email);
//console.log(password);
dispath({ type: LOGIN_FETCHING });
axios
.post("/api/auth/login", { email, password })
.then(({ data }) => {
console.log("Largo del data loggin", data.length);
dispath({ type: LOGIN_SUCCESS, payload: data });
setJWT(data.jwt);
routeHistory.replace(from);
})
.catch((error) => {
dispath({ type: LOGIN_FETCHING_FAILED });
/*// console.log(error.code);
console.log(JSON.stringify(error));
alert(error.message); */
const err = { error };
const ee = err.error.request.status;
if (ee == 403) {
alert("Usuario y/o contraseña incorrectos");
} else if (ee == 400) {
alert("Complete los campos para poder ingresar");
} else {
console.log(error);
alert("Algo salio mál contacte con el administrador de la pagina");
}
});
};
return (
/*
<Container className="my-5">
<Card>
<div className="m-3">
<FontAwesomeIcon
onClick={(e) => {
setRedirect("/");
}}
icon={faArrowLeft}
/>
</div>
<Container className="p-4">
<div>
<Form>
<Form.Group>
<Form.Label>Corro Electrónico</Form.Label>
<Form.Control type="email" placeholder="Enter email" required />
</Form.Group>
<Form.Group>
<Form.Label>Contraseña</Form.Label>
<Form.Control
type="password"
placeholder="<PASSWORD>"
required
/>
</Form.Group>
<div className="mx-auto" style={{ width: "200px" }}>
<Button variant="primary" type="submit">
Iniciar Sesión
</Button>
</div>
</Form>
</div>
</Container>
</Card>
</Container>
*/
/**LOGIN */
<div className="container1">
<div className="forms-container1">
<div className="signin-signup">
<form className="sign-in-form" style={{ "align-items": "center" }}>
<h2 className="title">Iniciar sesión</h2>
<div className="input-field">
<i className="fas fa-user"></i>
<input
name="email" // 1. Primero el name Tiene que ir asi para que lea la escritura
onChange={onChange} // 2. Luego el onChange
value={form.email} // 3. Luego el valor para que este capture
type="email"
placeholder="Nombre usuario"
/>
</div>
<div className="input-field">
<i className="fas fa-lock"></i>
<input
name="password"
value={form.password}
onChange={onChange}
type="password"
placeholder="<PASSWORD>"
/>
</div>
<Button onClick={onLogin} className="btn solid">
Iniciar Sesión
</Button>
<p className="social-text">
Encuentranos en nuestras redes sociales
</p>
<div className="social-media">
<a class="social-icon">
<i className="fab fa-facebook-f"></i>
</a>
<a className="social-icon">
<i className="fab fa-twitter"></i>
</a>
<a className="social-icon">
<i className="fab fa-google"></i>
</a>
<a className="social-icon">
<i className="fab fa-youtube"></i>
</a>
</div>
</form>
</div>
</div>
<div className="panels-container1">
<div className="panel left-panel">
<div className="content">
<h3>¿ Nuevo aquí ?</h3>
<p>Aprende desde casa y con tu celular con Your Courses</p>
<ButtonGeneral ruta="/signup" contenido="Crear cuenta" />
</div>
<img src={imgLogin} className="image" alt="imagen del login" />
</div>
</div>
</div>
);
};
export default LogIn;
<file_sep>/frontend-website-yourcourses_/src/components/private/AddLesson.js
import NavBar from "../common/Navbar";
import Footer from "../common/Footer";
import { Button, Form, Container, Card } from "react-bootstrap";
import { LESSONS_RESET } from "../../utilities/store/reducers/lessons.reducer";
import { useStateContext } from "../../utilities/Context";
import { useState } from "react";
import { paxios } from "../../utilities/Axios";
import { useHistory } from "react-router-dom";
const AddLesson = () => {
const [{ courses }, dispatch] = useStateContext();
const history = useHistory();
const _id = courses.currentId;
const [form, setForm] = useState({
name: "",
description: "",
video:"",
});
const onChange = (e) => {
e.preventDefault();
e.stopPropagation();
const { name, value } = e.target;
let newForm = { ...form, [name]: value };
setForm(newForm);
};
const AddNewLesson = (e) => {
e.preventDefault();
e.stopPropagation();
paxios
.post(`/api/courses/addLesson/${_id}`, form) // "/addLesson/:id",
.then((data) => {
console.log(data);
dispatch({ type: LESSONS_RESET });
history.push("/startit");
})
.catch((ex) => {
console.log(ex);
alert("Algo salio mál al ingresar");
});
};
return (
<div>
<NavBar />
<Container>
<Card className="mt-5">
<Form>
<Form.Group>
<Form.Label>Nombre de leccion</Form.Label>
<Form.Control
name="name"
value={form.name}
onChange={onChange}
type="text"
placeholder="Ej: Primera leccion de NodeJS"
/>
</Form.Group>
<Form.Group>
<Form.Label>Descripcion</Form.Label>
<Form.Control
name="description"
value={form.description}
onChange={onChange}
type="text"
placeholder="Ej: Passport"
/>
</Form.Group>
<Form.Group>
<Form.Label>Video URL</Form.Label>
<Form.Control
name="video"
value={form.video}
onChange={onChange}
type="text"
placeholder="Ej: https://"
/>
</Form.Group>
<Button onClick={AddNewLesson} variant="primary">
Guardar
</Button>
</Form>
</Card>
<Card className="mt-3">
<Container>
<h1>Instrucciones para agregar tu video</h1>
</Container>
<Container>
<Card className="m-3">
<Container>
<h2>
Primero sube el video a una plataforma de almacenamiento, en
este caso te recomendamos Google Drive
</h2>
<img style={{ "max-width": "100%" }} src="assets/paso1.jpeg" />
</Container>
</Card>
<Card className="m-3">
<Container>
<h2>
Luego haga clic derecho sobre el video y luego de clic en
compartir
</h2>
<img style={{ "max-width": "100%" }} src="assets/paso2.png" />
</Container>
</Card>
<Card className="m-3">
<Container>
<h2>
Aparecera lo siguiente y de clic en cambiar, como se muestra a
continuacion
</h2>
<img style={{ "max-width": "100%" }} src="assets/paso3.PNG" />
</Container>
</Card>
<Card className="m-3">
<Container>
<h2>
Luego presione clic donde dice restringido (Si el video nunca
ha sido compartido)y aparecera este menu, luego de click en:
Cualquier persona con el enlace como se muestra a continuacion
</h2>
<img style={{ "max-width": "100%" }} src="assets/paso4.PNG" />
</Container>
</Card>
<Card className="m-3">
<Container>
<h2>
A continuacion haga clic donde se muestra en la imagen, para
copiar el enlace al portapapeles
</h2>
<img style={{ "max-width": "100%" }} src="assets/paso5.PNG" />
</Container>
</Card>
<Card className="m-3">
<Container>
<h2>Haga clic en listo para confirmar los cambios</h2>
<img style={{ "max-width": "100%" }} src="assets/paso6.PNG" />
</Container>
</Card>
<Card className="m-3">
<Container>
<h2>
Pegue el enlace copiado en el formulario que se muestra en el
principio de esta pagina
</h2>
<img style={{ "max-width": "100%" }} src="assets/paso7.PNG" />
</Container>
</Card>
</Container>
</Card>
</Container>
<Footer />
</div>
);
};
export default AddLesson;
<file_sep>/frontend-website-yourcourses_/src/components/private/MyCourses.js
import { useStateContext } from "../../utilities/Context";
import { paxios } from "../../utilities/Axios";
import { useEffect } from "react";
import { useHistory } from "react-router-dom";
import CardDeck from "react-bootstrap/CardDeck";
import { Card, Container, Button, Row } from "react-bootstrap";
import Navbar from "../common/Navbar";
import Footer from "../common/Footer";
import imgLessons from "./Lessons.png";
import ButtonGeneral from "../common/ButtonGeneral";
import {
COURSES_LOADING,
COURSES_LOADED,
COURSES_RESET,
COURSES_ERROR,
COURSES_SET_CURRENT,
} from "../../utilities/store/reducers/courses.reducer";
import NavBar from "../common/Navbar";
const ListCourses = () => {
const [{ auth, courses }, dispatch] = useStateContext();
const history = useHistory();
console.log("El author", auth.user.email);
useEffect(() => {
dispatch({ type: COURSES_RESET });
dispatch({ type: COURSES_LOADING });
console.log("El author", auth.user.email);
paxios
.get(`/api/courses/${auth.user.email}`)
.then(({ data }) => {
dispatch({ type: COURSES_LOADED, payload: data });
console.log(data);
})
.catch((ex) => {
dispatch({ type: COURSES_ERROR });
}); //end paxios
}, []);
let ListElements = [];
ListElements = courses.courses.map((o) => {
return (
<div className="shadow-lg p-3 mb-5 bg-white rounded">
<CardDeck>
<Card className="text-center m-3">
<Card.Footer></Card.Footer>
<Card.Body>
<Card.Title>{o.name}</Card.Title>
<Card.Text>{o.author}</Card.Text>
<Card.Text>{o.description}</Card.Text>
<Card.Text>{o.information}</Card.Text>
</Card.Body>
<Card.Footer>
<small className="text-muted">$ {o.price}</small>
</Card.Footer>
<Card.Body>
<Button
onClick={() => {
dispatch({
type: COURSES_SET_CURRENT,
payload: { _id: o._id },
});
history.push("/courses/one");
}}
>
Ver lecciones
</Button>
<Button
onClick={() => {
dispatch({
type: COURSES_SET_CURRENT,
payload: { _id: o._id },
});
history.push("/newLesson");
}}
>
Agregar lecciones
</Button>
<Button>Eliminar</Button>
</Card.Body>
</Card>
</CardDeck>
</div>
);
});
console.log("Mis courses vienen: ", ListElements.length);
if (ListElements.length == 0) {
return (
<div>
<Navbar />
<Container>
<Row>
<h1 className="mx-auto mt-5">Aun no tienes cursos</h1>
</Row>
<Row xs={80} md={80} sm={4} className="justify-content-md-center">
<img style={{ "max-width": "100%" }} src={imgLessons} rounded />
</Row>
<Row>
<h2 className="mx-auto">¡Crea un curso ya!</h2>
</Row>
<Row>
<div className="mx-auto">
<ButtonGeneral ruta="/new" contenido="Crear Curso" />
</div>
</Row>
</Container>
<Footer />
</div>
);
} else {
return (
<div>
<NavBar />
<Container>{ListElements}</Container>
<Footer />
</div>
);
}
};
export default ListCourses;
<file_sep>/backend-webSite-YourCourses/controllers/authAndUserController.js
// Hacemos referencia a la clase
const authAndUserModel = require("../models/authAndUser");
const modelAuthAndUser = new authAndUserModel();
// Exportar la configuración de seguridad
const securityConfig = require("../config/security");
//const passport = require("passport");
exports.signUp = async (req, res, next) => {
try {
const message = [];
const { email, password, passwordVerify } = req.body;
if (!email) {
message.push({ message: "Debe tener un correo electrónico" });
}
if (!password) {
message.push({ message: "Debe tener una contraseña" });
}
if (!passwordVerify) {
message.push({ message: "Debe confirmar la contraseña" });
}
if (password != passwordVerify && passwordVerify != null) {
message.push({ message: "Las contraseñas no coinciden" });
}
if (message.length) {
res.status(400).json(message);
} else {
await modelAuthAndUser.addUser({
email,
password,
stateAccount: "Active",
});
res.status(201).json({ message: "Registrado con exito" });
}
} catch (error) {
if (error.toString().match(/MongoError: E11000.*/)) {
// Busca si ese ese error sobre el correo.
//console.log("YA EXISTE ESE CORREO");
res.status(500).json({ message: "Ese correo ya esta registrado" });
} else {
console.log(error);
res
.status(500)
.json({ message: "Algo salio mal, contacte con el administrador" });
}
}
};
exports.logIn = async (req, res, next) => {
try {
const message = [];
const { email, password } = req.body;
if (!email) {
// Si el correo viene vacio
message.push({ message: "Debe ingresar un correo electrónico" });
}
if (!password) {
// Si la contraseña viene vacia
message.push({ message: "Debe ingresar una contraseña" });
}
if (message.length) {
res.status(400).json(message);
} else {
const _idUser = await modelAuthAndUser.comparePassword(email, password);
if (_idUser == null) {
// Si devuelve null
//res.send(`Viene vacio: ${user}`);
message.push({ message: "El usuario no existe" });
}
if (_idUser == false) {
// Si devuelve falso
message.push({ message: "Correo y/o contraseña incorrecto/a" });
}
if (message.length) {
res.status(403).json(message);
} else {
// Si devuelve verdadero
const token = await securityConfig.getToken({ _id: _idUser, email });
res.status(200).json({
message: "Bienvenido/a",
user: { _id: _idUser, email },
jwt: token,
});
}
}
} catch (error) {
console.log(error);
}
};
exports.test = async (req, res, next) => {
res.send(`_id User: ${req.user._id}`);
};
<file_sep>/frontend-website-yourcourses_/src/components/common/Redirector.js
import { useState } from "react";
import { Redirect } from "react-router-dom";
const Redirector = () => {
let [redirect, setRedirect] = useState("");
if (redirect !== "") {
return <Redirect to={redirect}></Redirect>;
}
return setRedirect("/login");
};
export default Redirector;
<file_sep>/backend-webSite-YourCourses/models/lessons.js
// Importamos el archivo de la base de datos
const { RequestTimeout } = require("http-errors");
const mongoDB = require("../config/db");
// Importamos el objectId
const objectId = require("mongodb").ObjectID;
class lessons {
constructor() {
this.collection = null;
mongoDB
.getDb()
.then(async (db) => {
this.collection = await db.collection("lessons");
})
.catch((error) => {
throw error;
});
}
async getAllLessons() {
try {
const result = await this.collection.find({}).toArray();
return result;
} catch (error) {
throw error;
}
}
async getAllCoursesCourse(id) {
try {
console.log(id);
const courseId = new objectId(id);
const result = await this.collection.find({ courseId }).toArray();
return result;
} catch (error) {
throw error;
}
}
async getOneLesson(id) {
try {
const _id = new objectId(id);
const result = await this.collection.findOne({ _id });
return result;
} catch (error) {
throw error;
}
}
async addLesson(data) {
try {
let { id, name, description, video } = data;
console.log(id);
const courseId = new objectId(id);
const dat = {
courseId,
name,
description,
video,
};
await this.collection.insertOne(dat);
//return result;
} catch (error) {
throw error;
}
}
async updateLessonById(lessonId, data) {
try {
const _id = new objectId(lessonId);
const docOptions = { $set: data };
await this.collection.updateOne({ _id }, docOptions, {
returnOriginal: false,
});
} catch (error) {
throw error;
}
}
}
module.exports = lessons;
<file_sep>/backend-webSite-YourCourses/models/courses.js
// Importamos el archivo de la base de datos
const { RequestTimeout } = require("http-errors");
const mongoDB = require("../config/db");
// Importamos el objectId
const objectId = require("mongodb").ObjectID;
class courses {
constructor() {
this.collection = null;
mongoDB
.getDb()
.then(async (db) => {
this.collection = await db.collection("courses");
/* if (process.env.ENSURE_INDEX == "1") {
await this.collection.createIndex({ email: 1 }, { unique: true });
} */
})
.catch((error) => {
throw error;
});
}
async getAllCourses() {
try {
const result = await this.collection.find({}).toArray();
return result;
} catch (error) {
throw error;
}
}
async getAllCoursesByAuthor(author) {
try {
const result = await this.collection.find({ author }).toArray();
return result;
} catch (error) {
throw error;
}
}
async getOneCourse(id) {
try {
const _id = new objectId(id);
const result = await this.collection.findOne({ _id });
return result;
} catch (error) {
throw error;
}
}
async addCourse(data) {
try {
await this.collection.insertOne(data);
} catch (error) {
throw error;
}
}
async updateCourseById(courseId, data) {
try {
const _id = new objectId(courseId);
const docOptions = { $set: data };
await this.collection.updateOne({ _id }, docOptions, {
returnOriginal: false,
});
} catch (error) {
throw error;
}
}
async addLesson(courseId, name, description, video) {
try {
const _id = new objectId(courseId);
const lesson = {
id: objectId(),
name,
description,
video,
};
const docOperations = { $push: { lessons: lesson } };
await this.collection.updateOne({ _id }, docOperations, {
returnOriginal: false,
});
} catch (error) {
throw error;
}
}
async getAllLessonsByCourse(cursoId) {
try {
console.log(cursoId);
const _id = objectId(cursoId);
const result = await this.collection.findOne({ _id });
return result.lessons;
} catch (error) {
throw error;
}
}
async getOneLessonByCourse(cursoId, lessonId) {
try {
const _id = objectId(cursoId);
const result = await this.collection
.findOne({ _id })
.then((doc) => {
for (const i in doc.lessons) {
if (doc.lessons[i].id == lessonId) {
return doc.lessons[i];
}
}
})
.catch((error) => {
throw error;
});
return result;
} catch (error) {
throw error;
}
}
async updateOneLessonByCourse(cursoId, lessonId, name, description, video) {
try {
const _id = objectId(cursoId);
const id = objectId(lessonId);
const docOperations = {
$set: {
"lessons.$.name": name,
"lessons.$.description": description,
"lessons.$.video": video,
},
};
await this.collection.updateOne({ _id, "lessons.id": id }, docOperations);
} catch (error) {
throw error;
}
}
async subscribe(idCourse, idUser) {
try {
console.log(idCourse, idUser);
const inscriptioId = new objectId(idCourse);
const _id = new objectId(idUser);
const docOperations = { $addToSet: { inscriptions: inscriptioId } };
const reesult = await this.collection.findOneAndUpdate(
{ _id },
docOperations,
{
returnOriginal: false,
}
);
return reesult;
} catch (error) {
throw error;
}
}
async findSubscribe(idUser) {
try {
const _id = new objectId(idUser);
const reesult = await this.collection
.find({ inscriptions: _id })
.toArray();
return reesult;
} catch (error) {
throw error;
}
}
async verifySubs(idCourse, idUser) {
try {
const _id = new objectId(idCourse);
const id = new objectId(idUser);
const result = await this.collection.findOne({ _id, inscriptions: id });
if (!result) {
return false;
} else {
return true;
}
} catch (error) {
throw error;
}
}
}
module.exports = courses;
<file_sep>/frontend-website-yourcourses_/src/components/private/Lessons.js
import { useStateContext } from "../../utilities/Context";
import { paxios } from "../../utilities/Axios";
import { useEffect, useState, Link } from "react";
import { useHistory } from "react-router-dom";
import CardDeck from "react-bootstrap/CardDeck";
import { Card, Container, Button, Row } from "react-bootstrap";
import Navbar from "../common/Navbar";
import Footer from "../common/Footer";
import imgLessons from "./Lessons.png";
import {
LESSONS_LOADING,
LESSONS_LOADED,
LESSONS_ERROR,
LESSONS_RESET,
} from "../../utilities/store/reducers/lessons.reducer";
const ListCourses = () => {
const [{ auth, lessons, courses }, dispath] = useStateContext();
const history = useHistory();
const _id = courses.currentId;
//console.log("El Id", _id);
let vInscription = null;
// var [vInscription, seti] = useState(false);
// TODO: AQUI ESTA EL FOR
const cour = courses.courses;
let pertCourse = "";
for (const i in cour) {
//console.log(doc.lessons[i]);
if (cour[i]._id == _id) {
//console.log("Encontre el curso: ", cour[i]);
for (const j in cour[i].inscriptions) {
if (cour[i].inscriptions[j] == auth.user._id) {
//console.log("Encontre la inscription: ", cour[i].inscriptions[j]);
vInscription = true;
} else {
console.log("No encontre la inscripcion");
}
}
pertCourse = cour[i].author;
} else {
console.log("No encontre el curso :o");
}
}
useEffect(() => {
// paxios
// .get(`/api/courses/${_id}/inscription/${auth.user._id}`)
// .then(({ data }) => {})
// .catch((ex) => {
// console.log(ex);
// });
dispath({ type: LESSONS_RESET });
dispath({ type: LESSONS_LOADING });
paxios
.get(`/api/courses/lessons/${_id}`)
.then(({ data }) => {
dispath({ type: LESSONS_LOADED, payload: data });
})
.catch((ex) => {
dispath({ type: LESSONS_ERROR });
}); //end paxios
}, []);
let ListElements = [];
ListElements = lessons.lessons.map((o) => {
if (vInscription) {
return (
<CardDeck>
<Card className="text-center m-3">
<Card.Body>
<Card.Title>{o.name}</Card.Title>
<Card.Text>{o.description}</Card.Text>
<Button target="_blank" href={o.video}>
Ver video
</Button>
</Card.Body>
</Card>
</CardDeck>
);
} else {
if (pertCourse == auth.user.email) {
return (
<CardDeck>
<Card className="text-center m-3">
<Card.Body>
<Card.Title>{o.name}</Card.Title>
<Card.Text>{o.description}</Card.Text>
<Button target="_blank" href={o.video}>
Ver video
</Button>
</Card.Body>
</Card>
</CardDeck>
);
} else {
return (
<CardDeck>
<Card className="text-center m-3">
<Card.Body>
<Card.Title>{o.name}</Card.Title>
<Card.Text>{o.description}</Card.Text>
{/* <Button target="_blank" href={o.video}>
Ver video
</Button> */}
<Card.Text>Inscribite para ver las lecciones</Card.Text>
</Card.Body>
</Card>
</CardDeck>
);
}
}
});
//const cour = courses.courses[2].inscriptions.length;
console.log("El falso o verdadero: ");
if (pertCourse == auth.user.email) {
if (ListElements.length == 0) {
return (
<div>
<Navbar />
<Container>
<Row>
<h1 className="mx-auto mt-5">No hay lecciones aún</h1>
</Row>
<Row xs={80} md={80} sm={4} className="justify-content-md-center">
<img style={{ "max-width": "100%" }} src={imgLessons} rounded />
</Row>
<Row>
<h2 className="mx-auto">Vuelve mas tarde</h2>
</Row>
</Container>
<Footer />
</div>
);
} else {
return (
<div>
<Navbar />
<Container>{ListElements}</Container>
<Footer />
</div>
);
}
} else {
if (vInscription) {
console.log("Paso aqui al si true");
if (ListElements.length == 0) {
return (
<div>
<Navbar />
<Container>
<Row>
<h1 className="mx-auto mt-5">No hay lecciones aún</h1>
</Row>
<Row xs={80} md={80} sm={4} className="justify-content-md-center">
<img style={{ "max-width": "100%" }} src={imgLessons} rounded />
</Row>
<Row>
<h2 className="mx-auto">Vuelve mas tarde</h2>
</Row>
</Container>
<Footer />
</div>
);
} else {
return (
<div>
<Navbar />
<Container>{ListElements}</Container>
<Footer />
</div>
);
}
} else {
console.log("paso al if si false");
if (ListElements.length == 0) {
return (
<div>
<Navbar />
<Container>
<Row>
<h1 className="mx-auto mt-5">No hay lecciones aún</h1>
</Row>
<Row xs={80} md={80} sm={4} className="justify-content-md-center">
<img style={{ "max-width": "100%" }} src={imgLessons} rounded />
</Row>
<Row>
<h2 className="mx-auto">Vuelve mas tarde</h2>
</Row>
</Container>
<Footer />
</div>
);
} else {
return (
<div>
<Navbar />
<Container>
<Card>
<Button
onClick={() => {
paxios
.put(`/api/courses/${auth.user._id}/course/${_id}`)
.then((result) => {
history.push("/startit");
})
.catch((ex) => {
console.log(ex);
});
}}
>
Inscribirse
</Button>
</Card>
{ListElements}
</Container>
<Footer />
</div>
);
}
}
}
//
};
export default ListCourses;
<file_sep>/frontend-website-yourcourses_/src/utilities/PrivateRouter.js
import { Route, Redirect } from "react-router-dom";
import { useStateContext } from "./Context";
const PrivateRoute = (props) => {
const { component: MyCustomComponent, ...rest } = props;
const [{ auth }] = useStateContext();
return (
<Route
{...rest}
render={(props) => {
const { location } = props;
return auth.logged ? (
<MyCustomComponent {...props} />
) : (
<Redirect to={{ pathname: "/", state: { from: location } }} />
);
}}
/>
);
};
export default PrivateRoute;
<file_sep>/frontend-website-yourcourses_/src/utilities/store/Store.js
import appReducer from "./reducers/app.reducer";
import authReducer from "./reducers/auth.reducer";
import coursesReducer from "./reducers/courses.reducer";
import lessonsReducer from "./reducers/lessons.reducer";
function mainReducer(state = {}, action = {}) {
const { app, auth, courses, lessons } = state;
return {
app: appReducer(app, action),
auth: authReducer(auth, action),
courses: coursesReducer(courses, action),
lessons: lessonsReducer(lessons, action),
};
}
export default mainReducer;
<file_sep>/backend-webSite-YourCourses/routes/api/api_auth.js
// Importamos express
const express = require("express");
const router = express.Router();
// Exportar la configuración de seguridad
const securityConfig = require("../../config/security");
// Exportar el controlador
const authAndUserController = require("../../controllers/authAndUserController");
// Sign in
router.post("/signin", authAndUserController.signUp);
router.post("/login", authAndUserController.logIn);
module.exports = router;
<file_sep>/frontend-website-yourcourses_/src/utilities/Context.js
import {createContext, useContext, useReducer} from 'react';
//TODO: add Dispatching Configurations
let dispatchIsConfigured =false;
export const StateContext = createContext();
export const StateProvider = ({reducer, initialState, children})=>{
const reducerValue = useReducer(reducer, initialState);
//const [, dispatch] = reducerValue;
if (!dispatchIsConfigured){
//TODO: configure Dispatch elements
dispatchIsConfigured = true;
}
return (
<StateContext.Provider value={reducerValue}>
{children}
</StateContext.Provider>
);
}
export const useStateContext = () => useContext(StateContext);
<file_sep>/frontend-website-yourcourses_/src/components/private/Start.js
import { useStateContext } from "../../utilities/Context";
import Courses from "./Courses";
import Navbar from "../common/Navbar";
import Footer from "../common/Footer";
const Start = () => {
const [{ auth }] = useStateContext();
return (
<div>
<Navbar />
<Courses />
<Footer />
</div>
);
};
export default Start;
<file_sep>/frontend-website-yourcourses_/src/components/common/ButtonBackLogin.js
import { useState } from "react";
import { Redirect } from "react-router-dom";
import { Button } from "react-bootstrap";
const ButtonBackLogin = () => {
const [redirect, setRedirect] = useState("");
if (redirect !== "") {
return <Redirect to={redirect}></Redirect>;
}
return (
<div>
<Button
onClick={(e) => {
setRedirect("/login");
}}
>
Iniciar sesion
</Button>
</div>
);
};
export default ButtonBackLogin;
<file_sep>/frontend-website-yourcourses_/src/components/public/Splash.js
import { useEffect } from "react";
import { useStateContext } from "../../utilities/Context";
import { paxios, setJWT, setUnAuthInterceptor } from "../../utilities/Axios";
// import { Redirector } from "../common/Redirector";
import ButtonExit from "../common/ButtonExit";
import Navbar from "../common/Navbar";
import Footer from "../common/Footer";
import { Card} from "react-bootstrap";
import CardDeck from "react-bootstrap/CardDeck";
import { APP_INIT, APP_MIN } from "../../utilities/store/reducers/app.reducer";
import { JWT_INVALID } from "../../utilities/store/reducers/auth.reducer";
//import Page from '../cmns/Page';
import { useHistory, useLocation } from "react-router-dom";
import ButtonBackLogin from "../common/ButtonBackLogin";
import { Container } from "react-bootstrap";
const Splash = ({ children }) => {
//
const [{ app, auth }, dispatch] = useStateContext();
const routeHistory = useHistory();
const routeLocation = useLocation();
useEffect(() => {
if (!app.initialized) {
setTimeout(() => {
dispatch({ type: APP_MIN });
}, 0);
appInit(auth, dispatch, { routeHistory, routeLocation });
}
}, []);
console.log(app.minTimeElapsed);
if (!app.initialized && app.minTimeElapsed) {
return (
<div>
<CardDeck>
<Card className="text-center m-3">
<Card.Footer></Card.Footer>
<Navbar />
<Container>
<h1>
¡Oops Algo salio mal!
</h1>
<h2>No pudimos reconocerte, por favor inicia sesión</h2>
<ButtonExit contenido="Volver al inicio"></ButtonExit>
</Container>
</Card>
</CardDeck>
<Footer />
</div>
);
} else {
return <section>{children}</section>;
}
};
const unAuth = (dispatch, { routeLocation }) => {
return () => {
dispatch({ type: JWT_INVALID, payload: { to: routeLocation.pathname } });
};
};
const appInit = async (auth, dispatch, routeHooks) => {
//Setting unAuth
setUnAuthInterceptor(unAuth(dispatch, routeHooks));
if (auth.jwt === "" || auth.logged === false) {
dispatch({ type: APP_INIT });
} else {
try {
setJWT(auth.jwt);
await paxios.get("/api/heartbeat");
dispatch({ type: APP_INIT });
} catch (e) {
console.log(e);
}
}
};
export default Splash;
<file_sep>/frontend-website-yourcourses_/src/components/private/Courses.js
import { useStateContext } from "../../utilities/Context";
import { paxios } from "../../utilities/Axios";
import { useEffect } from "react";
import { useHistory } from "react-router-dom";
import CardDeck from "react-bootstrap/CardDeck";
import { Card, Container, Button } from "react-bootstrap";
import axios from "axios";
import {
COURSES_LOADING,
COURSES_LOADED,
COURSES_RESET,
COURSES_ERROR,
COURSES_SET_CURRENT,
} from "../../utilities/store/reducers/courses.reducer";
const ListCourses = () => {
const [{ auth, courses }, dispatch] = useStateContext();
const history = useHistory();
const ListElements = courses.courses.map((o) => {
if (auth.user.email != o.author) {
return (
<div className="col-md-4 shadow-lg p-3 mb-5 bg-white rounded">
<CardDeck>
<Card className="text-center mt-2">
<Card.Body>
<Card.Title>{o.name}</Card.Title>
<Card.Text>{o.author}</Card.Text>
<Card.Text>{o.description}</Card.Text>
<Card.Text>{o.information}</Card.Text>
</Card.Body>
<Card.Footer>
<small className="text-muted">$ {o.price}</small>
</Card.Footer>
<Card.Body>
<Button
onClick={() => {
dispatch({
type: COURSES_SET_CURRENT,
payload: { _id: o._id },
});
history.push("/courses/one");
}}
>
Ver más
</Button>
</Card.Body>
</Card>
</CardDeck>
</div>
);
} else {
return (
<div className="col-md-4 shadow-lg p-3 mb-5 bg-white rounded">
<CardDeck>
<Card className="text-center mt-2">
<Card.Body>
<Card.Title>{o.name}</Card.Title>
<Card.Text>{o.author}</Card.Text>
<Card.Text>{o.description}</Card.Text>
<Card.Text>{o.information}</Card.Text>
</Card.Body>
<Card.Footer>
<small className="text-muted">$ {o.price}</small>
</Card.Footer>
<Card.Body>
<Button
onClick={() => {
dispatch({
type: COURSES_SET_CURRENT,
payload: { _id: o._id },
});
history.push("/courses/one");
}}
>
Ver lecciones
</Button>
<Button
onClick={() => {
dispatch({
type: COURSES_SET_CURRENT,
payload: { _id: o._id },
});
history.push("/newLesson");
}}
>
Agregar lecciones
</Button>
<Button>Eliminar</Button>
</Card.Body>
</Card>
</CardDeck>
</div>
);
}
});
useEffect(() => {
dispatch({ type: COURSES_RESET });
dispatch({ type: COURSES_LOADING });
paxios
.get("/api/courses/allCourses")
.then(({ data }) => {
dispatch({ type: COURSES_LOADED, payload: data });
console.log(data);
})
.catch((ex) => {
dispatch({ type: COURSES_ERROR });
}); //end paxios
}, []);
return (
<div className="container">
<div className="row">
{ListElements}
</div>
</div>
);
};
export default ListCourses;
<file_sep>/frontend-website-yourcourses_/src/components/private/AddCourse.js
import NavBar from "../common/Navbar";
import { Button, Form, Container, Card } from "react-bootstrap";
import Footer from "../common/Footer";
import { COURSES_RESET } from "../../utilities/store/reducers/courses.reducer";
import { useStateContext } from "../../utilities/Context";
import { useState } from "react";
import { paxios } from "../../utilities/Axios";
import { useHistory } from "react-router-dom";
const AddCourse = () => {
const [, dispatch] = useStateContext();
const history = useHistory();
const [form, setForm] = useState({
name: "",
description: "",
information: "",
price: "",
});
const onChange = (e) => {
e.preventDefault();
e.stopPropagation();
const { name, value } = e.target;
let newForm = { ...form, [name]: value };
setForm(newForm);
};
const addNewCourse = (e) => {
e.preventDefault();
e.stopPropagation();
paxios
.post("/api/courses/new", form)
.then((data) => {
console.log(data);
dispatch({ type: COURSES_RESET });
history.push("/startit");
})
.catch((ex) => {
console.log(ex);
alert("Algo salio mál al ingresar");
});
};
return (
<div>
<NavBar />
<Container>
<Card className="mt-5">
<Form>
<Form.Group>
<Form.Label>Nombre del curso</Form.Label>
<Form.Control
name="name"
value={form.name}
onChange={onChange}
type="text"
placeholder="Ej: NodeJS Server Side"
/>
</Form.Group>
<Form.Group>
<Form.Label>Descripcion</Form.Label>
<Form.Control
name="description"
value={form.description}
onChange={onChange}
type="text"
placeholder="Ej: Desarrollo de APIs en NodeJS"
/>
</Form.Group>
<Form.Group>
<Form.Label>Informacion</Form.Label>
<Form.Control
name="information"
value={form.information}
onChange={onChange}
type="text"
placeholder="Ej: Comprederas los conceptos del desarrollo de NodeJS"
/>
</Form.Group>
<Form.Group>
<Form.Label>Precio</Form.Label>
<Form.Control
name="price"
value={form.price}
onChange={onChange}
type="text"
placeholder="Ej: $12"
/>
</Form.Group>
<Button onClick={addNewCourse} variant="primary">
Guardar
</Button>
</Form>
</Card>
</Container>
<Footer />
</div>
);
};
export default AddCourse;
<file_sep>/frontend-website-yourcourses_/src/components/public/SignUp.js
import { useState } from "react";
import { useStateContext } from "../../utilities/Context";
// import { paxios } from "../../utilities/Axios";
import { useHistory } from "react-router-dom";
import imgRegister from "./register.svg";
import "./Login&signUp.css";
import ButtonGeneral from "../common/ButtonGeneral";
import axios from "axios";
import {
SIGNIN_FETCHING,
SIGNIN_FETCHING_FAILED,
SIGNIN_SUCCES,
SIGNIN_END,
} from "../../utilities/store/reducers/auth.reducer";
import { Button } from "react-bootstrap";
const SingUp = () => {
const [, dispatch] = useStateContext();
const [form, setForm] = useState({
email: "",
password: "",
passwordVerify: "",
});
const history = useHistory();
const onChange = (e) => {
e.preventDefault();
e.stopPropagation();
const { name, value } = e.target;
let newForm = { ...form, [name]: value };
setForm(newForm);
};
const addNewUser = (e) => {
e.preventDefault();
e.stopPropagation();
dispatch({ type: SIGNIN_FETCHING });
axios
.post("api/auth/signin", form)
.then((data) => {
console.log(data);
dispatch({ type: SIGNIN_SUCCES });
history.push("/login");
})
.catch((ex) => {
console.log(ex);
dispatch({ type: SIGNIN_FETCHING_FAILED });
alert("Algo salio mál al registrar");
});
};
return (
<div className="container1">
<div className="forms-container1">
<div className="signin-signup">
<form
style={{ "align-items": "center" }}
action="#"
className="sign-in-form"
>
<h2 className="title">Crear cuenta</h2>
<div className="input-field">
<i className="fas fa-envelope"></i>
<input
name="email"
onChange={onChange}
value={form.email}
type="email"
placeholder="Correo electrónico"
/>
</div>
<div className="input-field">
<i className="fas fa-lock"></i>
<input
name="password"
value={form.password}
onChange={onChange}
type="password"
placeholder="<PASSWORD>"
/>
</div>
<div className="input-field">
<i className="fas fa-lock"></i>
<input
name="passwordVerify"
value={form.passwordVerify}
onChange={onChange}
type="password"
placeholder="Verifica tu contraseña"
/>
</div>
<Button onClick={addNewUser} className="btn solid">
Crear cuenta
</Button>
<p className="social-text">
Encuentranos en nuestras redes sociales
</p>
<div className="social-media">
<a className="social-icon">
<i className="fab fa-facebook-f"></i>
</a>
<a className="social-icon">
<i className="fab fa-twitter"></i>
</a>
<a className="social-icon">
<i className="fab fa-google"></i>
</a>
<a className="social-icon">
<i className="fab fa-youtube"></i>
</a>
</div>
</form>
</div>
</div>
<div className="panels-container1">
<div className="panel left-panel">
<div className="content">
<h3>¿Ya eres uno de nosotros?</h3>
<p>
Ingresa tus credenciales para poder disfrutar todo lo que Your Courses te ofrece.
</p>
<ButtonGeneral contenido="Iniciar Sesión" ruta="/login" />
</div>
<img src={imgRegister} className="image" alt="imagen del registro" />
</div>
</div>
</div>
);
};
export default SingUp;
| 67bb35203e4fe441840d6d8b622cba8e40066039 | [
"JavaScript"
] | 35 | JavaScript | WatchDog773/webSite-YourCourses | c806137c2dfacf93ab71c82a28aa8c6557adfd32 | 1182c8f2db25cdbba28102acbb4b61e2d95add34 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.